QUANT2IB Documentation

 

 MATLAB® Functions for automatic TWS popup handling

 

Note: If you start TWS using AutoStart, then the following popups are automatically handled.

             - Tip of the day ( this will be closed automatically )

             - Accept Incoming Connections (automatically clicks OK/YES)

 

Autostart - Automatically start the TWS

encryptIBPassword - encrypt IB Password

 

  Connectivity Functions

 

connect2TWS - Connect MATLAB® to Interactive Brokers' TWS

disconnectFromTWS - This function is used to disconnect from TWS

isDataMaintained - logical indication if Data is maintained in

isIBTWSConnectionLost - logical indication if connection is lost

isIBTWSConnectionRestored - logical indication if IB TWS Connection is Restored

 

  Order Management Functions

 

cancelAllOpenOrders - cancels all open orders

cancelOrder - Cancels an order identified by the Order id OID

getAvgFillPrice - This function is used to Request Average Fill Price if the order is filled

getOpenOrdersList - returns the open orders list, must be called after reqOpenOrders

isOrderCancelled - logical indication if Order is Cancelled

isOrderFilled - This function is used to know whether the order is filled

placeOrder - This function is used to place Order for the financial instrument

requestAllOpenOrders - receive All Open Orders-both API and TWS

requestOpenOrders - request Open Orders placed through API

requestExecutions - request Executions Information

getExecutionDetails - Get Execution Details

 

  Market Data Functions

 

getAskPrice - Request last ASK price

getAskSize - Request last ASK Size

getBidPrice - This function is used to get Bid Price of the financial instrument

getBidSize - Request bid size

getLastPrice - This function is used to get Last Price of the financial instrument

getLastSize - This function is used to get Last Size of the financial instrument

getQuoteData - Request quote data

reqHistData - Request historical market data.

reqMktData - Request market data.

 

  Account Management Functions

 

getAccountAttributeValue - getAccountAttributeValue Request the value of an account key

getAccountCashBalance - getAccountCashBalance Request account cash balance for a given currency

getAccountKeys - returns the available keys for the given account name

getAccountNames - returns the accounts names list

getFullAccountInformation - Get Full account information

requestAccountUpdates - Start receiving Account Updates

getPortfolioUpdates - Start receiving Portfolio Updates

 

  Error Message Functions

 

getErrorMessage - returns the error message associated with the ID

 
 

  Sample Usage of All Commands

 

Autostart

Connect to TWS API

Request Account Updates

Get the list of Account Names

Get Cash Balance

Get Account Keys

Get Account Attribute Value

Get Full Account Information -108 rows

Get Portfolio Updates

Request Market Data

Get LAST Price

Get BID price

Get ASK price

Get Last Size

Get Bid Size

Get Ask Size

Place order

Request All Open Orders

Cancel All Open Orders

Request Executions

Get Execution Details

cancel particular order

Request open Orders

Get Open Orders List

Check if the Order is FILLED

Check if the Order is Cancelled

Get Average Fill Price

Get Historical Market Data

Get Quote Data

Test if Connection is LOST

Test if data is maintained in case of connection loss

Test if Connection is restored

Disconnect From TWS

 
 
Trade with IB using MATLAB®®
 
 
 
  .........................................................
  What is the purpose of QUANT2IB software product?
.........................................................
  How do I write automated trading systems using QUANT2IB software product?
.........................................................
  Pricing and Support
  .........................................................
  How do I install the product?
   
 
 
   
   
   
   
   
   
   
   
   
 

Autostart - Automatically start the TWS

 help Autostart
 AUTOSTART Automatically start the TWS
 Run this script file to start the TWS and login Automatically
 Please wait for 25 seconds at the least for the TWS application
 To load. 
 
   
 

encryptIBPassword - encrypt IB Password

help encryptIBPassword
  ENCRYPTIBPASSWORD encrypt IB Password
  password is the IB password
  This can be used to encrypt the password to be later used in
  the initialisation files for autostarting.
  Please See Autostart for more information
 
   
 

connect2TWS - Connect MATLAB® to Interactive Brokers' TWS

help connect2TWS
 Connect MATLAB® to Interactive Brokers' TWS
 Optional Inputs:
           host = host id -default-'127.0.0.1'
           port = port number-default-7496
           clientid = any client id-default-0
  Output : Connected = 1 if connected, otherwise, it is NOT connected
 Copyright Exchange Systems Inc
 
 

