15 Using the Java connector object

15.1 Using the connector object

Each call to IBMatlab returns two output values:

data – generally contains the request ID or the requested query data

ibConnector – a Java object reference

In most cases, users do not need to use ibConnector and so we can generally ignore the second output value and simply call IBMatlab with a single output:

data = IBMatlab('action','query', ... );

However, flexible and feature-rich as IBMatlab is, it does not contain the entire set of functionalities exposed by IB’s Java API. We can use ibConnector to access some additional functionalities:

[data, ibConnector] = IBMatlab('action','query', ... );

ibConnector is a Java object of type IBMatlab.IBConnection. You can call its publicly-accessible methods (functions) just like any Matlab function. For example:

[data, ibConnector] = IBMatlab('action','query', ... );
flag = ibConnector.isConnected;
% no input params, so no ()
ibConnector.disconnectFromTWS(); % no real need for () here
ibConnector.cancelOrder(153745227);

There is an almost exact correlation between the methods in ibConnector and the methods documented in IB’s Java API (for both requests166 and responses167). This was done on purpose, to enable easy integration with IB. ibConnector is in many respects an interface object to IB’s Java API. Therefore, the official IB Java API documentation can usually be used to understand ibConnector, and if you have any question about this documentation you should ask IB about it.

When you call any of the request methods, you cannot directly call the corresponding event methods to receive and process the data. For example, if you call ibConnector.reqCurrentTime(), you cannot call the corresponding currentTime() method. Instead, currentTime() is automatically being called by the underlying Java engine as a new event. However, as noted in §11.1, all these events can be trapped and processed within Matlab callbacks. In this particular case, a currentTime event is raised and this can be trapped and processed in a user Matlab function specified by the CallbackCurrentTime parameter.

Note: All trade (buy/sell/short) orders must be placed exclusively through either the ibConnector interface (the placeOrder() method) or the IBMatlab name-value pair interface. Placing trade orders via both interfaces in a single IB-Matlab session will result in request ID mixup and failed trades: the IB server will reject trades that have duplicate or non-sequential IDs. Using duplicate and non-sequential IDs is not critical in many other IB requests, but is critical in the specific case of trade orders.

15.2 Programming interface

The following is the publicly-accessible interface of ibConnector:

// Contract, ContractDetails, EClientSocket, EWrapper, EWrapperMsgGenerator,
// Execution, ExecutionFilter, Order, OrderState, ScannerSubscription, UnderComp
import com.ib.client.*;

