3 Using IBMatlab
3.1 General usage
IB-Matlab uses the IB client (either TWS or IB Gateway) to connect to the IB server. To use IB-Matlab, either TWS or Gateway must be active. If an active IB client is not detected, IB-Matlab will automatically attempt to start TWS and to connect to it, but this may fail for some TWS installations. You can always start an IB client manually, before running IB-Matlab. If IB connection is unsuccessful, IB-Matlab will error.
IB-Matlab’s Matlab wrapper function is called IBMatlab. This function is contained in the IBMatlab.p file. The IBMatlab.m file includes basic syntax help, used as follows:
>> help IBMatlab
>> doc IBMatlab
The IBMatlab function accepts a variable number of parameters, and returns data in a query-specific format, usually a Matlab struct or a numeric ID.15
IBMatlab can accept input parameters in several formats:
As name-value pairs – for example:
>> data = IBMatlab('action','account', 'AccountName','DU12345');
You can omit the 'action' keyword if you specify the action as the first input parameter in IB-Matlab v2.20 or newer (12/2022):
>> data = IBMatlab('account', 'AccountName','DU12345');
As a struct (or struct array) of parameters – for example:
>> params = []; % initialize
>> params.Action = 'account';
>> params.AccountName = 'DU12345';
>> data = IBMatlab(params);
As a table of parameters, with the parameter names as the table field names
As field-separated rows in an input file (CSV or XLS) – for example:
>> data = IBMatlab('C:\MyData\inputFile.xlsx');
Where row #1 of the file contains the parameter names, and rows 2+ contain the parameter values, one row per IBMatlab command. For example:
In CSV files you can add comments following the % character, for example:
Action,Symbol,SecType,Quantity,Exchange,Currency,Type,LimitPrice
Buy,IBM,STK,10,SMART,USD,MKT % A Christmas gift for dad
These input formats are equivalent; use whichever format that you are comfortable with.
Note: if you choose to use the struct format and then to reuse this struct for different IBMatlab commands (by altering a few of the parameters), then the entire set of struct parameters is used, possibly including some leftover parameters from previous IBMatlab commands, that may lead to unexpected results. For example:
% 1st IBMatlab command – buy 10 GOOG at limit $600.00
>> params = []; % initialize
>> params.Action = 'buy';
>> params.Symbol = 'GOOG';
>> params.Quantity = 10;
>> params.Type = 'LMT';
>> params.LimitPrice = 600.00;
>> orderId1 = IBMatlab(params);
% 2nd IBMatlab command – sell 10 GOOG at limit $625.00
>> params.Action = 'sell'; % reuse the existing params struct
>> params.LimitPrice = 625.00;
>> orderId1 = IBMatlab(params);
The second IBMatlab command will sell all 10 units of GOOG, even if the user meant to sell just a single unit. This is because the params struct still contains the Quantity=10 field from the first IBMatlab command. To avoid unexpected results, I therefore advise to re-initialize the params struct (=[]) for each IBMatlab command.
IBMatlab is quite tolerant of user input: parameter names are case-insensitive (but most IB values are case-sensitive), parameter order does not matter, non-numeric parameters can be specified as either char arrays ('abc') or strings ("abc"), and some of these can be shortened. For example, the following are all equivalent:
>> data = IBMatlab('action','account', 'AccountName','DU12345');
>> data = IBMatlab('action','account_data', 'accountname','DU12345');
>> data = IBMatlab('Action','Account_Data', "AccountName","DU12345");
>> data = IBMatlab('ACTION','ACCOUNT_DATA', 'AccountName',"DU12345");
>> data = IBMatlab('AccountName','DU12345', 'action','account_data');
>> data = IBMatlab('Account', 'AccountName','DU12345'); %v2.20 or newer
The full list of acceptable input parameters is listed in the sections below, grouped by usage classification (action). Each action has a specific set of acceptable parameters.
When using IBMatlab, there is no need to worry about connecting/disconnecting from IB: IBMatlab automatically connects to whichever TWS/Gateway is currently active. If you logged-in to TWS/Gateway using a paper-trading username then IBMatlab will work on the simulated account; if you login to a live account then IBMatlab will connect to that account. The TWS account type is transparent to IBMatlab: the only way to control whether IBMatlab will use simulated or live trading is to login to TWS using the appropriate username. Refer to §13 below for additional details.
When using IBMatlab you may receive various error messages. See §14 below for details about handling these messages. For example, IB limits the rate of messages sent to the IB server to 50/sec. If you exceed this rate, you’ll receive an error message from IB:
[API.msg2] Max rate of messages per second has been exceeded: max=50 rec=55
3.2 Contract properties
The following contract (security/ticker) properties can be specified in IBMatlab:16
Parameter | Data type | Default | Description |
Symbol | string | (none) | The symbol of the underlying asset17 |
LocalSymbol | string | '' | The local exchange symbol of the underlying asset. When left empty, IB sometimes tries to infer it from Symbol and the other properties. |
SecType | string | 'STK' | 'STK' – stock equity and ETF (default) 'OPT' – option 'FUT' – future (CONTFUT=continuous) 'IND' – index 'FOP' – option on future 'CASH' – Forex 'WAR' – warrant 'BOND' – bond 'FUND' – mutual fund 'IOPT' – structured (Dutch Warrant) 'SSF' – single-stock future 'CMDTY' – commodity 'BAG' – combo-legs (see §9.5 below) |
Exchange | string | 'SMART' | The exchange that should process the request.18 SMART uses IB’s SmartRouting to optimize order execution time and cost.19 To specify the primary exchange, use the : or / separator,20 for example: 'SMART:ISLAND' or 'SMART/TSE'. |
Currency | string | 'USD' | The trading currency. This field can often be specified to avoid ambiguities (see §14.2). |
Expiry | string | '' | 'YYYYMM' or 'YYYYMMDD' format |
Multiplier | number | [] | The contract multiplier (for options) |
Strike | number | 0.0 | The strike price (for options) |
Right or Side | string | '' | One of: ‘P’, ‘PUT’, ‘C’, ‘CALL’ (for options) |
IncludeExpired | integer or logical flag | 0=false | If true, expired options/futures are considered, otherwise they are not. |
ConId | integer | [] | The contract ID (if known) |
SecId | string | '' | The security ID e.g. 'US0378331005' (Apple ISIN). Must be specified with SecIdType, or in unified form e.g. 'ISIN:US0378331005', 'RIC:AAPL.O' |
SecIdType | string | '' | The SecId type: 'ISIN', 'CUSIP' or 'RIC' 21 |
3.3 Returned data format
Many queries in IBMatlab return data in the form of a struct-array (a Matlab array of structs), for example (see §12.1):
>> data = IBMatlab('action','executions')
data =
1x12 struct array with fields:
orderId
execId
time
exchange
side
shares
symbol
price
permId
liquidation
cumQty
avgPrice
contract
execution
commission
For various purposes (readability, maintainability, performance, usability), users may wish to modify this data structure. You can easily convert the data using Matlab’s builtin functions struct2cell() (which converts the struct-array into a cell-array), or struct2table() (which converts the struct-array into a Matlab table object):
>> struct2cell(data')' %transpose data to convert 1xN struct arrayàNx1
12×15 cell array
{1552635901} {'0000e1a7…'} {'20241121 02:50:55'} {'CBOT'} {'BOT'} …
{1552635928} {'0000e1a7…'} {'20241121 02:51:07'} {'CFE'} {'SLD'} …
{1552635939} {'0000e1a7…'} {'20241121 02:51:12'} {'CBOT'} {'BOT'} …
{1552635945} {'0000e1a7…'} {'20241121 02:51:15'} {'CME'} {'SLD'} …
...
>> struct2table(data)
12×15 table
orderId execId time exchange side …
__________ _____________ _____________________ ________ _______ …
1552635901 {'0000e1a7…'} {'20241121 02:50:55'} {'CBOT'} {'BOT'} …
1552635928 {'0000e1a7…'} {'20241121 02:51:07'} {'CFE'} {'SLD'} …
1552635939 {'0000e1a7…'} {'20241121 02:51:12'} {'CBOT'} {'BOT'} …
1552635945 {'0000e1a7…'} {'20241121 02:51:15'} {'CME'} {'SLD'} …
...
Note: empty/non-struct data can’t be converted with struct2table() or struct2cell():
>> data = IBMatlab(…)
data =
[]
>> struct2cell(data)
Undefined function 'struct2cell' for input arguments of type 'double'.
>> struct2table(data)
Error using struct2table (line 26)
S must be a scalar structure, or a structure array with one column or one row.
15 A Java connector object is also returned, which can be used for low-level access to IB’s API. See §15 below for details.
16 This list closely mirrors IB’s Java API list of contract details. Some of the Java API properties mentioned in the online list (https://interactivebrokers.com/php/whiteLabel/Interoperability/Socket_Client_Java/java_properties.htm) are not supported by IBMatlab, but many of them can still be accessed via IB-Matlab’s Java connector object, as described in §15 below.
17 See https://groups.io/g/twsapi/topic/69675667 for a discussion of the difference between Symbol and LocalSymbol.
18 IB’s API uses ISLAND for NASDAQ requests; you can specify either NASDAQ or ISLAND in your IB-Matlab call (IB-Matlab versions 1.80+; earlier versions should specify ISLAND). Other exchange names are the same in TWS and IB-Matlab.
19 http://interactivebrokers.com/en/p.php?f=smartRouting. Note that IB does not support the default 'SMART' exchange for all combinations of SecType, Currency etc. In such cases, setting a specific Exchange name may avoid errors and empty results.
20 This is supported by TWS 942 or newer: http://interactivebrokers.com/en/?f=/en/software/apiReleaseNotes/api970.php. This syntax is sometimes not accepted by IB. As an alternative, use the m_primaryExchange field as explained in §9.6 below.
21 See https://interactivebrokers.com/en/software/apiReleaseNotes/api963.php. Note: SEDOL, FIGI are not supported. Also see §5.5.