disconnectFromTWS - This function is used to disconnect from TWS

help disconnectFromTWS
 This function is used to disconnect from TWS
 Inputs = none
 Outputs = connection closed called in the command window
 EXAMPLES
 disconnectFromTWS
 SEE ALSO
 isIBTWSConnectionLost
 Copyright Exchange Systems Inc
 
 
 

isDataMaintained - logical indication if Data is maintained in

case of connection loss

help isDataMaintained
 ISDATAMAINTAINED logical indication if Data is maintained in case of
 connection loss
 isDataMaintained returns 1 if data is maintained, else 0 if data is lost
 
 
 

isIBTWSConnectionLost - logical indication if connection is lost

help isIBTWSConnectionLost
 ISIBTWSCONNECTIONLOST logical indication if connection is lost
 isIBTWSConnectionLost returns 1 if connection is lost, else 0
 
 
 

isIBTWSConnectionRestored - logical indication if IB TWS Connection is Restored

help isIBTWSConnectionRestored
  ISIBTWSCONNECTIONRESTORED logical indication if IB TWS Connection is Restored
  returns 1 if connection is restored, else 0
 
   
 

cancelAllOpenOrders - cancels all open orders

 help cancelAllOpenOrders
 cancels all open orders
 Must be called after reqOpenOrders or reqAllOpenOrders
 Any OPEN orders would be cancelled.
 
 
 

cancelOrder - Cancels an order identified by the Order id OID

help cancelOrder
 Cancels an order identified by the Order id OID
 OID is the ID obtained when the order is placed
 EXAMPLES
 cancelOrder(1) Cancel order #1.
 See also placeOrder.
 
 
 

getAvgFillPrice - This function is used to Request Average Fill Price if the order is filled

help getAvgFillPrice
 This function is used to Request Average Fill Price if the order is filled
 Inputs = oid the id with which the order is placed (output of placeOrder)
 Outputs = average fill price
 usage: avgFillPrice = getAvgFillPrice ( oid )
 Copyright Exchange Systems Inc
 
 
 

getOpenOrdersList - returns the open orders list, must be called after reqOpenOrders

help getOpenOrdersList
  GETOPENORDERSLIST returns the open orders list, must be called after reqOpenOrders
  or reqAllOpenOrders
  returns the open orders placed the TWS API ONLY
  See Also:
  reqAllOpenOrders
 
   
 

isOrderCancelled - logical indication if Order is Cancelled

help isOrderCancelled
 ISORDERCANCELLED logical indication if Order is Cancelled
 isOrderCancelled(oid) oid is the id of the order
  returns 1 if the order is cancelled
 
 
 

isOrderFilled - This function is used to know whether the order is filled

help isOrderFilled
 This function is used to know whether the order is filled
 Inputs = oid the id with which the order is placed (output of placeOrder)
 Outputs = 1 if filled, 0 otherwise
 usage: filled = isOrderFilled( oid )
 Copyright Exchange Systems Inc
 
 
 

placeOrder - This function is used to place Order for the financial instrument

help placeOrder
 This function is used to place Order for the financial instrument
  id=placeOrder(symbol,secType,exchange,expiry,strike,right,currency,localSymbol,...
 	            action,totalQuantity,orderType,lmtPrice,auxPrice,tif,ocaGroup);
 Inputs:
    symbol  : Symbol of the financial instrument you intend to trade
    secType : STK OPT FUT IND FOP CASH BAG
    exchange: The order destination Exchange, such as Smart.
    Expiry  : The expiration date. Use the format YYYYMM.
    strike  : strike price in case of options
    right   : Specifies a Put or Call. Valid values are: P, PUT, C, CALL.
    currency: USD etc
    localSymbol : the local exchange symbol of the underlying asset.
    action : Action to be taken. Valid values are:BUY SELL
    totalQuantity : The order quantity.
    orderType : identifies the order type. Valid values are:
               MKT MKTCLS LMT LMTCLS PEGMKT STP STPLMT TRAIL REL VWAP
    lmtPrice : The LIMIT price, used for limit, stop-limit and relative orders.
             In all other cases specify zero. For relative orders with no
             limit price, also specify zero.
     auxPrice  : identifies the STOP price for stop-limit orders, and the
              offset amount for relative orders. In all other cases,
              specify zero.
    tif:Time in force: Values: 'DAY', 'GTC', 'IOC' GTD
    ocaGroup: ocagroup name to associate two orders so that one cancels the
            other
   Outputs: The id of the order placed
 Examples:
 Quantity = 1;
 Futures
 ESID4 = placeOrder('ES','FUT','GLOBEX','',0,'','USD','ESU6','BUY',
                     Quantity,'LMT',1277,0,'GTC','')
 YMID = placeOrder('YM','FUT','ECBOT','',0,'','USD','YM   JUN 06','SELL',
                                             Quantity,'MKT',0,0,'GTC','')
 Stocks
 EEMID =
 placeOrder('EEM','STK','SMART','',0,'','USD','EEM','BUY',100,'MKT',0,0,'GTC','')
 Copyright Exchange Systems Inc
 
 
 