public class IBConnection
{

public final static String DEFAULT_TWS_HOST = "localhost";
public final static int DEFAULT_TWS_PORT = 7496;
public final static int DEFAULT_TWS_CLIENT_ID = 1;

// Getter functions for the connection parameters
public String getHost()
public int getPort()
public int getClientId()

/*********************************
* Active requests to IB via TWS (may be called directly)
*********************************/

// Check if connected to TWS
public boolean isConnected()

// Disconnect from TWS
public void disconnectFromTWS()

// Request the version of TWS instance to which the API application is connected
public int getServerVersion()

// Request the time the API application made a connection to TWS
public String getTwsConnectionTime()

// Request the current server time
public void reqCurrentTime ()
public void Systime() // same as reqCurrentTime()

// Request market data
public void reqMktData(int tickerId, String symbol, String secType,
String expiry,
double strike, String right,
String exchange, String currency,
String localSymbol, String genericTickList,
boolean snapshotFlag)

public void reqMktData(int tickerId, String symbol, String secType,
String expiry,
double strike, String right,
String exchange, String currency,
String localSymbol,
boolean snapshotFlag)

public void reqMktData(int tickerId, Contract contract, String genericTickList,
boolean snapshotFlag)

public void reqMktData(int tickerId, Contract contract, boolean snapshotFlag)

// Cancel request for market data
public void cancelMktData(int tickerId)

// Request market depth data
public void reqMktDepth(int tickerId, String symbol, String secType,
String expiry,
double strike, String right,
String exchange, String currency, String localSymbol,
int numRows)
public void reqMktDepth(int tickerId, Contract contract, int numRows)

// Cancel request for market depth
public void cancelMktDepth(int tickerId)

// Request historic market data
public void reqHistoricalData (int tickerId, String symbol, String secType,
String expiry,
double strike, String right,
String exchange, String currency,
String localSymbol, String endDateTime,
String durationStr, String barSizeSetting,
String whatToShow,
int useRTH, int formatDate)

public void reqHistoricalData (int tickerId, Contract contract,
String endDateTime, String durationStr,
String barSizeSetting, String whatToShow,
int useRTH, int formatDate)

// Cancel request for historic data
public void cancelHistoricalData (int tickerId)

// Request contract details
public void reqContractDetails (int tickerId, Contract contract)

// Create a contract
public Contract createContract() // default Contract: USD on SMART, empty fields
public Contract createContract(String symbol, String secType, String expiry,
double strike, String right, String exchange,
String currency, String localSymbol)

// Create an order
public Order createOrder() // create default Order: Buy 0 LMT 0, RTH only
public Order createOrder(String action, int quantity, String type,
double lmtPrice, double auxPrice, String tif,
String ocaGroup,
int parentId, String goodAfterTime,
String goodTillDate,
double trailStopPrice,
int triggerMethod, boolean outsideRTH)

// Cancel a placed order (if still open)
public void cancelOrder(int tickerId)

// Place an order
public void placeOrder(int id, Contract contract, Order order)
public void placeOrder(int id, String symbol, String secType, String expiry,
double strike, String right, String exchange,
String currency, String localSymbol,String action,
int Quantity, String Type, double lmtPrice,
double auxPrice, String tif, String ocaGroup,
int parentId, String goodAfterTime,
String goodTillDate,
double trailStopPrice,
int triggerMethod, boolean outsideRTH)

// Request a list of current open orders for the requesting client and
// associate TWS open orders with the client.

// The association only occurs if the requesting client has a Client ID of 0.
public void reqOpenOrders ()

// Request a list of all open orders
public void reqAllOpenOrders ()

// Associate a new TWS with the client automatically.
// The association only occurs if the requesting client has a Client ID of 0.

public void reqAutoOpenOrders (boolean autoBindFlag)

// Request account values, portfolio, and account update time information
public void reqAccountUpdates (boolean subscribeFlag, String acctCode)

// Request a list of the day's execution reports
public void reqExecutions (int reqId, ExecutionFilter executionFilter)

// Request IB news bulletins
public void reqNewsBulletins (boolean allMsgsFlag)

// Cancel request for IB news bulletins
public void cancelNewsBulletins ()

// Request a list of Financial Advisor (FA) managed account codes
public void reqManagedAccts ()

// Request FA configuration information from TWS
public void requestFA (int faDataType)

// Modify FA configuration information from the API
public void replaceFA (int faDataType, String xmlStr)

// Request an XML doc that describes valid parameters of a scanner subscription
public void reqScannerParameters ()

// Request market scanner results
public void reqScannerSubscription (int tickerId,
ScannerSubscription scannerSubscription)
// Cancel request for a scanner subscription
public void cancelScannerSubscription (int tickerId)

// Requests real-time bars (only barSize=5 is currently supported by IB)168
public void reqRealTimeBars(int tickerId, Contract contract, int barSize,
String whatToShow,
boolean useRTH)
// Cancel request for real-time bars
public void cancelRealTimeBars(int tickerId)

// Exercise options
public void exerciseOptions(int tickerId, Contract contract, int exerciseAction,
int exerciseQuantity, String account, int override)

// Request Reuters global fundamental data. There must be a subscription to
// Reuters Fundamental setup in Account Management before you can receive data

public void reqFundamentalData(int id, Contract contract, String str)
// Cancel request for Reuters global fundamental data
public void cancelFundamentalData(int id)

// Request the next available reqId
public void reqNextValidId() // same as reqId() below
public void reqId() // a single ID
public void reqIds(int numIds) // multiple IDs

// Calculate the implied volatility of a contract
public void calculateImpliedVolatility(int tickerId, Contract contract,
double optionPrice, double underPrice)
// Cancel request to calculate the implied volatility of a contract
public void cancelCalculateImpliedVolatility(int tickerId)

// Calculate an option price
public void calculateOptionPrice(int tickerId, Contract contract,
double volatility, double underPrice)
// Cancel request to calculate an option price
public void cancelCalculateOptionPrice(int tickerId)

// Cancel all open API and TWS orders – 9.65
public void reqGlobalCancel()

// Request market data type – 9.66
// (1 for real-time streaming market data or 2 for frozen market data)
public void reqMarketDataType(int marketDataType)

// Request reception of the data from the TWS Account Window Summary tab – 9.69
public void reqAccountSummary(int reqId, String group, String tags)

// Cancel request for TWS Account Window Summary data – 9.69
public void cancelAccountSummary(int reqId)

// Request reception of real-time position data for an all accounts – 9.69
public void reqPositions()

// Cancel request for real-time position data – 9.69
public void cancelPositions()

// Set the level of API request and processing logging
public void setServerLogLevel (int logLevel)

// Set the message display level
// (0=display all messages; 1=display errors only; 2=display no messages)

public void setMsgDisplayLevel(int displayLevel)

// Get the message display level
public int getMsgDisplayLevel()

// Set the Done flag
public void setDone(boolean flag)

// Get the Done flag
public boolean isDone()

/****************************
* IB Callbacks (invoked automatically – should NOT be called directly!)
****************************/

// Receives error and informational messages
public void error(String str)
public void error(int data1, int data2, String str)
public void error(Exception e)

// Receives indication that the TWS connection has closed
public void connectionClosed()

// Receives market data
public void tickPrice(int tickerId, int field, double price, int canAutoExecute)

public void tickSize(int tickerId, int field, int size)

public void tickString(int tickerId, int field, String value)

public void tickGeneric(int tickerId, int field, double generic)

public void tickEFP(int tickerId, int field, double basisPoints,
String formattedBasisPoints,
double totalDividends,
int holdDays, String futureExpiry, double dividendImpact,
double dividendsToExpiry)

public void tickOptionComputation(int tickerId, int field, double impliedVol,
double delta, double modelPrice,
double pvDividend)

public void tickOptionComputation(int tickerId, int field, double impliedVol,
double delta, double optPrice,
double pvDividend, double gamma, double vega,
double theta, double undPrice)

public void tickSnapshotEnd(int reqId)

// Receives execution report information
public void execDetails(int orderId, Contract contract, Execution execution)

// Indicates end of execution report messages
public void execDetailsEnd(int reqId)

// Receives historical data results
public void historicalData(int reqId, String date, double open, double high,
double low, double close, int volume, int count,
double WAP, boolean hasGaps)

// Receives the next valid order ID upon connection
public void nextValidId(int orderId)

// Receives data about open orders
public void openOrder(int orderId, Contract contract, Order order)
public void openOrder(int orderId, Contract contract, Order order,
OrderState orderState)

// Indicates end of open orders messages
public void openOrderEnd()

// Receives data about orders status
public void orderStatus(int orderId, String status, int filled, int remaining,
double avgFillPrice, int permId, int parentId,
double lastFillPrice, int clientId)

public void orderStatus(int orderId, String status, int filled, int remaining,
double avgFillPrice, int permId, int parentId,
double lastFillPrice, int clientId, String whyHeld)

// Receives a list of Financial Advisor (FA) managed accounts
public void managedAccounts(String accountsList)

// Receives Financial Advisor (FA) configuration information
public void receiveFA(int faDataType, String xml)

// Receives an XML doc that describes valid parameters of a scanner subscription
public void scannerParameters(String xml)

// Receives market scanner results
public void scannerData(int reqId, int rank, ContractDetails contractDetails,
String distance, String benchmark, String projection,
String legsStr)
public void scannerDataEnd(int reqId)

// Receives the last time account information was updated
public void updateAccountTime(String timeStamp)

// Receives current account values
public void updateAccountValue(String key, String value, String currency)
public void updateAccountValue(String key, String value, String currency,
String accountName)

// Receives IB news bulletins
public void updateNewsBulletin(int msgId, int msgType, String message,
String origExchange)

// Receives market depth information
public void updateMktDepth(int tickerId, int position, int operation, int side,
double price, int size)

// Receives Level 2 market depth information
public void updateMktDepthL2(int tickerId, int position, String marketMaker,
int operation, int side, double price, int size)

// Receives current portfolio information
public void updatePortfolio(Contract contract, int position, double marketPrice,
double marketValue, double averageCost,
double unrealizedPNL, double realizedPNL)

public void updatePortfolio(Contract contract, int position, double marketPrice,
double marketValue, double averageCost,
double unrealizedPNL, double realizedPNL,
String accountName)

// Receives real-time bars data
public void realtimeBar(int reqId, long time, double open, double high,
double low, double close, long volume, double wap,
int count)

// Receives the current system time on the server
public void currentTime(long time)

// Receives contract information
public void contractDetails(int reqId, ContractDetails contractDetails)

// Receives bond contract information
public void bondContractDetails(int reqId, ContractDetails contractDetails)

// Identifies the end of a given contract details request
public void contractDetailsEnd(int reqId)

// Receives Reuters global fundamental market data
public void fundamentalData(int reqId, String data)

public void accountDownloadEnd(String accountName)

public void deltaNeutralValidation(int reqId, UnderComp underComp)

// Receives market data type information – 9.66
public void marketDataType(int reqId, int marketDataType)

// Receives commission report information – 9.67
public void commissionReport(CommissionReport commissionReport)

// Receives real-time position for an account – 9.69
public void position(String account, Contract contract, int pos)

// Indicates end of position messages – 9.69
public void positionEnd()

// Receives the data from the TWS Account Window Summary tab – 9.69
public void accountSummary(int reqId, String account, String tag, String value,
String currency)

// Indicates end of account-summary messages – 9.69
public void accountSummaryEnd(int reqId)

}

