Category Archives: Trading

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

How to submit an order to IB TWS via Matlab

Today I will show you how to submit an order to Interactive Brokers TWS directly from your Matlab work-space. In order to be able to do this you have to link Matlab to IB TWS first. Then, type in the following code to connect your Matlab station to IB TWS.

ib = ibtws('',7496);

Once connected, the next step is defining the IB contract that we would like to trade. 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';

The next step is to configure the parameters for the orders we prepare for submission:

ibLMTOrder = ib.Handle.createOrder;
ibLMTOrder.action = 'BUY';
ibLMTOrder.totalQuantity = 100;
ibLMTOrder.orderType = 'LMT';
ibLMTOrder.lmtPrice = 113;
ibLMTOrder.account = 'DUxxxxx6';

In this case we will submit a buy limit order @ 113 USD for 100 Apple* shares on account number DUxxxxx6. After the order is configured, we can also set a unique order identifier, and send the orders to Interactive Brokers.

id = orderid(ib);
result = createOrder(ib, ibContract, ibLMTOrder, id)

The Matlab Trading Toolbox function that submits the order is called createOrder. The function creates an IB Trader Workstation ibLMTOrder over the IB Trader Workstation connection ib for the ibContract with a unique order identifier id and returns the order result containing data about the completed order.

result = 
             STATUS: 'PreSubmitted'
             FILLED: 0
          REMAINING: 100
     AVG_FILL_PRICE: 0
            PERM_ID: '326506298'
          PARENT_ID: 0
    LAST_FILL_PRICE: 0
          CLIENT_ID: 0
           WHY_HELD: ''

Your Matlab work-space will show the following.

Matlab CreateOrder IBTWS

The code will generate and transmit the order from your trader workstation similar to the screenshot below.

Matlab Interactive Brokers IBTWS

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

Download contract data from IB TWS to Matlab

After having successfully linked Matlab to Interactive Brokers TWS, you can now explore your new Matlab-IB TWS machine. You may start with the simplest commands which will step by step lead you to your own automated algorithm. A first simple command to explore is “getdata” which has the syntax:

data = getdata(ib,ibContract)

and requests the data of a specific contract from your IB TWS.

The “getdata” command creates a matrix containing the current data of the requested financial instrument. Below you can find an example of retrieving the current 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';
ibContract.exchange = 'SMART';
ibContract.currency = 'USD';
% Request the data
data = getdata(ib,ibContract)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

The output will have the following structure:

data = 
LAST_PRICE: 119.05
LAST_SIZE: 1
VOLUME: 53.4M
BID_PRICE: 119.05
BID_SIZE: 19
ASK_PRICE: 119.06
ASK_SIZE: 9

* 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 link Matlab to Interactive Brokers TWS

Interactive Brokers TWS is becoming more and more popular thanks to its unique, fast and inexpensive technology. Because of this, there is an increasing interest to combine the classic Interactive Brokers TWS Trading Tool with other software that would provide more flexibility and advantages in terms of personalisation, automatisation, strategy building and so on. Today, I decided to share with you a correct and working procedure of linking Matlab to IB TWS.

Requirements:

Step 1: Download and Install Matlab 2013b or later (including Trading Toolbox 2.0 or later)

Step 2: Download and Install Java Runtime Environment (required to run IB TWS)

Step 3: Download and Install Interactive Brokers TWS Standalone 954 or later

Step 4: Download and Install Interactive Brokers TWS API Install 970.06

Step 5: Configure IB TWS

  • From TWS Classic go on: Edit – Global Configuration – API
  • From TWS Mosaic go on: File – Global Configuration – API

In “API – Settings” check:

  1. Enable ActiveX and Socket Clients
  2. Include FX positions when sending portfolio
  3. Create API message log file

Make sure the “Socket Port” is set to 7496

Set “Logging level” to “Detail”

Uncheck “Allow connections from local host only”, hit on “Create” and “Enter trusted API address” 127.0.0.1

Configure TWS API Settings

In “API – Precautions” check all the boxes.

Configure TWS API Precautions

Once all this is set, re-launch both, Matlab and TWS, and simply type in the Matlab Command Window the following command:

ib = ibtws('',7496)

The return should be:

Matlab IBTWS

Meaning that Matlab is successfully connected to your TWS local session.

The connection can be closed by using the IB Trader Workstation connection object ib:

close(ib)

Note: Some of you, when trying to connect, may encounter the following error:

>> ib = ibtws('',7496); Error using feval Server Creation Failed: The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more details.
Error in actxserver (line 86) h=feval(['COM.' convertedProgID], 'server', machinename, interface);
Error in ibtws (line 38)

This can be solved by installing the 32 bit Version of “Microsoft Visual C++ 2005 Redistributable”.