requestAllOpenOrders - receive All Open Orders-both API and TWS

help requestAllOpenOrders
 REQUESTALLOPENORDERS receive All Open Orders-both API and TWS
  No inputs or outputs. This function sets the parameters neccessary to
  start receiving all open orders
  See Also: getOpenOrdersList
  Example:
  requestAllOpenOrders
  openorderslist  = getopenOrdersList
 
 
 

requestOpenOrders - request Open Orders placed through API

help requestOpenOrders
 %REQUESTOPENORDERS request Open Orders placed through API
  No inputs or outputs. This function sets the parameters neccessary to
  start receiving all open orders
  See Also: getOpenOrdersList
  Example:
  requestOpenOrders
  openorderslist  = getopenOrdersList
 
   
 

requestExecutions - Request Executions

help requestExecutions
 REQUESTEXECUTIONS Get Executions Information
  Inputs:
  clientid : clientid of the connection
  accountcode : account code. Note: this is only relevant for Financial Advisor (FA) accounts.
  timeAfter : execution reports received after the specified time.
  		The format for timeFilter is "yyyymmdd-hh:mm:ss"
  symbol : order symbol
  secType: order security type
  exchange:the order exchange
  side    : order action
  Output : None. This function sets the parameters neccessary to start
            receiving executions.

  Example:
  requestExecutions(1234,' ','20060819-10:30:00','MSFT','STK','ISLAND','BUY');
  requestExecutions(1234);
 
   
 

getExecutionDetails - Get Execution Details

help getExecutionDetails
 GETEXECUTIONDETAILS Get Execution Details
  Inputs:
  orderId : orderId of the order for which execution info is requested(optional)
  Output : This function returns an array of executiondetails structure. This structure
  has the following fields.
        nContracts: # of contracts in this execution
        AcctNumber: account number
            symbol: symbol
          Exchange: exchange
       longORshort: bot or sold
      positionSize: position size for this symbol
             price: price

  Notes: requestExecutions api must be called before calling this method

  Example:
  getExecutionDetails(ordId);
  getExecutionDetails();
 
 
 

getAskPrice - Request last ASK price

help getAskPrice
 GETASKPRICE Request last ASK price
 tid is the id used in reqMktData
 Example:
  askprice = getAskPrice(2) where 2 is the id used in the reqMktData call
  See Also: reqMktData
 
   
 

getAskSize - Request last ASK Size

help getAskSize
 GETASKSIZE Request last ASK Size
 tid is the id used in reqMktData
 Example:
  asksize = getAskSize(2) where 2 is the id used in the reqMktData call
  See Also: reqMktData
 
 
 

getBidPrice - This function is used to get Bid Price of the financial instrument

help getBidPrice
 This function is used to get Bid Price of the financial instrument
 Inputs = tid the id with which the market data is requested
 Outputs = Bid Price of the instrument
 usage: bidPrice = getBidPrice(tid) tid is the id used in reqMktData
 Copyright Exchange Systems Inc
 
   
 

getBidSize - Request bid size

help getBidSize
 GETBIDSIZE Request bid size
 tid is the id used in reqMktData
 Example:
  bidsize = getBidSize(2) where 2 is the id used in the reqMktData call
  See Also: reqMktData
 
 
 

getLastPrice - This function is used to get Last Price of the financial instrument

help getLastPrice
 This function is used to get Last Price of the financial instrument
 Inputs = tid the id with which the market data is requested
 Outputs = Last Price of the instrument
 usage: LastPrice = getLastPrice(tid)
 Copyright Exchange Systems Inc 2006
 
 
 

