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.

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

import java.util.\*; import com.dukascopy.api.\*;
import com.quantisan.JFUtil.\*; @Library("JFQuantisan.jar") // place
this file in your ../JForex/Strategy/files folder public class
jfutilDemo implements IStrategy { private int counter = new
Random().nextInt(100); // notice the lack of fields to manage JForex
objects @Override public void onStart(IContext context) throws
JFException { // \*\* Essential steps \*\* // must initialize objects
once and for all JForexContext.setContext(context);
JForexAccount.setAccount(context.getAccount()); Set\<Instrument\> set =
new HashSet\<Instrument\>(context.getSubscribedInstruments()); set =
context.getSubscribedInstruments(); // get list of subscribed
instruments // subscribe to transitional instruments for currency
conversion calculations Pairer.subscribeTransitionalInstruments(set); //
\*\* End of essential steps \*\* Printer.println("-- Quantisan.com
JFUtil v2.0 alpha: Usage demo --"); Printer.println(""); } @Override
public void onBar(Instrument instrument, Period period, IBar askBar,
IBar bidBar) throws JFException { if (period != Period.TEN\_SECS)
return; // only run every 10 sec. // \*\*\* 1. access IContext and
IAccount from anywhere \*\*\* Printer.println("Account equity = " +
JForexAccount.getEquity()); // get an EMA indicator value double ema =
JForexContext.getIndicators().ema(instrument, Period.TEN\_SECS,
OfferSide.BID, IIndicators.AppliedPrice.MEDIAN\_PRICE, 14, 1);
Printer.println(instrument.toString() + " EMA = " + ema); // printing
the EMA value // \*\*\* 2. Profit/loss calculation to account currency
before placing your order \*\*\* // Demonstrating currency conversion
double risk = 100 \* Pairer.convertPipToAccountCurrency(instrument);
String symbol = JForexAccount.getAccountCurrency().getSymbol();
Printer.println(symbol + risk + " risked in for 1,000 units and 100 pips
move in " + instrument.toString()); // \*\* 3. Simplify order parameters
with order ticket builder \*\*\* // Demonstrating trade ordering String
label = instrument.toString().substring(0,2) + ++counter; OrderTicket
mktBuyTicket = new OrderTicket // order ticket .Builder(label, //
setting required ticket info instrument, IEngine.OrderCommand.BUY, 0.1)
.build(); // build ticket Orderer.placeOrder(mktBuyTicket); // placing
order // market buy order with a 100 pips stop and 100 pips target
double stopPrice = JForexContext.getPrice(instrument) - (100 \*
instrument.getPipValue()); double targetPrice =
JForexContext.getPrice(instrument) + (100 \* instrument.getPipValue());
label = instrument.toString().substring(0,2) + ++counter; OrderTicket
buySpTicket = new OrderTicket .Builder(label, instrument,
IEngine.OrderCommand.BUY, 0.1) .setStopLossPrice(stopPrice) // set stop
price to ticket .setTakeProfitPrice(targetPrice) // set target .build();
// \*\* 4. Single method to placing orders for all order types and
parameters \*\*\* Orderer.placeOrder(buySpTicket); } @Override public
void onAccount(IAccount account) throws JFException {
JForexAccount.setAccount(account); // update IAccount to latest }
@Override public void onStop() throws JFException { for (IOrder order :
Orderer.getOrders()) // close all orders Orderer.close(order); } }

Dissecting 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.

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

continue   →