Tutorial 1: writing a first strategy

Let's write a very basic strategy to introduce you the programming logic of Market Runner.

What will you learn?

We will locate our trading logic in the following call backs :

  • onOpen(), called once the open price of the bar has been observed
  • onClose(), called once a bar has been completed, ie, at the close event of the bar
  • onPositionOpened(), called once a position (long or short) has been set up
  • onPositionClosed() called once a position has been closed

We will also show how to define an external parameter.

What's the strategy logic?

This sample buys at the next day’s open price if the today’s close price is less than today’s open price by at least a given threshold, 1% in our case. The exit is done the same day, at the closing price.

What's the code?

The body of the strategy is defined as follows :

import static com.algodeal.marketData.instruments.Futures.*;
import com.algodeal.marketData.prices.*;
import com.algodeal.quantix.strategies.*;

@Instruments(futures={...})
public class Tutorial01 extends AbstractStrategy {
            ... Strategy behaviour ...
}

The threshold is our parameter. We define it as follows :

double openCloseThresholdPct = -0.01;

In the onOpen() call back, we check if we have to buy at the open of the market and send the corresponding order. The variable buyNextBar is a boolean which will change in the onClose() call back.

@Override
public void onOpen(OpenPrice openPrice) {
    if (buyNextBar) {
        buy(quantity, "Buy at open");
    }
}

In the onClose() call back, we calculate whether we have to enter into a position for the bar to come. If we have a position, we close it.

@Override
public void onClose(Bar bar) {
    if (hasPosition()) {
        closePosition("Sell at close");
    }
    buyNextBar = bar.getClose() / bar.getOpen() < openCloseThresholdPct + 1;
}

The call backs onPositionOpened() and onPositionClosed() are used to track the behavior of the strategy, we will see in the following tutorials that we can use them to set up specific exit conditions.

@Override
public void onPositionOpened() {
    System.out.println("PositionOpened on " + getInstrumentSymbol());
}

@Override
public void onPositionClosed() {
    System.out.println("PositionClosed on " + getInstrumentSymbol());
}

What does the result look like?

The strategy execution on the instrument "CAC 40" leads to the following result :

screenshot-Tutorial01-equityCurve.png

The Bar Chart Window is also useful to track your trades and display them on the bar chart :

screenshot-Tutorial01-barChart.png

What's next?

You might want to give a try to our second Tutorial