getLastSize - This function is used to get Last Size of the financial instrument

help getLastSize
 This function is used to get Last Size of the financial instrument
 Inputs = tid the id with which the market data is requested
 Outputs = Last Size of the instrument
 usage: LastSize = getLastSize(tid)
 Copyright Exchange Systems Inc
 
   
 

getQuoteData - Request quote data

help getQuoteData
  GETQUOTEDATA Request quote data
  tid is the id used in reqMktData
 
   
 

reqHistData - Request historical market data.

help reqHistData
 REQHISTDATA Request historical market data.
 reqHistData(tid,symbol,sectype,exch,expiry,strike,right,curr,lsymbol,
        endDateTime,durationStr,barSizeSetting,whatToShow,useRTH,formatDate,pauseSize)
 INPUTS: 16 Inputs in TOTAL--An Extra Input for Pause Size Setting

  id - the ticker id. Must be a unique value.
   When the market data returns, it will be identified by this tag.
   This is also used when canceling the market data.

   symbol  : Symbol of the financial instrument you intend to trade
   secType : STK OPT FUT IND FOP CASH BAG
   exchange: The order destination Exchange, such as Smart.
   Expiry  : The expiration date. Use the format YYYYMM.
   right   : Specifies a Put or Call. Valid values are: P, PUT, C, CALL.
   strike  : strike price in case of options
   currency: USD etc. specifies the currency. Ambiguities may require that
             this field be specified, for example, when SMART is the exchange and
             IBM is being requested (IBM can trade in GBP or USD).
             Given the existence of this kind of ambiguity, it is a good
             idea to always specify the currency.
   localSymbol : the local exchange symbol of the underlying asset.
   endDateTime - defines a query end date and time at any point during the
past 6 mos. Valid values include any date/time within the
past six months in the format: yyyymmdd HH:mm:ss zzz
                where "zzz" is the optional time zone.

 durationStr - set the query duration up to one week, using a time unit of
               seconds, days or weeks. Valid values include any integer
               followed by a space and then S(seconds), D (days) or W (week).
               If no unit is specified, seconds is used.

 barSizeSetting - specifies the size of the bars that will be returned
                  (within IB/TWS limits). Valid values include:
                         Bar Size
                         1 sec
                         5 secs
                         15 secs
                         30 secs
                         1 min.
                         2 mins
                         5 mins.
                         15 mins
                         30 mins
                         1 hour
                         1 day

 whatToShow - determines the nature of data being extracted. Valid values include:
  TRADES  MIDPOINT BID ASK BID/ASK

  useRTH - determines whether to return all data available during the requested
  time span, or only data that falls within regular trading hours.
 Valid values include:
 0 - all data is returned even where the market in question was outside of
its regular trading hours.
 1 - only data within the regular trading hours is returned, even if the
     requested time span falls partially or completely outside of the RTH.

 formatDate - determines the date format applied to returned bars. Valid values include:
 1 - dates applying to bars returned in the format:
 yyyymmdd{space}{space}hh:mm:dd
 2 - dates are returned as a long integer specifying the number of seconds since 1/1/1970 GMT.

 pauseSize - pause in seconds

 Output Parameters

 Output is a structure containing the following fields
  reqId - The ticker ID of the request to which this bar is responding.
 date - The date-time stamp of the start of the bar.
 The format is determined by the reqHistoricalData() formatDate parameter.
 open - bar opening price.
 high - high price during the time covered by the bar.
 low - low price during the time covered by the bar.
 close - bar closing price.
 volume - volume during the time covered by the bar.
 WAP - weighted average price during the time covered by the bar.
 hasGaps - whether or not there are gaps in the data.

Examples:
[YMdatahist ] = reqHistData(1007,'YM','FUT','ECBOT','',0.0,'','','YM   SEP 07',
				'20070629 17:15:00','6000 S','5 secs','TRADES',0,1,10);
[googdatahist ] =reqHistData(1007,'GOOG','STK','SMART','',0.0,'','','GOOG',
				'20070701 10:15:00','1 D','1 day','TRADES',0,1,10)

Updates
 Bar Size setting is now a string. Previously it was an integer.
 Added " Pause" setting in order to fully get the data from IB TWS;
 
   
 

reqMktData - Request market data.