15.3 Usage example

Let us use the Java connector object to implement the Arrival Price algo example that is provided in the official IB Java API (also see §9.8).169

This Arrival Price example shows how easy it is to convert Java code available in the official API or support forums (or even code supplied by IB’s API customer support team) to Matlab using IB-Matlab:

First, here is the original Java code:

import com.ib.client.TagValue;

Contract contract = new Contract();

Order order = new Order();

Vector<TagValue> algoParams = new Vector<TagValue>();

/** Stocks */
contract.m_symbol = "MSFT";
contract.m_secType = "STK";
contract.m_exchange = "SMART";
contract.m_currency = "USD";

/** Arrival Price */
algoParams.add( new TagValue("maxPctVol","0.01") );
algoParams.add( new TagValue("riskAversion","Passive") );
algoParams.add( new TagValue("startTime","9:00:00 EST") );
algoParams.add( new TagValue("endTime","15:00:00 EST") );
algoParams.add( new TagValue("forceCompletion","0") );
algoParams.add( new TagValue("allowPastEndTime","1") );

order.m_action = "BUY";
order.m_totalQuantity = 1;
order.m_orderType = "LMT";
order.m_lmtPrice = 0.14
order.m_algoStrategy = "ArrivalPx";
order.m_algoParams = algoParams;
order.m_transmit = false;

