All posts by steekoo

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.

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.

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';
ibContract.exchange = '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';
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”.