All posts by steekoo

Testing steekoo Algo-Trading on Forex

As promised in How to Build a Simple Algo-Trading Strategy, today I will share with you my results in implementing the simple Trend Following Strategy on Forex. The trades and all the data are of today 26th of February 2016 (CET).  I have randomly chosen the EUR.USD as currency pair and I had run the algo on 1 minute bars the whole afternoon from around 14:00 CET till 19:30 CET in the evening. The result is promising. Despite a very simple strategy ever known, I made a profit. Actually most of the time, the strategy bought lower and sold higher. A global overview can be observed on the chart below:

EUR.USD Chart Trades

In fact the code entered in a falling market and the first position opened was short 1M EUR.USD. The invested amount is always the same. If there is a cross of the short SMA above the long SMA, the computer buys 1M EUR against USD, if the short SMA goes under the long SMA, the algorithm sells 1M EUR.USD. With Interactive Brokers the leverage one can use to invest in EUR is 33:1, so the amount needed to expose yourself against EUR 1M is only the equivalent of EUR 30’303.03 in USD. After only around 5 hours of algo-trading the strategy made USD 6’663.59 net of commissions, which divided by the invested amount USD 32’800 (the equivalent of EUR 30’303.03 more or less), is 20.32% which is not bad at all.

FX Algo Profit

Again, this is only an example and it can be the hazard, however it worked. I will keep testing and post my results regularly. Of course the example will be provided with a long-term back-test as well. Feel free to ask questions, share your experience and comment.

How to Build a Simple Algo-Trading Strategy

Algorithmic Trading (also called algo-trading) is the practice of implementing investment strategies automatically via an algorithm which executes pre-programmed trading instructions. It is true that most of the time these trading systems are heavily reliant on complex mathematical formulas and high-speed, computer programs. However, today I will show that this is not something impossible to build and even simple individual investors with limited hardware and software resources can build basic algo-trading strategies.

The strategy we will going to launch below will be the implementation of the simplest theory every trader knows, which is the (Moving Average) Trend Following Strategy. This strategy uses two moving averages (1 short moving average and 1 long moving average). Following this strategy the trader will buy when the short moving average is above the long moving average and will sell when the short moving average is below the long one. As stated above, this is a very simplistic algo-trading strategy and it is for analysis purposes only. Also, the method and procedures are simple personal inventions, so please do your personal back-tests and analysis before applying it on real money.

The requirements for this experiments are the following:

The first step is connecting your Matlab workstation to Interactive Brokers TWS. Please follow the instructions on this article should you need help linking Matlab to IB TWS. Once everything is configured properly, we are going to connect the two workspaces:

% Connect to IB Standalone through API (port: 7496)
ib = ibtws('',7496);

Next, we are going to define the IB Contract details. In this example we will apply the strategy for a USD stock, chosen randomly as usually*

% Define contract parameters
ibContract = ib.Handle.createContract;
ibContract.symbol = 'AAPL';
ibContract.secType = 'STK';
ibContract.exchange = 'SMART';
ibContract.currency = 'USD';

Then, we will request the intra-day historical data which we will going to use for the calculation of the SMAs (Simple Moving Averages)

% Create the Period
startdate = floor(now);
enddate = now;
barsize = '1 min';
% Retrieve Time Series
data = timeseries(ib,ibContract,startdate,enddate,barsize);

Now, in order to avoid that we create an order every minute the condition is met, we will going to create two short SMAs and two long SMAs and will submit an order to the market only if there is a cross:

% Calculate SMA9 & SMA21
SMA9 = mean(data(end-8:end,5));
SMA21 = mean(data(end-20:end,5));
% Calculate SMA9old & SMA21old
SMA9old = mean(data(end-9:end-1,5));
SMA21old = mean(data(end-21:end-1,5));

With these, we will tell the system to submit a BUY order, for example, if and only if SMA(9) > SMA(21) and SMAold(9) < SMAold(21) together.

The following will be to create the strategies as stated above:

% Initiate the strategy
straty = 'HOLD';
% Buy Strategy
if SMA9 > SMA21
    if SMA9old < SMA21old
    straty = 'BUY';
    price = ask;
    end
end
% Sell Strategy
if SMA9 < SMA21
    if SMA9old > SMA21old
    straty = 'SELL';
    price = bid;
    end
end

Finally, we have to create an order which will buy or sell, if any of the above conditions are met. Here, for simplicity, I am going to create and submit a Market order for a quantity of 1’000 shares:

ibLMTOrder = ib.Handle.createOrder;
ibLMTOrder.action = straty;
ibLMTOrder.totalQuantity = 1000;
ibLMTOrder.orderType = 'MKT';
ibLMTOrder.account = 'DUxxxxx0';
% Set a unique order identifier, and send the orders to IB
id = orderid(ib);
result = createOrder(ib, ibContract, ibLMTOrder, id);

So, one part is done. Now the question is how to make all the above run every minute, so we can do something else while our computer is trading for us. In order to perform this, my idea was to create a timer and have it run the code above every 1 minute. What we have to do now is to save the code above as Strategy_SMA.m e.g., then run the following code in the same folder:

a = timer;
set(a,'executionMode','fixedRate','period',60);
set(a,'TimerFcn','Strategy_SMA');
start(a);

Congratulations, you just created your first automated trading strategy. Feel free to comment should you have any questions or should you need me to expand anything more in details. Back-test and trading charts will come shortly in the next article.

* The tickers shown in examples are random, for exercising purposes only and do not represent any advise to invest in them nor any other kind of advertising.

How to display IB TWS contract details in Matlab

The Trading Toolbox function to display Interactive Brokers TWS contract details in Matlab is called contractdetails and has the following syntax:

[d,reqid] = contractdetails(ib,ibContract)

Again, please be aware that for this function Trading Toolbox 2.2 or above is requested. Below I will show you an example where I will retrieve the contract details for a random US stock*.

After having linked Matlab to IB TWS, we must connect the two stations between them by running the following command:

ib = ibtws('',7496);

Once connected, the next step is to define the IB contract which details we would like to request. We will build the contract by using the minimum required information which is the contract symbol, security type, currency and routing destination.

ibContract = ib.Handle.createContract;
ibContract.symbol = 'AAPL';
ibContract.secType = 'STK';
ibContract.exchange = 'SMART';
ibContract.currency = 'USD';

Then run the script below which will export the contract details (d) and the request identifier reqid for the ibContract using the Interactive Brokers TWS (ib) connection.

[d,reqid] = contractdetails(ib,ibContract)

The output in your Matlab work-space will be then the following:

Contract Details IBTWS - Matlab CMD Window

Contract Details IBTWS - Matlab struct
* The tickers shown in examples are random, for exercising purposes only and do not represent any advise to invest in them nor any other kind of advertising.

Interactive Brokers TWS Generic Tick Types

As a part of the market data request Interactive Brokers provide several types of market data ticks. The generic market data tick types are:

Integer ID Value Tick Type Resulting Tick Value
100 Option Volume (currently for stocks) 29, 30
101 Option Open Interest (currently for stocks) 27, 28
104 Historical Volatility (currently for stocks) 23
106 Option Implied Volatility (currently for stocks) 24
162 Index Future Premium 31
165 Miscellaneous Stats 15, 16, 17, 18, 19, 20, 21
221 Mark Price (used in TWS P&L computations) 37
225 Auction values (volume, price and imbalance) 34, 35, 36
233 RTVolume – contains the last trade price, last trade size, last trade time, total volume, VWAP, and single trade flag. 48
236 Shortable 46
256 Inventory
258 Fundamental Ratios 47
292 Receive top news for underlying contracts from TWS for news feeds to which you have subscribed (in Account Management). Use secType = NEWS in the Contract object. See Requesting News for examples.

You will receive at least one news tick regardless of its timeliness (it could be new or it could be weeks old). Some news providers limit us to maximum news retention of 30 days, so those limitations may affect which news you see. Otherwise you will receive a maximum of five of the most recent news items in the last 24 hours, and you will receive additional news items as they come in.

62
411 Realtime Historical Volatility 58
456 IBDividends 59

Click here for the full Interactive Brokers API Reference Guide.

How to request live data from IB TWS to Matlab

It is possible to request and display real-time data to Matlab work-space from the Interactive Brokers TWS. The function retrieving live data from the IB TWS to Matlab is called realtime and has the following syntax:

tickerid = realtime(ib, ibContract, f, eventhandler) 

Please note that for this function Trading Toolbox 2.2 or above is requested. Below I will show you an example where I will retrieve real-time data for three random US stocks.

So, after having linked Matlab to IB TWS, we must connect the two stations between them by running the following command:

ib = ibtws('',7496);

Next, we have to create a figure where the real-time quotes will be displayed live.

f = findobj('Tag','IBStreamingDataWorkflow');
if isempty(f)
f = figure('Tag','IBStreamingDataWorkflow','MenuBar','none',...
'NumberTitle','off')
pos = f.Position;
f.Position = [pos(1) pos(2) pos(3)+37 109];
colnames = {'Trade','Size','Bid','BidSize','Ask','AskSize',...
'Total Volume'};
rownames = {'AAPL','TSLA','XOM'};
data = cell(3,6);
uitable(f,'Data',data,'RowName',rownames,'ColumnName',colnames,...
'Position',[10 30 582 76],'Tag','SecurityDataTable')
uicontrol('Style','text','Position',[10 5 497 20],'Tag','IBMessage')
uicontrol('Style','pushbutton','String','Close',...
'Callback',...
'evalin(''base'',''close(ib);close(findobj(''''Tag'''',''''IBStreamingDataWorkflow''''));'')',...
'Position',[512 5 80 20])
end

The following step is creating the IB contracts for which we are going to request the live quotes. In this example we will show live quotes for three contracts chosen randomly, here AAPL*, TSLA* and XOM*.

% Define the details for the 1st contract
ibContract1 = ib.Handle.createContract;
ibContract1.symbol = 'AAPL';
ibContract1.secType = 'STK';
ibContract1.exchange = 'SMART';
ibContract1.currency = 'USD';
% Create the 2nd IB contract
ibContract2 = ib.Handle.createContract;
ibContract2.symbol = 'TSLA';
ibContract2.secType = 'STK';
ibContract2.exchange = 'SMART';
ibContract2.currency = 'USD';
% Set the 3d IB contract details
ibContract3 = ib.Handle.createContract;
ibContract3.symbol = 'XOM';
ibContract3.secType = 'STK';
ibContract3.exchange = 'SMART';
ibContract3.currency = 'USD';

After that, create the contracts matrix by running the code:

contracts = {ibContract1;ibContract2;ibContract3};

In our example we will set f = 100, in order to retrieve the Option Volume tick type. For further details about other generic market data tick types, see Interactive Brokers API Reference Guide.

f = '100';

Then we can use the Matlab IBTWS sample ibExampleRealtimeEventHandler or create your own event handler function and run the real-time data request as below:

tickerID = realtime(ib,contracts,f,...
@(varargin)ibExampleRealtimeEventHandler(varargin{:}));

This will create your figure and display the requested live data as following:

Matlab Live Data from IB TWS

* The tickers shown in examples are random, for exercising purposes only and do not represent any advise to invest in them nor any other kind of advertising.