Category Archives: Coding

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'; = '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;
% Sell Strategy
if SMA9 < SMA21
    if SMA9old > SMA21old
    straty = 'SELL';
    price = bid;

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;

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.

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.

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',...
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);
'Position',[10 30 582 76],'Tag','SecurityDataTable')
uicontrol('Style','text','Position',[10 5 497 20],'Tag','IBMessage')
'Position',[512 5 80 20])

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'; = 'SMART';
ibContract1.currency = 'USD';
% Create the 2nd IB contract
ibContract2 = ib.Handle.createContract;
ibContract2.symbol = 'TSLA';
ibContract2.secType = 'STK'; = 'SMART';
ibContract2.currency = 'USD';
% Set the 3d IB contract details
ibContract3 = ib.Handle.createContract;
ibContract3.symbol = 'XOM';
ibContract3.secType = 'STK'; = '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,...

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.

Retrieve historical data from IB TWS to Matlab

You can retrieve the historical data for a specific contract from IB TWS to Matlab by using the ibtws “history” command. This command has the following syntax:

Hist_Data = history(ib, ibContract, Start_Date, End_Date)

and requests the historical data  for the defined ibContract from Start_Date to End_Date.

After having connected Matlab to Interactive Brokers TWS you can test the following example on how to retrieve historical data for a specific IB contract*

% Connect Matlab to IB TWS
ib = ibtws('',7496);
% Define the IB Contract
ibContract = ib.Handle.createContract;
ibContract.symbol = 'AAPL';
ibContract.secType = 'STK'; = 'SMART';
ibContract.currency = 'USD';
% Set the time horizon (in this example, last 30 business days)
Start_Date = today-30;
End_Date   = today;
% Get the historical data
Hist_Data = history(ib,ibContract,Start_Date,End_Date)

The output will have the following structure:

History Matlab IBTWS

Where each row shows the historical data for 1 day and the columns represent the following:

  • Numeric representation of a date
  • Open price
  • High price
  • Low price
  • Close price
  • Volume
  • Bar count
  • Weighted average price
  • Flag indicating if there are gaps in the bar

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