help reqMktData
 REQMKTDATA Request market data.
  Inputs:
    tid     : the ticker id. Must be a unique value.
       		  When the market data returns, it will be identified by this tag.
       		  This is also used when canceling the market data.
    symbol  : Symbol of the financial instrument you intend to trade
    secType : STK OPT FUT IND FOP CASH BAG
    exchange: The order destination Exchange, such as Smart.
    Expiry  : The expiration date. Use the format YYYYMM.
    strike  : strike price in case of options
    right   : Specifies a Put or Call. Valid values are: P, PUT, C, CALL.
    currency: USD etc. specifies the currency. Ambiguities may require that
              this field be specified, for example, when SMART is the exchange and
              IBM is being requested (IBM can trade in GBP or USD).
              Given the existence of this kind of ambiguity, it is a good
              idea to always specify the currency.
    localSymbol : the local exchange symbol of the underlying asset.
  outputs : None. Used to start requesting the data. use the other
  functions for getting the price related information after issuing this
  command.
  Examples:
    reqMktData(3,'ES','FUT','GLOBEX','',0,'','','ESU6')
    Request market data for ES Future for september at GLOBEX.
 
 
 

getAccountAttributeValue - getAccountAttributeValue Request the value of an account key

help getAccountAttributeValue
  getAccountAttributeValue Request the value of an account key
  must be called after requestAccountUpdates
  accountName is the IB account name (optional)
  currency by default is USD.
  Copyright Exchange Systems Inc
 
 
 

getAccountCashBalance - getAccountCashBalance Request account cash balance for a given currency

help getAccountCashBalance
 getAccountCashBalance Request account cash balance for a given currency
 must be called after requestAccountUpdates
 accountName is the account name (optional)
 currency -default value : USD
 
 
 

getAccountKeys - returns the available keys for the given account name

help getAccountKeys
  GETACCOUNTKEYS returns the available keys for the given account name
  must be called after requestAccountUpdates
  The accounname input is optional. If No input is given, the default
  connected account is assumed.
  See also
  getAccountAttributeValue
 
 
 

getAccountNames - returns the accounts names list

help getAccountNames
 GETACCOUNTNAMES returns the accounts names list,
  must be called after requestAccountUpdates
  see also:
 getAccountKeys, getAccountAttributeValue
 
   
 

getFullAccountInformation - Get Full account information

help  getFullAccountInformation
 Get Full account information
 All the information for all the keys corresponding to the particular account name
 Input Params:
 AccountName : Required: account name for for the account information
 Currency    : Optional: If not provided, Currency value will be looked up and used
 Output is  a cell array with attributes in the first column and their
 values in the second column.
 
   
 

requestAccountUpdates - Start receiving Account Updates

help requestAccountUpdates
 REQUESTACCOUNTUPDATES Start receiving Account Updates
  Inputs:
  subscribe : True to start receiving updates
  accountcode : account code.
  Output : None. This function sets the parameters neccessary to start
            receiving account related information.
  Example:
  requestAccountUpdates( 1,'');
 
   
 

getPortfolioUpdates - Start receiving Portfolio Updates

help getPortfolioUpdates
 GETPORTFOLIOUPDATES Start receiving Portfolio Updates
  Inputs:
  accountName: is the IB account name (optional)
  symbol: is the order symbol (optional)
  Output : Returns an array of portfolio structures, each structure contains the following fields

	nContracts: # of contracts
    	symbol: contract symbol
	position: net qty of the position
	TotContractSize: Total Contract Size

  Notes : This must be called after calling requestAccountUpdates.
  	If no parameters are passed, then portfolio updates for all accounts
  	and symbols will be returned.
  Example:
  getPortfolioUpdates();
  getPortfolioUpdates('DU1560');
  getPortfolioUpdates('DU1560','MSFT');
 
 
 

getErrorMessage - returns the error message associated with the ID

help getErrorMessage
 GETERRORMESSAGE returns the error message associated with the
  id where ID is the tickid or orderid
 
   
 

Sample Usage of All Commands

 
 

Autostart

%start TWS automatically
Autostart
pause(30)
s =

     0


w =

     ''
 
   
 
 

Connect to TWS API

%Type the following code and wait for *30* seconds
connect2TWS
format long g
pause(20)
Server Version:27
TWS Time at connection:20060806 19:28:18 CST

connected =

     1


ans =

     1

