Anatomy of a JForex strategy, Part 2

We looked at four of the six methods in the IStrategy Interface in a previous post. The last two methods, onTick and onBar, is where your strategy connect with market data. Either one, or both, of these methods is where you put your trading algorithm in. Your strategy would then be able to process the market data as they arrive one tick/bar at a time. Recall that IStrategy Interface is the skeleton of your strategy. And that IContext object is the heart of your strategy. onTick/onBar is the head of your strategy, which contains your trading algorithm, which is the brain.

onTick

Here's the method definition of onTick.

onTick(Instrument instrument, ITick tick) throws JFException { }

Important:onTick is called for each and every instrument that your JForex platform is subscribed to (the instrument list in your workspace box). Let me say that again, onTick is called for each and every instrument that your JForex platform is subscribed to. The standard practice is to filter out ticks for instruments that you don't want with a simple IF-return statement. if (instrument != myInstrument) return; Actual tick data is passed to your strategy using the ITick object from the onTick method's parameter. Take a look at the ITick javadoc entry to see what it offers.

onBar

public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException { }

onBar works in a similar manner to onTick. In which onBar is called for each and every subsribed instrument and period known to JForex. Similarly, you have to filter out all the unwanted instruments and periods or else there will be expected results from your strategy. Another point to note is that onBar provides both a IBar askBar and IBar bidBar, representing the ask and bid bars. Question: What happens when two or more periods overlap as in 13:45? 1, 5, and 15-minutes bars are all arriving at the same time (not to mention the periods in seconds too). Answer: According to Dukascopy Support in the forum, "They come in a strict order, for example (1min 1min 1min 1min 1min 5min 1min 1min 1min 1min 1min 5min ..) They come in cycles, where smaller periods comes first."

JForex Support Forum

As you program your strategy with JForex, you will no doubt come up with questions of your own. The best place to ask is at the official JForex Support Forum. This is the last of the three essential JForex resources that I alluded to earlier. Even if you don't have any specific question, there are sample codes, coding discussion, and hundreds of existing Q&A from other JForex developers posted in the forum.

Summary

The discussion so far has been very high level. To show you what you can actually do in an IStrategy, we will dissect a working strategy in the next post. And what else better to examine than the most popular JForex strategy of them all -- MA_Play.java.

Anatomy of a JForex strategy, Part 1

Continuing on from Part 1 of this series: Getting started learning JForex programming, now we're ready to discuss the real thing. You build JForex strategies by using the IStrategy Interface (What is an Interface?). Basically, an Interface is a code skeleton with a set of predefined empty methods that you'll need to implement yourself. The six standard methods of the IStrategy Interface are:

  1. onStart
  2. onStop
  3. onMessage
  4. onAccount
  5. onTick
  6. onBar

Below is an empty IStrategy Interface implementation, also known as a JForex strategy. This code will compile fine in JForex and you can even run it. But it doesn't do anything at all because there is no code to run in each of the methods. Each of the six methods will just be called and exit immediately.

import com.dukascopy.api.\*; 
public class EmptyStrategy implements IStrategy { 
    public void onStart(IContext context) throws JFException { } 
    public void onTick(Instrument instrument, ITick tick) throws JFException { } 
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar)
        throws JFException { } 
    public void onMessage(IMessage message) throws JFException { } 
    public void onAccount(IAccount account) throws JFException { } 
    public void onStop() throws JFException { } 
}

Each of the method is triggered by a specific event. You can probably guess what they are from their name.

onStart (line 5)

This is the first method that is called when you run your strategy. It will run once and only once at the start of your strategy. Normally you do your initialization in here. The thing to note for onStart is in line 5 of the code. The method signature of onStart is

public void onStart(IContext context) throws JFException

