Vector algorithm using tree composition
Sniffed this trick from the Incanter source. Here’s a demo of using tree composition to calculate a 2-d Euclidean distance between two points.
(def x [1 2])
(def y [4 5])
(defn- tree-comp-each [root branch & leaves]
(apply
root (map branch leaves)))
(defn euclidean-distance
[a b]
{:pre [(= (count a) (count b))]}
(sqrt
(apply
tree-comp-each
+
(fn [[x y]]
(pow (- x y) 2))
(map vector a b))))
I’ve only had exposures to tree traversal in the use of implementing searching and sorting algorithms. This trick here definitely widened my eyes to the wonders of functional programming. It’s more than just being able to pass and manipulate functions.
I need to think like a tree.
read moreJFUtil 2.0 alpha demonstration
Rather than talk about how much better JFUtil 2.0 is and all, I’ll just show you a demonstration strategy illustrating the features of this JForex utilities library.
Download the latest JFUtil from the project page. As this is an alpha release, I need your help in finding bugs and look for improvements. Leave me a message if you have any comment or suggestion please.
It’s best if you copy and paste the following demo strategy source code into your IDE or text editor for viewing.
read moreDissecting a JForex strategy — MA_Play.java
Having studied the anatomy of an empty JForex strategy (Part 1 and Part 2), it’s time to dissect a working one. MA_Play is the strategy that is included with every JForex API download as a demonstration. You can find the complete source code of this strategy in /src/singlejartest/ in the JForex API zipped package.
Recall that the first Interface method which runs at the start of the strategy is onStart. The onStart method of MA_Play is reproduced below.
public void onStart(IContext context) throws JFException {
engine = context.getEngine();
indicators = context.getIndicators();
this.console = context.getConsole();
console.getOut().println("Started");
}
The variables engine, indicators, and console are fields of the MA_Play class. They are global variables within the class. What lines 42–44 do is to save the IEngine, IIndicators, and IConsole objects for later use.
The last line of onStart, line 45, is merely to print a message on your JForex program console to notify the user that the strategy has started.
Once onStart is finished processing, the server is likely to call onTick if a market tick arrives. If it’s not during market hours, then there’s no tick and some other event might happen instead of onTick. Think of the methods as events rather than a linear process. You program your JForex strategy according to what you want to do with each of the six IStrategy Interface event.
For this particular strategy, the programmer decides to implement their strategy at the tick level. As such, much of the trading algorithm resides in onTick for MA_Play. Note that this is a design choice, you can use onBar if you want your strategy to process at the bar level (or you can use both onTick and onBar).
Here’s the source code for onTick in MA_Play.
public void onTick(Instrument instrument, ITick tick) throws JFException {
if (ma1[instrument.ordinal()] == -1) {
ma1[instrument.ordinal()] = indicators.ema(instrument, Period.TEN_SECS, OfferSide.BID, IIndicators.AppliedPrice.MEDIAN_PRICE, 14, 1);
}
double ma0 = indicators.ema(instrument, Period.TEN_SECS, OfferSide.BID, IIndicators.AppliedPrice.MEDIAN_PRICE, 14, 0);
if (ma0 == 0 || ma1[instrument.ordinal()] == 0) {
ma1[instrument.ordinal()] = ma0;
return;
}
double diff = (ma1[instrument.ordinal()] - ma0) / (instrument.getPipValue());
if (positionsTotal(instrument) == 0) {
if (diff > 1) {
engine.submitOrder(getLabel(instrument), instrument, IEngine.OrderCommand.SELL, 0.001, 0, 0, tick.getAsk()
+ instrument.getPipValue() * 10, tick.getAsk() - instrument.getPipValue() * 15);
}
if (diff < -1) {
engine.submitOrder(getLabel(instrument), instrument, IEngine.OrderCommand.BUY, 0.001, 0, 0, tick.getBid()
- instrument.getPipValue() * 10, tick.getBid() + instrument.getPipValue() * 15);
}
}
ma1[instrument.ordinal()] = ma0;
}
At a glance, you may notice that the variables ma0 and ma1 play a key role in determining the setup. Hint: To reverse engineer a strategy, it may be easier to work backward from when the order is placed, which is done by engine.submitOrder in this case.
ma0 and ma1 hold results from exponential moving averages (EMA). ma0 is the current value. ma1 is the previous bar’s value. Lines 56–63 check using IF tests (lines 56 and 60) to see if either of the variables hold invalid data. If the data is invalid, the indicator is calculated and the rest of the onTick is skipped with the return statement on line 62.
Note: Indicator values can sometimes be invalid (zero, negative, or Double.NaN, depending on the particular indicator implementation) if there is insufficient data to calculate it or an error occurred, for examples.
The EMAs are fetched in lines 57 and 59 using the IIndicators object (which was initialized in onStart). The JForex Wiki provides an explanation of its use.
Notice that ma1 is an array, which was declared in line 38 with a size equivalent to the number of all available JForex instruments. In particular, it is used with a special index value as in ma1[instrument.ordinal()]. In other words, it is asking for the current instrument’s slot in the ma1 array. The current instrument is the one that is passed into the method in line 55.
Moving down the code, another point of interest is line 65, showing the use of instrument.getPipValue().
Line 67 checks if the current total number of position is zero. If it is, meaning no opened position, then the strategy proceeds to check the entry signal to enter a trade (lines 68–76).
positionsTotal() is a custom method defined in lines 84–92. It uses a FOR loop to cycle through all the orders obtained from engine.getOrders(instrument)
Once either of the long or short condition, lines 68 and 72, respectively, is met, the strategy submits an order in lines 69 for a short and line 73 for a long. The particulars of submitting market orders is described in the JForex Wiki.
When you stop this strategy, onStop (lines 48–53) is called. For this strategy, the programmer loops through all the orders again using engine.getOrders() and closes each of the position with an order.close() command in line 50.
That is it for this trivial strategy. If there is one point that you should remember. Note my use of the many links to the JForex javadoc and JForex Wiki throughout this post. You are likely to find many of your answers from those two sources. If not, there’s always the JForex Support Board.
Now that you’ve had an idea of how MA_Play.java works, it’s time to test it. In the next post in January, we will discuss the JForex Historical Tester and what to watch for when running a strategy live.
read moreJFUtil: An open-source JForex utilities library
JFUtil is a Quantisan.com open-source project focused on reusable JForex trading strategy components. Latest version is 2.1.3 released on April 8, 2011. Please keep your local JFUtil library up to date for the latest patches and features.
Main Features
1. Access to IContext and IAccount from anywhere in your project files.
The one and only JForexContext object in JFUtil is a thread-safe, singleton object which can be called from anywhere within your projects, across any class file. No need to declare global IContext variables. No need to pass it around in parameters.
2. Simplify order submission with ticket builder.
Set your trade order parameters with an order ticket object using a builder constructor. You can build ticket with as few or as many parameters as you like. All with intuitive method names in the same ticket class.
OrderTicket buySpTicket = new OrderTicket .Builder(label, instrument, IEngine.OrderCommand.BUY, 0.1) .setStopLossPrice(stopPrice) // set stop price to ticket .setTakeProfitPrice(targetPrice) // set target .build();
3. No more confusion about indicator methods.
Indicators are encapsulated into their own bean object with their full function name and parameters are set using intuitive, clearly described methods.
// get an EMA indicator value by building an indicator bean
MovingAverage maBean = IndicatorBeanFactory.getMovingAverage();
// then sets its parameters with obvious method names
maBean.setAppliedPrice(IIndicators.AppliedPrice.MEDIAN_PRICE)
.setMAType(IIndicators.MaType.EMA)
.setWidth(14); // all of these are optional parameters
// feed the bean into a generic calculation method to get the result
double ema = Indicating.calculate(instrument, Period.ONE_MIN, maBean);
4. Implicit multi-threading for ordering.
Ease your main thread’s workload for processing incoming data and avoid your order manager holding up the traffic. All automatically performed in the background without extra coding for you.
5. Built-in popular numerical functions for forex trading.
Calculate expected profit or loss in your account currency. Saves you from writing boilerplate codes and reinventing the wheel.
6. Continuous improvements!
JFUtil is continuously being improved based on feedback from traders like you. See the changelog below for major changes since the initial release in November 2010.
Example
To best illustrate how JFUtil can make your JForex programming life easier, see this JForex strategy source code example.
Download
Download the latest JFUtil library jar file including the javadoc for your own use (use the @Library annotation in your strategy) or fork the project at Github to participate in this open-source project to make programming trading strategies in JForex easier for everyone.
Feedback
Please report any issue or discuss your question or recommendation in the comments section below. Alternatively, you can contact me directly.
Major Releases:
v2.1.0 – March 22, 2011 – indicator bean, label maker
v2.0.0 – March 8, 2011 – singleton access to JForex objects, order ticket building, global currency conversion, global printer utility.
v1.0 – November 24, 2010 – JFUtil 1.0
Maximal frustration in printing and parsing milliseconds in R
I’ve just spent an absurd amount of time figuring out how to parse millisecond times into R. (It’s standard practice to timestamp tick data with milliseconds timing in a flat data file.) Turns out that there are two problems that I faced. One being that there is a almost-hidden, footnote option in the strptime( ) function (for converting characters to POSIX) in which it describes using format = “%H:%M%OS” instead of “%H:%M:%S” to parse fractional seconds. However, the second, and what’s actually the one that’s wasted much my time, is the fact that R ignores milliseconds in printing by default!
For example, here’s an output for the POSIXct representation of the integer value 1286564400.
“2010-10-08 15:00:00 EDT”
So even though I figured how to represent millisecond times in R a few hours ago, I never knew I did it simply because R is not printing the output that I wanted on screen every time I tried!
After a couple hours of searching, trying, and frustrating, here’s the one-liner command that solved my problem.
> options(digits.secs=3)
which changes the options of the display and thus I can see the following output from the same input as above.
“2010-10-08 15:00:00.344 EDT”
I guess that’s why they say R has a steep learning curve! Yes, it is very powerful and flexible. But there are limited standards and the documentations are all over the place because it’s a mish mash of user-contributed packages!
read more

Recent Comments