Msg Recvd - id=-1 code=2104 Msg=Market data farm connection is OK:hkfarm
Msg Recvd - id=-1 code=2104 Msg=Market data farm connection is OK:usfuture
Msg Recvd - id=-1 code=2104 Msg=Market data farm connection is OK:usfarm
Msg Recvd - id=-1 code=2106 Msg=HMDS data farm connection is OK:ushmds2a
 
   
 
 

Request Account Updates

requestAccountUpdates( 1,'');
pause(5)
 
   
 
 

Get the list of Account Names

AccountName = getAccountNames;
pause(10)
 
   
 
 

Get Cash Balance

cashbalance = str2num(getAccountCashBalance( AccountName ))
pause(5)
cashbalance =

                  95709.82
 
   
 
 

Get Account Keys

keys = getAccountKeys(AccountName);
keys(1:5,:)
pause(5)
ans =

    'Currency'
    'DayTradesRemainingT+4'
    'TotalCashBalance'
    'FuturesPNL'
    'StockMarketValue'
 
   
 
 

Get Account Attribute Value

value = getAccountAttributeValue('Currency',AccountName )
valuewithnoaccountinput = getAccountAttributeValue('Currency')
pause(5)
value =

USD


valuewithnoaccountinput =

USD
 
   
 
 

Get Full Account Information -108 rows

accountInformation = getFullAccountInformation(AccountName);
accountInformation([1:47,49:end],:) % Not displaying Account Code
pause(5)
ans =

    'Currency'                            'USD'
    'DayTradesRemainingT+4'               [        -1]
    'TotalCashBalance'                    [  95709.82]
    'FuturesPNL'                          [   -281.25]
    'StockMarketValue'                    [         0]
    'RegTMargin-S'                        [         0]
    'TotalCashValue-S'                    [  83477.54]
    'LookAheadAvailableFunds'             [  90645.28]
    'ExcessLiquidity-S'                   [  83477.54]
    'OptionMarketValue'                   [         0]
    'LookAheadExcessLiquidity-C'          [   8538.06]
    'LookAheadMaintMarginReq-S'           [         0]
    'UnrealizedPnL'                       [    114.72]
    'NetLiquidation-C'                    [  14019.31]
    'UnrealizedPnL'                       [    114.72]
    'OptionMarketValue'                   [         0]
    'InitMarginReq-C'                     [  13696.88]
    'FuturesPNL'                          [   -281.25]
    'FullMaintMarginReq-C'                [   10957.5]
    'MaintMarginReq-S'                    [         0]
    'AccruedCash'                         [         0]
    'ExchangeRate'                        [         1]
    'Cushion'                             [  0.887612]
    'LookAheadNextChange'                 [1154957400]
    'UnalteredInitMarginReq'              [        -1]
    'FullExcessLiquidity-S'               [  83477.54]
    'RealizedPnL'                         [         0]
    'ExchangeRate'                        [         1]
    'PreviousDayEquityWithLoanValue'      [  91996.18]
    'MaintMarginReq-C'                    [   10957.5]
    'FullMaintMarginReq'                  [   10957.5]
    'Currency'                            'USD'
    'FutureOptionValue'                   [         0]
    'NetLiquidationByCurrency'            [  95709.82]
    'AccruedCash'                         [         0]
    'LookAheadInitMarginReq-C'            [   6851.56]
    'TotalCashValue'                      [  97496.85]
    'OptionMarketValue'                   [         0]
    'GrossPositionValue'                  [         0]
    'AvailableFunds-C'                    [    322.43]
    'FullAvailableFunds'                  [  83799.97]
    'BuyingPower'                         [ 346157.38]
    'LookAheadExcessLiquidity-S'          [  83477.54]
    'FullExcessLiquidity-C'               [   3061.81]
    'LookAheadInitMarginReq-S'            [         0]
    'DayTradesRemainingT+1'               [        -1]
    'NetLiquidation-S'                    [  83477.54]
    'DayTradesRemainingT+2'               [        -1]
    'FutureOptionValue'                   [         0]
    'RegTMargin'                          [         0]
    'NetLiquidationByCurrency'            [  95709.82]
    'CashBalance'                         [  95709.82]
    'InitMarginReq-S'                     [         0]
    'DayTradesRemainingT+3'               [        -1]
    'TotalCashBalance'                    [  95709.82]
    'LookAheadExcessLiquidity'            [   92015.6]
    'AccruedCash-S'                       [         0]
    'RealizedPnL'                         [         0]
    'EquityWithLoanValue'                 [  86539.35]
    'AvailableFunds'                      [  83799.97]
    'SMA'                                 [   83524.2]
    'AccountType'                         'UNIVERSAL'
    'ExcessLiquidity-C'                   [   3061.81]
    'LookAheadInitMarginReq'              [   6851.56]
    'Currency'                            'USD'
    'FullAvailableFunds-S'                [  83477.54]
    'AccruedCash'                         [         0]
    'MaintMarginReq'                      [   10957.5]
    'LookAheadMaintMarginReq'             [   5481.25]
    'AccountReady'                        [         1]
    'Leverage-S'                          [         0]
    'ExcessLiquidity'                     [  86539.35]
    'AvailableFunds-S'                    [  83477.54]
    'FullAvailableFunds-C'                [    322.43]
    'TotalCashBalance'                    [  95709.82]
    'FullMaintMarginReq-S'                [         0]
    'EquityWithLoanValue-C'               [   3061.81]
    'StockMarketValue'                    [         0]
    'FuturesPNL'                          [   -281.25]
    'DayTradesRemaining'                  [        -1]
    'RealizedPnL'                         [         0]
    'CashBalance'                         [  95709.82]
    'RegTEquity'                          [  83477.54]
    'StockMarketValue'                    [         0]
    'FullExcessLiquidity'                 [  86539.35]
    'AccruedCash-C'                       [         0]
    'InitMarginReq'                       [  13696.88]
    'PreviousDayEquityWithLoanValue-S'    [  91996.18]
    'FullInitMarginReq-C'                 [  13696.88]
    'TotalCashValue-C'                    [  14019.31]
    'CashBalance'                         [  95709.82]
    'PNL'                                 [         1]
    'FullInitMarginReq'                   [  13696.88]
    'FutureOptionValue'                   [         0]
    'GrossPositionValue-S'                [         0]
    'NetLiquidationByCurrency'            [  95709.82]
    'LookAheadAvailableFunds-C'           [   7167.74]
    'LookAheadMaintMarginReq-C'           [   5481.25]
    'SMA-S'                               [   83524.2]
    'NetLiquidation'                      [  97496.85]
    'ExchangeRate'                        [         1]
    'LookAheadAvailableFunds-S'           [  83477.54]
    'FullInitMarginReq-S'                 [         0]
    'UnrealizedPnL'                       [    114.72]
    'RegTEquity-S'                        [  83477.54]
    'EquityWithLoanValue-S'               [  83477.54]
    'UnalteredMaintMarginReq'             [        -1]
 
   
 
 

