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.

Laisser un commentaire