The object in the parameter and given to you in this method is an IContext object. If IStrategy is the skeleton, then IContext is the heart of the strategy. Please take a look at this javadoc link to IContext to see what this object does. Javadoc?: Now is a good time to introduce the second of the three essential resources of a JForex programmer. The JForex Javadoc is the single most up-to-date API documentation explaining each and every object and methods of the JForex API. Think of it like a reference manual. Note that although it's comprehensive, most of the explanation is very sparse and possibly incomplete. IContext is a core JForex object to access many important components of the JForex system, such as the ordering engine, charts, console, indicators... You get the idea. It is important! You typically want to keep a local copy of it as this is the only time (in onStart) that this object will be passed to you in IStrategy.

onStop (line 26)

As the name suggest, this method is called once you send a stop command to your strategy. You do your program wrap-up such as logging and flushing data here. Not much out of the ordinary with this one.

onMessage (line 18)

Whereas we know when onStart and onStop will be called, onMessage is an asynchronous method in that you don't know exactly when it will run. This method is called when the Dukascopy server sends your strategy a message. For example, the server calls onMessage to let you know that your order has been filled. You receive and process the server message by accessing the IMessage object that is passed to you. Important:There is no guarantee that you will receive each and every message sent to your strategy from the server. Perhaps your strategy process is clogged. Or maybe your internet connection had a hiccup. If your strategy onMessage doesn't get called by the server for whatever reason, the server couldn't care less and won't be checking nor trying again. So don't do anything critical like managing your orders in onMessage!

onAccount (line 22)

This method is called whenever your account information update is received. The method provides access to the IAccount object, which you use to get your account information. Say if you have an open position, your account information changes on every tick because your equity is cash + unrealized profit/loss. In that case, onAccount is called every 5 seconds by the server at most to avoid flooding your strategy. More Important:The IAccount object is not connected live to your account in the server. It is merely a snapshot of your account. For example, if you keep a local copy of an IAccount object. Do some trading to change your balance. Then ask the same IAccount for account balance information, you will not see a change. As such, always update your local copy of IAccount within the onAccount method to keep your account information up-to-date for your strategy's use.

To be continued

onStart, onStop, onMessage, and onAccount methods are administrative methods for your strategy. The last two methods that we'll discuss, onTick and onBar, is where the magic happens in a strategy. I am saving the best for last in the next post.

Getting started learning JForex programming

The biggest problem I had when learning to program my own trading strategies in JForex is finding where to start learning. There were few JForex documentation available at the time and I had to teach myself through painstaking trial and error with the help of Dukascopy's technical support. Things have certainly changed for the better as a JForex community is starting to sprout and documentation for it is at least sufficient to get anyone started. This post is the first of a series of quick beginner's guide to learning JForex programming by putting all these resources in a tutorial.

JForex is a Java tool

JForex is actually not a programming language. It is an application programming interface (API) for use with the standard Java programming language. As such, the first step to learning to program in JForex is to learn Java. Luckily, Java is one of the most popular programming languages. So there're plenty of resources on and off the web to learn Java programming. Some examples of free online tutorials are:

  1. The Java Tutorials -- This is an official tutorial from the developer of Java themselves. Highly recommended.
  2. Beginners Java Tutorial -- More geared for the absolute beginners to programming.

If you prefer a book, I would recommend Head First Java, 2nd Edition. I brushed up on my Java from this book. Don't dwell on Java too much though as you only need to know the basics to get started with JForex. Just read a few chapters to understand the Java syntax and then move on. You can always refer back to them later.

Diving into JForex

The JForex Wiki is one of the three essential resources for JForex programmers. I will be referring to some specific pages of the Wiki in much of this series of posts. If you haven't done so already, signup for a DEMO account at Dukascopy. Then launch the JForex platform and follow the instructions on the Use in JForex wiki page to assemble your first JForex strategy!

Summary

So far so good? By this point, I hope you can understand basic Java source code and know how to start/open, compile, and run a JForex strategy. In the next post in this learning JForex series, we will study the anatomy of a JForex strategy.

JFUtil: 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

←   newer continue   →