Get Portfolio Updates

[portfolio] = getPortfolioUpdates('AccountName','Symbol' )
pause(5)
portfolio =

         nContracts: 1
             symbol: {'ES'}
           position: 1
    TotContractSize: 1
 
   
 
 

Request Market Data

EStick=1
reqMktData(EStick,'ES','FUT','GLOBEX','',0,'','','ESU6')
pause(3)
EStick =

     1
 
   
 
 

Get LAST Price

ESlast = getLastPrice(EStick)
pause(3)
ESlast =

                    1284.5
 
   
 
 

Get BID price

ESbid = getBidPrice(EStick)
pause(3)
ESbid =

                    1284.5
 
   
 
 

Get ASK price

ESask = getAskPrice(EStick)
pause(3)
ESask =

                   1284.75
 
   
 
 

Get Last Size

ESlastSize = getLastSize(EStick)
pause(3)
ESlastSize =

     1
 
   
 
 

Get Bid Size

ESbidSize = getBidSize(EStick)
pause(3)
ESbidSize =

    51
 
   
 
 

Get Ask Size

ESaskSize = getAskSize(EStick)
pause(3)
ESaskSize =

    33
 
   
 
 

Place order

Quantity = 1;
ESID = placeOrder('ES','FUT','GLOBEX','',0,'','USD','ESU6','BUY',
                  Quantity,'MKT',0,0,'GTC','')
pause(3)
YMID = placeOrder('YM','FUT','ECBOT','',0,'','USD','YM   SEP 06',
                  'SELL',Quantity,'LMT',11380,0,'GTC','')
