All posts by steekoo

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'; = '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
            PERM_ID: '326506298'
          PARENT_ID: 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.

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.

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'; = 'SMART';
ibContract.currency = 'USD';
% Request the data
data = getdata(ib,ibContract)

The output will have the following structure:

data = 
LAST_PRICE: 119.05
BID_PRICE: 119.05
ASK_PRICE: 119.06

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


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”

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:


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

A three steps trading strategy

Today I will share with you a basic three steps trading strategy. The following will require a minimum technical analysis basis. I will try to explain everything in detail, but if I miss something, feel free to comment. The credits for this strategy go to my colleague and friend Yann. The strategy may be applied to any type of contract. Here we will use for an investment decision in the Apple’s stock price. So let’s start!

1. The first thing to look at, is the trend. The trend is the general direction of an instrument, so let’s have a look. An uptrend for all of them: monthly, weekly and daily charts is a concrete sign to go long.

Monthly Candles Chart

Apple Monthly Chandles

Weekly Candles Chart

Apple Weekly Chandles

Daily Candles Chart

Apple Daily Chandles

As from the charts above all of them confirm the uptrend, however I find the daily one very week, so in this case I would leave Apple aside and focus on a different contract. Here, for analysis purposes I will consider the uptrend confirmed and continue with the next step.

2. The next study to check is the RSI = Relative Strength Index. We will draw the RSI (14) on a daily candles chart and look for a divergence.

Apple Daily RSI

As from the chart above there is a clear evidence of negative divergence, because the  indicator (RSI) fails to confirm the new maximum made by the stock price. In fact the stock registers a decrease in value confirming the negative divergence alert. So, at this step I expect the value of the stock to decrease and wouldn’t take a long position in Apple anymore. Step 2 failed to confirm the buy signal.

3. Despite that, I will continue with the next step and draw the Short Term and Long Term Exponential Moving Averages: EMA (9) and EMA (21).

Apple Daily EMAs

We will use the EMAs here to identify current trends and trends reversals. We saw in the chart before that a negative divergence identified with the RSI occurred and this was confirmed by a fall in shares’ prices. However as the short EMA (9) crosses over the long EMA (21) this is a signal of a new beginning uptrend. Here again the message of the chart is to buy. So, if the short EMA is above the long EMA we believe in being in an uptrend and expect the prices to grow more. If the short EMA is below the long EMA we believe that we are in a downtrend, so we expect the prices to fall more. The cross of the two EMAs signals a trend reversal. So, what to do?

At this point, what to do with the information the charts provided you, depends only on your risk taste and investment horizon. For example if you would like to open and close the position within a 2-4 week period, you need a more recent and more detailed chart. So, let’s draw the hourly candle chart.

Apple Hourly Chandles

The hourly chart confirms the recent uptrend, there is no divergence and the short EMA (9) is clearly above the long EMA (21). So, from the point of view of the side to take, all the ways point to go long, but is this enough? Do we know when to buy and at what price?

The second most important principle in Technical Analysis is the timing. It doesn’t serve at anything to know that we have to buy if we do not know the right entering price. For doing this one of the most used tool are the Fibonacci Retracements.

Apple Fibonacci Retracement

After having drawn the Fibonacci Retracements we can see that the stock is in a critical position now, being right under the 50% line which plays the role of resistance in this moment. At this point, my strategy would be to wait until the 50% line gets broken and if this is the case to buy right over the 50% line with a stop loss at the 61.8% level, a first take profit at the 38.2% level and a second one at the 23.6% level.

Note: none of the above constitutes an advise to invest in the mentioned instruments. The contracts are chosen randomly and the strategy is not a guarantee of success.