client.placeOrder(40, contract, order);

And now for the corresponding Matlab code (notice how closely it resembles the original Java code):170

import com.ib.client.TagValue;

% Get the ibConnector reference from IBMatlab
[dummy, ibConnector] = IBMatlab('action','account');

% If IB-Matlab is already connected we can get this reference faster:
[dummy, ibConnector] = IBMatlab(); % faster alternative

% Next, create the contract for the requested security
contract = ibConnector.createContract(...
'MSFT','STK','',0,'','SMART','USD','MSFT');

% Alternatively, we could have done as follows:
contract = ibConnector.createContract();
contract.m_symbol = 'MSFT';
contract.m_secType = 'STK';
contract.m_exchange = 'SMART'; %=default value so not really needed
contract.m_currency = 'USD'; %=default value so not really needed
% end of alternative code

% Now set the Arrival Price algoParams
algoParams = java.util.Vector;
algoParams.add( TagValue('maxPctVol','0.01') );
algoParams.add( TagValue('riskAversion','Passive') );
algoParams.add( TagValue('startTime','9:00:00 EST') );
algoParams.add( TagValue('endTime','15:00:00 EST') );
algoParams.add( TagValue('forceCompletion','0') );
algoParams.add( TagValue('allowPastEndTime','1') );

% Now create the order, using algoParams
order = ibConnector.createOrder('BUY', 1, 'LMT', 0.14, 0, '', ...
'', 0, '', '', realmax, 0, false);

order.m_algoStrategy = 'ArrivalPx';
order.m_algoParams = algoParams;
order.m_transmit = false;

% Finally, send the order to the IB server
ibConnector.placeOrder(40, contract, order);

Note: A related mechanism, using the Hold parameter, is explained in §9.6 above.

Note: field names of IB’s Java objects (e.g. contract, order) have a m_ prefix (e.g. contract.m_symbol, order.m_transmit). IB-Matlab v2.19 onward reports such objects as Matlab structs without the m_ prefix (e.g. contract.symbol, order.transmit), but whenever we use the original Java objects we must add a m_ prefix to the field names. In the example above, contract and order were created using ibConnector, as Java objects, so we must use a m_ prefix of field names to modify the Java field values.


166 https://interactivebrokers.github.io/tws-api/classIBApi_1_1EClientSocket.html

167 https://interactivebrokers.github.io/tws-api/interfaceIBApi_1_1EWrapper.html

168 http://interactivebrokers.github.io/tws-api/realtime_bars.html

169 http://interactivebrokers.github.io/tws-api/ibalgos.html#arrivalprice, http://interactivebrokers.com/en/software/tws/usersguidebook/algos/arrival_price.htm, http://interactivebrokers.com/en/index.php?f=1122

170 This code can be downloaded from: http://UndocumentedMatlab.com/files/IBMatlab_ArrivalPriceAlgo.m