pause(3)
%YMID1 = placeOrder('YM','FUT','ECBOT','',0,'','USD','YM   SEP 06',
                    'SELL',Quantity,'LMT',0,0,'GTC','')
ESID =

   107


YMID =

   108
 
   
 
 

Request ALL Open Orders

requestAllOpenOrders
openorders = getOpenOrdersList
pause(3)
openorders =

     []
 
   
 
 

Cancel All Open Orders

cancelAllOpenOrders
pause(3)
Msg Recvd - id=108 code=202 Msg=Order Canceled - reason:
 
   
 
 

Request Executions

 requestExecutions('ClientId' )
pause(5)
 
   
 
 

Get Execution Details

 requestExecutions('orderId' )
pause(5)execstruct =

      nContracts: 1
      AcctNumber: 'DU1329'
          symbol: {'ES'}
        Exchange: {'GLOBEX'}
     longORshort: {'BOT'}
    positionSize: 1
           price: 1333
 
   
 
 

cancel particular order

YMID = placeOrder('YM','FUT','ECBOT','',0,'','USD','YM   SEP 06',
                  'SELL',Quantity,'LMT',11380,0,'GTC','');
pause(3)
cancelOrder(YMID);
pause(2)
Msg Recvd - id=109 code=202 Msg=Order Canceled - reason:
 
   
 
 

Check if the Order is FILLED

%if *1* order is Filled, Otherwise it is not filled
isOrderFilled(ESID)
pause(1)
ans =

     1
 
   
 
 

Check if the Order is Cancelled

cancelled = isOrderCancelled( YMID )
pause(1)
cancelled =

     1
 
   
 
 

Get Average Fill Price

ESprice = getAvgFillPrice(ESID)
pause(1)
ESprice =

                   1284.75
 
   
 
 

Get Historical Market Data

%Please wait for 20 seconds
%[data open high low close] = reqHistData(1005,'ES','FUT','GLOBEX','',0.0,
               '','','ESM6','20060523 17:15:00','30600 S','1 min','MIDPOINT',1,2,10);
tic
clear YMdata;
[YMdata ] = reqHistData(1007,'YM','FUT','ECBOT','',0.0,'','','YM   SEP 06',
                        '20060523 17:15:00','30600 S','10 mins','MIDPOINT',0,1,10)
toc
pause(10)
getting historical data..Please wait

YMdata =

          open: [9x1 double]
          high: [9x1 double]
           low: [9x1 double]
         close: [9x1 double]
        volume: [9x1 double]
          date: [9x18 char]
    MATLAB®date: [9x1 double]

Elapsed time is 20.149689 seconds.
 
   
 
 

Get Quote Data

%This will give you information about the last trade
qdata = char(getQuoteData(EStick))
pause(3)
qdata =

QuoteData -  LAST - 1@1284.5 BID - 77@1284.5 ASK - 38@1284.75
                  HIGH - 1285.75 LOW - 1284.25 Volume - 1720
 
   
 
 

Request open Orders

requestOpenOrders
pause(3)
 
   
 
 

Get Open Orders List

open = getOpenOrdersList
pause(3)
open =

     []
 
   
 
 

Test if Connection is LOST

%isIBTWSConnectionLost returns 1 if connection is lost, else 0
lost = isIBTWSConnectionLost
pause(3)
lost =

     0
 
   
 
 

Test if data is maintained in case of connection loss

%isDataMaintained returns 1 if data is maintained, else 0 if data is lost
%This returns 0 if connection is NOT lost in the first place.
maintained = isDataMaintained
pause(2)
maintained =

     0
 
   
 
 

Test if Connection is restored

isIBTWSConnectionRestored returns 1 if connection is restored, else 0

%This returns 0 if connection is NOT lost in the first place.
         restored = isIBTWSConnectionRestored
         pause(2)
restored =

     0
 
   
 
 

Disconnect From TWS

%disconnectFromTWS
   
 
   
   
   
 

Copyright 2006 Exchange Systems Inc. All rights reserved. Privacy Policy
1051 Perimeter Drive, Suite 1175, Schaumburg, IL 60173, USA
MATLAB® is registered trademarks of The MathWorks, Inc.& IB and TWS are service marks and/or trademarks of Interactive Brokers LLC.
Trading Technologies® and X_TRADER® are registered trademarks and TT™ is a trademark of Trading Technologies International, Inc.