Interactive Brokers API Reference Guide
Interactive Brokers API Reference Guide
April 2015
Sun, Sun Microsystems, the Sun Logo and Java are trademarks or registered trademarks of Sun Microsystems, Inc. in the
United States and other countries. Excel, Windows and Visual Basic (VB) are trademarks or registered trademarks of the
Microsoft Corporation in the United States and/or in other countries.
Any symbols displayed within these pages are for illustrative purposes only, and are not intended to portray any recom-
mendation.
Contents
Contents i
Overview 31
Recommendations 37
General 41
Trusted IP Addresses 42
The Request 49
Tutorial: Requesting Real-Time Market Data4. Obtain the Last Available Error 50
Why is it important to first clear the error formula before correcting our request? 51
Tutorial: Requesting Historical Data3. Request the Data - Add the Code 62
Duration 64
Bar Sizes 65
Tickers Page 72
Placing Orders 76
If-Filled order 88
Price-change order 88
Executions Page 96
Viewing Executions 97
Account Page 98
Modules 127
Macros 127
Active X 137
connect() 143
disconnect() 143
reqCurrentTime() 143
setServerLogLevel() 143
reqMktDataEx() 144
cancelMktData() 144
calculateImpliedVolatility() 144
cancelCalculateImpliedVolatility() 145
calculateOptionPrice() 145
cancelCalculateOptionPrice() 145
reqMarketDataType() 145
placeOrderEx() 146
cancelOrder() 146
reqOpenOrders() 146
reqAllOpenOrders() 146
reqAutoOpenOrders() 146
reqIds() 147
exerciseOptionsEx() 147
reqGlobalCancel() 148
reqExecutionsEx() 148
reqContractDetailsEx() 148
reqMktDepthEx() 149
cancelMktDepth() 149
reqAccountUpdates() 149
reqAccountSummary() 150
cancelAccountSummary() 153
reqPositions() 153
cancelPositions() 153
reqNewsBulletins() 153
cancelNewsBulletins() 154
reqManagedAccts() 154
requestFA() 154
replaceFA() 154
reqHistoricalDataEx() 155
cancelHistoricalData() 157
reqScannerParameters() 157
reqScannerSubscriptionEx() 157
cancelScannerSubscription() 158
reqRealTimeBarsEx() 158
cancelRealTimeBars() 159
createComboLegList() 159
createContract() 159
createExecutionFilter() 159
createOrder() 160
createScannerSubscription() 160
createTagValueList 160
createUnderComp() 160
reqFundamentalData() 160
cancelFundamentalData() 161
queryDisplayGroups() 161
subscribeToGroupEvents() 161
updateDisplayGroup() 161
unsubscribeFromGroupEvents() 162
connectionClosed() 164
currentTime() 164
errMsg() 164
tickPrice() 164
tickSize() 165
tickOptionComputation() 165
tickGeneric() 166
tickString() 166
tickEFP() 166
tickSnapshotEnd() 167
marketDataType() 167
orderStatus() 168
openOrderEx() 169
openOrderEnd() 169
nextValidId() 169
permId() 170
deltaNeutralValidation() 170
updateAccountValue() 170
updatePortfolioEx() 172
updateAccountTime() 173
accountDownloadEnd() 173
accountSummary() 173
accountSummaryEnd 176
position() 176
positionEnd() 177
updateNewsBulletin() 177
contractDetailsEx() 177
contractDetailsEnd() 177
bondContractDetails() 178
execDetailsEx() 179
execDetailsEnd() 179
commissionReport() 179
updateMktDepth() 180
updateMktDepthL2() 180
managedAccounts() 181
receiveFA() 181
historicalData() 182
scannerParameters() 182
scannerDataEx() 182
scannerDataEnd() 183
realtimeBar() 183
fundamentalData() 184
displayGroupList() 184
displayGroupUpdated() 184
IExecution 186
IExecutionFilter 187
ICommissionReport 188
IContract 188
IContractDetails 190
IComboLeg 191
IComboLegList 192
IOrder 192
OrderComboLeg 201
IOrderState 201
IScannerSubscription 202
ITagValueList 203
ITagValue 203
IUnderComp 203
Example 205
C++ 209
EClientSocket() 234
eConnect() 235
eDisconnect() 235
isConnected() 235
reqCurrentTime() 235
serverVersion() 235
setLogLevel() 236
TwsConnectionTime() 236
checkMessages() 236
reqMktData() 236
cancelMktData() 237
calculateImpliedVolatility() 237
cancelCalculateImpliedVolatility() 237
calculateOptionPrice() 238
cancelCalculateOptionPrice() 238
reqMarketDataType() 238
placeOrder() 238
cancelOrder() 239
reqOpenOrders() 239
reqAllOpenOrders() 239
reqAutoOpenOrders() 239
reqIDs() 240
exerciseOptions() 240
reqGlobalCancel() 240
reqAccountUpdates() 241
reqAccountSummary() 242
cancelAccountSummary() 244
reqPositions() 244
cancelPositions() 244
reqExecutions() 244
reqContractDetails() 245
reqMktDepth() 245
cancelMktDepth() 245
reqNewsBulletins() 246
cancelNewsBulletins() 246
reqManagedAccts() 246
requestFA() 246
replaceFA() 246
reqHistoricalData() 247
cancelHistoricalData() 249
reqScannerParameters() 249
reqScannerSubscription() 249
cancelScannerSubscription() 250
reqRealTimeBars() 250
cancelRealTimeBars() 251
reqFundamentalData() 251
cancelFundamentalData() 252
queryDisplayGroups() 252
subscribeToGroupEvents() 252
updateDisplayGroup() 252
unsubscribeFromGroupEvents() 253
winError() 255
error() 255
connectionClosed() 255
currentTime() 255
tickPrice() 255
tickSize() 256
tickOptionComputation() 256
tickGeneric() 257
tickString() 257
tickEFP() 258
tickSnapshotEnd() 258
marketDataType() 259
orderStatus() 259
openOrder() 261
openOrderEnd() 261
nextValidId() 261
deltaNeutralValidation() 262
updateAccountValue() 262
updatePortfolio() 263
updateAccountTime() 263
accountDownloadEnd() 263
accountSummary() 263
accountSummaryEnd 266
position() 266
positionEnd() 266
updateNewsBulletin() 266
contractDetails() 267
contractDetailsEnd() 267
bondContractDetails() 267
execDetails() 267
execDetailsEnd() 268
commissionReport() 268
updateMktDepth() 268
updateMktDepthL2() 269
managedAccounts() 270
receiveFA() 270
historicalData() 270
scannerParameters() 271
scannerData() 271
scannerDataEnd() 271
realtimeBar() 272
fundamentalData() 272
displayGroupList() 273
displayGroupUpdated() 273
Execution 274
ExecutionFilter 275
Contract 276
ContractDetails 277
ComboLeg 279
Order 280
OrderState 288
ScannerSubscription 289
UnderComp 290
CommissionReport 290
Example 292
Java 295
EClientSocket() 301
eConnect() 302
eDisconnect() 302
isConnected() 302
setServerLogLevel() 302
reqCurrentTime() 303
serverVersion() 303
TwsConnectionTime() 303
reqMktData() 303
cancelMktData() 304
calculateImpliedVolatility() 304
cancelCalculateImpliedVolatility() 304
calculateOptionPrice() 304
cancelCalculateOptionPrice() 305
reqMarketDataType() 305
placeOrder() 305
cancelOrder() 305
reqOpenOrders() 306
reqAllOpenOrders 306
reqAutoOpenOrders() 306
reqIDs() 306
exerciseOptions() 306
reqGlobalCancel() 307
reqAccountUpdates() 307
reqAccountSummary() 308
cancelAccountSummary() 311
reqPositions() 311
cancelPositions() 311
reqExecutions() 311
reqContractDetails() 311
reqMktDepth() 312
cancelMktDepth() 312
reqNewsBulletins() 312
cancelNewsBulletins() 312
reqManagedAccts() 313
requestFA() 313
replaceFA() 313
reqAccountSummary() 313
cancelAccountSummary() 316
reqPositions() 316
cancelPositions() 316
reqScannerParameters() 316
reqScannerSubscription() 316
cancelScannerSubscription() 317
reqHistoricalData() 317
cancelHistoricalData() 319
reqRealTimeBars() 319
cancelRealTimeBars() 320
reqFundamentalData() 320
cancelFundamentalData() 321
queryDisplayGroups() 321
subscribeToGroupEvents() 321
updateDisplayGroup() 321
unsubscribeFromGroupEvents() 322
currentTime() 324
error() 324
connectionClosed() 324
tickPrice() 324
tickSize() 325
tickOptionComputation() 326
tickGeneric() 327
tickString() 327
tickEFP() 327
tickSnapshotEnd() 328
marketDataType() 328
orderStatus() 328
openOrder() 330
openOrderEnd() 330
nextValidId() 330
deltaNeutralValidation() 331
updateAccountValue() 331
updatePortfolio() 331
updateAccountTime() 332
accountDownloadEnd() 332
accountSummary() 332
accountSummaryEnd 335
position() 335
positionEnd() 335
contractDetails() 335
contractDetailsEnd() 336
bondContractDetails() 336
execDetails() 336
execDetailsEnd() 336
commissionReport() 337
updateMktDepth() 337
updateMktDepthL2() 338
updateNewsBulletin() 338
managedAccounts() 339
receiveFA() 339
historicalData() 339
scannerParameters() 340
scannerData() 340
scannerDataEnd() 340
realtimeBar() 340
fundamentalData() 341
displayGroupList() 341
displayGroupUpdated() 342
Execution 343
ExecutionFilter 344
CommissionReport 345
Contract 345
ContractDetails 346
ComboLeg 348
OrderComboLeg 349
Order 349
OrderState 357
ScannerSubscription 357
UnderComp 359
Example 360
C# 367
EClientSocket() 385
eConnect() 385
eDisconnect() 385
isConnected() 385
setServerLogLevel() 385
reqCurrentTime() 386
reqGlobalCancel() 386
reqMktData() 386
cancelMktData() 387
calculateImpliedVolatility() 387
cancelCalculateImpliedVolatility() 387
calculateOptionPrice() 387
cancelCalculateOptionPrice() 388
reqMarketDataType() 388
placeOrder() 388
cancelOrder() 388
reqOpenOrders() 389
reqAllOpenOrders 389
reqAutoOpenOrders() 389
reqIDs() 389
exerciseOptions() 389
reqGlobalCancel() 390
reqAccountUpdates() 390
reqAccountSummary() 391
cancelAccountSummary() 394
reqPositions() 394
cancelPositions() 394
reqExecutions() 394
reqContractDetails() 394
reqMktDepth() 395
cancelMktDepth() 395
reqNewsBulletins() 395
cancelNewsBulletins() 395
reqManagedAccts() 396
requestFA() 396
replaceFA() 396
reqScannerParameters() 397
reqScannerSubscription() 397
cancelScannerSubscription() 397
reqHistoricalData() 397
cancelHistoricalData() 399
reqRealTimeBars() 400
cancelRealTimeBars() 400
reqFundamentalData() 401
cancelFundamentalData() 401
queryDisplayGroups() 401
subscribeToGroupEvents() 401
updateDisplayGroup() 402
unsubscribeFromGroupEvents() 402
currentTime() 404
error() 404
connectionClosed() 404
tickPrice() 404
tickSize() 405
tickOptionComputation() 406
tickGeneric() 406
tickString() 407
tickEFP() 407
tickSnapshotEnd() 407
marketDataType() 408
orderStatus() 408
openOrder() 410
openOrderEnd() 410
nextValidId() 410
deltaNeutralValidation() 410
updateAccountValue() 411
updatePortfolio() 411
updateAccountTime() 412
accountDownloadEnd() 412
accountSummary() 412
accountSummaryEnd 415
position() 415
positionEnd() 415
contractDetails() 415
contractDetailsEnd() 416
bondContractDetails() 416
execDetails() 416
execDetailsEnd() 416
commissionReport() 417
updateMktDepth() 417
updateMktDepthL2() 417
updateNewsBulletin() 418
managedAccounts() 418
receiveFA() 419
historicalData() 419
historicalDataEnd() 419
scannerParameters() 420
scannerData() 420
scannerDataEnd() 420
realtimeBar() 420
fundamentalData() 421
displayGroupList() 421
displayGroupUpdated() 422
Execution 423
ExecutionFilter 424
CommissionReport 425
Contract 425
ContractDetails 426
ComboLeg 428
Order 429
OrderComboLeg 437
OrderState 438
ScannerSubscription 438
UnderComp 439
Advisors 441
Running the ActiveX for Excel API on 64-bit Windows XP Systems 452
Apply Extended Order Attributes to Individual Orders and Groups of Orders 478
POSIX 509
Reference 511
Valid Duration and Bar Size Settings for Historical Data Requests 525
Example 538
RTVolume 538
Support for Mini Options - ActiveX, Java and C++ APIs 576
Requirements 577
To request only Fly On The Wall (FLY) News for IBM 580
To request only Fly On The Wall and Briefing.com (BRF) news for IBM 580
Index 585
l Connecting through the TWS requires that you have the application running, but also allows you to test and con-
firm that your API orders are working correctly.
l Connecting through the IB Gateway allows you to use the API without a large GUI application running, but does
not provide an interface for you to test and confirm API activity.
Regardless of the connection method you use, the API allows you to:
To view syntax for specific functionality, see the DDE for Excel, ActiveX, C++, Java or C# topics in this guide. Cus-
tomers with no programming expertise should begin with the DDE for Excel section, which uses an everyday Excel®
spreadsheet to link to TWS via the API.
Note: API topics are written for experienced programmers and provide little guidance for non-tech-
nical users.
To develop and test your API program, we recommend that you use the sample application and connect via TWS. Once
you are satisfied that the API works as designed, you can use the GUI-less IB Gateway to connect, if you desire.
Note: A variety of useful troubleshooting tips and other answers to common questions can be
found in the Frequently Asked Questions section of this guide.
For a complete description of all Trader Workstation’s API settings, see the TWS Users’ Guide.
You must have the IB Gateway running while connected to the API.
Recommendations
Before you use our TWS API to create your own customized trading application, you should consider the following
important recommendations:
l Placing Orders by Conid - When you place an order by conid, you must provide the conid AND the exchange. If
you provide extra fields when placing an order by conid, the order may not work.
l Order IDs - Each order you place must have a unique Order ID. We recommend that you increment your own
Order IDs to avoid conflicts between orders placed from your API application. To resolve issues with Order IDs,
click the Reset API order ID sequence button on the API - Settings panel in TWS Global Configuration.
l Please test your API application with an IB Paper Trading account to catch and avoid any errors. You can request
a Paper Trading account from Account Management.
l While the API supports up to eight simultaneous API connections using the same login to a single running TWS,
we recommend that you avoid this scenario. If possible, use a single API connection for your application to avoid
performance overhead.
If your API order violates these settings, you will receive an error message. For example, the default precautionary setting
for order size is 500. If you place an order for 1000 shares of stock, you will receive an error message indicating that the
size specified violates the constraints specified in the default order settings. TWS precautionary settings apply to API
orders placed from ALL API technologies.
You can override the precautionary settings by doing one of the following:
In TWS:
l On the Configure menu, select API then All API Settings. Select the Bypass Order Precautions for API Orders
check box, then click OK. All of your API orders will ignore the precautionary settings in TWS.
l In the Order Presets, enter higher precautionary setting limits for the desired instrument types and or tickers. On
the Configure menu, select Order then select Order Presets. Select the instrument type or ticker on the left, enter
the desired limits in the Precautionary Settings section of the page, then click OK.
In the IB Gateway:
l From the Configure menu, select Settings. Select the Bypass Order Precautions for API Orders checkbox and
click OK. All of your API orders will ignore the precautionary settings you had set via a TWS session.
Now, user can place a second order. This order is assigned an Order ID of 2:
In this example, a user initially decides to buy 100 shares and sets the limit price to $85.25. Then, customer wants to
modify the same order and change the limit price to $86.25. Note that the first order is assigned an Order ID of 3:
You can now modify the limit price for this order by calling the same .placeOrder method and using the same Order ID
of 3, with the limit price modified to $86.25
General
l Enable Active X and Socket Clients - Check to enable integration using ActiveX or socket clients including
Java and C++.
l Enable DDE clients - Check to enable integration with TWS with TWS through DDE.
l Download open orders on connection - uncheck if you do not want to download all open orders when you con-
nect to your API.
l Include FX positions when sending portfolio - If you have the Include FX Positions feature activated, all FX pos-
itions will be included when portfolio updates are sent the to API client. Uncheck this box if you don't want FX
positions sent to the API client when the portfolio updates are sent.
l Send status updates for EFP and Volatility orders with "Continuous Update" flag - If you have Continuous
Update activated for EFP or Volatility orders, all updates are sent to the API client by default. Uncheck if you
don't want these updates sent from TWS to the API client.
l Use negative numbers to bind automatic orders - if checked, all orders that are automatically bound to an API
client via the reqOpenOrders or reqAutoOpenOrders calls or via system-generated orders (i.e. volatility hedging
orders) will be assigned negative API order IDs. Otherwise, these orders will be assigned incremental API order
IDs. Volatility hedging orders will have the order ID “parent API order ID + 1” when possible.
l Create API message log file - check to create a message log file. Use the Logging Level selector to define the
level of detail in the log.
l Include market data in API message - shows market data in the API log file.
l Socket port - Enter a socket port number which allows you to access multiple instances of TWS or IB Gateway
running on a single host. By assigning a unique socket port number to each TWS or IB Gateway instance, a
single ActiveX or socket API client will be able to access each of these instances. This does not apply to DDE cli-
ents.
l Logging Level - Set the level of log detail for the API text log. System gives the most general level of logging;
Detail gives the most detailed level. Note that Detail uses more computing resources and may result in a decrease
in performance.
l Master API client ID - The API client with the specified client ID will receive all orders, even those placed by
other API clients. This differs from the Client ID of “0” which will receive all orders sent from the TWS GUI.
l Timeout to send bulk data to API - define the time in seconds that TWS will wait before disconnecting the API
client if data cannot be sent quickly enough.
Trusted IP Addresses
If you connect to the API through a trusted IP address, the connection is not questioned. Otherwise, you will get a veri-
fication message asking if you are sure you want to make the connection.
Note: This procedure is usually only necessary when troubleshooting the most extreme API prob-
lems.
DDE is an acronym for Dynamic Data Exchange, a Microsoft-created communication method that allows multiple applic-
ations that are running simultaneously to exchange data and commands. We use this protocol to link Excel with your run-
ning version of TWS or the IB Gateway, allowing you to view real-time market data (including market depth) manage
orders and monitor your executions and account information using an Excel spreadsheet.
The following figure shows the Tickers page in the Excel DDE API sample spreadsheet.
One of the most common inquiries we receive at Interactive Brokers is how to export data from TWS into Excel. Since
TWS does not have functionality to export intraday, we often direct customers to the TWS API and its Excel worksheets
in particular. You need to be aware that the distributed DDE for Excel API worksheets are not tools to be used on a
daily basis. All of our sample applications are merely demonstrations of the API capabilities aimed at experienced pro-
grammers who will in turn use them as a reference to develop more complex and robust systems.
This document is a brief tutorial that explains how retrieve market data through MS Excel via the TWS DDE for Excel
API. All of the VBA code included in this tutorial is kept to a minimum and is intended to be illustrative.
Interactive Brokers does not offer any programming assistance. We therefore strongly advise interested customers to use
the TWS DDE for Excel API to become familiar with the technologies involved, such as the DDE protocol and VBA.
This tutorial has been developed using Excel 2010 and the 9.72 version of the TWS API components.
Before you continue with this tutorial, you will need to do the following:
1. Download TWS API Version 9.72 from http://interactivebrokers.github.io/, and then install the API.
2. Log into TWS, which must be up and running while you are using the DDE for Excel API. Enable DDE client
connectivity by clicking Edit > Global Configuration > API > Settings, and then check the Enable DDE clients
box as shown below.
3. Open a new, blank spreadsheet in Excel. You do not have to use the DDE for Excel sample spreadsheet for this
tutorial.
You can view market data for multiple products that update in real time within Excel itself. Requests via the DDE for
Excel API are nothing but Excel formulas (DDE data links), each formula serving a very specific purpose. Market Data
retrieval requires at least two different DDE links: one to start the market data subscription and one to receive the spe-
cific tick type.
The formula to start the request must provide TWS with enough information so that TWS can unambiguously identify
which instrument you want. As a first example, we will request FX market data (EUR.USD). Copy and paste the fol-
lowing formula (DDE link) into a cell in your new, blank Excel spreadsheet:
=Ssample123|tik!'id1?req?EUR_CASH_IDEALPRO_USD_~/'
In the example above, sample123 is simply a placeholder for your username. Replace sample 123 with the username you
used to log into TWS. This applies to all subsequent DDE links described in this tutorial.
When you copy the formula into any cell of an Excel spreadsheet, the cell should automatically display 0.
After you have done this, TWS will be aware that a DDE link is requesting EUR.USD data.
Once TWS recognizes our DDE link trying to pull EUR.USD data, we can read it. We are currently interested in know-
ing the bid price of the EUR.USD FX pair. Therefore, we need to use the formula:
=Ssample123|tik!id1?bid
Paste the above formula into the same Excel spreadsheet to see the result:
The value displayed on cell D2 is the exact same value the TWS displays for the EUR.USD bid price and will keep
updating as long as the request is active.
As described in the previous steps of this tutorial, the first formula asks TWS to open a DDE channel through which we
can obtain EUR.USD data, while the second one pulls the bid price for EUR.USD.
The Request
The requesting formula must contain all necessary elements so that TWS can unambiguously identify the desired con-
tract. In this case:
=S[twsuser]|tik!'id[reqestId]?req?[symbol]_[sectype]_[exchange]_[currency]_~/'
Where:
Attribute Description
twsuser The username with which
you logged into TWS.
requestId The request’s unique iden-
tifier (any positive
integer).
symbol The contract’s symbol
(EUR).
sectype The kind of contract
(CASH).
exchange The exchange from which
we want to pull the data
(IDEALPRO).
currency The contract’s currency
(USD).
Example
=Ssample123|tik!'id1?req?EUR_CASH_IDEALPRO_USD_~/'
Once the request is made, the price is received by passing in the exact same ID used in the request formula:
=S[twsuser]|tik!id[requestId]?bid
Where
Attribute Description
twsuser The username with which
you logged into TWS.
requestId The same number used in
the request’s identifier.
Example
=Ssample123|tik!id1?bid
Unfortunately things do not always work as expected. The slightest error in the DDE link or the contract description that
you provide will prevent you from receiving the market data from TWS. The first and most obvious step in solving this
problem is to make sure that your DDE links are correct and contain no spelling errors or typographical errors such as
unwanted spaces or characters.
If the formula is correct but you are still not able to see any data, you can ask the TWS about any errors generated in
response to your request. In most cases, TWS will be able to point us in the right direction.
TWS can only remember the most recent error. This is very important to remember because your Excel spreadsheet will
often have many active requests with multiple possibilities for errors. Be sure that all previous requests are working as
expected before creating a new one. This will help identify any problem.
There are three formulas that you need to use. Enter each formula into its own cell in your Excel worksheet:
Formula Description
=S[twsuser]|err!id Obtains the
failed request’s
unique ID.
=S[twsuser]|err!errorCode The error code.
=S[twsuser]|err!errorMsg The description
of the error.
Let's look at an example. In the following figure, the real time data request formula’s symbol has been intentionally mod-
ified to EUE instead of EUR. We've entered the three error formulas into three separate cells. We will receive an error for
that request (the request ID is 1), along with the error code and description (No security definition has been found for the
request). This error means that the contract for which we are requesting data cannot be found. In other words, the descrip-
tion of the contract in the DDE link is wrong.
Once you know what caused the error, you should clear the error formulas first, and then correct the original DDE link.
When you do this, you will notice that the error formulas will return a 0 value:
Why is it important to first clear the error formula before correcting our request?
We mentioned earlier on that TWS will hold the last available error message of the last failed request. This implies that
TWS will remember that, as in our example, the request identified with id X, has an error associated to it. It is very tempt-
ing to simply correct the typo in our request. However, this will create an “orphan” error in TWS and this "Can't find
EId" error will also be sent to your Excel worksheet, as shown in the following image. This orphan error is basically
TWS saying “I cannot find an error for this request.”
You might think that you can easily ignore this error. Imagine, however, that you have many DDE links in your Excel
worksheet and one of them resulted in a “no security definition has been found” error. Later, another link in your sheet
causes the “Can’t find EId” error to appear. You will only be able to see the last error, which is not really telling you
much about why your Excel worksheet is not working as you expect. While this logic applies to all errors, this last error
can be particularly misleading.
REMEMBER: Be sure that all of your previous requests are working as expected before moving to the next one.
The TWS DDE for Excel API lets you retrieve data for any instrument available in TWS. So far we have been using the
simplest instrument of all: CASH. Using slight variations of the same formula, you can define any security type available
in TWS.
The best way of finding a contract’s description is often in TWS itself. In TWS, you can easily check a contract’s descrip-
tion by right-clicking the contract and then selecting Contract Info > Description. The Contract Description window in
TWS looks like this:
FX Pairs
Formula
=S[twsuser]|tik!'id[reqId]?req?[symbol]_[SecType]_[exchange]_[currency]_~/'
Example
=Ssample123|tik!'id1?req?EUR_CASH_IDEALPRO_USD_~/'
STK
Formula
=S[twsuser]|tik!'id[reqId]?req?[symbol]_[SecType]_[exchange]_[currency]_~/'
Example
=Ssample123|tik!'id2?req?MSFT_STK_SMART_USD_~/'
FUT
Note: For futures, we can use a slight variation on the formula (req2 instead of req1). This allows
us to define FUT contracts using the future contract’s own symbol instead of its underlying
symbol. Using the future’s symbol lets you correctly define the contract without having to
specify its multiplier or its expiration date.
Formula
=S[twsuser]|tik!'id[reqId]?req2?[symbol]_[SecType]_[exchange]_[currency]_~/'
Example
=Ssample123|tik!'id3?req2?ESU5_FUT_GLOBEX_USD_~/'
Formula
=S[twsuser]|tik!'id[reqId]?req?[underlying_symbol]_[SecType]_[expiry]_[multiplier]_[exchange]_[currency]_~_~/'
Example
=Ssample123|tik!'id3?req?ES_FUT_201503_50_GLOBEX_USD_~_~/'
OPT
Formula
=S[twsuser]|tik!'id[reqId]?req?[underlying_symbol]_[SecType]_[expiry]_[strike]_[P/C]_[multiplier]_[exchange]_[currency]
_~_~/'
Example
=Ssample123|tik!'id4?req?DBK_OPT_20160617_28_C_100_DTB_EUR_~_~/'
FOP
Formula
=S[twsuser]|tik!'id[reqId]?req?[underlying_symbol]_[SecType]_[expiry]_[strike]_[P/C]_[multiplier]_[exchange]_[currency]
_~_[tradingClass]/'
Example
=Ssample123|tik!'id5?req?EUR_FOP_20150605_1.33_C_125000_GLOBEX_USD_~_XT/'
IND
Formula
=S[twsuser]|tik!'id[reqId]?req?[symbol]_[SecType]_[exchange]_[currency]_~/'
Example
=Ssample123|tik!'id6?req?ES_IND_GLOBEX_USD_~/'
BAG
Formula
=S[twsuser]|tik!'id[reqId]?req?[symbol]_[SecType]_[exchange]_[currency]_CMBLGS_[num of legs]_[legId]_[legQuantity]
_[legAction]_[legExchange]_[legPrice]...CMBLGS_~/'
Example
=Ssample123|tik!'id7?req?
USD_BAG_SMART_USD_CMBLGS_2_109385219_1_BUY_SMART_0_9408_1_SELL_SMART_0_CMBLGS_~/'
So far we have only shown you how to retrieve the bid price for a contract but many other data values are available.
=S[twsuser]|tik!id[requestId]?bidSize
=S[twsuser]|tik!id[requestId]?bid
=S[twsuser]|tik!id[requestId]?ask
=S[twsuser]|tik!id[requestId]?askSize
=S[twsuser]|tik!id[requestId]?last
=S[twsuser]|tik!id[requestId]?lastSize
=S[twsuser]|tik!id[requestId]?high
=S[twsuser]|tik!id[requestId]?low
=S[twsuser]|tik!id[requestId]?volume
=S[twsuser]|tik!id[requestId]?close
=S[twsuser]|tik!id[requestId]?bidImpliedVol
=S[twsuser]|tik!id[requestId]?bidDelta
=S[twsuser]|tik!id[requestId]?askImpliedVol
=S[twsuser]|tik!id[requestId]?askDelta
=S[twsuser]|tik!id[requestId]?lastImpliedVol
=S[twsuser]|tik!id[requestId]?lastDelta
=S[twsuser]|tik!id[requestId]?modelVolatility
=S[twsuser]|tik!id[requestId]?modelDelta
=S[twsuser]|tik!id[requestId]?modelPrice
=S[twsuser]|tik!id[requestId]?pvDividend
=S[twsuser]|tik!id[requestId]?modelGamma
=S[twsuser]|tik!id[requestId]?modelVega
=S[twsuser]|tik!id[requestId]?modelTheta
=S[twsuser]|tik!id[requestId]?modelUndPrice
This tutorial has been developed using Excel 2010 and the 9.72 version of the TWS API components.
Before you continue with this tutorial, you will need to do the following:
1. Download TWS API Version 9.72 from http://interactivebrokers.github.io/, and then install the API.
2. Log into TWS, which must be up and running while you are using the DDE for Excel API. Enable DDE client
connectivity by clicking Edit > Global Configuration > API > Settings, and then check the Enable DDE clients
box as shown below.
3. Open a new, blank spreadsheet in Excel. You do not have to use the DDE for Excel sample spreadsheet for this
tutorial.
Just as with real time data, historical data requests need first to ask the TWS to “prepare” the data we are interested in.
The TWS needs to know not only the specific instrument but also:
l The ending date and time from which we want to collect the data, formatted as:
o yyyymmdd hh:mm:ss
l The time duration comprising the data from the ending date going back in time.
l The bar size (IB provides historical data in open, high, low and close bar data format).
l The type of data (i.e. MIDPOINT, TRADES, etc.).
l Whether we want data generated during regular trading session or not.
l The date format in which each bar’s time and date will be presented.
=[twsuser]|hist!'id[requestId]?req?[symbol]_[type]_[exchange]_[currency]_~/[yyyymmdd]singleSpace[HH]singleColon
[mm]singleColon[ss]_[duration amount]singleSpace[duration unit]_[bar size]_[rth only?]_[what to show]_[date
format]'
Attribute Description
twsuser The username with which
you logged into TWS.
requestId The request’s unique iden-
tifier (any positive
integer).
symbol The instrument’s symbol.
type The type of instrument.
exchange The instrument’s
exchange.
currency The instrument’s currency
(USD).
Yyyymmdd HH:mm:ss End date for the historical
data query.
duration amount The number of time units
for the duration time.
duration unit The duration's time unit.
bar size The bar size.
rth only Set to 1 to obtain only
data generated during reg-
ular trading hours (RTH),
or set to 0 to get all data
generated during and out-
side of of RTH.
what to show The type of data:
MIDPOINT, TRADES,
BID, ASK, etc.
data format Set to 1 to format the res-
ulting bars’ date as
yyyymmss hh:mm:ss. Set
to 2 to express the res-
ulting bars’ time as the
number of seconds since
1970.
Our DDE links cannot contain certain special characters such as spaces or colons, but you will need to use these char-
acters in your DDE formula. To overcome this limitation, we have provided keywords that you can use in place of the
actual special character: singleSpace and singleColon. For example, if you want to specify an end date and time such as
March 2, 2015 at 23:59:59 in the format specified above, you would then enter:
20150302 23:59:59
20150302singleSpace23singleColon59singleColon59
This applies to all cases in which you need spaces or colons in the DDE formula. This is particularly important when
describing futures or options contracts because you can then use their local symbols, which often include spaces. For
example, the DBK futures contract expiring on May 2015 has a local symbol DBKG MAY 15 which you would provide
as:
DBKGsingleSpaceMAYsingleSpace15
Let's continue with our historical data request. As an example, try to pull MIDPOINT historical data for the EUR.USD
currency pair prior to February 27th 2015 at 23:59:59 in thirty minutes bars (9), for a duration of one day (1 D). The cor-
rect formula for this request is:
=Ssample123|hist!'id4?req?EUR_CASH_IDEALPRO_USD_~/20150227singleSpace23singleColon59singleColon59_
1singleSpaceD_9_MIDPOINT_1_1'
Copy the above formula into an empty cell in your Excel worksheet. Notice that the cell displays PROCESSING, which,
if everything proceeds without error, will change into RECEIVED”:
At this point, you have just told TWS that you want our EUR.USD historical data and TWS replied that the data has
been received from the server and is ready to be viewed.
This is where the process becomes slightly complicated because, unlike real time market data, where each incoming price
is obtained using a very specific formula, you will not fetch each bar one by one with a formula (this is quite fortunate
since we could be expecting hundreds of bars!). Instead, you will read all the bars together using a single DDE request
and then display them in your worksheet with the help of some VBA code. For purposes of simplicity, we will keep the
coding to minimum.
In the next steps, we will briefly describe how to add a button to a spreadsheet for the sake of completeness but remem-
ber that it is out of the scope of IB's support to provide any assistance on using Excel.
In this step, you will add a button to your blank worksheet which, once the TWS has replied to your historical data
request with the “RECEIVED” status, will help you manually invoke the VBA routines which pull the historical data
from TWS.
First, open the Developer tab in Excel and click on the Button form control:
Next, click anywhere in your spreadsheet to place the button. The Assign Macro dialog opens; this is where you asso-
ciate a VBA macro with your button. Name your function fetchHistoricalData and then click the New button in the dia-
log.
Excel automatically opens the VBA editor, which displays the skeleton of the newly-created macro.
In the next step, you will add the code to the macro you just created.
Here are the routines which will finally obtain the data from the TWS:
Sub fetchHistoricalData()
'This variable will store the incoming data
l The DDE server name, which is your TWS username prefixed with a capital S
l The DDE “topic” for historical data: “hist”
l A third parameter which is just the remaining fragment of the DDE link: id[requestId]?result
The third parameter contains the request ID you used in the requesting formula (4). Remember this same procedure from
the previous tutorial when you requested real time data. Your request/retrieve formulas both need to include the exact
same ID.
If you correctly entered the code into your macro in the VBA editor as shown above, your Excel worksheet should look
very similar to the image below. (Note that we have changed the button label to Historical from its default value).
Just after the data is retrieved from TWS, the requesting formula will change its output to FINISHED.
It is very important for to wait until the request formula’s output changes from PROCESSING to RECEIVED before you
try to pull the actual data from TWS. If the cell displays PROCESSING for too long, then it is very likely there was an
error in your request. If this happens, make use of the error retrieval formulas explained in the Market Data tutorial.
In the example in the previous step, you pulled midpoint historical data for EUR.USD from TWS.
Most of the formula’s components are self-explanatory with the exception of duration and bar sizes, which require very
specific codes (shown below), and the What to Show parameter, which can be MIDPOINT, TRADES, BID, ASK, BID_
ASK, HISTORICAL_VOLATILITY or OPTION_IMPLIED_VOLATILITY.
Duration
Bar Sizes
For your reference, we've included examples of historical data request formulas for a variety of different contract types.
Stocks
Yahoo MIDPOINT data, all available trading hours, 300 seconds in 30 seconds bars ending on August 1, 2014 at
23:59:59 with date expressed in milliseconds.
=Ssample123|hist!'id3?req?YHOO_STK_ISLAND_USD_~/20140801singleSpace23singleColon59singleColon59_
300singleSpaceS_4_MIDPOINT_0_2'
Futures
Swiss Market Index (SMI) September 2015 Future (local symbol FSMI SEP 15) Bid/Ask combined data, all available trad-
ing hours, two days in 30 minutes bars ending on February 27, 2015.
=Ssample123|hist!'id5?req2?FSMIsingleSpaceSEPsingleSpace15_FUT_SOFFEX_CHF_
~/20150227singleSpace23singleColon59singleColon59_2singleSpaceD_9_BID_ASK_1_1'
30 years Treasury bond expiring March 2015 (local symbol ZB SEP 15 – note the three spaces between ZB and SEP),
data generated only during regular trading hours, TRADES data for 1 month in day bars.
=Ssample123|hist!'id6?req2?ZBsingleSpacesingleSpacesingleSpaceSEPsingleSpace15_FUT_ECBOT_USD_
~/20150227singleSpace23singleColon59singleColon59_1singleSpaceM_11_ASK_0_1'
Options
Deutsche Bank CALL option expiring June 17, 2016 midpoint data in day bars during one month.
=Ssample123|hist!'id1?req?DBK_OPT_20160617_28_C_100_DTB_EUR_~_~/20150227singleSpace23singleCo-
lon59singleColon59_1singleSpaceM_11_MIDPOINT_1_1'
Interactive Brokers PUT option expiring September 18, 2015 one week of Bid/Ask combined data in hourly bars.
=Ssample123|hist!'id2?req?IBKR_OPT_20150918_32_P_100_SMART_USD_~_~/20150227singleSpace23singleCo-
lon59singleColon59_1singleSpaceW_10_BID_ASK_1_1'
Futures on Options
=Ssample123|hist!'id9?req?EUR_FOP_20150508_1.2_C_125000_GLOBEX_USD_~_
6E/20150227singleSpace23singleColon59singleColon59_1singleSpaceM_10_TRADES_1_1'
The sample spreadsheet currently comprises several pages complete with sample data and action buttons that make it
easy for you to get market data, send orders and view your activity.
Note: Windows users can download the beta test version of the API by using the Windows
Beta column, or revert to the previous production version by selecting Downgrade to Pre-
vious Version.
6. Save the installation program to your computer, and if desired, select a different directory. Click Save. Note that
the API installation file is named for the API version; for example, TWS API 9.70.
7. Close any versions of TWS, the IB Gateway and Excel that you have running.
8. Locate the API installation program you just saved to your computer, then double-click the file to begin the API
installation.
9. Follow the instructions in the installation wizard. By default, the sample DDE spreadsheet is located in the
samples\Excel folder in your API installation folder.
Note: Before you can use the spreadsheet, you must have TWS running and configured to support
the DDE API. You can also run the sample against the IB Gateway but we recommend you
start by running TWS.
To configure the application to support accessing its functionality via the API
1. On the Edit menu select Global Configuration.
2. Click API in the left pane, and select Settings.
3. On the right panel, check Enable DDE clients to enable integration with TWS with TWS through DDE. Down-
load sample programs from the Software page on the IB website.
4. Set the rest of the API parameters as required. For details, see Trader Workstation API Settings.
Note: Not more than one API application can simultaneously access a single instance. With the
exception of DDE, the API application does not need to be running on the same computer
on which the application is running.
In Microsoft Excel 2007, click the Microsoft Office Button, click Excel Options, and then
click Trust Center in the Excel Options window. In the Trust Center, click Macro Settings,
then change your settings as required.
In previous versions of Excel, select Macro from the Tools menu, and then select Security.
Set security to Medium or Low.
3. In the User Name field in the Which Trader Workstation? area, type your account user name. Note that you must
type your User Name on each page of the worksheet to properly connect.
We recommend using this spreadsheet as the starting point for your API application. This means that when new features
are added, you will need to cut and paste your information from your Excel spreadsheet to the newly released sample
spreadsheet, then save the application under a different filename.
Page Description
Tickers Lets you set up your ticker lines and request market data. You can
view market data for all asset types including EFPs and combination
orders.
Basic Orders Lets you send and modify orders, and set up combination orders and
EFPs.
Extended Order Attrib- Used in conjunction with the Basic Orders, Advanced Orders, Condi-
utes tional Orders and Advisors pages, this page lets you change the time
in force, create Hidden or Iceberg orders and apply many other order
attributes.
Conditional Orders Lets you create an order whose submission is contingent on other con-
ditions being met, for example an order based on a prior fill.
Open Orders Shows you transmitted orders that are still working, including those
that have been accepted by the IB system, and those that are working
at an exchange.
Advanced Orders Lets you send and modify advanced orders types that require the use
of extended order attributes, such as Bracket, Scale and Trailing Stop
Limit orders.
Executions Lets you view all execution reports, and includes a filtering box so
you can limit your results.
Executions Reporting Linked to the Executions page, this page lets you run four different
types of execution reports.
Account Provides up to date account information.
Bond Contract Details Lets you collect bond contract-specific information you will need for
other actions, including bond coupon and maturity date.
Market Depth Lets you view market depth for selected quotes.
Advisors Lets Financial Advisors send and modify FA orders.
Note: Two additional pages, Old Style Executions and Old Style Account-Portfolio, represent func-
tionality that has been replaced by other pages in the spreadsheet (Executions, Account and
Portfolio pages). While these older pages are still included in the TswDde.xls sample spread-
sheet, they are no longer documented in this API Users’ Guide and you should not use
them.
Tickers Page
For stocks, you only need to specify the Symbol, Type, Exchange (usually SMART), and Currency.
The Exchange field accepts the following values: SMART (for smart order routing), and any valid exchange acronym.
TWS market data updates every 300 milliseconds by default, so setting the refresh rate to 250 will get every tick to the
spreadsheet.
The server processing rate affects the speed at which the DDE handles requests between TWS and the spreadsheet.
Clicking this button cancels all market data, historical data, market scanner subscriptions, and other data requests. If you
add your own links to existing or new pages, update the clearAllLinks macro to clear those links as well. Each page in
the spreadsheet contains its own clearLinks macro; these are all called by the clearAllLinks macro.
Button Description
Create Ticker Opens the Ticker box. Enter information to create a market data
line.
Combo Legs Opens the Combination Legs box. Enter contract details to cre-
ate legs of a combination order one by one.
Request Market Data Select a line and click to get market data for the selected con-
tract.
Set Refresh Rate The Refresh Rate value is in milliseconds, and determines how
often the DDE link to TWS is refreshed. The default refresh
rate is 1000 (updates every 1 second), and the allowed range
is 100ms to 2000ms, inclusive.
Note that the TWS market data updates every 300 mil-
liseconds. This means the default "every 1 second" rate will
only show 30% of the ticks. A Refresh Rate of 250 will get
every tick to the spreadsheet.
Set Processing Rate Set the TWS/DDE server message processing rate (also in mil-
liseconds) to affect the speed at which DDE will handle
requests between the spreadsheet and TWS. The allowed range
is 100ms to 2000ms, inclusive.
Button Description
Set Log Level This specifies the level of log entry detail used when pro-
cessing API requests. Valid values include:
1 = SYSTEM
2 = ERROR
3 = WARNING
4 = INFORMATION
5 = DETAIL
Show Errors Jumps to the Error Code field and shows the most recent error
code.
Show Bulletins Opens the News Bulletins message. If you subscribe to bul-
letins, news will appear in the RED box in the upper right
corner of the spreadsheet.
Clear All Links Clears all DDE links to the TWS.
l Create an order.
l Create a "basket" of orders.
l Modify and cancel orders.
l Create combination orders.
Placing Orders
This topic describes how to place the following types of orders on the Orders page:
l Simple orders
l Basket orders
l Modified orders
Note: Ensure that TWS is running, and that you have entered your user name in the User
Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet
to properly connect to TWS.
To place an order
1. Click the Basic Orders tab at the bottom of the spreadsheet.
2. Define a contract by typing a symbol in a blank Symbol field, then entering information in the relevant contract
description fields.
3. Select a contract and set up the order using the Order Description fields.
You must define the Action (Buy, Sell or Short Sell), Quantity, Order Type, Limit Price (unless it's a market order)
and if necessary, the Aux. Price for order types that require it.
4. If desired, apply extended order attributes by clicking the Apply Extended Template button on the toolbar. This
applies all attributes you have defined on the Extended Order Attributes page.
5. Click the Place/Modify Order button in the Toolbar section of the page.
2. Click the Basic Orders tab to build the combo leg definitions. Click the Combo Legs button on the Basic
Orders page toolbar and enter leg information. Your leg information is translated into the format:
[CMBLGS]_[NumOfLegs]_[Combo Leg Definitions]_[CMBLGS]
where:
o [CMBLGS] is the delimiter used to identify the start and end of the leg definitions
o [NumOfLegs] is the number of leg definitions
o [Combo Leg Definitions] defines N leg definitions, and each leg definition consists of [conid]_[ratio]_[action]_
[exchange]_[openClose], so the resulting combo substring looks as follows:
CMBLGS_2_17496957_1_BUY_EMPTY_0_15910089_1_SELL_EMPTY_0_CMBLGS
3. The combination leg definitions must occur before the extended order attributes. The full place order DDE request
string will look like this:
=acctName|ord!id12345?place?BUY_1_XYZ_BAG_ISE_LMT_1_CMBLGS_2_12345678_1_BUY_EMPTY_0_
12345679_1_SELL_EMPTY_0_CMBLGS_DAY_EMPTY_0_O_0_EMPTY_0_EMPTY_0_0_0EMPTY_0_0
If the order legs do not constitute a valid combination, one of the following errors will be returned:
o 312 = The combo details are invalid.
o 313 = The combo details for '<leg number>' are invalid.
o 314 = Security type 'BAG' requires combo leg details.
o 315 = Stock combo legs are restricted to SMART exchange.
Note: 1. The exchange for the leg definition must match that of the combination order. The excep-
tion is for a STK leg definition, which must specify the SMART exchange.
2. The openClose leg definition value is always 'SAME' (i.e.0) for retail accounts. For insti-
tutional accounts, the value may be any of the following: (SAME, OPEN, CLOSE).
l Limit (LMT)
l Market (MKT)
l Limit if Touched (LIT)
l Market if Touched (MIT)
l Market on Close (MOC)
l Limit on Close (LOC)
l Pegged to Market (PEGMKT)
l Relative (REL)
l Stop (STP)
l Stop Limit (STPLMT)
l Trailing Stop (TRAIL)
l Trailing Stop Limit (TRAILLIMIT)
l Volume-Weighted Average Price (VWAP)
l Volatility orders (VOL)
Button Description
Combo Legs Opens the Combination Legs box. Enter contract details to cre-
ate legs of a combination order one by one.
Place/Modify Orders After you have completed the Order Description fields, and
defined any extended attributes, click to create an order for the
selected contract.
Cancel Order This button cancels the order(s) you have highlighted.
Apply Extended Template Applies the current values on the Extended Order Attributes
page to the highlighted order row.
Show Errors Jumps to the Error Code field and shows the error code.
The Extended Order Attributes page includes all of the optional attributes you can use when you send an order, such as
setting a display size to create an iceberg order, adding orders to an OCA group, and setting the transmit date for a Good
After Time order. Once you define the attributes on this page, you can apply them to a single order or selected group of
orders using the Apply Extended Template button, which occurs on both the Orders page and the Conditional Orders
page. The attributes populate the extended order attributes fields that follow the Order Status fields to the far right of the
page.
l When appended to orderDescription, the number and order of attributes cannot be changed.
l For any attribute that is not defined, use the value 'EMPTY' or {}. Since a string length is limited to 255 char-
acters, we recommend using the open/close curly braces {}.
l A place order message for a simple stock limit day order looks as follows, with the primary exchange "Supersoes"
separating the extended attributes:
=psmith12|ord!'id1814454745?place?BUY_1_MSFT_STK_SMART_USD_LMT_26_{}_DAY_{}_{}_O_0_{}_1_
{}_0_0_0_0_0_0_{}_{}_{}_{}_{}_{}_{}_{}_SUPERSOES_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}
_{}_1_2_3_4_5'
Note: You can also use this procedure to apply extended order attributes to orders on the Condi-
tional Orders page.
When you place the order or group of orders, the extended order attribute values you entered are applied to the
order.
For example, you might want to assign a unique Order Ref number to a group or basket of orders. To do this, you
would enter the number for the Order Ref attribute on the Extended Order Attributes page, then select all the
orders in the group on the Orders page and click Apply Extended Template.
4. Delete the value of the extended order attributes you used for the order from the Extended Order Attributes page.
These values will still apply to all subsequent orders that you place from the DDE for Excel API spreadsheet
unless you remove the value.
This parameter can be useful for example when working with basket orders.
First, prepare a basket of orders (untransmitted), then when ready, set the
value of the transmit parameter of each order to 1 to transmit the basket for
execution.
parentId String (the order ID used for the parent order, use for bracket and auto trail-
ing stop orders)
blockOrder 0 (not a block order)
1 (this is a block order)
sweepToFill 0 (not a sweep-to-fill order)
1 (this is a sweep-to-fill order)
displaySize Publicly disclosed order size for iceberg orders. The value is a number that
should be stored as a String.
triggerMethod Specifies how simulated Stop, Stop-Limit, and Trailing Stop orders are
triggered:
l O - the default value. The "double bid/ask" method will be used for
orders for OTC stocks and US options. All other orders will use the
"last" method.
l 1 - use "double bid/ask" method, where stop orders are triggered
based on two consecutive bid or ask prices.
l 2 - "last" method, where stop orders are triggered based on the last
price.
l 3 - "double-last" method, where stop orders are triggered based on
last two prices.
l 4 – “bid-ask” method. For a buy order, a single occurrence of the
bid price must be at or above the trigger price. For a sell order, a
single occurrence of the ask price must be at or below the trigger
price.
l 7 – “last-or-bid-ask” method. For a buy order, a single bid price or
the last price must be at or above the trigger price. For a sell order, a
single ask price or the last price must be at or below the trigger
price.
l 8 – “mid-point” method, where the midpoint must be at or above
(for a buy) or at or below (for a sell) the trigger price, and the spread
between the bid and ask must be less than 0.1% of the midpoint.
For a complete description of Trigger Methods, see Modify the Trigger
Method in the Trader Workstation Users' Guide.
Discretionary Amount Used in conjunction with a limit order to give the order a greater price
(SMART Routing) range over which to execute.
Good After Time Enter the date and time after which the order will become active. Use the
format YYYYMMDD hh:mm:ss TMZ, where TMZ is optional three-letter
time zone identifier. Allowed timezones are listed here.
Good 'Till Date The order continues working until the close of market on the date you
enter. Use the format YYYYMMDD. To specify a time of day to close the
order, enter the time using the format HH:MM:SS. Specify the time zone
using a valid three-letter acronym.
FA Group For Advisor accounts only. The name of the Financial Advisor group to
which the trade will be allocated to. Use an empty String if not applicable.
FA Method For Advisor accounts only. The share allocation method.
l EqualQuantity
l NetLiq
l AvailableEquity
l PctChange
FA Percentage For Advisor accounts only. The share allocation percentage.
FA Profile For Advisor accounts only. The name of the Share Allocation profile.
Short Sale Slot For institutions only. Valid values are 1 (broker holds shares) and 2 (shares
come from elsewhere).
Short Sale Location Institutional accounts only. Indicates the location where the shares to short
should originate.
Used only when Short Sale Slot is set to 2 (which means that the shares to
short are held elsewhere and not with Interactive Brokers).
0 = false
1 = true
Minimum Qty Identifies the order as a minimum quantity order.
Percent Offset The percent offset for relative orders.
Electronic Trade Only Indicates whether to exclude exchanges whose quotes are not automatically
executable. If this option is selected, IB will use its best efforts to determine
which exchanges' quotes are immediately automatically executable, and
which exchanges' quotes would require manual (human) handling, and IB
will route only to those exchanges offering automatic execution. Please
note that while IB will use its best efforts, it is not always possible to
determine whether quote is automatically executable.
0 = false
1 = true
Firm Quote Only 0 = false
1 = true
Continuous Update For volatility orders only. Indicates whether the price should be auto-
matically updated as the underlying stock price moves.
0 = false
1 = true
Hedge Delta Aux Price Enter the Aux Price for Hedge Delta order types that require one.
Trail Stop Price Used for Trailing Stop Limit orders only. This is the stop trigger price for
TRAILLMT orders.
Scale Component Size Used for Scale orders only, this value defines the order size of the each
order component.
Outside RTH Indicates whether the order should be allowed to execute outside of reg-
ular trading hours of the trading venue where the contract is listed.
0 = false
1 = true
Use the Conditional Orders page to create an order whose submission is contingent on other conditions being met, for
example, an order based on a prior fill or a change in the bid or ask price. To see the Condition Statement fields, use the
scroll bar on the bottom of the page to scroll to the right.
2. In the Condition Statements area, use the Statement field to set the criteria which must be met to trigger the order.
When the Statement = TRUE, your order will be submitted.
The sample spreadsheet includes a pair of orders, with the second orders transmission depending on the first order
being completely filled. In this case, the Statement field trigger is that the value in cell T10 (the Filled field) must
be equal to the value in M10 (the order Quantity field).
3. Type ADD in the ADD/MOD field because you are creating a one-time order.
4. Define the remaining order parameters just as you did in the Order Description area.
5. Complete the necessary fields on the Conditional Orders page according to the syntax in the following table.
Field Description
Statement An Excel function which returns a true or false. When true, the order will be
submitted; when false, nothing happens.
ADD/MOD Use ADD for a one-time order. Use MOD to continue checking and modi-
fying the order until it is completely filled. This is the field that activates a
conditional order, and orders will be activated only with the "ADD" or
"MOD" tags.
If you use ADD, leave the Order Description fields blank because once the
condition is TRUE, the Order Description fields will be overwritten.
Action BUY
SELL
Quantity Enter the quantity of the order.
Order Type Refer to list of supported order types.
Lmt Price The limit price for Limit and Stop Limit order types.
Field Description
Aux. Price The stop-election price for Stop and Stop Limit order types, or the offset for
relative orders.
All of the fields described above may be variables that depend on other cells, so any type of conditional order may be
created.
If-Filled order
An if-filled order is an order that executes if a prior order executes. To create an if-filled order with the condition "If a
Buy order fully executes, enter a sell limit order at a price of $50.00":
Field Value
Statement Filled cell = 100
ADD/MOD ADD
Action SELL
Quantity 100
Order Type LMT
Lmt Price 50
Aux. Price empty
Price-change order
A price-change order will be triggered if a specific bid or ask price is greater than, less than or equal to a specific price.
To create a price change order with the condition "If the bid price drops below 81.20, submit a buy limit order for 200
shares with a limit price of $81.10:
Field Value
Statement On the Tickers page, put your cursor in the bid price field
you want to use, then copy the value that appears in the for-
mula bar (“=” entry field) at the top of the spreadsheet. This
value looks something like this:
=username|tik!id4?bid
where "4" identifies the bid price for a specific contract.
Paste this in the formula bar ("=" entry field) for the State-
ment, and add your qualifier, "=" ">" or "<" followed by the
price. In this example, the formula would be:
=username|tik!id4?bid<81.20
ADD/MOD ADD
Action BUY
Field Value
Quantity 200
Order Type LMT
Lmt Price 81.10
Aux. Price Not used in this example.
Button Description
Combo Legs Opens the Combination Legs box. Enter contract details to cre-
ate legs of a combination order one by one.
Place/Modify Order After you have completed the Order Description fields, and
defined any extended attributes, click to create an order for the
selected contract.
Apply Extended Template Applies all attributes on the Extended Order Attributes page to
the selected order(s).
Cancel Order This button cancels the order(s) you have highlighted.
Show Errors Jumps to the Error Code field and shows the error code.
Use the Advanced Orders page to create complex orders that require the use of extended order attributes, including:
l Bracket orders
l VOL orders
l Trailing Stop Limit Orders
l Scale Orders
l Relative Orders
For more information about using extended order attributes for individual orders or groups of orders, see Apply Extended
Order Attributes to Individual Orders and Groups of Orders
3. Click the Advanced Orders tab, highlight the first order in the bracket order, then click the Place/Modify Order
button.
The order is not executed, but the system generates an Order ID.
4. Copy the Order ID for the first order, omitting the “id” prefix, then click the Extended Order Attributes tab and
paste the Order ID into the Value field for Parent Order Id (row 14). This value will be applied to all subsequent
orders until you remove it from the Extended Order Attributes page.
The first order of the bracket order is now the primary order.
5. Click the Advanced Orders tab, highlight the second order, then click the Place/Modify Order button.
The order is not executed but is now associated with the primary order by means of the Parent Order Id extended
order attribute.
6. Click the Extended Order Attributes tab and change the value for Transmit back to 1 (row 13).
7. Click the Advanced Orders tab, highlight the third order in the bracket order, then click the Place/Modify Order
button. The entire bracket order is transmitted.
8. When you are done placing your bracket order, go to the Extended Order Attributes page and delete the Parent
Order Id value you entered. If you do not, this value will be applied to all subsequent orders that you place in the
spreadsheet.
l Volatility
l Volatility Type
l Reference Price Type
l Continuous Update
l Underlying Range (Low) - optional
l Underlying Range (High) - optional
l Hedge Delta Order Type - optional
l Hedge Delta Aux Price - optional
l trailing amount
l stop price
l limit price
l limit offset
In the DDE for Excel API spreadsheet, you enter the trailing amount, stop price and limit price. There is no field or exten-
ded order attribute for the limit offset value. You must include the limit offset in the stop price (the Trail Stop Price
extended order attribute).
3. On the Advanced Orders page, select the order row and click the Apply Extended Template button. The scale
order values are applied to the selected order and displayed in the Extended Order Attributes section of the page.
4. Click the Place/Modify Order button.
5. When you are done placing your order, go to the Extended Order Attributes page and delete the scale order val-
ues you entered. If you do not, these values will be applied to all subsequent orders that you place in the spread-
sheet.
Button Description
Combo Legs Opens the Combination Legs box. Enter contract details to cre-
ate legs of a combination order one by one.
Place/Modify Orders After you have completed the Order Description fields, and
defined any extended attributes, click to create an order for the
selected contract.
Cancel Order This button cancels the order(s) you have highlighted.
Apply Extended Template Applies the current values on the Extended Order Attributes
page to the highlighted order row.
Show Errors Jumps to the Error Code field and shows the error code.
The Open Orders page shows you all transmitted orders, including those that have been accepted by the IB system, and
those that are working at an exchange. Once you have subscribed, the page is updated each time you submit a new order,
Once an order executes, it remains on the Open Orders page for 30 seconds, with the Status value changed to FILLED.
Then the filled order is cleared and you can see it on the Executions page if you subscribed to real-time executions.
Button Description
Subscribe to Open Orders Once you enter a valid user name, clicking this button queries
TWS and returns all open orders. Once you subscribe to open
orders, this page updates each time there is a new open order.
Cancel Open Orders Sub- Cancels the open orders subscription. The page will no longer
scription show your open orders.
Clear Open Orders Removes all open orders from the page.
Show Errors Jumps to the Error Code field and shows the error code.
Executions Page
When you subscribe to executions, the Executions page displays information about all completed trades (also called “exe-
cution reports”).
Viewing Executions
Note: Ensure that TWS is running, and that you have entered your user name in the User
Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet
to properly connect to TWS.
To view executions
1. Click the Executions tab at the bottom of the spreadsheet.
2. Click the Subscribe to Executions button in the toolbar.
Button Description
Subscribe to Executions After you have entered a valid user name, this button queries
TWS and returns information about all valid executions. After
you subscribe to executions, this page updates each time an
order executes.
Cancel Executions Sub- Click to cancel the execution subscription.
scription
Clear Executions Removes all execution reports from the page.
Show Errors Jumps to the Error Code field and shows the error code.
Once you have subscribed to executions on the Executions page, you can use the Executions Reporting page to run
reports based on an Order ID, Order Reference number, VOL order key, or strategy
From a programming point of view, the Executions Reporting page is a practical example of how you can extract array
subscription data from the named ranges into which the data is put when it is received, and how such data can be used in
your own custom DDE for Excel API applications.
Account Page
l View account details including your current Equity with Loan Value and Available funds.
l View list of advisor-managed account codes.
l View your current portfolio.
Button Description
Subscribe to Account Each click gives you data for a specific account value. All
Updates blank lines that precede the Account Portfolio section will hold
data. Continue to click until all lines are populated.
Cancel Account Sub- Click this button one time for each position you hold. When
scription you get a line of "0's" you know you have downloaded all cur-
rent positions. These values continue to update in real-time.
Clear Account Data Clears all information from the page. You must first cancel your
subscription before you can clear the data.
Request Managed For advisor accounts, click this button one time for each
Accounts account.
Show Errors Jumps to the Error Code field and shows the error code.
Day Trades Remaining The number of day trades you have left for a
T+1, T+2, T+3, T+4 4-day pattern day-trader.
Margin Account:
Total cash value + stock value + bond value
+ (non-U.S. & Canada securities options
value)
For Commodities:
Cash Account: Total cash value + com-
modities option value - futures maintenance
margin requirement + minimum (0, futures
PNL)
Margin Account:
Total cash value + commodities option value
- futures maintenance margin requirement
Excess Liquidity Equity with Loan Value - Maintenance mar-
gin
Exchange Rate The exchange rate of the currency to your
base currency.
For commodities:
Net Liquidation Value - Initial margin
For Commodities:
Net Liquidation value - Initial margin
Look Ahead Available For Securities:
Funds Equity with loan value - look ahead initial
margin.
For Commodities:
Net Liquidation value - look ahead initial
margin.
Look Ahead Excess Equity with loan value - look ahead main-
Liquidity tenance margin.
Look Ahead Init Mar- Initial margin requirement as of next period's
gin Req margin change in the base currency of the
account.
Look Ahead Maint Maintenance margin requirement as of next
Margin Req period's margin change in the base currency
of the account.
Maint Margin Req Maintenance margin requirement in the base
currency of the account.
For Commodities:
Total cash value + commodities options value
For Commodities:
Cash Account : Total cash value + com-
modities option value - futures maintenance
margin requirement + minimum (0, futures
PNL)
Margin Account : Total cash value - futures
maintenance margin requirement
Portfolio Page
The Portfolio page displays all of your current positions. This page communicates with TWS and updates the values
every three minutes, which you can see in the Last Update Time field in the Which Trader Workstation? area of the
page.
Button Description
Subscribe to Portfolio Click to view all current portfolio data.
Updates
Button Description
Cancel Portfolio Sub- Cancels the connection to TWS that updates your portfolio
scription information.
Clear Portfolio Data Removes all data from the page. You must cancel your sub-
scription before you can clear all data.
Show Errors Jumps to the Error Code field and shows the error code.
Use the Historical Data page to request historical data for an instrument based on data you enter in query fields. The
query results display on a separate worksheet page and creates a new page for the results if the page doesn't currently
exist. Note that since the query returns in a named range of cells, you can write VBA macros to perform computations on
it, and you can chart and sort the data in Excel.
Note: For information about historical data request limitations, see Historical Data Limitations.
Button Description
Create Ticker Opens the Ticker box. Enter information to create a market data
line.
Combo Legs Opens the Combination Legs box. Enter contract details to cre-
ate legs of a combination order one by one.
Request Historical Data Submits your historical data query to TWS and displays the res-
ults on a separate worksheet page.
Parameter Description
End Date/Time Use the format yyyymmdd {space}hh:mm:ss{space}tmz where the time zone
is allowed (optionally)after a space at the end.
Duration This is the time span the request will cover, and is specified using the
format integer {space} unit, where valid units are:
l S (seconds)
l D (days)
l W (weeks)
l Y (years)
This unit is currently limited to one. If no unit is specified, seconds are used.
Bar Size Specifies the size of the bars that will be returned. The following bar sizes
may be used, and are specified using the parametric value:
Parameter Description
What to Show Determines the nature of the data extracted. Valid values include:
l TRADES
l MIDPOINT
l BID
l ASK
l BID_ASK
l HISTORICAL_VOLATILITY
l OPTION_IMPLIED_VOLATILITY
All but the Bid/Ask data contain the start time, open, high, low, close,
volume and weighted average price during the time slice queried.
For the Bid/Ask query, the open and close values are the time-weighted aver-
age bid and the time-weighted average offer, respectively. These bars are
identical to the TWS charts' candlestick bars.
l 0 - all data available during the time span requested is returned, includ-
ing time intervals when the market in question was outside of regular
trading hours.
l 1 - only data within the regular trading hours for the product reques-
ted is returned, even if the time span falls partially or completely out-
side.
For a request with a duration of 300 seconds and a bar of one second, the query return looks like this (the scroll bar on
the right side of the page allows you to scroll down and see all 300 bars).
Note that the new page is added to the right of the existing tabs on the worksheet.
Use the Market Scanner page to subscribe to TWS market scanners. These scanners allow you to define criteria and set fil-
ters that return the top x number of underlyings which meet all scan criteria. The scan is continually updated in real time.
Setting these field to TRUE forces the scan results page to pop to the front of your application every time it
updates. To stop this behavior, set the value of this field to FALSE.
c. Type values for the rest of the scan parameters in the lightly shaded section of the page.
3. Click the Start Scanner Subscription button in the toolbar. A new page for the scanner is created and is dis-
played after the subscription is processed.
Parameter Description
Page name The name that will be given to the new page that is created
with the scanner data.
Activate Page? If set to true, the new scanner page will display on top of the
worksheet every time the scan results update. This could be as
often as every minute.
Scan Code The type of scan.
Instrument The instrument type used in the scan.
Location code The market used (i.e. US Stocks) for the scan.
Stock type filter Allows you to specify just stocks, just ETFs, or both.
Number of rows The number of rows of data to return in the results.
Price Above Filters out returns with prices below the named price. Can be
left empty.
Price Below Filters out returns with prices above the named price. Can be
left empty.
Average volume above Filters out returns with an average volume below the named
price. Can be left empty.
Average Option Volume Filters out returns with an average option volume below the
Above named price. Can be left empty.
Market Cap Above Filters out returns with a market capitalization value below the
named price. Can be left empty.
Market Cap Below Filters out returns with a market capitalization value above the
named price. Can be left empty.
Moody Rating Above Filters out returns with a Moody rating below the named price.
Can be left empty.
Moody Rating Below Filters out returns with a Moody rating above the named price.
Can be left empty.
S & P Rating Above Filters out returns with an S&P rating below the named price.
Can be left empty.
S & P Rating Below Filters out returns with an S&P rating above the named price.
Can be left empty.
Maturity Date Above Filters out returns with a maturity date below the named price.
Can be left empty.
Parameter Description
Maturity Date Below Filters out returns with a maturity date above the named price.
Can be left empty.
Coupon Rate Above Filters out returns with a coupon rate below the named price.
Can be left empty.
Coupon Rate Below Filters out returns with a coupon rate above the named price.
Can be left empty.
Exclude Convertible Filters out convertible bonds. Can be left empty.
Scanner Settings Pairs For example "Annual/True" used on the Top Option Implied
Vol% Gainers would instruct the scan to return annualized
volatilities.
Delimit setting pairs by slashes.
Button Description
Start Scanner Sub- Creates and displays a new page for results of the selected mar-
scription ket scanner.
Cancel Scanner Sub- Cancels the market scanner.
scription
Show Errors Jumps to the Error Code field and shows the error code.
Note: To get more detailed market scan results than are available in the DDE for Excel API spread-
sheet, run the Market Scanners in TWS.
Hot by Price Range The largest price range (from Top Price Range cal-
(HOT_BY_PRICE_RANGE) culation) over the volatility.
Top Volume Rate The top volume rate per minute.
(TOP_VOLUME_RATE)
Lowest Option Imp Vol Shows the top underlying contracts (stocks or
(LOW_OPT_IMP_VOLAT) indices) with the lowest vega-weighted implied
volatility of near-the-money options with an expir-
ation date in the next two months.
Most Active by Opt Open Interest Returns the top 50 underlying contracts with the
(OPT_OPEN_INTEREST_MOST_ (highest number of outstanding call contracts) +
ACTIVE) (highest number of outstanding put contracts)
Not Open Contracts that have not traded today.
(NOT_OPEN)
Implied volatility is calculated using a 100-step binary tree for American style options, and a Black-
Scholes model for European style options. Interest rates are calculated using the settlement prices from
the day's Eurodollar futures contracts, and dividends are based on historical payouts.
The IB 30-day volatility is the at-market volatility estimated for a maturity thirty calendar days for-
ward of the current trading day. It is based on option prices from two consecutive expiration months.
The first expiration month is that which has at least eight calendar days to run. The implied volatility
is estimated for the eight options on the four closest to market strikes in each expiry. The implied
volatilities are fit to a parabola as a function of the strike price for each expiry. The at-the-market
implied volatility for an expiry is then taken to be the value of the fit parabola at the expected future
price for the expiry. A linear interpolation (or extrapolation, as required) of the 30-day variance based
on the squares of the at-market volatilities is performed. V30 is then the square root of the estimated
variance. If there is no first expiration month with less than sixty calendar days to run, we do not cal-
culate a V30.
Use the Contract Details page to request contract-specific information such as supported order types, valid exchanges, the
contract ID, and so on.
Button Description
Request Contract Details Returns information on the selected contract.
Show Errors Jumps to the Error Code field and shows the error code.
Use the Bond Contract Details page to request contract-specific information for bonds, including the coupon, ratings,
bond type, maturity date, and so on.
Note: Beginning with TWS Version 921, some bond contract data will be suppressed and will not
be available from the API. All bond contract data will continue to be available from Trader
Workstation, but only the following bond contract data will be available from the API:
- Contract ID
- Minimum Tick
- CUSIP (if you have subscribed to the CUSIP service)
- Rating (if you have subscribed to ratings)
1. Click the Bond Contract Details tab at the bottom of the spreadsheet.
2. Enter the ticker symbol for which you want to request contract details.
3. Click the Request Bond Contract Details button on the toolbar.
Note: Beginning with TWS Version 921, some bond contract data will be suppressed and will not
be available from the API. All bond contract data will continue to be available from Trader
Workstation, but only the following bond contract data will be available from the API:
- Contract ID
- Minimum Tick
- CUSIP (if you have subscribed to the CUSIP service)
- Rating (if you have subscribed to ratings)
Button Description
Request Bond Contract Details Gets bond information data for the selected contract.
Show Errors Jumps to the Error Code field and shows the error code.
Use the Market Depth page to view market depth for selected contracts. You can also view market depth for NYSE-listed
products through the Open Book Market Data Subscription, and NASDAQ-listed products through the TotalView Mar-
ket Data Subscriptions, if you have signed up for those subscriptions.
To reset the market data refresh rate for tickers and market depth
1. Click the Tickers or Market Depth tab at the bottom of the spreadsheet.
2. Type the desired market data refresh rate in milliseconds in the Refresh Rate field in the Which Trader Work-
station? area.
3. Move your cursor out of the Refresh Rate field.
4. Click the Set Refresh Rate button on the toolbar.
2. In the Declarations section at the top of the code window for the page, change the number value in numDis-
playRows = 10 to a higher/lower value, then click the Save button on the VBE toolbar.
3. Close the Visual Basic Editor.
Button Description
Request Market Depth View bid/ask depth prices for the selected contract.
Cancel Market Depth Cancel market depth for the selected contract.
Set Refresh Rate Resets the refresh rate (in milliseconds) for market
data.
Show Errors Jumps to the Error Code field and shows the error
code.
Advisors Page
If you are a Financial Advisor and manage multiple accounts, use the Advisors page to create FA orders that:
Note: You must set up your managed accounts, account groups, methods and allocation profiles in
TWS before you can place FA orders in the DDE for Excel API sample spreadsheet.
You can use the Advisors page to set up an order and allocate all shares in the order to a single account.
You can also use the Advisors page to set up an order using an FA account group and FA method.
You can also use the Advisors page to set up an order using an FA allocation profile.
6. Highlight the order row, then click the Apply Extended button to apply the extended order attribute value to the
order. The value for FA Profile is applied to the selected order and displayed in the Extended Order Attributes sec-
tion of the page.
7. Click the Place/Modify Order button.
8. When you are done allocating shares to the account, delete the FA Profile value you entered on the Extended
Order Attributes page. If you do not delete this value, it will be applied to all subsequent orders placed from the
DDE for Excel API spreadsheet.
Button Description
Combo Legs Opens the Combination Legs box. Enter contract details to create
legs of a combination order one by one.
Place/Modify Orders After you have completed the Order Description fields, and
defined any extended attributes, click to create an order for the
selected contract.
Cancel Order This button cancels the order(s) you have highlighted.
Apply Extended Applies the current values on the Extended Order Attributes page
to the highlighted order row.
Show Errors Jumps to the Error Code field and shows the error code.
To view the Visual Basic code behind the DDE for Excel API spreadsheet, press Alt+F11 from any page. The Visual
Basic Editor opens:
l Project Explorer
l Properties Window
l Code Window
The Project Explorer contains a list of objects used in the spreadsheet. These object correspond to the pages in the spread-
sheet; to view the code for a particular page, double-click the page’s corresponding object in the Project Explorer.
Modules
The Visual Basic code includes the following modules (visible in the VBE Project Explorer):
l ArrayQueries
l ErrorDisplay
l Orders
l util
The util module contains many pre-defined constants that you can use when you program your own DDE API applic-
ation. Using these constants instead of hard-coded values will make your application more robust and easier to maintain.
Specifically, the following util functions are particularly useful in building new Visual Basic functionality:
l composeLink – put together a link that receives data, such as a market data bid size, option model volatility, or
execution id.
l composeControlLink – put together a link that causes operations to occur, such as subscribing to market data, pla-
cing orders, or subscribing to the market scanner.
l composeContractReq – Read a contract description out of a page like Tickers or Orders, and build the DDE string
representing it.
Macros
The DDE API sample spreadsheet uses Microsoft Excel macros extensively. Each toolbar button on every page in the
spreadsheet runs a macro when you click it. For example, when you click the Request Market Data button on the Tickers
page, you are actually running a macro called requestMarketData.
You can see all the macros used in the sample spreadsheet by opening the Excel Macro dialog. From there you can
choose to edit the macro, which opens macro code in the Visual Basic Editor.
Note: You must enable macros when you open Excel or none of the macros in the spreadsheet will
function.
For information about recording, editing and viewing macros, refer to your Microsoft Excel documentation.
Named Ranges
Named ranges are a Microsoft Excel feature that lets you assign meaningful names to a single cell or a range of cells in
Microsoft Excel. The TwsDde.xls sample spreadsheet used named ranges extensively.
Named ranges help you to move data around on worksheets without breaking existing logic. It also makes important data
available to your own custom macros and worksheets.
You can view all the named ranges used in the spreadsheet by doing the following, depending on which version of
Excel you are using:
l In Excel 2007, you can see a complete list of all named ranges used in the spreadsheet by clicking Formulas then
clicking Name Manager. The Name Manager displays every named range used in the spreadsheet, the value of
the range, and the page and range of cells covered by the range.
l In earlier versions of Excel, you can view the named ranges by selecting Name > Define from the Tools menu.
You can also download a free Name Manager from Microsoft that has additional functionality for these earlier ver-
sions of Excel.
The following screen shows the Name Manager for the DDE for Excel API sample spreadsheet:
The table below defines possible cell values for DDE-supported functionality. The basic syntax, which appears in the
Excel formula bar (the "=" field at the top of the spreadsheet) when you put your cursor in a cell, is:
=server|topic!id?reqType?field2
or
=server|error!error (for an optional tag that will display errors)
where:
Request number of hold days until the server tik idn holdDays
expiry of the EFP
Account statement control key server acct idn acctv Account code (for
Advisor-managed
accounts only)
Request one account value string server acct idn key
Market data refresh rate server refreshRate idn millisec Number of milliseconds
News bulletin message type server news newsType Refer to note 4 below
Set the server log level server logLevel <log_ Refer to note 5 below.
level>
l Save your own copy of our DDE-linked Excel spreadsheet, TwsDde.xls or create your own blank Excel spread-
sheet.
l Add a blank sheet to your saved copy o f TwsDde.xls or to your own blank Excel spreadsheet.
The following procedure demonstrates how to use DDE syntax to request and receive market data on a blank Excel
spreadsheet. The request string tells TWS that you want to request market data for a specific symbol. The receiving
strings display the appropriate market data.
3. Type the following three receiving strings in three separate cells to receive the last price, volume and closing
price of AAPL stock:
=Sdemo123|tik!id1?last
=Sdemo123|tik!id1?volume
=Sdemo123|tik!id1?close
Note the following:
o Your username is identical in all three strings.
o The ID number (id in the strings above) must be identical in both the request and receiving strings. In this
case, the ID number is assigned to 1 (=Sdemo123|tik!id1?last). If the ID number is not the same in
both the request and receiving strings, then all the related strings are going to receive zeros.
If you have entered the strings correctly, you have properly configured TWS to accept communication from the
DDE for Excel API, and the stock is trading, then your Excel sheet should look like the screen shown below. The
request string will displays 0 and the receiving links will display the values for the last price, volume and closing
price for AAPL stock.
Note: Beginning with API Version 9.71, the ActiveX component code based was migrated to the
C# API, and the ActiveX API source code is located in the source/CSharpClient folder in
the API installation directory.
The API software also includes an ActiveX for Excel sample spreadsheet, which duplicates most of the functionality of
the DDE for Excel sample spreadsheet but is based on the ActiveX control, Tws.ocx. See ActiveX for Excel for details.
To register the ActiveX control with Visual Basic, follow these instructions:
1. From the Components menu in your VB project, select the TWS ActiveX control (Tws.ocx, located in the
bin/ActiveX folder in your API Installation folder).
2. Click Apply.
3. Verify that the TWS control appears in the toolbar with all standard controls.
ActiveX Methods
ActiveX methods allow your application to call functions and request information from TWS.
connect()
Call this method to connect to the host application.
Public Overridable Sub connect(ByVal host as String, ByVal port as Integer, ByVal clientID as Integer
port Integer Must match the port specified in TWS on the Configure>API>Socket Port
field.
clientID Integer A number used to identify this client connection. All orders placed/modified
from this client will be associated with this client identifier.
disconnect()
Call this method to terminate the connections the host application. Calling this method does not cancel orders that have
already been sent.
reqCurrentTime()
Returns the current system time on the server side.
setServerLogLevel()
Public Overridable Sub setServerLogLevel(ByVal logLevel As Integer)
l 1 = SYSTEM
l 2 = ERROR
l 3 = WARNING
l 4 = INFORMATION
l 5 = DETAIL
The default level is ERROR. See API Logging for more details.
reqMktDataEx()
Call this method to request market data. The market data will be returned by the tickPrice(), tickSize(), tick-
OptionComputation(), tickGeneric(), tickString() and tickEFP() events in dispinterface_DTwsEvents.
Public Overridable Sub reqMktDataEx(ByVal tickerId As Integer, ByVal contract As TWSLib.IContract, ByVal gen-
ericTicks As String, ByVal snapshot As Integer, ITagValueList* mktDataOptions)
cancelMktData()
After calling this method, market data for the specified id will stop flowing.
calculateImpliedVolatility()
Call this function to calculate volatility for a supplied option price and underlying price.
cancelCalculateImpliedVolatility()
Call this function to cancel a request to calculate volatility for a supplied option price and underlying price.
calculateOptionPrice()
Call this function to calculate option price and greek values for a supplied volatility and underlying price.
Public Overridable Sub calculateOptionPrice(ByVal reqId As Integer, ByVal contract As TWSLib.IContract, ByVal
volatility As Double, ByVal underPrice As Double)
cancelCalculateOptionPrice()
Call this function to cancel a request to calculate option price and greek values for a supplied volatility and underlying
price.
reqMarketDataType()
The API can receive frozen market data from Trader Workstation. Frozen market data is the last data recorded in our sys-
tem. During normal trading hours, the API receives real-time market data. If you use this function, you are telling TWS to
automatically switch to frozen market data after the close. Then, before the opening of the next trading day, market data
will automatically switch back to real-time market data.
placeOrderEx()
Call this method to place an order. The order status will be returned by the orderStatus() event in dispinterface_
DTwsEvents.
Public Overridable Sub placeOrderEx(ByVal orderId As Integer, ByVal contract As TWSLib.IContract, ByVal
order As TWSLib.IOrder)
cancelOrder()
Call this method to cancel an order.
reqOpenOrders()
Call this method to request the open orders that were placed from this client. Each open order will be fed back through
the openOrderEx() events.
Note: The client with a clientId of 0 will also receive the application-owned open orders. These
orders will be associated with the client and a new orderId will be generated. This asso-
ciation will persist over multiple API and application sessions.
reqAllOpenOrders()
Call this method to request the open orders that were placed from all clients and also from the application.Each open
order will be fed back through the orderStatus() event.
Note: No association is made between the returned orders and the requesting client
reqAutoOpenOrders()
Call this method to request that newly created application orders be implicitly associated with the client. When a new
application order is created, the order will be associated with the client, and fed back through the orderStatus() event.
Note: This request can only be made from a client with a clientId of 0.
reqIds()
Call this function to request the next valid ID that can be used when placing an order. After calling this method, the nex-
tValidId() event will be triggered, and the id returned is that next valid ID. That ID will reflect any autobinding that has
occurred (which generates new IDs and increments the next valid ID therein).
exerciseOptionsEx()
Call this method to exercise options.
Public Overridable Sub exerciseOptionsEx(ByVal tickerId As Integer, ByVal contract As TWSLib.IContract, ByVal
exerciseAction As Integer, ByVal exerciseQuantity As Integer, ByVal account As String, ByVal override As Integer)
1 = exercise
2 = lapse
exerciseQuantity Integer The number of contracts to be exercised
account String For institutional orders. Specifies the IB account.
0 = do not override
1 = override
reqGlobalCancel()
Use this method to cancel all open orders globally. It cancels both API and TWS open orders.
If the order was created in TWS, it also gets canceled. If the order was initiated in the API, it also gets canceled.
reqExecutionsEx()
When this method is called, the execution reports that meet the filter criteria are downloaded to the client via the execDe-
tailsEx() event in dispinterface_DTwsEvents. To view executions beyond the past 24 hours, open the Trade Log in TWS
and, while the Trade Log is displayed, request the executions again from the API.
reqContractDetailsEx()
Call this method to download all details for a particular contract. The contract details will be received via the con-
tractDetailsEx() callback in dispinterface_DTwsEvents.
reqMktDepthEx()
Call this method to request market depth for a specific contract. The market depth will be returned by the updateMk-
tDepth() and updateMktDepthL2() events.
Public Overridable Sub reqMktDepthEx(ByVal tickerId As Integer, ByVal contract As TWSLib.IContract, ByVal
numRows As Integer, ITagValueList* mktDepthDataOptions)
cancelMktDepth()
After calling this method, market depth for the specified id will stop flowing.
reqAccountUpdates()
Call this method to request account updates. The account data will be fed back through the updateAccountTime(),
updateAccountValue() and updatePortfolioEx() events.
acctCode String The account code for which to receive account and portfolio updates.
The API’s updateAccountValue() event handler delivers all of the account information.
l Strings or keys with a suffix of –C, such as AvailableFunds-C, EquityForInitial-C, NetLiquidation-C, correspond
to Commodities in the TWS Account Window.
l Keys with a suffix of –S, such as EquityForMaintenance-S, FullAvailableFunds-S or NetLiquidation-S, correspond
to Securities in the TWS Account Window.
l Keys without any suffix correspond to Totals in the TWS Account Window.
The image below is an actual example of how to compare TWS’s Account Window and the API’s account data. In this
particular case, we try to link three specific keys NetLiquidation, NetLiquidation-C, and NetLiquidation-S to the TWS
Account Window.
For more information about the information presented in the TWS Account Window, see https://in-
stitutions.interactivebrokers.com/en/software/tws/usersguidebook/realtimeactivitymonitoring/the_account_window.htm
reqAccountSummary()
Call this method to request and keep up to date the data that appears on the TWS Account Window Summary tab. The
data is returned by accountSummary().
reqAccountSummary() only allows two concurrent requests. If you use reqAccountSummary() to request more than two
concurrent account summaries, you will receive an error: 322|Error processing request. To resolve this error, unsubscribe
from one reqAccountSummary() request and then resubmit the request.
Note: This request can only be made when connected to an FA managed account.
Public Overridable Sub reqAccountSummary(ByVal messageType As Integer, ByVal version As Integer, ByVal
reqId As Integer, ByVal groupName As String, tags As String)
l AccountType
l NetLiquidation
l TotalCashValue — Total cash including futures pnl
l SettledCash — For cash accounts, this is the same as
TotalCashValue
l AccruedCash — Net accrued interest
l BuyingPower — The maximum amount of marginable US stocks the
account can buy
l EquityWithLoanValue — Cash + stocks + bonds + mutual funds
l PreviousDayEquityWithLoanValue
l GrossPositionValue — The sum of the absolute value of all stock
and equity option positions
l RegTEquity
l RegTMargin
l SMA — Special Memorandum Account
l InitMarginReq
l MaintMarginReq
l AvailableFunds
l ExcessLiquidity
l Cushion — Excess liquidity as a percentage of net liquidation value
l FullInitMarginReq
l FullMaintMarginReq
l FullAvailableFunds
l FullExcessLiquidity
l LookAheadNextChange — Time when look-ahead values take effect
l LookAheadInitMarginReq
l LookAheadMaintMarginReq
l LookAheadAvailableFunds
l LookAheadExcessLiquidity
l HighestSeverity — A measure of how close the account is to liquid-
ation
cancelAccountSummary()
Cancels the request for Account Window Summary tab data.
Note: This request can only be made when connected to an FA managed account.
Public Overridable Sub cancelAccountSummary(ByVal messageId As Integer, ByVal version As Integer, ByVal
reqId As Integer)
reqPositions()
Requests real-time position data for all accounts.
cancelPositions()
Cancels real-time position updates.
reqNewsBulletins()
Call this method to start receiving news bulletins. Each bulletin will be returned by the updateNewsBulletin() event.
cancelNewsBulletins()
Call this method to stop receiving news bulletins.
reqManagedAccts()
Call this method to request the list of managed accounts. The list will be returned by the managedAccounts() event.
Note: This request can only be made when connected to a Financial Advisor account.
requestFA()
Call this method to request FA configuration information from the server. The data returns in an XML string via the
receiveFA() event.
l 1 = GROUPS
l 2 = PROFILE
l 3 =ACCOUNT ALIASES
replaceFA()
Call this method to modify FA configuration information from the API. Note that this can also be done manually.
cxml String The XML string containing the new FA configuration information.
reqHistoricalDataEx()
Call this method to start receiving historical data results through the historicalData() event.
Bar Size
l 1 sec
l 5 secs
l 15 secs
l 30 secs
l 1 min
l 2 mins
l 3 mins
l 5 mins
l 15 mins
l 30 mins
l 1 hour
l 1 day
whatToShow String Determines the nature of data being extracted. Valid values
include:
l TRADES
l MIDPOINT
l BID
l ASK
l BID_ASK
l HISTORICAL_VOLATILITY
l OPTION_IMPLIED_VOLATILITY
useRTH Integer Determines whether to return all data available during the
requested time span, or only data that falls within regular trad-
ing hours. Valid values include:
l 0 - all data is returned even where the market in question
was outside of its regular trading hours.
l 1 - only data within the regular trading hours is returned,
even if the requested time span falls partially or com-
pletely outside of the RTH.
Note: For information about historical data request limitations, see Historical Data Limitations.
cancelHistoricalData()
Used if an internet disconnect has occurred or the results of a query are otherwise delayed and the application is no
longer interested in receiving the data.
reqScannerParameters()
Requests an XML string that describes all possible scanner queries.
reqScannerSubscriptionEx()
Call the reqScannerSubscriptionEX() method to start receiving market scanner results through the scannerDataEx() event.
cancelScannerSubscription()
Public Overridable Sub cancelScannerSubscription(ByVal tickerId As Integer)
reqRealTimeBarsEx()
Call the reqRealTimeBarsEx() method to start receiving real time bar results through the realtimeBar() event.
l TRADES
l BID
l ASK
l MIDPOINT
cancelRealTimeBars()
Used if an Internet disconnect has occurred or the results of a query are otherwise delayed and the application is no
longer interested in receiving the data.
createComboLegList()
This factory method is used to create an IComboLegList COM object.
You must use the factory “create” methods to create the COM objects in this section. For example, the cre-
ateComboLegList() method creates an IComboLeg object. The IComboLeg object contains the definition of the leg list.
createContract()
This factory method is used to create an IContract COM object.
You must use the factory “create” methods to create the COM objects described in this chapter. The createContract()
method creates an IContract object, which contains a description of the contract for which market data is being requested.
createExecutionFilter()
This factory method is used to create an IExecutionFilter COM object.
You must use the factory “create” methods to create the COM objects described in this chapter. The cre-
ateExecutionFilter() method creates an IExecutionFilter object, which contains the filter criteria used to determine which
execution reports are returned.
createOrder()
This factory method is used to create an IOrder COM object.
You must use the factory “create” methods to create the COM objects described in this chapter. The createOrder() method
creates an IOrder object, which contains the details of an order.
createScannerSubscription()
This factory method is used to create an IScannerSubscription COM object.
You must use the factory “create” methods to create the COM objects described in this chapter. The cre-
ateScannerSubscription() method creates an IScannerSubscription object, which contains a summary of the scanner sub-
scription parameters.
createTagValueList
This factory method is used to create ITagValueList and ITagValue objects.
You must use the factory “create” methods to create the COM objects described in this chapter.
createUnderComp()
This factory method is used to create an IUnderComp COM object.
You must use the factory “create” methods to create the COM objects described in this chapter. The createUnderComp()
method creates an IUnderComp object, which is used to define a Delta-Neutral Combo contract.
reqFundamentalData()
Call this method to receive Reuters global fundamental data for stocks. There must be a subscription to Reuters Fun-
damental set up in Account Management before you can receive this data.
reqFundamentalData() can handle conid specified in the Contract object, but not tradingClass or multiplier. This is
because reqFundamentalData() is used only for stocks and stocks do not have a multiplier and trading class.
Public Overridable Sub reqFundamentalData(ByVal reqId As Integer, ByVal contract As TWSLib.IContract, ByVal
reportType As String)
cancelFundamentalData()
Call this method to stop receiving Reuters global fundamental data.
queryDisplayGroups()
void queryDisplayGroups(reqId As Integer)
subscribeToGroupEvents()
subscribeToGroupEvents(requestId As Integer, groupId As Integer)
updateDisplayGroup()
updateDisplayGroup(requestId As Integer, contractInfo As String)
contractInfo String The encoded value that uniquely represents the contract in
IB. Possible values include:
unsubscribeFromGroupEvents()
unsubscribeFromGroupEvents(requestId As Integer)
ActiveX Events
ActiveX events receive information from the system and make it available to an application. This section defines the Act-
iveX events you can receive via the DTwsEvents interface.
connectionClosed()
This event is triggered when TWS closes the sockets connection with the ActiveX control, or when TWS is shut down.
Sub connectionClosed()
currentTime()
This method receives the current system time on the server side.
errMsg()
This event is called when there is an error with the communication or when TWS wants to send a message to the client.
errorCode Integer Error codes are documented in the Error Codes topic.
errorString String This is the textual description of the error, also documented in the Error
Codes topic.
tickPrice()
This function is called when the market data changes. Prices are updated immediately with no delay.
l 1 = bid
l 2 = ask
l 4 = last
l 6 = high
l 7 = low
l 9 = close
tickSize()
This function is called when the market data changes. Sizes are updated immediately with no delay.
size Integer The bid size, ask size, last size or trading volume, depending on the tick-
Type value.
tickOptionComputation()
Sub tickOptionComputation(ByVal id As Integer, ByVal tickType As Integer, ByVal impliedVol As Double, ByVal
delta As Double, ByVal optPrice As Double, ByVal pvDividend As Double, ByVal gamma As Double, ByVal vega
As Double, ByVal theta As Double, ByVal undPrice As Double)
tickGeneric()
This method is called when the market data changes. Values are updated immediately with no delay.
tickString()
This method is called when the market data changes. Values are updated immediately with no delay.
tickEFP()
This method is called when the market data changes. Values are updated immediately with no delay.
Sub tickEFP(ByVal tickerId As Integer, ByVal field As Integer, ByVal basisPoints As Double, ByVal format-
tedBasisPoints As String, ByVal totalDividends As Double, ByVal holdDays As Integer, ByVal futureExpiry As
String, ByVal dividendImpact As Double, ByVal dividendsToExpiry As Double))
tickSnapshotEnd()
This is called when a snapshot market data subscription has been fully handled and there is nothing more to wait for.
This also covers the timeout case.
marketDataType()
TWS sends a marketDataType (type) callback to the API, where type is set to Frozen or RealTime, to announce that mar-
ket data has been switched between frozen and real-time. This notification occurs only when market data switches
between real-time and frozen. The marketDataType( ) callback accepts a reqId parameter and is sent per every sub-
scription because different contracts can generally trade on a different schedule.
orderStatus()
This event is called whenever the status of an order changes. It is also fired after reconnecting if the client has any open
orders.
Sub orderStatus(ByVal id As Integer, ByVal status As String, ByVal filled As Integer, ByVal remaining As Integer,
ByVal avgFillPrice As Double, ByVal permId As Integer, ByVal parentId As Integer, ByVal lastFillPrice As
Double, ByVal clientId As Integer, ByVal whyHeld As String)
Note: It is possible that orderStatus() may return duplicate messages. It is essential that you filter
the message accordingly.
For more information about partial fills, see Order Status for Partial Fills.
openOrderEx()
This method is called to feed in open orders.
openOrderEnd()
This is called at the end of a given request for open orders.
void openOrderEnd()
nextValidId()
This event is called after a successful connection to TWS.
permId()
This event is always received after an order Status event. It gives the permId for the specified order id. The permId will
remain the same from session to session.
permId Integer This id will remain the same from session to session
deltaNeutralValidation()
Upon accepting a Delta-Neutral RFQ(request for quote), the server sends a deltaNeutralValidation() message with the
UnderComp structure. If the delta and price fields are empty in the original request, the confirmation will contain the cur-
rent values from the server. These values are locked when the RFQ is processed and remain locked until the RFQ is can-
celed.
updateAccountValue()
This event updates a single account value.
Sub updateAccountValue(ByVal key As String, ByVal value As String, ByVal curency As String, ByVal accoun-
tName As String)
account String states the account the message applies to. Useful for Financial Advisor
sub-account messages.
updatePortfolioEx()
This callback is made in response to the reqAccountUpdates() method.
unrealizedPNL Double The difference between the current market value of your open pos-
itions and the average cost, or Value - Average Cost.
realizedPNL Double Shows your profit on closed positions, which is the difference
between your entry execution cost (execution price + commissions to
open the position) and exit execution cost ((execution price + com-
missions to close the position)
accountName String The name of the account to which the message applies. Useful for Fin-
ancial Advisor sub-account messages.
updateAccountTime()
This event sends the time at which the account values and portfolio market prices were calculated.
accountDownloadEnd()
This event is called after a batch updateAccountValue() and updatePortfolioEx() is sent.
accountSummary()
Returns the data from the TWS Account Window Summary tab in response to reqAccountSummary().
Sub accountSummary(ByVal messageType As Integer, ByVal version As Integer, ByVal requestId As Integer, ByVal
account As String, tag As String, value As String, currency As String)
l AccountType
l TotalCashValue — Total cash including futures pnl
l SettledCash — For cash accounts, this is the same as
TotalCashValue
l AccruedCash — Net accrued interest
l BuyingPower — The maximum amount of marginable US stocks the
account can buy
l EquityWithLoanValue — Cash + stocks + bonds + mutual funds
l PreviousEquityWithLoanValue
l GrossPositionValue — The sum of the absolute value of all stock
and equity option positions
l RegTEquity
l RegTMargin
l SMA — Special Memorandum Account
l InitMarginReq
l MaintMarginReq
l AvailableFunds
l ExcessLiquidity
l Cushion — Excess liquidity as a percentage of net liquidation value
l FullInitMarginReq
l FullMaintMarginReq
l FullAvailableFunds
l FullExcessLiquidity
l LookAheadNextChange — Time when look-ahead values take effect
l LookAheadInitMarginReq
l LookAheadMaintMarginReq
l LookAheadAvailableFunds
l LookAheadExcessLiquidity
l HighestSeverity — A measure of how close the account is to liquid-
ation
l DayTradesRemaining — The Number of Open/Close trades a user
could put on before Pattern Day Trading is detected. A value of "-1"
accountSummaryEnd
This method is called once all account summary data for a given request are received.
position()
This event returns real-time positions for all accounts in response to the reqPositions() method.
Sub position(ByVal messageId As Integer, ByVal version As Integer, ByVal account as String, ByVal conid As
Integer, ByVal underlying As String, ByVal securityType As String, ByVal expiry As String, ByVal strike As String,
ByVal right As String, ByVal multiplier As String, ByVal exchange As String, ByVal currency As String, By Val
ibLocalSymbol As String, ByVal position As double)
positionEnd()
This is called once all position data for a given request are received and functions as an end marker for the position()
data.
updateNewsBulletin()
This event is triggered for each new bulletin if the client has subscribed (i.e. by calling the reqNewsBulletins() method).
Sub updateNewsBulletin(ByVal msgId As Short, ByVal msgType As Short, ByVal message As String, ByVal origEx-
change As String)
contractDetailsEx()
This event is called only in response to the reqContractDetailsEx() method having been called.
contractDetailsEnd()
This method is called once all contract details for a given request are received. This helps to define the end of an option chain.
bondContractDetails()
Beginning with TWS Version 921, some bond contract data is suppressed and is not be available from the API. All bond
contract data continues to be available from Trader Workstation, but only the following bond contract data is available
from the API:
l Contract ID
l Minimum Tick
l CUSIP (if you have subscribed to the CUSIP service)
l Rating (if you have subscribed to ratings)
Sub bondContractDetails(ByVal symbol As String, ByVal secType As String, ByVal cusip As String, ByVal coupon
As Double, ByVal maturity As String, ByVal issueDate As String, ByVal ratings As String, ByVal bondType As
String, ByVal couponType As String, ByVal convertible As Integer, ByVal callable As Integer, ByVal putable As
Integer, ByVal descAppend As String, ByVal exchange As String, ByVal curency As String, ByVal marketName As
String, ByVal tradingClass As String, ByVal conId As Integer, ByVal minTick As Double, ByVal orderTypes As
String, ByVal validExchanges As String, ByVal nextOptionDate As String, ByVal nextOptionType As String, ByVal
nextOptionPartial As Integer, ByVal notes As String)
execDetailsEx()
This event is called when the reqExecutionsEx() method is invoked, or when an order is filled.
Sub execDetailsEx(ByVal reqId As Integer, ByVal contract As TWSLib.IContract, ByVal execution As TWSLib.IEx-
ecution)
contract IContract This object contains a full description of the contract that was
executed.
execution IExecution This structure contains addition order execution details.
execDetailsEnd()
This method is called once all executions have been sent to a client in response to reqExecutionsEx()
commissionReport()
The commissionReport() callback is triggered as follows:
updateMktDepth()
This function is called when the market depth changes.
Sub updateMktDepth(ByVal id As Integer, ByVal position As Integer, ByVal operation As Integer, ByVal side As
Integer, ByVal price As Double, ByVal size As Integer)
l 0 = insert (insert this new order into the row identified by 'pos-
ition')·
l 1 = update (update the existing order in the row identified by
'position')·
l 2 = delete (delete the existing order at the row identified by 'pos-
ition')
side Integer The side of the book to which this order belongs. Valid values are:
l 0 = ask
l 1 = bid
updateMktDepthL2()
This function is called when the Level II market depth changes.
Sub updateMktDepthL2(ByVal id As Integer, ByVal position As Integer, ByVal marketMaker As String, ByVal oper-
ation As Integer, ByVal side As Integer, ByVal price As Double, ByVal size As Integer)
l 0 = insert (insert this new order into the row identified by 'pos-
ition')·
l 1 = update (update the existing order in the row identified by
'position')·
l 2 = delete (delete the existing order at the row identified by
'position')
side Integer Identifies the side of the book that this order belongs to. Valid values
are:
l 0 = ask
l 1 = bid
managedAccounts()
This event is fired when a successful connection is made to an account. It is also fired when the reqManagedAccts()
method is invoked.
receiveFA()
This event receives previously requested FA configuration information from TWS.
l 1 = GROUPS
l 2 = PROFILE
l 3 =ACCOUNT ALIASES
cxml String The XML string containing the previously requested FA configuration
information.
historicalData()
This event receives requested historical data from TWS.
Sub historicalData(ByVal reqId As Integer, ByVal date As String, ByVal open As Double, ByVal high As Double,
ByVal low As Double, ByVal close As Double, ByVal volume As Integer, ByVal barCount As Integer, ByVal WAP
As Double, ByVal hasGaps As Integer)
scannerParameters()
Sub scannerParameters(ByVal xml As String)
scannerDataEx()
This event receives the requested market scanner data results.
Sub scannerDataEx(ByVal reqId As Integer, ByVal rank As Integer, ByVal contractDetails As TWSLib.ICon-
tractDetails, ByVal distance As String, ByVal benchmark As String, ByVal projection As String, ByVal legsStr As
String)
scannerDataEnd()
This function is called when the snapshot is received and marks the end of one scan.
realtimeBar()
This method receives the real-time bars data results.
Sub realtimeBar(ByVal tickerId As Integer, ByVal time As Integer, ByVal open As Double, ByVal high As Double,
ByVal low As Double, ByVal close As Double, ByVal volume As Integer, ByVal WAP As Double, ByVal Count As
Integer)
fundamentalData()
This method is called to receive Reuters global fundamental market data. There must be a subscription to Reuters Fun-
damental set up in Account Management before you can receive this data.
l Company overview
l Financial summary
l Financial ratios
l Financial statements
l Analyst estimates
l Company calendar
displayGroupList()
This callback is a one-time response to queryDisplayGroups().
displayGroupUpdated()
This is sent by TWS to the API client once after receiving the subscription request subscribeToGroupEvents(), and will
be sent again if the selected contract in the subscribed display group has changed.
contractInfo String The encoded value that uniquely represents the contract in
IB. Possible values include:
l IExecution
l IExecutionFilter
l ICommissionReport
l IContract
l IContractDetails
l IComboLeg
l IComboLegList
l IOrder
l IOrderState
l IScannerSubscription
l ITagValueList
l ITagValue
l IUnderComp
You must use the factory “create” methods to create the COM objects in this section. Once a COM object has been cre-
ated by a factory method, the COM object is tied to a corresponding TWS COM object (an instance of the COM object).
Do not try to pass a COM object to another instance of a TWS COM object.
IExecution
Attribute Description
acctNumber() As String The customer account number.
avgPrice() As Double Average price. Used in regular trades, combo trades
and legs of the combo. Does not include com-
missions.
clientId() As Integer The id of the client that placed the order.
Attribute Description
orderId() As Integer The order id.
Note: TWS orders have a fixed
order id of "0."
permId() As Integer The TWS id used to identify orders, remains the same
over TWS sessions.
price() As Double The order execution price, not including com-
missions.
shares() As Integer The number of shares filled.
side() As String Specifies if the transaction was a sale or a purchase.
Valid values are:
l BOT
l SLD
time() As String The order execution time.
evRule() As String Contains the Economic Value Rule name and the
respective optional argument. The two values should
be separated by a colon. For example, aus-
sieBond:YearsToExpiration=3. When the optional
argument is not present, the first value will be fol-
lowed by a colon.
evMultiplier As Double Tells you approximately how much the market value
of a contract would change if the price were to
change by 1. It cannot be used to get market value by
multiplying the price by the approximate multiplier.
IExecutionFilter
Attribute Description
acctCode() As String Filter the results of the reqExecutionsEx() method based
on an account code. Note: this is only relevant for Fin-
ancial Advisor (FA) accounts.
clientId() As Integer Filter the results of the reqExecutionsEx() method based
on the clientId.
exchange() As String Filter the results of the reqExecutionsEx() method based
on the order exchange.
secType() String Filter the results of the reqExecutionsEx() method based
on the order security type.
Attribute Description
side() As String Filter the results of the reqExecutionsEx() method based
on the order action.
ICommissionReport
Attribute Description
commission() As Double The commission amount.
IContract
Attribute Description
comboLegs() As Object Dynamic memory structure used to store the leg
definitions for this contract.
comboLegsDescrip() As String Description for combo legs
conId() As Integer The unique contract identifier.
currency() As String 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 spe-
cify the currency.
exchange() As String The order destination, such as Smart.
expiry() As String The expiration date. Use the format YYYYMM.
Attribute Description
includeExpired() As Integer If set to true, contract details requests and historical
data queries can be performed pertaining to expired
contracts.
Note: Historical data queries on expired contracts
are limited to the last year of the contracts life, and
are initially only supported for expired futures con-
tracts,
localSymbol() As String This is the local exchange symbol of the underlying
asset.
multiplier() As String Allows you to specify a future or option contract
multiplier. This is only necessary when multiple pos-
sibilities exist.
primaryExch() As String Identifies the listing exchange for the contract (do
not list SMART).
right() As String Specifies a Put or Call. Valid values are: P, PUT, C,
CALL.
secId as String Unique identifier for the secIdType.
secIdType As String Security identifier, when querying contract details or
when placing orders. Supported identifiers are:
l STK
l OPT
l FUT
l IND
l FOP
l CASH
l BAG
l NEWS
strike() As Double The strike price.
symbol() As String This is the symbol of the underlying asset.
Attribute Description
tradingClass() As String The trading class name for this contract.
IContractDetails
Attribute Description
category() As String The industry category of the underlying. For example,
InvestmentSvc.
contractMonth() As String The contract month. Typically the contract month of the
underlying for a futures contract.
industry() As String The industry classification of the underlying/product. For
example, Financial.
liquidHours() As String The liquid trading hours of the product. For example,
20090507:0930-1600;20090508:CLOSED.
longName() As String The descriptive name of the asset.
marketName() String The market name for this contract.
minTick() As Double The minimum price tick.
orderTypes() As String The list of valid order types for this contract.
priceMagnifier() Integer Allows execution and strike prices to be reported con-
sistently with market data, historical data and the order
price, i.e. Z on LIFFE is reported in index points and not
GBP.
ratings() As String Identifies the credit rating of the issuer. A higher credit
rating generally indicates a less risky investment. Bond
ratings are from Moody's and S&P respectively.
secIdList() As Object A list of contract identifiers that the customer is allowed
to view (CUSIP, ISIN, etc.)
subcategory() As String The industry subcategory of the underlying. For example,
Brokerage.
summary() As Object A contract summary.
timeZoneId() As String The ID of the time zone for the trading hours of the
product. For example, EST.
tradingHours() As String The trading hours of the product. For example,
20090507:0700-1830,1830-2330;20090508:CLOSED.
underConId() As String The underlying contract ID.
validExchanges() As String The list of exchanges this contract is traded on.
Attribute Description
evRule() As String Contains the Economic Value Rule name and the respect-
ive optional argument. The two values should be sep-
arated by a colon. For example,
aussieBond:YearsToExpiration=3. When the optional
argument is not present, the first value will be followed
by a colon.
evMultiplier As Double Tells you approximately how much the market value of a
contract would change if the price were to change by 1.
It cannot be used to get market value by multiplying the
price by the approximate multiplier.
Bond Values
bondType() As String The type of bond, such as "CORP."
callable() As Integer Values are True or False. If true, the bond can be called
by the issuer under certain conditions.
convertible() As Integer Values are True or False. If true, the bond can be con-
verted to stock under certain conditions.
coupon() As Double The interest rate used to calculate the amount you will
receive in interest payments over the course of the year.
IComboLeg
Attribute Description
action() As String The side (buy or sell) for the leg you are constructing.
conId() As Integer The unique contract identifier specifying the security.
Attribute Description
exchange() As String The exchange to which the complete combination order will be routed.
openClose() As Integer Specifies whether the order is an open or close order. Valid values are:
l 0 - Same as the parent security. This is the only option for retail
customers.
l 1 - Open. This value is only valid for institutional customers.
l 2 - Close. This value is only valid for institutional customers.
l Unknown - (3)
ratio() As Integer Select the relative number of contracts for the leg you are constructing.
To help determine the ratio for a specific combination order, refer to
the Interactive Analytics section of the User's Guide.
IComboLegList
Attribute Description
Add() As Object Adds combo legs to a combo leg list.
Count() As Integer Leg count.
Item(Integer) As Object Get leg by index.
IOrder
Attribute Description
Order Identifiers
clientId() As Integer The id of the client that placed this order.
orderId() As Integer The id for this order.
Attribute Description
permId() As Integer The TWS id used to identify orders, remains the
same over TWS sessions.
Main Order Fields
action() As String Identifies the side. Valid values are: BUY, SELL,
SSHORT
auxPrice() As Double This is the STOP price for stop-limit orders, and
the offset amount for relative orders. In all other
cases, specify zero.
lmtPrice() As Double This is 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 spe-
cify zero.
orderType() As String Identifies the order type.
Attribute Description
ocaType() As Integer Tells how to handle remaining orders in an OCA
group when one order or part of an order
executes. Valid values include:
l 0 = False
l 1 = True
parentId() As Integer The order ID of the parent order, used for bracket
and auto trailing stop orders.
percentOffset() As Double The percent offset amount for relative orders.
Attribute Description
rule80A() As String Values include:
l Individual = 'I'
l Agency = 'A',
l AgentOtherMember = 'W'
l IndividualPTIA = 'J'
l AgencyPTIA = 'U'
l AgentOtherMemberPTIA = 'M'
l IndividualPT = 'K'
l AgencyPT = 'Y'
l AgentOtherMemberPT = 'N'
sweepToFill() As Integer Specifies if the order is a Sweep-to-Fill order.
tif() As String The time in force. Valid values are: DAY, GTC,
IOC, GTD.
transmit() As Integer Specifies whether the order will be transmitted by
TWS.
triggerMethod() As Integer Specifies how Simulated Stop, Stop-Limit and
Trailing Stop orders are triggered. Valid values
are:
Attribute Description
trailingPercent() As Double Specify the trailing amount of a trailing stop
order as a percentage. Observe the following
guidelines when using the trailingPercent field:
Attribute Description
origin() As Integer The order origin. For institutional customers only.
Valid values are 0 = customer, 1 = firm
shortSaleSlot() As Integer Valid values are 1 or 2.
SMART Routing Only
discretionaryAmt() As Double The amount off the limit price allowed for dis-
cretionary orders.
eTradeOnly() As Integer Trade with electronic quotes.
0 = no, 1 = yes
firmQuoteOnly() As Integer Trade with firm quotes.
0 = no, 1 = yes
nbboPriceCap() As Double Maximum smart order distance from the NBBO.
optOutSmartRouting() As Integer Use to opt out of default SmartRouting for orders
routed directly to ASX. This attribute defaults to
false unless explicitly set to true. When set to
false, orders routed directly to ASX will NOT use
SmartRouting. When set to true, orders routed dir-
ectly to ASX orders WILL use SmartRouting.
notHeld() As Integer For IBDARK orders only. Orders routed to
IBDARK are tagged as “post only” and are held
in IB's order book, where incoming SmartRouted
orders from other IB customers are eligible to
trade against them.
BOX or VOL Orders Only
auctionStrategy() As Integer Values include:
l match = 1
l improvement = 2
l transparent = 3
For orders on BOX only.
BOX Exchange Orders Only
delta() As Double The stock delta. For orders on BOX only.
startingPrice() As Double The auction starting price. For orders on BOX
only.
stockRefPrice() As Double The stock reference price. The reference price is
used for VOL orders to compute the limit price
sent to an exchange (whether or not Continuous
Update is selected), and for price range mon-
itoring.
Pegged-to-Stock and VOL Orders Only
Attribute Description
stockRangeLower() As Double The lower value for the acceptable underlying
stock price range. For price improvement option
orders on BOX and VOL orders with dynamic
management.
stockRangeUpper() As Double The upper value for the acceptable underlying
stock price range. For price improvement option
orders on BOX and VOL orders with dynamic
management.
Volatility Orders Only
continuousUpdate() As Integer VOL orders only. Specifies whether TWS will
automatically update the limit price of the order
as the underlying price moves.
deltaNeutralOrderType() As String VOL orders only. Enter an order type to instruct
TWS to submit a delta neutral trade on full or par-
tial execution of the VOL order. For no hedge
delta order to be sent, specify NONE.
deltaNeutralAuxPrice() As Integer VOL orders only. Use this field to enter a value if
the value in the deltaNeutralOrderType field is
an order type that requires an Aux price, such as a
REL order.
referencePriceType() As Integer VOL orders only. Specifies how you want TWS
to calculate the limit price for options, and for
stock range price monitoring.
Valid values include:
l 1 = Average of NBBO
l 2 = NBB or the NBO depending on the
action and right.
volatility() As Double The option price in volatility, as calculated by
TWS' Option Analytics. This value is expressed
as a percent and is used to calculate the limit
price sent to the exchange.
volatilityType() As Integer Values include:
l 1 = Daily volatility
l 2 = Annual volatility
deltaNeutralOpenClose() As String Specifies whether the order is an Open or a Close
order and is used when the hedge involves a CFD
and the order is clearing away.
Attribute Description
deltaNeutralShortSale () As Integer Used when the hedge involves a stock and indic-
ates whether or not it is sold short.
scaleInitLevelSize() As Integer For Scale orders: Defines the size of the first, or
initial, order component.
scaleInitPosition() As Integer For extended Scale orders.
scaleSubsLevelSize() As Integer For Scale orders: Defines the order size of the sub-
sequent scale order components. Used in con-
junction with scaleInitLevelSize().
scaleTable As String Manual table for Scale orders.
Attribute Description
hedgeParam() As String Beta = x for Beta hedge orders, ratio = y for Pair
hedge order
hedgeType() As String For hedge orders. Possible values are:
l D = Delta
l B = Beta
l F = FX
l P = Pair
Clearing Information
account() As String The account. For institutional customers only.
clearingAccount() As String For IBExecution customers: Specifies the true
beneficiary of the order. This value is required for
FUT/FOP orders for reporting to the exchange.
clearingIntent() As String For IBExecution customers: Valid values are: IB,
Away, and PTA (post trade allocation).
settlingFirm() As String Institutional only.
Algo Orders Only
algoStrategy() As String For information about API Algo orders, see
IBAlgo Parameters.
What If
whatIf() As Integer Use to request pre-trade commissions and margin
information.
If set to true, margin and commissions data is
received back via the OrderState() object for the
openOrder() callback.
Smart Combo Routing
smartComboRoutingParams() As Object Support for Smart combo routing.
Attribute Description
OrderComboLegs() As Object Holds attributes for all legs in a combo order.
Solicited Orders
bool solicited True = solicited (orders initiated by a broker
through the brokers research and design)
OrderComboLeg
Attribute Description
double price Order-specific leg price.
IOrderState
Attribute Description
commission() As Double Shows the commission amount on the order.
commissionCurrency() As String Shows the currency of the commission value.
equityWithLoan() As String Shows the impact the order would have on your
equity with loan value.
initMargin() As String Shows the impact the order would have on your ini-
tial margin.
maintMargin() As String Shows the impact the order would have on your
maintenance margin.
maxCommission() As Double Used in conjunction with the minCommission field,
this defines the highest end of the possible range
into which the actual order commission will fall.
minCommission() As Double Used in conjunction with the maxCommission field,
this defines the lowest end of the possible range into
which the actual order commission will fall.
status() As String Displays the order status.
warningText() As String Displays a warning message if warranted.
IScannerSubscription
Attribute Description
averageOptionVolumeAbove () As Integer Can leave empty.
Attribute Description
stockTypeFilter() As String Valid values are:
l CORP = Corporation
l ADR = American Depositary Receipt
l ETF = Exchange Traded Fund
l REIT = Real Estate Investment Trust
l CEF = Closed End Fund
volumeAbove() As Integer Filter out contracts with a volume lower than
this value. Can be left blank.
ITagValueList
Attribute Description
Count() As Integer The number of tag-value pairs (IBAlgo parameters).
Item(Integer) As Object A tag-value pair (IBAlgo parameter). For more information,
see IBAlgo Parameters.
ITagValue
Attribute Description
tag() As String An IBAlgo order parameter. For more information, see IBAlgo
Parameters.
value() As String The value of the IBAlgo parameter.
IUnderComp
Attribute Description
conId() As Integer The unique contract identifier specifying the security. Used
for Delta-Neutral Combo contracts.
delta() As Double The underlying stock or future delta. Used for Delta-Neutral
Combo contracts.
price() As Double The price of the underlying. Used for Delta-Neutral Combo
contracts.
ActiveX Properties
The table below defines properties you can use when connecting to a server using ActiveX.
Property Description
String TwsConnectionTime Connection time.
long serverVersion Server Version.
Example
In this example, a customer places a BUY order on a calendar spread for GOOG. To buy one calendar spread means:
Here is a summary of the steps required to place a combo order using the API:
l Obtain the contract id (conId) for each leg. Get this number by invoking the reqContractDetailsEx() method.
l Include each leg on the IComboLeg COM object by populating the related fields.
l Implement the placeOrderEx() method with the IContract and IOrder COM objects.
con1.symbol = "GOOG"
con1.secType = "OPT"
con1.expiry = "200909"
con1.strike = 150.0
con1.right = "C"
con1.multiplier = "100"
con1.exchange = "SMART"
con1.currency = "USD"
Tws1.reqContractDetailsEx(1, con1)
'Second Leg
Dim con2 As TWSLib.IContract
con2 = Tws1.createContract
con2.symbol = "GOOG"
con2.secType = "OPT"
con2.expiry = "201101"
con2.strike = 150.0
con2.right = "C"
con2.multiplier = "100"
con2.exchange = "SMART"
con2.currency = "USD"
Tws1.reqContractDetailsEx(2, con2)
If e.reqId = 1 Then
leg1 = contract.conId 'to obtain conId for the first leg
End If
If e.reqId = 2 Then
leg2 = contract.conId 'to obtain conId for the second leg
End If
End Sub
2. Once the program has acquired the conId value for each leg, include it in the ComboLeg object:
TWSLib.IComboLegList
addAllLegs = Tws1.createComboLegList
Leg1.conId = leg1_conId
Leg1.ratio = 1
Leg1.action = "SELL"
Leg1.exchange = "SMART"
Leg1.openClose = 0
Leg1.shortSaleSlot = 0
Leg1.designatedLocation = ""
Leg1.conId = leg2_conId
Leg1.ratio = 1
Leg1.action = "BUY"
Leg1.exchange = "SMART"
Leg1.openClose = 0
Leg1.shortSaleSlot = 0
Leg1.designatedLocation = ""
3. Invoke the placeOrder() method with the appropriate contract and order objects:
Dim contract As TWSLib.IContract
contract = Tws1.createContract
contract.symbol = "USD"
contract.secType = "BAG"
contract.exchange = "SMART"
contract.currency = "USD"
contract.comboLegs = addAllLegs
order.action = "BUY"
order.totalQuantity = 1
order.orderType = "MKT"
Note: Beginning with API Version 9.72, the C++ MFC implementation has been deprecated. If you
are running API Version 9.72 or higher and want to use the C++ API, you must use the
POSIX implementation.
Note: Please note, as of API 9.72, the MFC based C++ client is deprecated. The present tutorial is
valid only for versions 9.71 and below.
Note: All the code provided with this example is “as is” and for illustrative purposes only.
For this tutorial, we are using Interactive Brokers C++ API (v. 9.71) and displaying it in an MFC-based application using
Microsoft Visual Studio 2010 Professional Edition.
For your convenience, you can request the full sample solution resulting from this tutorial by contacting our API Support
team at [email protected].
In this first part of the tutorial, you will create new project in Visual Studio.
2. In New Project dialog, select Visual C++ from the list of Installed Templates on the left, then select MFC Applic-
ation.
3. Type HelloIBMFC as the project name in the Name field, then click the Browse button and choose a location for
the project on your computer.
4. Click OK.
5. Click Next.
6. The next screen in the wizard lets you choose the kind of application you want to create. For this tutorial, make
the following selections:
o Application Type = Dialog based
o Project style = MFC standard
o Use of MFC = Use MFC as a shared DLL.
7. Click Next.
8. The next screen in the wizard lets you choose some additional User Interface options. For this tutorial, disable all
of these options by deselecting all check boxes, then click Finish.
9. The result will be our empty project showing an application with a single dialog. This simple user interface will
be the shell of your sample application.
Continue to the next step in this tutorial, 2. Prepare the User Interface.
In this part of the tutorial, you will modify the user interface of your application.
2. Next, you need to add an area in which to display market data. To do this, open the Toolbox either by using the
toolbox tab on the left side of the screen or by selecting View > Toolbox from the menu.
3. In the Toolbox dialog, select the List Box component, then drag and drop the component into the application’s
dialog and resize it so that it resembles the image below.
In this part of the tutorial, you will add the API source files to your project.
2. Next, you need to tell Visual Studio to include both directories in your project. Open the Property Pages for your
project by selecting Project -> HelloIBMFC Properties from the Visual Studio menu.
3. In the Properties dialog, navigate to Configuration Properties > C/C++ > Additional Include Directories >
Edit.
4. Add the Shared and src directories that you just copied to your application directory earlier.
7. Navigate to the previously copied src directory and select the files EClientSocket.cpp and ECli-
entSocketBase.cpp, then click Add.
If you were to try to compile and run the project at this stage, it might show the following errors:
8. To prevent these errors, open the Property Pages by selecting Project -> HelloIBMFC Properties from the Visual
Studio menu, then change the Character Set to <inherit from parent or project defaults> as shown below.
Now we are ready for coding. The IB API needs to implement the EWrapper virtual class (interface). For this example we
will implement it in the application’s dialog class (CHelloIBMFCDlg) by inheriting from it.
Another key component of Interactive Broker’s API is the EClient class, which provides the methods used to com-
municate to the TWS. In this step of the tutorial, you will add the code required to connect your application to TWS.
2. In the HelloIBMFCDlg.cpp file, initialize this variable on the class constructor (CHel-
loIBMFCDlg::CHelloIBMFCDlg). Don't forget to include EClientSocket’s header.
3. Now you are finally ready to connect to TWS. In Visual Studio’s Resource View, open the Design dialog, then
double-click the Get Data button. This automatically adds the OnBnClickedOK() method to the dialog class.
Now add the connectivity code to the OnBnClickedOk() method as shown below.
When you started modifying our user interface, you added a List Box component. In this step, you will make use of it
with the help of the CHScrollListBox.cpp file, located in the API’s Shared directory. This class is nothing but an exten-
sion of the CListBox MFC class and contains some useful methods.
2. Navigate to the API's Shared directory and select the file HScrollListBox.cpp, then click Add.
3. In the file HelloIBMFCDlg.h, add a CHScrollListBox member variable to our main dialog just as we did with the
EClient class:
4. In the HelloIBMFCDlg.cpp file, link the CHScrollListBox member variable to the GUI’s List Box component via
the MFC wizard’s auto-generated DoDataExchange method’s implementation:
5. When the client application connects to the TWS, it receives the next valid order id on its nextValidId() method,
so in the same file, you can use this same method to send the event to the GUI:
In this final step of the tutorial, you will add the code required to request market data from TWS.
3. In the same file, trigger the request upon reception of the next valid id:
4. In the same file, add the code that will display some results:
For your convenience, you can request the full sample solution resulting from this tutorial by contacting our API Support
team at [email protected].
reqMktData() reqManagedAccts()
cancelMktData() requestFA()
calculateImpliedVolatility() replaceFA()
cancelCalculateImpliedVolatility()
Historical Data
calculateOptionPrice()
cancelCalculateOptionPrice() reqHistoricalData()
reqMarketDataType() cancelHistoricalData()
placeOrder() reqScannerParameters()
cancelOrder() reqScannerSubscription()
reqOpenOrders() cancelScannerSubscription()
reqAllOpenOrders()
Real Time Bars
reqAutoOpenOrders()
reqIDs() reqRealTimeBars()
exerciseOptions() cancelRealTimeBars()
reqGlobalCancel()
Fundamental Data
Account and Portfolio
reqFundamentalData()
reqAccountUpdates() cancelFundamentalData()
reqAccountSummary()
cancelAccountSummary() Display Groups
reqPositions()
queryDisplayGroups()
cancelPositions()
subscribeToGroupEvents()
Executions updateDisplayGroups()
unsubscribeFromGroupEvents()
reqExecutions()
EClientSocket()
This is the constructor.
Parameter Description
ptr The pointer to an object that was derived from the EWrapper base class.
eConnect()
This function must be called before any other. There is no feedback for a successful connection, but a subsequent attempt
to connect will return the message "Already connected."
eDisconnect()
Call this function to terminate the connections with TWS. Calling this function does not cancel orders that have already been sent.
void eDisconnect()
Parameter Description
ptr The pointer to an object that was derived from the EWrapper base class.
isConnected()
Call this function to check if there is a connection with TWS
void isConnected()
reqCurrentTime()
Returns the current system time on the server side.
void reqCurrentTime()
serverVersion()
Returns the version of the TWS instance to which the API application is connected.
serverVersion()
setLogLevel()
The default detail level is ERROR. For more details, see API Logging.
l 1 = SYSTEM
l 2 = ERROR
l 3 = WARNING
l 4 = INFORMATION
l 5 = DETAIL
TwsConnectionTime()
Returns the time the API application made a connection to TWS.
TwsConnectionTime()
checkMessages()
This function should be called frequently (every 1 second) to check for messages received from TWS.
void checkMessages()
reqMktData()
Call this function to request market data. The market data will be returned by the tickPrice and tickSize events.
void reqMktData(TickerId id, const Contract &contract, IBString &genericTicks, bool snapshot, const
TagValueListSPtr& mktDataOptiosn)
cancelMktData()
After calling this function, market data for the specified id will stop flowing.
calculateImpliedVolatility()
Call this function to calculate volatility for a supplied option price and underlying price.
cancelCalculateImpliedVolatility()
Call this function to cancel a request to calculate volatility for a supplied option price and underlying price.
calculateImpliedVolatility(TickerId reqId)
calculateOptionPrice()
Call this function to calculate option price and greek values for a supplied volatility and underlying price.
void calculateOptionPrice(TickerId reqId, const Contract &contract, double volatility, double underPrice)
cancelCalculateOptionPrice()
Call this function to cancel a request to calculate the option price and greek values for a supplied volatility and under-
lying price.
cancelCalculateOptionPrice(TickerId reqId)
reqMarketDataType()
The API can receive frozen market data from Trader Workstation. Frozen market data is the last data recorded in our sys-
tem. During normal trading hours, the API receives real-time market data. If you use this function, you are telling TWS to
automatically switch to frozen market data after the close. Then, before the opening of the next trading day, market data
will automatically switch back to real-time market data.
reqMarketDataType(int marketDataType)
placeOrder()
Call this function to place an order. The order status will be returned by the orderStatus event.
void placeOrder( OrderId id, const Contract &contract, const Order &order)
cancelOrder()
Call this function to cancel an order.
reqOpenOrders()
Call this function to request the open orders that were placed from this client. Each open order will be fed back through
the openOrder() and orderStatus() functions on the EWrapper.
void reqOpenOrders()
Note: The client with a clientId of 0 will also receive the TWS-owned open orders. These orders
will be associated with the client and a new orderId will be generated. This association will
persist over multiple API and TWS sessions.
reqAllOpenOrders()
Call this function to request the open orders placed from all clients and also from TWS. Each open order will be fed back
through the openOrder() and orderStatus() functions on the EWrapper.
void reqAllOpenOrders()
Note: No association is made between the returned orders and the requesting client.
reqAutoOpenOrders()
Call this function to request that newly created TWS orders be implicitly associated with the client. When a new TWS
order is created, the order will be associated with the client, and fed back through the openOrder() and orderStatus() func-
tions on the EWrapper.
Note: This request can only be made from a client with clientId of 0.
reqIDs()
Call this function to request from TWS the next valid ID that can be used when placing an order. After calling this func-
tion, the nextValidId() event will be triggered, and the id returned is that next valid ID. That ID will reflect any auto-
binding that has occurred (which generates new IDs and increments the next valid ID therein).
exerciseOptions()
void exerciseOptions(TickerId id, const Contract &contract, int exerciseAction, int exerciseQuantity, const IBString
&account, int override)
reqGlobalCancel()
Use this function to cancel all open orders globally. It cancels both API and TWS open orders.
If the order was created in TWS, it also gets canceled. If the order was initiated in the API, it also gets canceled.
void reqGlobalCancel()
reqAccountUpdates()
Call this function to start getting account values, portfolio, and last update time information.
l Strings or keys with a suffix of –C, such as AvailableFunds-C, EquityForInitial-C, NetLiquidation-C, correspond
to Commodities in the TWS Account Window.
l Keys with a suffix of –S, such as EquityForMaintenance-S, FullAvailableFunds-S or NetLiquidation-S, correspond
to Securities in the TWS Account Window.
l Keys without any suffix correspond to Totals in the TWS Account Window.
The image below is an actual example of how to compare TWS’s Account Window and the API’s account data. In this
particular case, we try to link three specific keys NetLiquidation, NetLiquidation-C, and NetLiquidation-S to the TWS
Account Window.
For more information about the information presented in the TWS Account Window, see https://in-
stitutions.interactivebrokers.com/en/software/tws/usersguidebook/realtimeactivitymonitoring/the_account_window.htm
reqAccountSummary()
Call this method to request and keep up to date the data that appears on the TWS Account Window Summary tab. The
data is returned by accountSummary().
reqAccountSummary() only allows two concurrent requests. If you use reqAccountSummary() to request more than two
concurrent account summaries, you will receive an error: 322|Error processing request. To resolve this error, unsubscribe
from one reqAccountSummary() request and then resubmit the request.
Note: This request can only be made when connected to an FA managed account.
l AccountType
l NetLiquidation,
l TotalCashValue — Total cash including futures pnl
l SettledCash — For cash accounts, this is the same as
TotalCashValue
l AccruedCash — Net accrued interest
l BuyingPower — The maximum amount of marginable US
stocks the account can buy
l EquityWithLoanValue — Cash + stocks + bonds + mutual
funds
l PreviousDayEquityWithLoanValue,
l GrossPositionValue — The sum of the absolute value of all
stock and equity option positions
l RegTEquity,
l RegTMargin,
l SMA — Special Memorandum Account
l InitMarginReq,
l MaintMarginReq,
l AvailableFunds,
l ExcessLiquidity,
l Cushion — Excess liquidity as a percentage of net liquidation
value
l FullInitMarginReq,
l FullMaintMarginReq,
l FullAvailableFunds,
l FullExcessLiquidity,
l LookAheadNextChange — Time when look-ahead values take
effect
l LookAheadInitMarginReq,
l LookAheadMaintMarginReq,
l LookAheadAvailableFunds,
l LookAheadExcessLiquidity,
cancelAccountSummary()
Cancels the request for Account Window Summary tab data.
reqPositions()
Requests real-time position data for all accounts.
void reqPositions()
cancelPositions()
Cancels real-time position updates.
void cancelPositions()
reqExecutions()
When this function is called, the execution reports that meet the filter criteria are downloaded to the client via the
execDetails() function. To view executions beyond the past 24 hours, open the Trade Log in TWS and, while the Trade
Log is displayed, request the executions again from the API.
reqContractDetails()
Call this function to download all details for a particular underlying. The contract details will be received via the con-
tractDetails() function on the EWrapper.
reqMktDepth()
Call this function to request market depth for a specific contract. The market depth will be returned by the updateMk-
tDepth() and updateMktDepthL2() events.
void reqMktDepth (TickerID id, const Contract &contract, int numRows, const TagValueListSPtr& mktDepthOp-
tions)
cancelMktDepth()
After calling this function, market depth data for the specified id will stop flowing.
reqNewsBulletins()
Call this function to start receiving news bulletins. Each bulletin will be returned by the updatedNewsBulletin() event.
cancelNewsBulletins()
Call this function to stop receiving news bulletins.
void cancelNewsBulletins()
reqManagedAccts()
Call this function to request the list of managed accounts. The list will be returned by the managedAccounts() function
on the EWrapper.
Note: This request can only be made when connected to a FA managed account.
void reqManagedAccts()
requestFA()
Call this function to request FA configuration information from TWS. The data returns in an XML string via a
"receiveFA" ActiveX event.
requestFA(faDataType faDataType)
l 1 = GROUPS
l 2 = PROFILE
l 3 = ACCOUNT ALIASES
replaceFA()
Call this function to modify FA configuration information from the API. Note that this can also be done manually in
TWS itself.
l 1 = GROUPS
l 2 = PROFILE
l 3 =ACCOUNT ALIASES
cxml IBString The XML string containing the new FA con-
figuration information.
reqHistoricalData()
void reqHistoricalData (TickerId id, const Contract &contract, const IBString &endDateTime, const IBString &dur-
ationStr, const IBString &barSizeSetting, const IBString &whatToShow, int useRTH, int formatDate, const
TagValueListSPtr& chartOptions)
l 1 sec
l 5 secs
l 15 secs
l 30 secs
l 1 min
l 2 mins
l 3 mins
l 5 mins
l 15 mins
l 30 mins
l 1 hour
l 1 day
whatToShow IBString Determines the nature of data being extracted. Valid values
include:
l TRADES
l MIDPOINT
l BID
l ASK
l BID_ASK
l HISTORICAL_VOLATILITY
l OPTION_IMPLIED_VOLATILITY
useRTH int Determines whether to return all data available during the reques-
ted time span, or only data that falls within regular trading hours.
Valid values include:
For a information about historical data request limitations, see Historical Data Limitations.
cancelHistoricalData()
Used if an internet disconnect has occurred or the results of a query are otherwise delayed and the application is no
longer interested in receiving the data.
reqScannerParameters()
Requests an XML string that describes all possible scanner queries.
void reqScannerParameters()
reqScannerSubscription()
void reqScannerSubscription(int tickerId, const ScannerSubscription &subscription, const TagValueListSPtr& scan-
nerSubscriptionsOptions)
cancelScannerSubscription()
void cancelScannerSubscription(int tickerId)
reqRealTimeBars()
Call the reqRealTimeBars() function to start receiving real time bar results through the realtimeBar() EWrapper function.
void reqRealTimeBars(TickerId id, Contract contract, int barSize, const IBString &whatToShow, bool useRTH,
const TagValueListSPtr& realTimeBarsOptions)
l TRADES
l BID
l ASK
l MIDPOINT
cancelRealTimeBars()
Call the cancelRealTimeBars() function to stop receiving real time bar results.
reqFundamentalData()
Call this function to receive Reuters global fundamental data for stocks. There must be a subscription to Reuters Fun-
damental set up in Account Management before you can receive this data.
reqFundamentalData() can handle conid specified in the Contract object, but not tradingClass or multiplier. This is
because reqFundamentalData() is used only for stocks and stocks do not have a multiplier and trading class.
cancelFundamentalData()
Call this function to stop receiving Reuters global fundamental data.
queryDisplayGroups()
queryDisplayGroups(int reqId)
subscribeToGroupEvents()
subscribeToGroupEvents(int reqId, int groupId)
updateDisplayGroup()
updateDisplayGroup(int reqId, const IBString& contractInfo)
contractInfo IBString The encoded value that uniquely represents the contract in
IB. Possible values include:
unsubscribeFromGroupEvents()
unsubscribeFromGroupEvents(int reqId)
winError()
This event is called when there is an error on the client side.
error()
This event is called when there is an error with the communication or when TWS wants to send a message to the client.
virtual void error(const int id, const int errorCode, const IBString errorString)
connectionClosed()
This function is called when TWS closes the sockets connection with the ActiveX control, or when TWS is shut down.
currentTime()
This function receives the current system time on the server side.
tickPrice()
This function is called when the market data changes. Prices are updated immediately with no delay.
virtual void tickPrice(TickerId TickerId, TickType tickType, double price, int canAutoExecute)
l 1 = bid
l 2 = ask
l 4 = last
l 6 = high
l 7 = low
l 9 = close
price double The bid, ask or last price, the daily high, daily low or last day
close, depending on tickType value.
canAutoExecute int Specifies whether the price tick is available for automatic exe-
cution. Possible values are:
tickSize()
This function is called when the market data changes. Sizes are updated immediately with no delay.
l 0 = bid size
l 3 = ask size
l 5 = last size
l 8 = volume
size int Could be the bid size, ask size, last size or trading volume, depending
on the tickType value.
tickOptionComputation()
This function is called when the market in an option or its underlier moves. TWS’s option model volatilities, prices, and
deltas, along with the present value of dividends expected on that options underlier are received.
virtual void tickOptionComputation(TickerID tickerId, TickType tickType, double impliedVol, double delta, double
optPrice, double pvDividend, double gamma, double vega, double theta, double undPrice)
l 10 = Bid
l 11 = Ask
l 12 = Last
impliedVol double The implied volatility calculated by the TWS option modeler, using
the specified ticktype value.
delta double The option delta value.
optPrice double The option price.
pvDividend double The present value of dividends expected on the options underlying
instrument.
gamma double The option gamma value.
vega double The option vega value.
theta double The option theta value.
undPrice double The price of the underlying.
tickGeneric()
This function is called when the market data changes. Values are updated immediately with no delay.
tickString()
This function is called when the market data changes. Values are updated immediately with no delay.
tickEFP()
This function is called when the market data changes. Values are updated immediately with no delay.
virtual void tickEFP(TickerId tickerId, TickType tickType, double basisPoints, const IBString& format-
tedBasisPoints, double totalDividends, int holdDays, const IBString& futureExpiry, double dividendImpact, double
dividendsToExpiry)
tickSnapshotEnd()
This is called when a snapshot market data subscription has been fully handled and there is nothing more to wait for.
This also covers the timeout case.
marketDataType()
TWS sends a marketDataType(type) callback to the API, where type is set to Frozen or RealTime, to announce that mar-
ket data has been switched between frozen and real-time. This notification occurs only when market data switches
between real-time and frozen. The marketDataType( ) callback accepts a reqId parameter and is sent per every sub-
scription because different contracts can generally trade on a different schedule.
orderStatus()
This event is called whenever the status of an order changes. It is also fired after reconnecting to TWS if the client has
any open orders.
virtual void orderStatus(OrderId orderId, const IBString &status, int filled, int remaining, double avgFillPrice, int
permId, int parentId, double lastFillPrice, int clientId, const IBString& whyHeld)
Note: It is possible that orderStatus() may return duplicate messages. It is essential that you filter
the message accordingly.
filled int Specifies the number of shares that have been executed.
For more information about partial fills, see Order Status for Partial
Fills.
remaining int Specifies the number of shares still outstanding.
avgFillPrice double The average price of the shares that have been executed. This para-
meter is valid only if the filled parameter value is greater than zero.
Otherwise, the price parameter will be zero.
permId int The TWS id used to identify orders. Remains the same over TWS ses-
sions.
openOrder()
This function is called to feed in open orders.
virtual void openOrder(OrderId orderId, const Contract&, const Order&, const OrderState&)
order Order The Order class gives the details of the open order.
orderState OrderState The orderState class includes attributes used for both pre and post
trade margin and commission data.
openOrderEnd()
This is called at the end of a given request for open orders.
void openOrderEnd()
nextValidId()
This function is called after a successful connection to TWS.
deltaNeutralValidation()
Upon accepting a Delta-Neutral RFQ(request for quote), the server sends a deltaNeutralValidation() message with the
UnderComp structure. If the delta and price fields are empty in the original request, the confirmation will contain the cur-
rent values from the server. These values are locked when the RFQ is processed and remain locked until the RFQ is can-
celed.
updateAccountValue()
This function is called only when ReqAccountUpdates on EClientSocket object has been called.
virtual void updateAccountValue(const IBString& key, const IBString& value, const IBString& currency, const
IBString& accountName)
updatePortfolio()
This function is called only when reqAccountUpdates on EClientSocket object has been called.
virtual void updatePortfolio(const Contract& contract, int position, double marketPrice, double marketValue, double
averageCost, double unrealizedPNL, double realizedPNL, const IBString& accountName)
position int This integer indicates the position on the contract. If the position is 0,
it means the position has just cleared.
marketPrice double Unit price of the instrument.
marketValue double The total market value of the instrument.
averageCost double The average cost per share is calculated by dividing your cost (exe-
cution price + commission) by the quantity of your position.
unrealizedPNL double The difference between the current market value of your open positions
and the average cost, or Value - Average Cost.
realizedPNL double Shows your profit on closed positions, which is the difference between
your entry execution cost (execution price + commissions to open the
position) and exit execution cost ((execution price + commissions to
close the position)
accountName IBString States the account to which the message applies. Useful for Financial
Advisor sub-account messages.
updateAccountTime()
This function is called only when reqAccountUpdates on EClientSocket object has been called.
accountDownloadEnd()
This is called after a batch updateAccountValue() and updatePortfolio() is sent.
accountSummary()
Returns the data from the TWS Account Window Summary tab in response to reqAccountSummary().
virtual void accountSummary(int reqID, const IBString& account, const IBString& tag, const IBString& value, const
IBString& currency)
l AccountType
l TotalCashValue — Total cash including futures pnl
l SettledCash — For cash accounts, this is the same as
TotalCashValue
l AccruedCash — Net accrued interest
l BuyingPower — The maximum amount of marginable US
stocks the account can buy
l EquityWithLoanValue — Cash + stocks + bonds + mutual
funds
l PreviousEquityWithLoanValue
l GrossPositionValue — The sum of the absolute value of all
stock and equity option positions
l RegTEquity
l RegTMargin
l SMA — Special Memorandum Account
l InitMarginReq
l MaintMarginReq
l AvailableFunds
l ExcessLiquidity
l Cushion — Excess liquidity as a percentage of net liquidation
value
l FullInitMarginReq
l FullMaintMarginReq
l FullAvailableFunds
l FullExcessLiquidity
l LookAheadNextChange — Time when look-ahead values take
effect
l LookAheadInitMarginReq
l LookAheadMaintMarginReq
l LookAheadAvailableFunds
l LookAheadExcessLiquidity
l HighestSeverity — A measure of how close the account is to
accountSummaryEnd
This method is called once all account summary data for a given request are received.
position()
This event returns real-time positions for all accounts in response to the reqPositions() method.
virtual void position(const IBString& account, const Contract& contract, int position)
positionEnd()
This is called once all position data for a given request are received and functions as an end marker for the position()
data.
updateNewsBulletin()
This event is triggered for each new bulletin if the client has subscribed (i.e. by calling the reqNewsBulletins() function.
virtual void updateNewsBulletin(int msgId, int msgType, const IBString& message, const IBString& origExch
contractDetails()
This function is called only when reqContractDetails function on the EClientSocket object has been called.
contractDetailsEnd()
This function is called once all contract details for a given request are received. This helps to define the end of an option chain.
bondContractDetails()
This function is called only when reqContractDetails function on the EClientSocket object has been called for bonds.
execDetails()
This event is fired when the reqExecutions() functions is invoked, or when an order is filled.
virtual void execDetails(int reqId, const Contract& contract, const Execution& execution)
contract Contract This structure contains a full description of the contract that
was executed.
execution Execution This structure contains addition order execution details.
execDetailsEnd()
This function is called once all executions have been sent to a client in response to reqExecutions().
commissionReport()
The commissionReport() callback is triggered as follows:
updateMktDepth()
This function is called when the market depth changes.
virtual void updateMktDepth(TickerId id, int position, int operation, int side, double price, int size)
l 0 = insert (insert this new order into the row identified by 'pos-
ition')·
l 1 = update (update the existing order in the row identified by
'position')·
l 2 = delete (delete the existing order at the row identified by 'pos-
ition')
side int Identifies the side of the book that this order belongs to. Valid values
are:
l 0 = ask
l 1 = bid
price double The order price.
size int The order size.
updateMktDepthL2()
This function is called when the Level II market depth changes.
virtual void updateMktDepthL2(TickerId id, int position, IBString marketMaker, int operation, int side, double price,
int size)
l 0 = ask
l 1 = bid
price double The order price.
size int The order size.
managedAccounts()
This function is called when a successful connection is made to an account. It is also called when the reqManagedAccts()
function is invoked.
receiveFA()
This event receives previously requested FA configuration information from TWS.
l 1 = GROUPS
l 2 = PROFILE
l 3 =ACCOUNT ALIASES
cxml IBString The XML string containing the previously requested FA con-
figuration information.
historicalData()
This function receives the requested historical data results.
virtual void historicalData(TickerId reqId, const IBString& date, double open, double high, double low, double close,
int volume, int barCount, double WAP, int hasGaps)
scannerParameters()
This function receives an XML document that describes the valid parameters that a scanner subscription can have.
scannerData()
This function receives the requested market scanner data results.
virtual void scannerData(int reqId, int rank, const ContractDetails &contractDetails, IBString &distance, IBString
&benchmark, IBString &projection, IBString &legsStr)
scannerDataEnd()
This function is called when the snapshot is received and marks the end of one scan.
realtimeBar()
This function receives the real-time bars data results.
virtual void realtimeBar(TickerId reqId, long time, double open, double high, double low, double close, long volume,
double wap, int count)
fundamentalData()
This function is called to receive Reuters global fundamental market data. There must be a subscription to Reuters Fun-
damental set up in Account Management before you can receive this data.
l Company overview
l Financial summary
l Financial ratios
l Financial statements
l Analyst estimates
l Company calendar
displayGroupList()
This callback is a one-time response to queryDisplayGroups().
displayGroupUpdated()
This is sent by TWS to the API client once after receiving the subscription request subscribeToGroupEvents(), and will
be sent again if the selected contract in the subscribed display group has changed.
contractInfo IBString The encoded value that uniquely represents the contract in
IB. Possible values include:
SocketClient Properties
The tables below define properties for the Execution, Contract and Order classes, and classes that are closely related to
them.
l Execution
l ExecutionFilter
l Contract
l ContractDetails
l ComboLeg
l Order
l OrderState
l ScannerSubscription
l UnderComp
l CommissionReport
Execution
Attribute Description
IBString execId Unique order execution id.
IBString time The order execution time.
IBString acctNumber The customer account number.
IBString exchange Exchange that executed the order.
IBString side Specifies if the transaction was a sale or a purchase. Valid val-
ues are:
l BOT
l SLD
int shares The number of shares filled.
double price The order execution price, not including commissions.
int permId The TWS id used to identify orders, remains the same over
TWS sessions.
long clientId The id of the client that placed the order.
Note: TWS orders have a fixed client id
of 0.
long orderId The order id.
Note: TWS orders have a fixed order id
of 0.
Attribute Description
int liquidation Identifies the position as one to be liquidated last should the
need arise.
int cumQty Cumulative quantity. Used in regular trades, combo trades and
legs of the combo.
double avgPrice Average price. Used in regular trades, combo trades and legs
of the combo. Does not include commissions.
IBString evRule Contains the Economic Value Rule name and the respective
optional argument. The two values should be separated by a
colon. For example, aussieBond:YearsToExpiration=3. When
the optional argument is not present, the first value will be fol-
lowed by a colon.
double evMultiplier Tells you approximately how much the market value of a con-
tract would change if the price were to change by 1. It cannot
be used to get market value by multiplying the price by the
approximate multiplier.
ExecutionFilter
Attribute Description
IBString acctCode Filter the results of the reqExecutions() function based
on an account code. Note: this is only relevant for FA
managed accounts.
IBString exchange Filter the results of the reqExecutions() function based
on the order exchange.
IBString secType Filter the results of the reqExecutions() function based
on the order security type.
Note: Refer to the Contract struct for the list of valid
security types.
IBString side Filter the results of the reqExecutions() function based
on the order action.
Note: Refer to the Order struct for the list of valid
order actions.
IBString symbol Filter the results of the reqExecutions() function based
on the order symbol.
IBString time Filter the results of the reqExecutions() function based
on execution reports received after the specified time.
The format for timeFilter is "yyyymmdd-hh:mm:ss"
long clientId Filter the results of the reqExecutions() function based
on the clientId.
Contract
Attribute Description
vector<ComboLeg> comboLegs Dynamic memory structure used to store the leg defin-
itions for this contract.
IBString comboLegsDescrip Description for combo legs.
Attribute Description
IBString secIdType Security identifier, when querying contract details or
when placing orders. Supported identifiers are:
l ISIN (Example: Apple: US0378331005)
l CUSIP (Example: Apple: 037833100)
l SEDOL (Consists of 6-AN + check digit.
Example: BAE: 0263494)
l RIC (Consists of exchange-independent RIC
Root and a suffix identifying the exchange.
Example: AAPL.O for Apple on NASDAQ.)
IBString secType This is the security type. Valid values are:
l STK
l OPT
l FUT
l IND
l FOP
l CASH
l BAG
l NEWS
double strike The strike price.
IBString symbol This is the symbol of the underlying asset.
IBString tradingClass The trading class name for this contract.
ContractDetails
Attribute Description
bool callable For Bonds. Values are True or False. If true, the
bond can be called by the issuer under certain con-
ditions.
IBString category The industry category of the underlying. For
example, InvestmentSvc.
IBString contractMonth The contract month. Typically the contract month
of the underlying for a futures contract.
bool convertible For Bonds. Values are True or False. If true, the
bond can be converted to stock under certain con-
ditions.
Attribute Description
double coupon For Bonds. The interest rate used to calculate the
amount you will receive in interest payments over
the course of the year.
IBString industry The industry classification of the under-
lying/product. For example, Financial.
IBString liquidHours The liquid trading hours of the product. For
example, 20090507:0930-
1600;20090508:CLOSED.
IBString longName The descriptive name of the asset.
IBString marketName The market name for this contract.
double minTick The minimum price tick.
Bool nextOptionPartial For Bonds, relevant if the bond has embedded
options, i.e., is the next option full or partial?
IBString orderTypes The list of valid order type for this contract
long priceMagnifier Allows execution and strike prices to be reported
consistently with market data, historical data and
the order price, i.e. Z on LIFFE is reported in index
points and not GBP.
bool putable For Bonds. Values are True or False. If true, the
bond can be sold back to the issuer under certain
conditions.
TagValueListSPtr secIdList() A list of contract identifiers that the customer is
allowed to view (CUSIP, ISIN, etc.)
IBString subcategory The industry subcategory of the underlying. For
example, Brokerage.
Contract summary A contract structure.
IBString tradingHours The trading hours of the product. For example,
20090507:0700-1830,1830-
2330;20090508:CLOSED.
IBString timeZoneId The ID of the time zone for the trading hours of
the product. For example, EST.
IBString underConId The underlying contract ID.
IBString evRule Contains the Economic Value Rule name and the
respective optional argument. The two values
should be separated by a colon. For example, aus-
sieBond:YearsToExpiration=3. When the optional
argument is not present, the first value will be fol-
lowed by a colon.
Attribute Description
double evMultiplier Tells you approximately how much the market
value of a contract would change if the price were
to change by 1. It cannot be used to get market
value by multiplying the price by the approximate
multiplier.
Bond Values
IBString bondType For Bonds. The type of bond, such as "CORP."
IBString couponType For Bonds. The type of bond coupon, such as
"FIXED."
IBString cusip For Bonds. The nine-character bond CUSIP or the
12-character SEDOL.
IBString descAppend For Bonds. A description string containing further
descriptive information about the bond.
IBString issueDate For Bonds. The date the bond was issued.
IBString maturity For Bonds. The date on which the issuer must
repay the face value of the bond.
IBString nextOptionDate For Bonds, relevant if the bond has embedded
options.
IBString nextOptionType For Bonds, relevant if the bond has embedded
options.
IBString notes For Bonds, if populated for the bond in IB's data-
base
IBString ratings For Bonds. Identifies the credit rating of the issuer.
A higher credit rating generally indicates a less
risky investment. Bond ratings are from Moody's
and S&P respectively.
IBString validExchanges The list of exchanges on which this contract is
traded.
ComboLeg
Attribute Description
IBString action The side (buy or sell) for the leg you are constructing.
long conId The unique contract identifier specifying the security.
IBString des- If shortSaleSlot == 2, the designatedLocation must be specified.
ignatedLocation Otherwise leave blank or orders will be rejected.
IBString exchange The exchange to which the complete combination order will be routed.
Attribute Description
long openClose Specifies whether the order is an open or close order. Valid values are:
l Same - (0) same as the parent security. This is the only option for retail
customers.
l Open - (1) only valid for institutional customers.
l Close - (2) only valid for institutional customers.
l Unknown
long ratio Select the relative number of contracts for the leg you are constructing. To help
determine the ratio for a specific combination order, refer to the Interactive Ana-
lytics section of the User's Guide.
Order
Attribute Description
Order Identifiers
long clientId The id of the client that placed this order.
long orderId The id for this order.
long permId The TWS id used to identify orders, remains the same over TWS ses-
sions.
Main Order Fields
IBString action Identifies the side. Valid values are: BUY, SELL, SSHORT
double auxPrice This is the STOP price for stop-limit orders, and the offset amount
for relative orders. In all other cases, specify zero.
double lmtPrice This is 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.
IBString orderType Identifies the order type.
Attribute Description
bool allOrNone 0 = no, 1 = yes
bool blockOrder If set to true, specifies that the order is an ISE Block order.
int displaySize The publicly disclosed order size, used when placing Iceberg orders.
l 0 = False
l 1 = True
Attribute Description
long parentId The order ID of the parent order, used for bracket and auto trailing
stop orders.
double percentOffset The percent offset amount for relative orders.
IBString rule80A Values include:
l Individual = 'I'
l Agency = 'A',
l AgentOtherMember = 'W'
l IndividualPTIA = 'J'
l AgencyPTIA = 'U'
l AgentOtherMemberPTIA = 'M'
l IndividualPT = 'K'
l AgencyPT = 'Y'
l AgentOtherMemberPT = 'N'
IBString tif The time in force. Valid values are: DAY, GTC, IOC, GTD.
bool sweepToFill If set to true, specifies that the order is a Sweep-to-Fill order.
double trailingPercent Specify the trailing amount of a trailing stop order as a percentage.
Observe the following guidelines when using the trailingPercent
field:
Attribute Description
int triggerfunction Specifies how Simulated Stop, Stop-Limit and Trailing Stop orders
are triggered. Valid values are:
Attribute Description
IBString faGroup The Financial Advisor group the trade will be allocated to -- use an
empty String if not applicable.
IBString faMethod The Financial Advisor allocation function the trade will be alloc-
ated with -- use an empty String if not applicable.
IBString faPercentage The Financial Advisor percentage concerning the trade's allocation -
- use an empty String if not applicable.
IBString faProfile The Financial Advisor allocation profile the trade will be allocated
to -- use an empty String if not applicable.
Institutional (non-cleared) Only
IBString designatedLocation Used only when shortSaleSlot = 2.
double discretionaryAmt The amount off the limit price allowed for discretionary orders.
Attribute Description
bool firmQuoteOnly Trade with firm quotes.
0 = no, 1 = yes
double nbboPriceCap Maximum smart order distance from the NBBO.
bool optOutSmartRouting Use to opt out of default SmartRouting for orders routed directly to
ASX. This attribute defaults to false unless explicitly set to true.
When set to false, orders routed directly to ASX will NOT use
SmartRouting. When set to true, orders routed directly to ASX
orders WILL use SmartRouting.
BOX or VOL Orders Only
l match = 1
l improvement = 2
l transparent = 3
For orders on BOX only.
BOX Exchange Orders Only
double delta The stock delta. For orders on BOX only.
double startingPrice The auction starting price. For orders on BOX only.
double stockRefPrice The stock reference price. The reference price is used for VOL
orders to compute the limit price sent to an exchange (whether or
not Continuous Update is selected), and for price range monitoring.
double stockRangeLower The lower value for the acceptable underlying stock price range. For
price improvement option orders on BOX and VOL orders with
dynamic management.
double stockRangeUpper The upper value for the acceptable underlying stock price range. For
price improvement option orders on BOX and VOL orders with
dynamic management.
Volatility Orders Only
bool continuousUpdate VOL orders only. Specifies whether TWS will automatically update
the limit price of the order as the underlying price moves.
int deltaNeutralAuxPrice VOL orders only. Use this field to enter a value if the value in the
deltaNeutralOrderType field is an order type that requires an Aux
price, such as a REL order.
IBString deltaNeutralOrderType VOL orders only. Enter an order type to instruct TWS to submit a
delta neutral trade on full or partial execution of the VOL order. For
no hedge delta order to be sent, specify NONE.
Attribute Description
int referencePriceType VOL orders only. Specifies how you want TWS to calculate the
limit price for options, and for stock range price monitoring.
Valid values include:
l 1 = Average of NBBO
l 2 = NBB or the NBO depending on the action and right.
double volatility The option price in volatility, as calculated by TWS' Option Ana-
lytics. This value is expressed as a percent and is used to calculate
the limit price sent to the exchange.
int volatilityType Values include:
l 1 = Daily volatility
l 2 = Annual volatility
IBString deltaNeutralOpenClose Specifies whether the order is an Open or a Close order and is used
when the hedge involves a CFD and the order is clearing away.
bool deltaNeutralShortSale Used when the hedge involves a stock and indicates whether or not
it is sold short.
int deltaNeutralShortSaleSlot Has a value of 1 (the clearing broker holds shares) or 2 (delivered
from a third party). If you use 2, then you must specify a deltaNeut-
ralDesignatedLocation.
int scaleInitLevelSize For Scale orders: Defines the size of the first, or initial, order com-
ponent.
int scaleInitPosition() For extended Scale orders.
Attribute Description
int scalePriceAdjustInterval() For extended Scale orders.
double scalePriceIncrement For Scale orders: Defines the price increment between scale com-
ponents. This field is required.
double scaleProfitOffset() For extended Scale orders.
int scaleSubsLevelSize For Scale orders: Defines the order size of the subsequent scale
order components. Used in conjunction with scaleInitLevelSize().
IBString hedgeParam Beta = x for Beta hedge orders, ratio = y for Pair hedge order
IBString hedgeType For hedge orders. Possible values are:
l D = Delta
l B = Beta
l F = FX
l P = Pair
Clearing Information
IBString algoStrategy For information about API Algo orders, see IBAlgo Parameters.
Attribute Description
IBString algoId Identifies an order generated by algorithmic trading.
What If
bool whatIf Use to request pre-trade commissions and margin information.
If set to true, margin and commissions data is received back via the
OrderState() object for the openOrder() callback.
Order Combo Legs
Solicited Orders
bool solicited True = solicited (orders initiated by a broker through the brokers
research and design)
bool m_notHeld For IBDARK orders only. Orders routed to IBDARK are tagged as
“post only” and are held in IB's order book, where incoming
SmartRouted orders from other IB customers are eligible to trade
against them.
TagValueListSPtr order- For internal use only. Use the default value XYZ.
MiscOptions
OrderState
Attribute Description
double commission Shows the commission amount on the order.
IBString commissionCurrency Shows the currency of the commission value.
IBString equityWithLoan Shows the impact the order would have on your
equity with loan value.
IBString initMargin Shows the impact the order would have on your
initial margin.
Attribute Description
IBString maintMargin Shows the impact the order would have on your
maintenance margin.
double maxCommission Used in conjunction with the minCommission
field, this defines the highest end of the possible
range into which the actual order commission will
fall.
double minCommission Used in conjunction with the maxCommission
field, this defines the lowest end of the possible
range into which the actual order commission will
fall.
IBString status Displays the order status.
IBString warningText Displays a warning message if warranted.
ScannerSubscription
Attribute Description
double abovePrice Filter out contracts with a price lower than this value. Can be left
blank.
int aboveVolume Filter out contracts with a volume lower than this value. Can be left
blank.
int aver- Can leave empty.
ageOptionVolumeAbove
double belowPrice Filter out contracts with a price higher than this value. Can be left
blank.
double couponRateAbove Filter out contracts with a coupon rate lower than this value. Can be
left blank.
double couponRateBelow Filter out contracts with a coupon rate higher than this value. Can be
left blank.
IBString excludeConvertible Filter out convertible bonds. Can be left blank.
Attribute Description
IBString moodyRatingAbove Filter out contracts with a Moody rating below this value. Can be left
blank.
IBString moodyRatingBelow Filter out contracts with a Moody rating above this value. Can be left
blank.
int numberOfRows Defines the number of rows of data to return for a query.
IBString scanCode Can be left blank.
IBString scannerSettingPairs Can leave empty. For example, a pairing "Annual, true" used on the
"top Option Implied Vol % Gainers" scan would return annualized
volatilities.
IBString spRatingAbove Filter out contracts with an S&P rating below this value. Can be left
blank.
IBString spRatingBelow Filter out contracts with an S&P rating above this value. Can be left
blank.
IBString stockTypeFilter Valid values are:
l CORP = Corporation
l ADR = American Depositary Receipt
l ETF = Exchange Traded Fund
l REIT = Real Estate Investment Trust
l CEF = Closed End Fund
UnderComp
Attribute Description
int conId The unique contract identifier specifying the security. Used for Delta-
Neutral Combo contracts.
double delta The underlying stock or future delta. Used for Delta-Neutral Combo
contracts.
double price The price of the underlying. Used for Delta-Neutral Combo contracts.
CommissionReport
Attribute Description
double commission The commission amount.
Attribute Description
double yield() The yield.
Example
In this example, a customer places a BUY order for a CLK9 futures contract and a SELL order for a CLM9 futures con-
tract. In this procedure, the customer must invoke reqContractDetails() to obtain the conId for both CLK9 and CLM9 con-
tracts.
Here is a summary of the steps required to place a combo order using the API:
l Obtain the contract id (conId) for each leg. Get this number by invoking the reqContractDetails() method.
l Include each leg on the ComboLeg object by populating the related fields.
l Implement the placeOrder() method with the Contract and Order socket client properties.
con2.m_localSymbol = "CLM9";
con2.m_secType = "FUT";
con2.m_exchange = "NYMEX";
con2.m_currency = "USD";
The conId values are delivered by the following event. If reqId is equal to 1, then the conid is for the CLK9 con-
tract. If reqId is equal to 2, then the conId is for CLM9.
2. Assign all the related values for combo orders and combine them:
leg1.conId = Leg1_conId;
leg1.ratio = 1;
leg1.action = "BUY";
leg1.exchange = "NYMEX";
leg1.openClose = 0;
leg1.shortSaleSlot = 0;
leg1.designatedLocation = "";
leg2.conId = Leg2_conId;
leg2.ratio = 1;
leg2.action = "SELL";
leg2.exchange = "NYMEX";
leg2.openClose = 0;
leg2.shortSaleSlot = 0;
leg2.designatedLocation = "";
3. Invoke the placeOrder() method with the appropriate contract and order objects. As shown below, it includes the
addAllLegs declaration in the contract object.
order.m_action = "BUY";
order.m_totalQuantity = 1;
order.m_orderType = "MKT";
To run the Java Test Client sample program from a new project in NetBeans
1. Open NetBeans and click New Project to start the wizard.
2. In the Projects area, select Java Application and click Next.
3. In the New Java Application window, name your project, choose a location, and uncheck the check box for
Create Main Class.
4. Click Finish.
5. To set up Java to use the API, right-click the project you just created, then select Properties.
6. From the source category click Add Folder.
7. Navigate to the folder where the TWS API is installed. The folders you want to add are called source\JavaCli-
ent\com and samples\Java\apidemo. Click OK.
8. Press F6 to run the sample java project. When the message says "Project Samplejavacode does not have main class
set" select apidemo and click OK.
The Java Test Client’s sample application window is pictured below.
Note: This procedure assumes that you are using Eclipse Helios 3.6.2, but other versions of Eclipse
should also work.
b. Type the project name. For this example, name the project My API Program.
e. Click Finish.
d. Right-click the package com.ib in the Package Explorer panel, then select Import.
f. Click Browse… , then locate the folder where the API is installed (typically source\JavaClient\com). Select
the ib folder (for example, C:\TWS API 9.70\source\JavaClient\com\ib), then click OK.
d. Right-click the package apidemoin the Package Explorer panel, then select Import.
f. Click Browse… , then locate the folder where the Java Test Client is installed (typically samples\Java\).
Select the apidemofolder (for example, C:\TWS API 9.70\samples\Java\apidemo), then click OK.
b. This is what you should see and you are ready to create your own customized program:
EClientSocket()
This is the constructor.
EClientSocket(AnyWrapper anyWrapper)
eConnect()
This function must be called before any other. There is no feedback for a successful connection, but a subsequent attempt
to connect will return the message "Already connected."
eDisconnect()
Call this method to terminate the connections with TWS. Calling this method does not cancel orders that have already
been sent.
void eDisconnect()
isConnected()
Call this method to check if there is a connection with TWS.
void isConnected()
setServerLogLevel()
The default level is ERROR. Refer to the API logging page for more details.
l 1 = SYSTEM
l 2 = ERROR
l 3 = WARNING
l 4 = INFORMATION
l 5 = DETAIL
reqCurrentTime()
Returns the current system time on the server side via the currentTime() EWrapper method.
void reqCurrentTime()
serverVersion()
Returns the version of the TWS instance to which the API application is connected.
void serverVersion()
TwsConnectionTime()
Returns the time the API application made a connection to TWS.
void TwsConnectionTime ()
reqMktData()
Call this method to request market data. The market data will be returned by the tickPrice(), tickSize(), tick-
OptionComputation(), tickGeneric(), tickString() and tickEFP() methods.
void reqMktData(int tickerId, Contract contract, String genericTicklist, boolean snapshot, Lis<TagValue>
mktDataOptions)
cancelMktData()
After calling this method, market data for the specified Id will stop flowing.
calculateImpliedVolatility()
Call this function to calculate volatility for a supplied option price and underlying price.
cancelCalculateImpliedVolatility()
Call this function to cancel a request to calculate volatility for a supplied option price and underlying price.
calculateImpliedVolatility(int reqId)
calculateOptionPrice()
Call this function to calculate option price and greek values for a supplied volatility and underlying price.
cancelCalculateOptionPrice()
Call this function to cancel a request to calculate the option price and greek values for a supplied volatility and under-
lying price.
cancelCalculateOptionPrice(int reqId)
reqMarketDataType()
The API can receive frozen market data from Trader Workstation. Frozen market data is the last data recorded in our sys-
tem. During normal trading hours, the API receives real-time market data. If you use this function, you are telling TWS to
automatically switch to frozen market data after the close. Then, before the opening of the next trading day, market data
will automatically switch back to real-time market data.
reqMarketDataType(int type)
placeOrder()
void placeOrder( int id, Contract contract, Order order)
cancelOrder()
Call this method to cancel an order.
reqOpenOrders()
Call this method to request any open orders that were placed from this API client. Each open order will be fed back
through the openOrder() and orderStatus() methods on the EWrapper.
Note: The client with a clientId of "0" will also receive the TWS-owned open orders. These orders
will be associated with the client and a new orderId will be generated. This association will
persist over multiple API and TWS sessions.
void reqOpenOrders()
reqAllOpenOrders
Call this method to request all open orders that were placed from all API clients linked to one TWS, and also from the
TWS. Note that you can run up to 8 API clients from a single TWS. Each open order will be fed back through the
openOrder() and orderStatus() methods on the EWrapper.
Note: No association is made between the returned orders and the requesting client.
void reqAllOpenOrders()
reqAutoOpenOrders()
Call this method to request that newly created TWS orders be implicitly associated with the client. When a new TWS
order is created, the order will be associated with the client and automatically fed back through the openOrder() and
orderStatus() methods on the EWrapper.
reqIDs()
Call this function to request the next valid ID that can be used when placing an order. After calling this method, the nex-
tValidId() event will be triggered, and the id returned is that next valid ID. That ID will reflect any autobinding that has
occurred (which generates new IDs and increments the next valid ID therein).
exerciseOptions()
Call the exerciseOptions() method to exercise options.
Note: SMART is not an allowed exchange in exerciseOptions() calls, and TWS does a request for
the position in question whenever any API initiated exercise or lapse is attempted.
void exerciseOptions(int tickerId, Contract contract, int exerciseAction, int exerciseQuantity, String account, int over-
ride)
l 1 = exercise
l 2 = lapse
exerciseQuantity int The number of contracts to be exercised
account String For institutional orders. Specifies the IB account.
override int Specifies whether your setting will override the system's natural
action. For example, if your action is "exercise" and the option
is not in-the-money, by natural action the option would not exer-
cise. If you have override set to "yes" the natural action would
be overridden and the out-of-the money option would be exer-
cised. Values are:
l 0 = do not override
l 1 = override
reqGlobalCancel()
Use this method to cancel all open orders globally. It cancels both API and TWS open orders.
If the order was created in TWS, it also gets canceled. If the order was initiated in the API, it also gets canceled.
void reqGlobalCancel()
reqAccountUpdates()
Call this function to start getting account values, portfolio, and last update time information. The account data will be
fed back through the updateAccountTime(), updateAccountValue() and updatePortfolio() EWrapper methods.
The account information resulting from the invocation of reqAccountUpdates() is the same information that appears in
Trader Workstation’s Account Window. When trying to determine the definition of each variable or key within the API
account data, it is essential that you use the TWS Account Window as guidance.
l Strings or keys with a suffix of –C, such as AvailableFunds-C, EquityForInitial-C, NetLiquidation-C, correspond
to Commodities in the TWS Account Window.
l Keys with a suffix of –S, such as EquityForMaintenance-S, FullAvailableFunds-S or NetLiquidation-S, correspond
to Securities in the TWS Account Window.
l Keys without any suffix correspond to Totals in the TWS Account Window.
The image below is an actual example of how to compare TWS’s Account Window and the API’s account data. In this
particular case, we try to link three specific keys NetLiquidation, NetLiquidation-C, and NetLiquidation-S to the TWS
Account Window.
For more information about the information presented in the TWS Account Window, see https://in-
stitutions.interactivebrokers.com/en/software/tws/usersguidebook/realtimeactivitymonitoring/the_account_window.htm
reqAccountSummary()
Call this method to request and keep up to date the data that appears on the TWS Account Window Summary tab. The
data is returned by accountSummary().
reqAccountSummary() only allows two concurrent requests. If you use reqAccountSummary() to request more than two
concurrent account summaries, you will receive an error: 322|Error processing request. To resolve this error, unsubscribe
from one reqAccountSummary() request and then resubmit the request.
Note: This request can only be made when connected to a Financial Advisor (FA) account.
l AccountType
l NetLiquidation,
l TotalCashValue — Total cash including futures pnl
l SettledCash — For cash accounts, this is the same as TotalCashValue
l AccruedCash — Net accrued interest
l BuyingPower — The maximum amount of marginable US stocks the
account can buy
l EquityWithLoanValue — Cash + stocks + bonds + mutual funds
l PreviousDayEquityWithLoanValue,
l GrossPositionValue — The sum of the absolute value of all stock and
equity option positions
l RegTEquity,
l RegTMargin,
l SMA — Special Memorandum Account
l InitMarginReq,
l MaintMarginReq,
l AvailableFunds,
l ExcessLiquidity,
l Cushion — Excess liquidity as a percentage of net liquidation value
l FullInitMarginReq,
l FullMaintMarginReq,
l FullAvailableFunds,
l FullExcessLiquidity,
l LookAheadNextChange — Time when look-ahead values take effect
l LookAheadInitMarginReq,
l LookAheadMaintMarginReq,
l LookAheadAvailableFunds,
l LookAheadExcessLiquidity,
l HighestSeverity — A measure of how close the account is to liquid-
ation
l DayTradesRemaining — The Number of Open/Close trades a user
cancelAccountSummary()
Cancels the request for Account Window Summary tab data.
reqPositions()
Requests real-time position data for all accounts.
void reqPositions()
cancelPositions()
Cancels real-time position updates.
void cancelPositions()
reqExecutions()
When this method is called, the execution reports from the last 24 hours that meet the filter criteria are downloaded to
the client via the execDetails() method. To view executions beyond the past 24 hours, open the Trade Log in TWS and,
while the Trade Log is displayed, request the executions again from the API.
reqContractDetails()
Call this method to download all details for a particular contract. The contract details will be received via the con-
tractDetails() method on the EWrapper.
reqMktDepth()
Call this method to request market depth for a specific contract. The market depth will be returned by the updateMk-
tDepth() and updateMktDepthL2() methods.
cancelMktDepth()
After calling this method, market depth data for the specified Id will stop flowing.
reqNewsBulletins()
Call this method to start receiving news bulletins. Each bulletin will be returned by the updateNewsBulletin() method.
cancelNewsBulletins()
Call this method to stop receiving news bulletins.
void cancelNewsBulletins()
reqManagedAccts()
Call this method to request the list of managed accounts. The list will be returned by the managedAccounts() method on
the EWrapper.
Note: This request can only be made when connected to a Financial Advisor (FA) account
void reqManagedAccts()
requestFA()
Call this method to request FA configuration information from TWS. The data returns in an XML string via the
receiveFA() method.
l 1 = GROUPS
l 2 = PROFILE
l 3 = ACCOUNT ALIASES
replaceFA()
Call this method to request new FA configuration information from TWS. The data returns in an XML string via a
"receiveFA" method.
l 1 = GROUPS
l 2 = PROFILE
l 3 = ACCOUNT ALIASES
xml String The XML string containing the new FA con-
figuration information.
reqAccountSummary()
Call this method to request and keep up to date the data that appears on the TWS Account Window Summary tab. The
data is returned by accountSummary().
reqAccountSummary() only allows two concurrent requests. If you use reqAccountSummary() to request more than two
concurrent account summaries, you will receive an error: 322|Error processing request. To resolve this error, unsubscribe
from one reqAccountSummary() request and then resubmit the request.
Note: This request can only be made when connected to a Financial Advisor (FA) account.
l AccountType
l NetLiquidation,
l TotalCashValue — Total cash including futures pnl
l SettledCash — For cash accounts, this is the same as TotalCashValue
l AccruedCash — Net accrued interest
l BuyingPower — The maximum amount of marginable US stocks the
account can buy
l EquityWithLoanValue — Cash + stocks + bonds + mutual funds
l PreviousDayEquityWithLoanValue,
l GrossPositionValue — The sum of the absolute value of all stock and
equity option positions
l RegTEquity,
l RegTMargin,
l SMA — Special Memorandum Account
l InitMarginReq,
l MaintMarginReq,
l AvailableFunds,
l ExcessLiquidity,
l Cushion — Excess liquidity as a percentage of net liquidation value
l FullInitMarginReq,
l FullMaintMarginReq,
l FullAvailableFunds,
l FullExcessLiquidity,
l LookAheadNextChange — Time when look-ahead values take effect
l LookAheadInitMarginReq,
l LookAheadMaintMarginReq,
l LookAheadAvailableFunds,
l LookAheadExcessLiquidity,
l HighestSeverity — A measure of how close the account is to liquid-
ation
l DayTradesRemaining — The Number of Open/Close trades a user
cancelAccountSummary()
Cancels the request for Account Window Summary tab data.
reqPositions()
Requests real-time position data for all accounts.
void reqPositions()
cancelPositions()
Cancels real-time position updates.
void cancelPositions()
reqScannerParameters()
Call the reqScannerParameters() method to receive an XML document that describes the valid parameters that a scanner
subscription can have.
void reqScannerParameters()
reqScannerSubscription()
Call the reqScannerSubscription() method to start receiving market scanner results through the scannerData() EWrapper
method.
cancelScannerSubscription()
Call the cancelScannerSubscription() method to stop receiving market scanner results.
Parameter Description
reqHistoricalData()
Call the reqHistoricalData() method to start receiving historical data results through the historicalData() EWrapper
method.
void reqHistoricalData (int id, Contract contract, String endDateTime, String durationStr, String barSizeSetting,
String whatToShow, int useRTH, int formatDate, List<TagValue> chartOptions)
l " S (seconds)
l " D (days)
l " W (weeks)
l " M (months)
l " Y (years)
If no unit is specified, seconds are used. Also, note "years" is
currently limited to one.
barSizeSetting String Specifies the size of the bars that will be returned (within
IB/TWS limits). Valid bar size values include:
l 1 sec
l 5 secs
l 15 secs
l 30 secs
l 1 min
l 2 mins
l 3 mins
l 5 mins
l 15 mins
l 30 mins
l 1 hour
l 1 day
whatToShow String Determines the nature of data being extracted. Valid values
include:
l TRADES
l MIDPOINT
l BID
l ASK
l BID_ASK
l HISTORICAL_VOLATILITY
l OPTION_IMPLIED_VOLATILITY
Note: For more information about historical data request limitations, see Historical Data Lim-
itations.
cancelHistoricalData()
Call the cancelHistoricalData() method to stop receiving historical data results.
reqRealTimeBars()
Call the reqRealTimeBars() method to start receiving real time bar results through the realtimeBar() EWrapper method.
void reqRealTimeBars(int tickerId, Contract contract, int barSize, String whatToShow, boolean useRTH, Vect-
or<TagValue> realTimeBarOptions)
cancelRealTimeBars()
Call this method to stop receiving real time bar results.
reqFundamentalData()
Call this method to receive Reuters global fundamental data for stocks. There must be a subscription to Reuters Fun-
damental set up in Account Management before you can receive this data.
reqFundamentalData() can handle conid specified in the Contract object, but not tradingClass or multiplier. This is
because reqFundamentalData() is used only for stocks and stocks do not have a multiplier and trading class.
cancelFundamentalData()
Call this method to stop receiving Reuters global fundamental data.
queryDisplayGroups()
queryDisplayGroups(int reqId)
subscribeToGroupEvents()
subscribeToGroupEvents(int reqId, int groupId)
updateDisplayGroup()
updateDisplayGroup(int reqId, const String contractInfo)
contractInfo String The encoded value that uniquely represents the contract in
IB. Possible values include:
unsubscribeFromGroupEvents()
unsubscribeFromGroupEvents(int reqId)
currentTime()
This method receives the current system time on the server side.
error()
This method is called when there is an error with the communication or when TWS wants to send a message to the cli-
ent.
void error(Exception e)
This method is called when TWS wants to send an error message to the client. (V1).
connectionClosed()
This method is called when TWS closes the sockets connection, or when TWS is shut down.
void connectionClosed()
tickPrice()
This method is called when the market data changes. Prices are updated immediately with no delay.
l 1 = bid
l 2 = ask
l 4 = last
l 6 = high
l 7 = low
l 9 = close
price double Specifies the price for the specified field
canAutoExecute int Specifies whether the price tick is avail-
able for automatic execution. Possible val-
ues are:
tickSize()
This method is called when the market data changes. Sizes are updated immediately with no delay.
l 0 = bid size
l 3 = ask size
l 5 = last size
l 8 = volume
size int Specifies the size for the specified field
tickOptionComputation()
This method is called when the market in an option or its underlier moves. TWS’s option model volatilities, prices, and
deltas, along with the present value of dividends expected on that options underlier are received.
void tickOptionComputation(int tickerId, int field, double impliedVol, double delta, double optPrice, double
pvDividend, double gamma, double vega, double theta, double undPrice)
l 10 = Bid
l 11 = Ask
l 12 = Last
impliedVol double The implied volatility calculated by the TWS
option modeler, using the specified ticktype
value.
delta double The option delta value.
optPrice double The option price.
pvDividend double The present value of dividends expected on the
options underlier
gamma double The option gamma value.
vega double The option vega value.
theta double The option theta value.
undPrice double The price of the underlying.
tickGeneric()
This method is called when the market data changes. Values are updated immediately with no delay.
tickString()
This method is called when the market data changes. Values are updated immediately with no delay.
tickEFP()
This method is called when the market data changes. Values are updated immediately with no delay.
void tickEFP(int tickerId, int tickType, double basisPoints, String formattedBasisPoints, double impliedFuture, int
holdDays, String futureExpiry, double dividendImpact, double dividendsToExpiry)
tickSnapshotEnd()
This is called when a snapshot market data subscription has been fully handled and there is nothing more to wait for.
This also covers the timeout case.
marketDataType()
TWS sends a marketDataType(type) callback to the API, where type is set to Frozen or RealTime, to announce that mar-
ket data has been switched between frozen and real-time. This notification occurs only when market data switches
between real-time and frozen. The marketDataType( ) callback accepts a reqId parameter and is sent per every sub-
scription because different contracts can generally trade on a different schedule.
orderStatus()
This method is called whenever the status of an order changes. It is also fired after reconnecting to TWS if the client has
any open orders.
void orderStatus(int orderId, String status, int filled, int remaining, double avgFillPrice, int permId, int parentId,
double lastFillPrice, int clientId, String whyHeld)
Note: It is possible that orderStatus() may return duplicate messages. It is essential that you filter
the message accordingly.
For more information about partial fills, see Order Status for Partial
Fills.
remaining int Specifies the number of shares still outstanding.
avgFillPrice double The average price of the shares that have been executed. This parameter
is valid only if the filled parameter value is greater than zero. Other-
wise, the price parameter will be zero.
permId int The TWS id used to identify orders. Remains the same over TWS ses-
sions.
openOrder()
This method is called to feed in open orders.
openOrderEnd()
This is called at the end of a given request for open orders.
void openOrderEnd()
nextValidId()
This method is called after a successful connection to TWS.
deltaNeutralValidation()
Upon accepting a Delta-Neutral RFQ(request for quote), the server sends a deltaNeutralValidation() message with the
UnderComp structure. If the delta and price fields are empty in the original request, the confirmation will contain the cur-
rent values from the server. These values are locked when the RFQ is processed and remain locked until the RFQ is can-
celed.
updateAccountValue()
This method is called only when reqAccountUpdates() method on the EClientSocket object has been called.
updatePortfolio()
This method is called only when reqAccountUpdates() method on the EClientSocket object has been called.
void updatePortfolio(Contract contract, int position, double marketPrice, double marketValue, double averageCost,
double unrealizedPNL, double realizedPNL, String accountName)
updateAccountTime()
This method is called only when reqAccountUpdates() method on the EClientSocket object has been called.
accountDownloadEnd()
This event is called after a batch updateAccountValue() and updatePortfolio() is sent.
accountSummary()
Returns the data from the TWS Account Window Summary tab in response to reqAccountSummary().
void accountSummary(int reqId, String account, String tag, String value, String currency)
l AccountType
l TotalCashValue — Total cash including futures pnl
l SettledCash — For cash accounts, this is the same as
TotalCashValue
l AccruedCash — Net accrued interest
l BuyingPower — The maximum amount of marginable
US stocks the account can buy
l EquityWithLoanValue — Cash + stocks + bonds +
mutual funds
l PreviousEquityWithLoanValue
l GrossPositionValue — The sum of the absolute value of
all stock and equity option positions
l RegTEquity
l RegTMargin
l SMA — Special Memorandum Account
l InitMarginReq
l MaintMarginReq
l AvailableFunds
l ExcessLiquidity
l Cushion — Excess liquidity as a percentage of net
liquidation value
l FullInitMarginReq
l FullMaintMarginReq
l FullAvailableFunds
l FullExcessLiquidity
l LookAheadNextChange — Time when look-ahead val-
ues take effect
l LookAheadInitMarginReq
l LookAheadMaintMarginReq
l LookAheadAvailableFunds
l LookAheadExcessLiquidity
l HighestSeverity — A measure of how close the account
accountSummaryEnd
This method is called once all account summary data for a given request are received.
position()
This event returns real-time positions for all accounts in response to the reqPositions() method.
positionEnd()
This is called once all position data for a given request are received and functions as an end marker for the position()
data.
void positionEnd()
contractDetails()
This method is called only when reqContractDetails method on the EClientSocket object has been called.
contractDetailsEnd()
This method is called once all contract details for a given request are received. This helps to define the end of an option
chain.
bondContractDetails()
This method is called only when reqContractDetails method on the EClientSocket object has been called for bonds.
execDetails()
This method is called when the reqExecutions() method is invoked, or when an order is filled.
contract Contract This structure contains a full description of the contract that was
executed.
execDetailsEnd()
This method is called once all executions have been sent to a client in response to reqExecutions().
commissionReport()
The commissionReport() callback is triggered as follows:
updateMktDepth()
This method is called when the market depth changes.
void updateMktDepth(int tickerId, int position, int operation, int side, double price, int size)
l 0 = ask
l 1 = bid
price double The order price.
size int The order size.
updateMktDepthL2()
This method is called when the Level II market depth changes.
void updateMktDepthL2(int tickerId, int position, String marketMaker, int operation, int side, double price, int size)
l 0 = insert (insert this new order into the row identified by 'pos-
ition')·
l 1 = update (update the existing order in the row identified by
'position')·
l 2 = delete (delete the existing order at the row identified by 'pos-
ition')
side int Identifies the side of the book that this order belongs to. Valid values
are:
l 0 = ask
l 1 = bid
price double The order price.
size int The order size.
updateNewsBulletin()
This method is triggered for each new bulletin if the client has subscribed (i.e. by calling the reqNewsBulletins() method.
managedAccounts()
This method is called when a successful connection is made to an account. It is also called when the reqManagedAccts()
method is invoked.
receiveFA()
This method receives previously requested FA configuration information from TWS.
l 1 = GROUPS
l 2 = PROFILE
l 3 =ACCOUNT ALIASES
xml String The XML string containing the previously
requested FA configuration information.
historicalData()
This method receives the requested historical data results.
void historicalData (int reqId, String date, double open, double high, double low, double close, int volume, int count,
double WAP, boolean hasGaps)
WAP double The weighted average price during the time covered by the bar.
hasGaps boolean Whether or not there are gaps in the data.
scannerParameters()
This method receives an XML document that describes the valid parameters that a scanner subscription can have.
scannerData()
This method receives the requested market scanner data results.
void scannerData(int reqId, int rank, ContractDetails contractDetails, String distance, String benchmark, String pro-
jection, String legsStr)
scannerDataEnd()
This method is called when the snapshot is received and marks the end of one scan.
realtimeBar()
This method receives the real-time bars data results.
void realtimeBar(int reqId, long time, double open, double high, double low, double close, long volume, double wap,
int count)
fundamentalData()
This method is called to receive Reuters global fundamental market data. There must be a subscription to Reuters Fun-
damental set up in Account Management before you can receive this data.
l Company overview
l Financial summary
l Financial ratios
l Financial statements
l Analyst estimates
l Company calendar
displayGroupList()
This callback is a one-time response to queryDisplayGroups().
displayGroupUpdated()
This is sent by TWS to the API client once after receiving the subscription request subscribeToGroupEvents(), and will
be sent again if the selected contract in the subscribed display group has changed.
contractInfo String The encoded value that uniquely represents the contract in
IB. Possible values include:
l Execution
l ExecutionFilter
l CommissionReport
l Contract
l ContractDetails
l ComboLeg
l Order
l OrderState
l ScannerSubscription
l UnderComp
Execution
Attribute Description
String m_acctNumber The customer account number.
double m_avgPrice Average price. Used in regular trades, combo
trades and legs of the combo. Does not include
commissions.
int m_clientId The id of the client that placed the order.
Note: TWS orders have a fixed client id of "0."
int m_cumQty Cumulative quantity. Used in regular trades,
combo trades and legs of the combo.
String m_exchange Exchange that executed the order.
String m_execId Unique order execution id.
int m_liquidation Identifies the position as one to be liquidated
last should the need arise.
int m_orderId The order id.
Attribute Description
String m_side Specifies if the transaction was a sale or a pur-
chase. Valid values are:
l BOT
l SLD
String m_time The order execution time.
String m_evRule Contains the Economic Value Rule name and the
respective optional argument. The two values
should be separated by a colon. For example, aus-
sieBond:YearsToExpiration=3. When the
optional argument is not present, the first value
will be followed by a colon.
double m_evMultiplier Tells you approximately how much the market
value of a contract would change if the price
were to change by 1. It cannot be used to get mar-
ket value by multiplying the price by the approx-
imate multiplier.
ExecutionFilter
Attribute Description
String m_acctCode Filter the results of the reqExecutions() method based on an
account code. Note: this is only relevant for Financial
Advisor (FA) accounts.
int m_clientId Filter the results of the reqExecutions() method based on
the clientId.
String m_exchange Filter the results of the reqExecutions() method based on
theorder exchange.
String m_secType Filter the results of the reqExecutions() method based on
the order security type.
Note: Refer to the Contract struct for the list of valid secur-
ity types.
String m_side Filter the results of the reqExecutions() method based on
the order action.
Note: Refer to the Order class for the list of valid order
actions.
String m_symbol Filter the results of the reqExecutions() method based on
the order symbol.
String m_time Filter the results of the reqExecutions() method based on
execution reports received after the specified time.
The format for timeFilter is "yyyymmdd-hh:mm:ss"
CommissionReport
Attribute Description
double m_commission() The commission amount.
Contract
Attribute Description
Vector m_comboLegs Dynamic memory structure used to store the leg definitions for
this contract.
String m_currency 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.
boolean m_includeExpired If set to true, contract details requests and historical data quer-
ies can be performed pertaining to expired contracts.
Note: Historical data queries on expired contracts are limited
to the last year of the contracts life, and are initially only sup-
ported for expired futures contracts,
String m_localSymbol This is the local exchange symbol of the underlying asset.
String m_primaryExch Identifies the listing exchange for the contract (do not list
SMART).
String m_right Specifies a Put or Call. Valid values are: P, PUT, C, CALL.
String m_secIdType Security identifier, when querying contract details or when pla-
cing orders. Supported identifiers are:
l STK
l OPT
l FUT
l IND
l FOP
l CASH
l BAG
l NEWS
ContractDetails
Attribute Description
String m_category The industry category of the underlying. For example, Invest-
mentSvc.
String m_contractMonth The contract month. Typically the contract month of the under-
lying for a futures contract.
String m_liquidHours The regular trading hours of the product. For example,
20090507:0930-1600;20090508:CLOSED.
String m_orderTypes The list of valid order types for this contract.
String m_subcategory The industry subcategory of the underlying. For example, Broker-
age.
String m_timeZoneId The ID of the time zone for the trading hours of the product. For
example, EST.
String m_tradingHours The total trading hours of the product. For example,
20090507:0700-1830,1830-2330;20090508:CLOSED.
String m_evRule Contains the Economic Value Rule name and the respective
optional argument. The two values should be separated by a
colon. For example, aussieBond:YearsToExpiration=3. When the
optional argument is not present, the first value will be followed
by a colon.
double m_evMultiplier Tells you approximately how much the market value of a con-
tract would change if the price were to change by 1. It cannot be
used to get market value by multiplying the price by the approx-
imate multiplier.
Bond Values
boolean m_callable For Bonds. Values are True or False. If true, the bond can be
called by the issuer under certain conditions.
boolean m_convertible For Bonds. Values are True or False. If true, the bond can be con-
verted to stock under certain conditions.
double m_coupon For Bonds. The interest rate used to calculate the amount you
will receive in interest payments over the course of the year.
String m_cusip For Bonds. The nine-character bond CUSIP or the 12-character
SEDOL.
String m_issueDate For Bonds. The date the bond was issued.
String m_maturity For Bonds. The date on which the issuer must repay the face
value of the bond.
boolean m_putable For Bonds. Values are True or False. If true, the bond can be
sold back to the issuer under certain conditions.
String m_ratings For Bonds. Identifies the credit rating of the issuer. A higher
credit rating generally indicates a less risky investment. Bond rat-
ings are from Moody's and S&P respectively.
String m_notes For Bonds, if populated for the bond in IB's database
ComboLeg
Attribute Description
String m_action The side (buy or sell) for the leg you are con-
structing.
int m_conId The unique contract identifier specifying the
security.
String m_designatedLocation If shortSaleSlot == 2, the designatedLocation
must be specified. Otherwise leave blank or
orders will be rejected.
String m_exchange The exchange to which the complete com-
bination order will be routed.
int m_openClose Specifies whether the order is an open or close
order. Valid values are:
Attribute Description
int m_ratio Select the relative number of contracts for the
leg you are constructing. To help determine the
ratio for a specific combination order, refer to
the Interactive Analytics section of the User's
Guide.
int m_shortSaleSlot For institutional customers only.
OrderComboLeg
Attribute Description
double m_price Order-specific leg price.
Order
Attribute Description
Order Identifiers
int m_clientId The id of the client that placed this order.
int m_orderId The id for this order.
int m_permid The TWS id used to identify orders, remains the same over
TWS sessions.
Main Order Fields
String m_action Identifies the side. Valid values are: BUY, SELL, SSHORT
double m_auxPrice This is the STOP price for stop-limit orders, and the offset
amount for relative orders. In all other cases, specify zero.
double m_lmtPrice This is 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.
String m_orderType Identifies the order type.
Attribute Description
boolean m_blockOrder If set to true, specifies that the order is an ISE Block order.
int m_displaySize The publicly disclosed order size, used when placing Iceberg
orders.
String m_goodAfterTime The trade's "Good After Time," format
"YYYYMMDD hh:mm:ss (optional time zone)"
Use an empty String if not applicable.
String m_goodTillDate You must enter GTD as the time in force to use this string.
The trade's "Good Till Date," format "YYYYMMDD hh:m-
m:ss (optional time zone)"
Use an empty String if not applicable.
boolean hidden If set to true, the order will not be visible when viewing the
market depth. This option only applies to orders routed to the
ISLAND exchange.
int m_minQty Identifies a minimum quantity order type.
String m_ocaGroup Identifies an OCA (one cancels all) group.
int m_ocaType Tells how to handle remaining orders in an OCA group when
one order or part of an order executes. Valid values include:
Attribute Description
boolean overridePercentageConstraints Precautionary constraints are defined on the TWS Presets page,
and help ensure tha tyour price and size order values are reas-
onable. Orders sent from the API are also validated against
these safety constraints, and may be rejected if any constraint
is violated. To override validation, set this parameter’s value
to True.
Valid values include:
l 0 = False
l 1 = True
string m_rule80A Values include:
l Individual = 'I'
l Agency = 'A',
l AgentOtherMember = 'W'
l IndividualPTIA = 'J'
l AgencyPTIA = 'U'
l AgentOtherMemberPTIA = 'M'
l IndividualPT = 'K'
l AgencyPT = 'Y'
l AgentOtherMemberPT = 'N'
boolean m_sweepToFill If set to true, specifies that the order is a Sweep-to-Fill order.
String m_tif The time in force. Valid values are: DAY, GTC, IOC, GTD.
bool m_transmit Specifies whether the order will be transmitted by TWS. If set
to false, the order will be created at TWS but will not be sent.
Attribute Description
int m_triggerMethod Specifies how Simulated Stop, Stop-Limit and Trailing Stop
orders are triggered. Valid values are:
String m_faGroup The Financial Advisor group the trade will be allocated to --
use an empty String if not applicable.
String m_faMethod The Financial Advisor allocation function the trade will be
allocated with -- use an empty String if not applicable.
Attribute Description
String m_faPercentage The Financial Advisor percentage concerning the trade's
allocation -- use an empty String if not applicable.
String m_faProfile The Financial Advisor allocation profile the trade will be alloc-
ated to -- use an empty String if not applicable.
Institutional (non-cleared) Only
String m_designatedLocation Used only when shortSaleSlot = 2.
double m_discretionaryAmt The amount off the limit price allowed for discretionary orders.
l match = 1
l improvement = 2
l transparent = 3
For orders on BOX only.
BOX Exchange Orders Only
Attribute Description
Pegged-to-Stock and VOL Orders Only
double m_stockRangeLower The lower value for the acceptable underlying stock price
range. For price improvement option orders on BOX and VOL
orders with dynamic management.
double m_stockRangeUpper The upper value for the acceptable underlying stock price
range. For price improvement option orders on BOX and VOL
orders with dynamic management.
Volatility Orders Only
boolean m_continuousUpdate VOL orders only. Specifies whether TWS will automatically
update the limit price of the order as the underlying price
moves.
String m_deltaNeutralOrderType VOL orders only. Enter an order type to instruct TWS to sub-
mit a delta neutral trade on full or partial execution of the VOL
order. For no hedge delta order to be sent, specify NONE.
int m_deltaNeutralAuxPrice VOL orders only. Use this field to enter a value if the value in
the deltaNeutralOrderType field is an order type that requires
an Aux price, such as a REL order.
int m_referencePriceType VOL orders only. Specifies how you want TWS to calculate
the limit price for options, and for stock range price mon-
itoring.
Valid values include:
l 1 = Average of NBBO
l 2 = NBB or the NBO depending on the action and
right.
double m_volatility The option price in volatility, as calculated by TWS' Option
Analytics. This value is expressed as a percent and is used to
calculate the limit price sent to the exchange.
int m_volatilityType Values include:
l 1 = Daily volatility
l 2 = Annual volatility
String m_deltaNeutralOpenClose Specifies whether the order is an Open or a Close order and is
used when the hedge involves a CFD and the order is clearing
away.
boolean m_deltaNeutralShortSale Used when the hedge involves a stock and indicates whether or
not it is sold short.
Attribute Description
int m_deltaNeutralShortSaleSlot Has a value of 1 (the clearing broker holds shares) or 2
(delivered from a third party). If you use 2, then you must spe-
cify a deltaNeutralDesignatedLocation.
int m_scaleInitLevelSize For Scale orders: Defines the size of the first, or initial, order
component.
int m_scaleInitPosition() For extended Scale orders.
double m_scalePriceIncrement For Scale orders: Defines the price increment between scale
components. This field is required.
double m_scaleProfitOffset() For extended Scale orders.
int m_scaleSubsLevelSize For Scale orders: Defines the order size of the subsequent scale
order components. Used in conjunction with scaleInitLevelSize
().
String m_scaleTable Manual table for Scale orders.
String m_hedgeParam Beta = x for Beta hedge orders, ratio = y for Pair hedge order
Attribute Description
String m_hedgeType For hedge orders. Possible values are:
l D = Delta
l B = Beta
l F = FX
l P = Pair
Clearing Information
Solicited Orders
Attribute Description
OrderComboLegs() As Object Holds attributes for all legs in a combo order.
Not Held
boolean m_notHeld For IBDARK orders only. Orders routed to IBDARK are tagged
as “post only” and are held in IB's order book, where incoming
SmartRouted orders from other IB customers are eligible to
trade against them.
Vector<TagValue> For internal use only. Use the default value XYZ.
m_orderMiscOptions
OrderState
Attribute Description
double m_commission Shows the commission amount on the order.
String m_commissionCurrency Shows the currency of the commission value.
String m_equityWithLoan Shows the impact the order would have on your
equity with loan value.
String m_initMargin Shows the impact the order would have on your ini-
tial margin.
String m_maintMargin Shows the impact the order would have on your
maintenance margin.
double m_maxCommission Used in conjunction with the minCommission field,
this defines the highest end of the possible range
into which the actual order commission will fall.
double m_minCommission Used in conjunction with the maxCommission field,
this defines the lowest end of the possible range into
which the actual order commission will fall.
string m_status Displays the order status.
String m_warningText Displays a warning message if warranted.
ScannerSubscription
Attribute Description
double m_abovePrice Filter out contracts with a price lower than this value. Can be left
blank.
Attribute Description
int m_aboveVolume Filter out contracts with a volume lower than this value. Can be left
blank.
int m_aver- Can leave empty.
ageOptionVolumeAbove
double m_belowPrice Filter out contracts with a price higher than this value. Can be left
blank.
double m_couponRateAbove Filter out contracts with a coupon rate lower than this value. Can be
left blank.
double m_couponRateBelow Filter out contracts with a coupon rate higher than this value. Can be
left blank.
String m_excludeConvertible Filter out convertible bonds. Can be left blank.
String m_instrument Defines the instrument type for the scan.
String m_locationCode The location.
String m_matur- Filter out contracts with a maturity date earlier than this value. Can be
ityDateAbove left blank.
String m_maturityDateBelow Filter out contracts with a maturity date later than this value. Can be
left blank.
double m_marketCapAbove Filter out contracts with a market cap lower than this value. Can be left
blank.
double m_marketCapBelow Filter out contracts with a market cap above this value. Can be left
blank.
String m_moodyRat- Filter out contracts with a Moody rating below this value. Can be left
ingAbove blank.
String m_moodyRat- Filter out contracts with a Moody rating above this value. Can be left
ingBelow blank.
int m_numberOfRows Defines the number of rows of data to return for a query.
Attribute Description
String m_stockTypeFilter Valid values are:
l CORP = Corporation
l ADR = American Depositary Receipt
l ETF = Exchange Traded Fund
l REIT = Real Estate Investment Trust
l CEF = Closed End Fund
UnderComp
Attribute Description
int m_conId The unique contract identifier specifying the security. Used for Delta-
Neutral Combo contracts.
double m_delta The underlying stock or future delta. Used for Delta-Neutral Combo
contracts.
double m_price The price of the underlying. Used for Delta-Neutral Combo contracts.
Example
In this example, a customer places a BUY order on a calendar spread for GOOG. To buy one calendar spread means:
Here is a summary of the steps required to place a combo order using the API:
l Obtain the contract id (conId) for each leg. Get this number by invoking the reqContractDetails() method.
l · Include each leg on the ComboLeg object by populating the related fields.
l · Implement the placeOrder() method with the Contract and Order socket client properties.
con1.m_symbol = "GOOG";
con1.m_secType = "OPT";
con1.m_expiry = “200909”;
con1.m_strike = 150.0
con1.m_right = “C”
con1.m_multiplier = “100”
con1.m_exchange = "SMART”;
con1.m_currency = "USD";
.reqContractDetails(1, con1);
//Second leg
con2.m_symbol = "GOOG";
con2.m_secType = "OPT";
con2.m_expiry = “201101”;
con2.m_strike = 150.0
con2.m_right = “C”
con2.m_multiplier = “100”
con2.m_exchange = "SMART”;
con2.m_currency = "USD";
.reqContractDetails(2, con2);
if (reqId == 1)
{ Leg1_conId = contract.m_conId;} // to obtain conId for first leg
if (reqId == 2)
{ Leg2_conId = contract.m_conId;} // to obtain conId for second leg
}
2. Once the program has acquired the conId value for each leg, include it in the ComboLeg object:
ComboLeg leg1 = new ComboLeg(); // for the first leg
ComboLeg leg2 = new ComboLeg(); // for the second leg
Vector addAllLegs = new Vector();
leg1.m_conId = Leg1_conId;
leg1.m_ratio = 1;
leg1.m_action = "SELL";
leg1.m_exchange = "SMART";
leg1.m_openClose = 0;
leg1.m_shortSaleSlot = 0;
leg1.m_designatedLocation = "";
leg2.m_conId = Leg2_conId;
leg2.m_ratio = 1;
leg2.m_action = "BUY";
leg2.m_exchange = "SMART";
leg2.m_openClose = 0;
leg2.m_shortSaleSlot = 0;
leg2.m_designatedLocation = "";
addAllLegs.add(leg1);
addAllLegs.add(leg2);
3. Invoke the placeOrder() method with the appropriate contract and order objects:
Contract contract = new Contract();
Order order = new Order();
contract.m_symbol = "USD"; // For combo order use “USD” as the symbol value
all the time
order.m_action = “BUY”;
order.m_totalQuantity = 1;
order.m_orderType = “MKT”
.placeOrder(OrderId, contract, order);
Note: For more information on combination orders, see the TWS Users Guide topic About Com-
bination Orders.
void onHowToDetermineOption(){
contract.m_symbol = "IBKR";
contract.m_secType = "OPT";
contract.m_expiry = "20120316";
contract.m_strike = 20.0;
contract.m_right = "P";
contract.m_multiplier = "100";
contract.m_exchange = "SMART";
contract.m_currency = "USD";
order.m_action = "BUY";
order.m_totalQuantity = 1;
order.m_orderType = "LMT";
order.m_lmtPrice = enteredLmtPrice;
void inUsingOptionSymbologyInitiative(){
order.m_action = "BUY";
order.m_totalQuantity = 1;
order.m_orderType = "LMT";
order.m_lmtPrice = enteredLmtPrice;
void onHowtoDetermineFuture(){
contract.m_symbol = "ES";
contract.m_secType = "FUT";
contract.m_expiry = "201109";
contract.m_exchange = "GLOBEX";
contract.m_currency = "USD";
order.m_action = "BUY";
order.m_totalQuantity = 1;
order.m_orderType = "LMT";
order.m_lmtPrice = enteredLmtPrice;
void inUsingLocalSymbolForFuture(){
contract.m_localSymbol = "ESU1";
contract.m_secType = "FUT";
contract.m_exchange = "GLOBEX";
contract.m_currency = "USD";
order.m_action = "BUY";
order.m_totalQuantity = 1;
order.m_orderType = "LMT";
order.m_lmtPrice = enteredLmtPrice;
void onHowToDetermineStock(){
contract.m_symbol = "IBKR";
contract.m_secType = "STK";
contract.m_exchange = "SMART";
contract.m_currency = "USD";
order.m_action = "BUY";
order.m_totalQuantity = 100;
order.m_orderType = "LMT";
order.m_lmtPrice = enteredLmtPrice;
l CSharp API sample code - located in the samples/CSharp folder in your API installation directory (typically
TWS API X.XX, where X.XX is the current version number);
l CSharp source code - located in the source/CSharpClient folder in your API installation directory.
This chapter describes the C# (C Sharp) API, including the following topics:
Note: For this tutorial, we are using Interactive Brokers C# API (v. 9.71) and creating the sample
application in Microsoft Visual Studio 2010 Professional Edition.
Note: All the code provided with this example is “as is” and for illustrative purposes only.
For your convenience, you can request the full sample solution resulting from this tutorial by contacting our API Support
team at [email protected].
In this first part of the tutorial, you will create new C# Console Application in Visual Studio.
2. In New Project dialog, select Visual C# from the list of Installed Templates on the left, then select Console Applic-
ation.
3. Type HelloIBCSharp as the project name in the Name field, then click the Browse button and choose a location
for the project on your computer.
4. Click OK.
Continue to the next step in this tutorial, 2. Add the CSharpAPI Project.
Now that the project has been created, the first thing that you need to do is to add a reference to the pre-built C# API
DLL file (which is the result of opening and building the C# API project), or directly add the C# API project to the solu-
tion. Adding the entire C# API project lets gives you access to the API source code for reference while developing.
2. Navigate to the API's source/CSharpClientdirectory and select the file CSharpAPI.csproj, then click Open.
3. Now that both projects are shown in the Solution Explorer, you need to add a reference of CSharpAPI to Hel-
loIBCSharp. Right-click the HelloIBCSharp project , then select Add Reference from the menu.
4. The CSharpAPI project appears on the Projects tab of the Add Reference dialog. Click CSharpAPI, and then
click OK to finish adding the reference.
Continue to the next step in this tutorial, 3. Add the DLL Reference.
In this step of the tutorial, instead of adding the complete CSharpAPI project to your solution, you will directly add a ref-
erence to the pre-built DLL (Dynamic Link Library).
The resulting DLL will be created in your API installation directory's the /source/csharpclient/bin/Release folder
as CSharpAPI.dll.
3. Right-click the HelloIBCSharp project in the Solution Explorer, then click Add reference.
4. On the resulting dialog’s Browse tab, navigate to the location of the DLL (/source/csharpclient/bin/Release in
your API installation directory) and select the library:
Continue to the next step in this tutorial, 4. Implement the EWrapper Interface.
IB’s C# API consists mainly of a client socket (ESocketClient) containing a reference to an object which implements the
EWrapper interface. It is because of this interface’s implementation that the client application (HelloIBCSharp) can
receive and handle all incoming messages sent by TWS/IB Gateway. In this step of the tutorial, you will implement the
EWrapper interface.
2. In the Add New Item dialog, select Class, then enter the name of the new class as EWrapperImpl. Click Add.
3. Given that EWrapperImpl will implement the EWrapper, extend your new class as shown below in the file EWrap-
perImpl.cs.
4. Since you also want to use the EWrapperImpl class to communicate with the TWS/IB Gateway, you will need to
add an EClientSocket member variable along with its get/set properties. Note that in the class constructor, you ini-
tialize the clientSocket variable passing a reference of the newly created EWrapperImpl object.
If you were to try to compile and run the project at this stage, you would see errors like the ones shown below.
These errors indicate that EWrapperImpl is not implementing all of the methods declared in the EWrapper inter-
face. In order to proceed, you need to provide at least an empty shell of all methods declared in EWrapper.
5. Save all files.
Continue to the next step in this tutorial, 5. Connect to TWS.
In this step of the tutorial, you will add the code required to connect your application to TWS.
2. Note that after connecting, you also added a call to prevent the application from exiting immediately. Imme-
diately after the connection is established, TWS will automatically send some messages like managed accounts
and the server time. The following image shows the EWrapperImpl methods which get triggered:
In the final step of this tutorial, you will add code to your solution to request market data and display it on the screen.
1. After we request the market data, it will mainly arrive via the tickPrice() and tickSize() methods. Our imple-
mentation of them will be very simple as we only want to show the messages on the program’s console window
via Console.
In the file EWrapperImpl, add the following lines of code to implement the relevant methods.
2. Next, in the main method in the file Program.cs, you need to define a contract whose market data you want to
request. Forex pairs are the ideal candidates as they do not require any market data subscription, so in this tutorial,
you will show the price and sizes for the EUR.GBP contract.
To do this, your main class will look like the code in the following image.
The lines in the larger box pictured above show the contract’s definition while on the line in the smaller box pic-
tured above represents the actual market data request (using the reqMktData() method). When requesting real-time
market data, you must provide an identifier to which the incoming data is matched. This identifier is the tickerId
parameter, which is passed to the tickSize and tickPrice events on the EWrapper’s interface and its implementing
class.
3. Save all files.
4. Build and run your application. You should be able to see all the incoming values, as pictured below.
Note the underlined Ticker Id: 1 fragment. This indicates that the received data corresponds to the request iden-
tified by Id 1.
This simple tutorial was an introduction on how to create the first C# program from scratch. The C# API provides two
sample solutions demonstrating the rest of the API functionality.
For your convenience, you can request the full sample solution resulting from this tutorial by contacting our API Support
team at [email protected].
C# EClientSocket Methods
This section describes the class EClientSocket methods you use when connecting to TWS using C#. The list of methods
includes:
EClientSocket()
This client class contains all the available methods to communicate with IB. Up to eight clients can be connected to a
single instance of the TWS/Gateway simultaneously.
eConnect()
Establishes a connection to TWS/Gateway. After establishing a connection successfully, TWS/Gateway will provide the
next valid order id, server's current time, managed accounts and open orders among others depending on the TWS/Gate-
way version.
eDisconnect()
Call this method to terminate the connections with TWS. Calling this method does not cancel orders that have already
been sent.
isConnected()
Call this method to check if there the API client is connected to TWS/Gateway.
setServerLogLevel()
The default level is ERROR. Refer to the API logging page for more details.
l 1 = SYSTEM
l 2 = ERROR
l 3 = WARNING
l 4 = INFORMATION
l 5 = DETAIL
reqCurrentTime()
Requests the server's current system time. The currentTime() EWrapper method returns the time.
reqGlobalCancel()
Use this method to cancel all open orders. It cancels orders placed from the API client and orders placed directly in TWS.
reqMktData()
Call this method to request market data. The market data will be returned by the tickPrice(), tickSize(), tick-
OptionComputation(), tickGeneric(), tickString() and tickEFP() methods.
public void reqMktData(int tickerId, Contract contract, string genericTickList, bool snapshot)
cancelMktData()
Cancels a market data request.
calculateImpliedVolatility()
Request the calculation of the implied volatility based on hypothetical option and its underlying prices. The calculation
will be return in EWrapper's tickOptionComputation() callback.
public void calculateImpliedVolatility(int reqId, Contract contract, double optionPrice, double underPrice)
cancelCalculateImpliedVolatility()
Cancels a request to calculate implied volatility for a supplied option price and underlying price.
calculateOptionPrice()
Calculates an option's price based on the provided volatility and its underlying's price. The calculation will be returned
in the EWrapper tickOptionComputation() callback.
cancelCalculateOptionPrice()
Call this function to cancel a request to calculate the option price and greek values for a supplied volatility and under-
lying price.
cancelCalculateOptionPrice(int reqId)
reqMarketDataType()
The API can receive frozen market data from Trader Workstation. Frozen market data is the last data recorded in our sys-
tem. During normal trading hours, the API receives real-time market data. If you use this function, you are telling TWS to
automatically switch to frozen market data after the close. Then, before the opening of the next trading day, market data
will automatically switch back to real-time market data.
reqMarketDataType(int marketDataType)
placeOrder()
public void placeOrder( int id, Contract contract, Order order)
cancelOrder()
Call this method to cancel an order.
reqOpenOrders()
Requests all open orders that were placed from this specific API client (identified by the API client ID). Each open order
will be fed back through the openOrder() and orderStatus() events.
Note: The client with a clientId of "0" will also receive the TWS-owned open orders. These orders
will be associated with the client and a new orderId will be generated. This association will
persist over multiple API and TWS sessions.
reqAllOpenOrders
Requests all open orders submitted by any API client as well as those directly placed in the TWS. The existing orders
will be received via the openOrder() and orderStatus() events.
Note: No association is made between the returned orders and the requesting client.
reqAutoOpenOrders()
Requests all order placed on the TWS directly. Only the orders created after this request has been made will be returned.
When a new TWS order is created, the order will be associated with the client and automatically fed back through the
openOrder() and orderStatus() events.
reqIDs()
Requests the next valid order ID.
exerciseOptions()
Call this method to exercise options.
Note: SMART is not an allowed exchange in exerciseOptions() calls, and TWS does a request for
the position in question whenever any API initiated exercise or lapse is attempted.
public void exerciseOptions(int tickerId, Contract contract, int exerciseAction, int exerciseQuantity, string account,
int override)
l 1 = exercise
l 2 = lapse
exerciseQuantity int The number of contracts to be exercised.
account string For institutional orders. Specifies the destination account.
override int Specifies whether your setting will override the system's natural
action. For example, if your action is "exercise" and the option
is not in-the-money, by natural action the option would not exer-
cise. If you have override set to "yes" the natural action would
be overridden and the out-of-the money option would be exer-
cised. Values are:
l 0 = do not override
l 1 = override
reqGlobalCancel()
Use this method to cancel all open orders. It cancels orders placed from the API client and orders placed directly in TWS.
reqAccountUpdates()
Subscribes to a specific account's information and portfolio. Use this method to start and stop a subscription to a single
account. As a result of this subscription, the account's information, portfolio and last update time will be received via the
updateAccountTime(), updateAccountValue() and updatePortfolio() EWrapper events.
You can subscribe to only one account at a time. A second subscription request for another account when the previous
subscription is still active will cause the first one to be canceled in favor of the second. Consider using reqPositions() if
you want to retrieve all your accounts' portfolios directly.
l Strings or keys with a suffix of –C, such as AvailableFunds-C, EquityForInitial-C, NetLiquidation-C, correspond
to Commodities in the TWS Account Window.
l Keys with a suffix of –S, such as EquityForMaintenance-S, FullAvailableFunds-S or NetLiquidation-S, correspond
to Securities in the TWS Account Window.
l Keys without any suffix correspond to Totals in the TWS Account Window.
The image below is an actual example of how to compare TWS’s Account Window and the API’s account data. In this
particular case, we try to link three specific keys NetLiquidation, NetLiquidation-C, and NetLiquidation-S to the TWS
Account Window.
For more information about the information presented in the TWS Account Window, see https://in-
stitutions.interactivebrokers.com/en/software/tws/usersguidebook/realtimeactivitymonitoring/the_account_window.htm
reqAccountSummary()
This method will subscribe to the account summary as presented on the TWS Account Summary tab. The data is returned
by accountSummary().
Note: This request can only be made when connected to a Financial Advisor (FA) account.
reqAccountSummary() only allows two concurrent requests. If you use reqAccountSummary() to request more than two
concurrent account summaries, you will receive an error: 322|Error processing request. To resolve this error, unsubscribe
from one reqAccountSummary() request and then resubmit the request.
l AccountType
l NetLiquidation,
l TotalCashValue — Total cash including futures pnl
l SettledCash — For cash accounts, this is the same as TotalCashValue
l AccruedCash — Net accrued interest
l BuyingPower — The maximum amount of marginable US stocks the
account can buy
l EquityWithLoanValue — Cash + stocks + bonds + mutual funds
l PreviousDayEquityWithLoanValue,
l GrossPositionValue — The sum of the absolute value of all stock and
equity option positions
l RegTEquity,
l RegTMargin,
l SMA — Special Memorandum Account
l InitMarginReq,
l MaintMarginReq,
l AvailableFunds,
l ExcessLiquidity,
l Cushion — Excess liquidity as a percentage of net liquidation value
l FullInitMarginReq,
l FullMaintMarginReq,
l FullAvailableFunds,
l FullExcessLiquidity,
l LookAheadNextChange — Time when look-ahead values take effect
l LookAheadInitMarginReq,
l LookAheadMaintMarginReq,
l LookAheadAvailableFunds,
l LookAheadExcessLiquidity,
l HighestSeverity — A measure of how close the account is to liquid-
ation
l DayTradesRemaining — The Number of Open/Close trades a user
cancelAccountSummary()
Cancels the request for Account Window Summary tab data.
reqPositions()
Requests real-time position data for all accounts.
cancelPositions()
Cancels real-time position updates.
reqExecutions()
Requests all the day's executions matching the filter criteria. Only the current day's executions can be retrieved. Along
with the executions, the CommissionReport will also be returned. Execution details are returned to the client via execDe-
tails(). To view executions beyond the past 24 hours, open the Trade Log in TWS and, while the Trade Log is displayed,
request the executions again from the API.
reqContractDetails()
This method returns all contracts matching the contract provided. It can also be used to retrieve complete options and
futures chains. The contract details will be received via the contractDetails() method on the EWrapper.
reqMktDepth()
Call this method to request market depth (order book) for a specific contract. The market depth will be returned by the
updateMktDepth() and updateMktDepthL2() methods.
cancelMktDepth()
Cancels market depth for the specified ID.
reqNewsBulletins()
Call this method to start receiving news bulletins. Each bulletin will be returned by the updateNewsBulletin() method.
cancelNewsBulletins()
Call this method to stop receiving news bulletins.
reqManagedAccts()
Requests the accounts to which the logged-in user has access. The list will be returned by managedAccounts().
Note: This request can only be made when connected to a Financial Advisor (FA) account
requestFA()
Requests Financial Advisor configuration information from TWS. The data returns in an XML string via receiveFA().A
Financial Advisor can define three different configurations:
1. Groups: offer traders a way to create a group of accounts and apply a single allocation method to all accounts in
the group.
2. Profiles: lets you allocate shares on an account-by-account basis using a predefined calculation value.
3. Account Aliases: lets you easily identify accounts by meaningful names rather than account numbers.
l 1 = GROUPS
l 2 = PROFILE
l 3 = ACCOUNT ALIASES
replaceFA()
Call this method to request new FA configuration information from TWS. The data returns in an XML string via a
"receiveFA" method.
l 1 = GROUPS
l 2 = PROFILE
l 3 = ACCOUNT ALIASES
reqScannerParameters()
Requests all valid parameters that a scanner subscription can have.
reqScannerSubscription()
Starts a subscription to market scan results based on the provided parameters.
cancelScannerSubscription()
Cancels a scanner subscription.
Parameter Description
reqHistoricalData()
Requests contracts' historical data. The resulting bars will be returned in through historicalData(). When requesting his-
torical data, a finishing time and date is required along with a duration string. For example, having:
will return three days of data counting backwards from July 1st 2013 at 23:59:59 GMT, resulting in all the available bars
of the last three days until the date and time specified. It is possible to specify a time zone.
public void reqHistoricalData(int tickereId, Contract contract, string endDateTime, string durationString, string
barSizeSetting, string whatToShow, int useRTH, int formatDate, List<TagValue> chartOptions)
l " S (seconds)
l " D (days)
l " W (weeks)
l " M (months)
l " Y (years)
If no unit is specified, seconds are used. Also, note "years"
is currently limited to one.
barSizeSetting string Specifies the size of the bars that will be returned (within
IB/TWS limits). Valid bar size values include:
l 1 sec
l 5 secs
l 15 secs
l 30 secs
l 1 min
l 2 mins
l 3 mins
l 5 mins
l 15 mins
l 30 mins
l 1 hour
l 1 day
l TRADES
l MIDPOINT
l BID
l ASK
l BID_ASK
l HISTORICAL_VOLATILITY
l OPTION_IMPLIED_VOLATILITY
useRTH int Determines whether to return all data available during the
requested time span, or only data that falls within regular
trading hours. Valid values include:
Note: For more information about historical data request limitations, see Historical Data Lim-
itations.
cancelHistoricalData()
Cancels a historical data request.
reqRealTimeBars()
Requests real time bars, which are returned via realtimeBar(). Currently, only 5-second bars are provided. This request is
subject to the same pacing restrictions as any historical data request.
public void reqRealTimeBars(int tickerId, Contract contract, int barSize, string whatToShow, bool useRTH,Vect-
or<TagValue> realTimeBarOptions)
cancelRealTimeBars()
Call this method to stop receiving real time bar results.
reqFundamentalData()
Call this method to receive Reuters global fundamental data for stocks. There must be a subscription to Reuters Fun-
damental set up in Account Management before you can receive this data.
reqFundamentalData() can handle conid specified in the Contract object, but not tradingClass or multiplier. This is
because reqFundamentalData() is used only for stocks and stocks do not have a multiplier and trading class.
cancelFundamentalData()
Call this method to stop receiving Reuters global fundamental data.
queryDisplayGroups()
queryDisplayGroups(int reqId)
subscribeToGroupEvents()
subscribeToGroupEvents(int reqId, int groupId)
updateDisplayGroup()
updateDisplayGroup(int reqId, const String contractInfo)
contractInfo String The encoded value that uniquely represents the contract in
IB. Possible values include:
unsubscribeFromGroupEvents()
unsubscribeFromGroupEvents(int reqId)
C# EWrapper Methods
This section describes the class EWrapper methods you can use when connecting to TWS. The list of methods includes:
currentTime()
This method receives the current system time on IB's server as a result of calling reqCurrentTime().
error()
This method is called when there is an error with the communication or when TWS wants to send a message to the cli-
ent.
errorCode int The code identifying the error. For information on error codes,
see Error Codes.
errorMsg string The description of the error.
void error(Exception e)
This method is called when TWS wants to send an error message to the client. (V1).
connectionClosed()
This method is called when TWS closes the sockets connection, or when TWS is shut down.
void connectionClosed()
tickPrice()
Market data tick price callback, handles all price-related ticks.
field int Specifies the type of price. Pass the field value
into TickType.getField(int tickType) to retrieve
the field description. For example, a field value
of 1 will map to bidPrice, a field value of 2 will
map to askPrice, etc.
l 1 = bid
l 2 = ask
l 4 = last
l 6 = high
l 7 = low
l 9 = close
price double The actual price.
canAutoExecute int Specifies whether the price tick is available for
automatic execution. Possible values are:
tickSize()
Market data tick size callback, handles all size-related ticks.
field int The type of size being received. Pass the field value into Tick-
Type.getField(int tickType) to retrieve the field description. For
example, a field value of 0 will map to bidSize, a field value of 3
will map to askSize, etc.
l 0 = bid size
l 3 = ask size
l 5 = last size
l 8 = volume
size int The actual size.
tickOptionComputation()
This method is called when the market in an option or its underlying moves. TWS’s option model volatilities, prices, and
deltas, along with the present value of dividends expected on that option's underlying are received.
void tickOptionComputation(int tickerId, int field, double impliedVol, double delta, double optPrice, double
pvDividend, double gamma, double vega, double theta, double undPrice)
l 10 = Bid
l 11 = Ask
l 12 = Last
impliedVol double The implied volatility calculated by the TWS
option modeler, using the specified tick type value.
delta double The option delta value.
optPrice double The option price.
pvDividend double The present value of dividends expected on the
option's underlying.
gamma double The option gamma value.
vega double The option vega value.
theta double The option theta value.
undPrice double The price of the underlying.
tickGeneric()
Market data callback.
tickString()
Market data callback.
field int Specifies the type of tick being received. Pass the field
value into TickType.getField(int tickType) to retrieve
the field description. For example, a field value of 45
will map to lastTimestamp, etc.
value String The value of the specified field.
tickEFP()
Market data callback for Exchange for Physicals.
void tickEFP(int tickerId, int tickType, double basisPoints, string formattedBasisPoints, double impliedFuture, int
holdDays, String futureExpiry, double dividendImpact, double dividendsToExpiry)
field int Specifies the type of tick being received. Pass the field value
into TickType.getField(int tickType) to retrieve the field
description. For example, a field value of 38 will map to
bidEFP, etc.
basisPoints double Annualized basis points, which is representative of the fin-
ancing rate that can be directly compared to broker rates.
formattedBasisPoints String Annualized basis points as a formatted string that depicts them
in percentage form.
impliedFuture double Implied futures price.
holdDays int The number of hold days until the expiry of the EFP.
futureExpiry String The expiration date of the single stock future.
dividendImpact double The dividend impact upon the annualized basis points interest
rate.
dividendsToExpiry double The dividends expected until the expiration of the single stock
future.
tickSnapshotEnd()
This is called when a snapshot market data subscription has been fully received and there is nothing more to wait for.
This also covers the timeout case.
marketDataType()
TWS sends a marketDataType(type) callback to the API, where type is set to Frozen or RealTime, to announce that mar-
ket data has been switched between frozen and real-time. This notification occurs only when market data switches
between real-time and frozen. The marketDataType( ) callback accepts a reqId parameter and is sent per every sub-
scription because different contracts can generally trade on a different schedule.
orderStatus()
This method is called whenever the status of an order changes. It is also called after reconnecting to TWS if the client
has any open orders.
void orderStatus(int orderId, string status, int filled, int remaining, double avgFillPrice, int permId, int parentId,
double lastFillPrice, int clientId, String whyHeld)
Note: It is possible that orderStatus() may return duplicate messages. It is essential that you filter
the message accordingly.
l PendingSubmit - indicates that you have transmitted the order, but have
not yet received confirmation that it has been accepted by the order des-
tination. NOTE: This order status is not sent by TWS and should be
explicitly set by the API developer when an order is submitted.
l PendingCancel - indicates that you have sent a request to cancel the
order but have not yet received cancel confirmation from the order des-
tination. At this point, your order is not confirmed canceled. You may
still receive an execution while your cancellation request is pending.
NOTE: This order status is not sent by TWS and should be explicitly
set by the API developer when an order is canceled.
l PreSubmitted - indicates that a simulated order type has been accepted
by the IB system and that this order has yet to be elected. The order is
held in the IB system until the election criteria are met. At that time the
order is transmitted to the order destination as specified .
l Submitted - indicates that your order has been accepted at the order des-
tination and is working.
l ApiCanceled - after an order has been submitted and before it has been
acknowledged, an API client client can request its cancellation, pro-
ducing this state.
l Cancelled - indicates that the balance of your order has been confirmed
canceled by the IB system. This could occur unexpectedly when IB or
the destination has rejected your order.
l Filled - indicates that the order has been completely filled.
l Inactive - indicates that the order has been accepted by the system (sim-
ulated orders) or an exchange (native orders) but that currently the order
is inactive due to system, exchange or other issues.
filled int Specifies the number of shares that have been executed.
For more information about partial fills, see Order Status for Partial Fills.
remaining int Specifies the number of shares still outstanding.
avgFillPrice double The average price of the shares that have been executed. This parameter is valid
only if the filled parameter value is greater than zero. Otherwise, the price para-
meter will be zero.
permId int The TWS id used to identify orders. Remains the same over TWS sessions.
parentId int The order ID of the parent order, used for bracket and auto trailing stop orders.
lastFilledPrice double The last price of the shares that have been executed. This parameter is valid
only if the filled parameter value is greater than zero. Otherwise, the price para-
meter will be zero.
whyHeld String This field is used to identify an order held when TWS is trying to locate shares
for a short sell. The value used to indicate this is 'locate'.
openOrder()
This callback feeds in open orders.
openOrderEnd()
This is called at the end of a given request for open orders.
void openOrderEnd()
nextValidId()
Receives the next valid Order ID.
deltaNeutralValidation()
Upon accepting a Delta-Neutral RFQ(request for quote), the server sends a deltaNeutralValidation() message with the
UnderComp structure. If the delta and price fields are empty in the original request, the confirmation will contain the cur-
rent values from the server. These values are locked when the RFQ is processed and remain locked until the RFQ is can-
celed.
updateAccountValue()
This callback receives the subscribed account's information in response to reqAccountUpdates(). You can only subscribe
to one account at a time.
updatePortfolio()
Receives the subscribed account's portfolio in response to reqAccountUpdates(). If you want to receive the portfolios of
all managed accounts, use reqPositions().
void updatePortfolio(Contract contract, int position, double marketPrice, double marketValue, double averageCost,
double unrealizedPNL, double realizedPNL, string accountName)
updateAccountTime()
Receives the last time at which the account was updated.
accountDownloadEnd()
This event is called when the receipt of an account's information has been completed.
accountSummary()
Returns the account information from TWS in response to reqAccountSummary().
void accountSummary(int reqId, string account, string tag, string value, string currency)
l AccountType
l Net Liquidation
l TotalCashValue — Total cash including futures pnl
l SettledCash — For cash accounts, this is the same as
TotalCashValue
l AccruedCash — Net accrued interest
l BuyingPower — The maximum amount of marginable
US stocks the account can buy
l EquityWithLoanValue — Cash + stocks + bonds +
mutual funds
l PreviousEquityWithLoanValue
l GrossPositionValue — The sum of the absolute value of
all stock and equity option positions
l RegTEquity
l RegTMargin
l SMA — Special Memorandum Account
l InitMarginReq
l MaintMarginReq
l AvailableFunds
l ExcessLiquidity
l Cushion — Excess liquidity as a percentage of net
liquidation value
l FullInitMarginReq
l FullMaintMarginReq
l FullAvailableFunds
l FullExcessLiquidity
l LookAheadNextChange — Time when look-ahead val-
ues take effect
l LookAheadInitMarginReq
l LookAheadMaintMarginReq
l LookAheadAvailableFunds
l LookAheadExcessLiquidity
accountSummaryEnd
This is called once all account information for a given reqAccountSummary() request are received.
position()
This event returns open positions for all accounts in response to the reqPositions() method.
positionEnd()
This is called once all position data for a given request are received and functions as an end marker for the position()
data.
void positionEnd()
contractDetails()
Returns all contracts matching the requested parameters in reqContractDetails(). For example, you can receive an entire
option chain.
contractDetailsEnd()
This method is called once all contract details for a given request are received. This helps to define the end of an option
chain.
bondContractDetails()
Sends bond contract data when the reqContractDetails() method has been called for bonds.
execDetails()
Returns executions from the last 24 hours as a response to reqExecutions(), or when an order is filled.
contract Contract This structure contains a full description of the contract that was
executed.
execDetailsEnd()
This method is called once all executions have been sent to a client in response to reqExecutions().
commissionReport()
This callback returns the commission report portion of an execution and is triggered immediately after a trade execution,
or by calling reqExecution().
updateMktDepth()
Returns market depth (the order book) in response to reqMktDepth().
void updateMktDepth(int tickerId, int position, int operation, int side, double price, int size)
l 0 = ask
l 1 = bid.
price double The order price.
size int The order size.
updateMktDepthL2()
Returns Level II market depth in response to reqMktDepth().
void updateMktDepthL2(int tickerId, int position, string marketMaker, int operation, int side, double price, int size)
l 0 = insert (insert this new order into the row identified by 'pos-
ition')·
l 1 = update (update the existing order in the row identified by
'position')·
l 2 = delete (delete the existing order at the row identified by 'pos-
ition').
side int Identifies the side of the book that this order belongs to. Valid values
are:
l 0 = ask
l 1 = bid.
price double The order price.
size int The order size.
updateNewsBulletin()
Provides news bulletins if the client has subscribed (i.e. by calling the reqNewsBulletins() method).
managedAccounts()
Receives a comma-separated string containing IDs of managed accounts.
receiveFA()
This method receives Financial Advisor configuration information from TWS.
l 1 = GROUPS
l 2 = PROFILE
l 3 =ACCOUNT ALIASES
faXmlData string The XML string containing the previously requested
FA configuration information.
historicalData()
Receives the historical data in response to reqHistoricalData().
void historicalData (int reqId, string date, double open, double high, double low, double close, int volume, int count,
double WAP, bool hasGaps)
WAP double The weighted average price during the time covered by the bar.
hasGaps bool Whether or not there are gaps in the data.
historicalDataEnd()
Marks the end of receipt of historical data.
scannerParameters()
This method receives an XML document that describes the valid parameters that a scanner subscription can have.
scannerData()
This method receives the requested market scanner data results.
void scannerData(int reqId, int rank, ContractDetails contractDetails, string distance, string benchmark, string pro-
jection, string legsStr)
scannerDataEnd()
Marks the end of one scan (the receipt of scanner data has ended).
realtimeBar()
Updates real time 5-second bars.
void realtimeBar(int reqId, long time, double open, double high, double low, double close, long volume, double wap,
int count)
fundamentalData()
This method is called to receive Reuters global fundamental market data. There must be a subscription to Reuters Fun-
damental set up in Account Management before you can receive this data.
l Company overview
l Financial summary
l Financial ratios
l Financial statements
l Analyst estimates
l Company calendar
displayGroupList()
This callback is a one-time response to queryDisplayGroups().
displayGroupUpdated()
This is sent by TWS to the API client once after receiving the subscription request subscribeToGroupEvents(), and will
be sent again if the selected contract in the subscribed display group has changed.
contractInfo string The encoded value that uniquely represents the contract in
IB. Possible values include:
C# SocketClient Properties
The tables below define attributes for the following classes:
l Execution
l ExecutionFilter
l CommissionReport
l Contract
l ContractDetails
l ComboLeg
l Order
l OrderComboLeg
l OrderState
l ScannerSubscription
l UnderComp
Execution
Attribute Description
int orderId The order id.
l BOT
l SLD
int shares The number of shares filled.
double price The order execution price, not including commissions.
Attribute Description
int permId The TWS id used to identify orders, remains the same over
TWS sessions.
int liquidation Identifies the position as one to be liquidated last should the
need arise.
int cumQty Cumulative quantity. Used in regular trades, combo trades
and legs of the combo.
double avgPrice Average price. Used in regular trades, combo trades and legs
of the combo. Does not include commissions.
string orderRef Allows the API client to add a reference to an order.
string evRule Contains the Economic Value Rule name and the respective
optional argument. The two values should be separated by a
colon. For example, aussieBond:YearsToExpiration=3. When
the optional argument is not present, the first value will be
followed by a colon.
double evMultiplier Tells you approximately how much the market value of a con-
tract would change if the price were to change by 1. It can-
not be used to get market value by multiplying the price by
the approximate multiplier.
ExecutionFilter
Attribute Description
int clientId Filter the results of the reqExecutions() method based on
the clientId.
string acctCode Filter the results of the reqExecutions() method based on an
account code. Note: this is only relevant for Financial
Advisor (FA) accounts.
string time Filter the results of the reqExecutions() method based on
execution reports received after the specified time.The
format for timeFilter is "yyyymmdd-hh:mm:ss"
string symbol Filter the results of the reqExecutions() method based on
the order symbol.
string secType Filter the results of the reqExecutions() method based on
the order security type.
Note: Refer to the Contract object for the list of valid secur-
ity types.
string exchange Filter the results of the reqExecutions() method based on
the order exchange.
string side Filter the results of the reqExecutions() method based on
the order action.
Note: Refer to the Order class for the list of valid order
actions.
CommissionReport
Attribute Description
string execId() Unique order execution id.
double commission() The commission amount.
Contract
Attribute Description
l STK
l OPT
l FUT
l IND
l FOP
l CASH
l BAG
l NEWS
string right Specifies a Put or Call. Valid values are: P, PUT, C, CALL.
Vector comboLegs Dynamic memory structure used to store the leg definitions for
this contract.
string currency 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.
string localSymbol This is the local exchange symbol of the underlying asset.
string primaryExch Identifies the listing exchange for the contract (do not list
SMART).
bool includeExpired If set to true, contract details requests and historical data quer-
ies can be performed pertaining to expired contracts.
Note: Historical data queries on expired contracts are limited
to the last year of the contracts life, and are initially only sup-
ported for expired futures contracts,
string secIdType Security identifier, when querying contract details or when pla-
cing orders. Supported identifiers are:
UnderComp underComp Delta and underlying price for Delta-Neutral combo orders.
Underlying (STK or FUT), delta and underlying price goes into
this attribute.
ContractDetails
Class that describes extended contract details, including bond contract details.
Attribute Description
string orderTypes The list of valid order types for this contract.
string contractMonth The contract month. Typically the contract month of the under-
lying for a futures contract.
string category The industry category of the underlying. For example, Invest-
mentSvc.
string subcategory The industry subcategory of the underlying. For example, Broker-
age.
string timeZoneId The ID of the time zone for the trading hours of the product. For
example, EST.
string tradingHours The total trading hours of the product. For example,
20090507:0700-1830,1830-2330;20090508:CLOSED.
string liquidHours The regular trading hours of the product. For example,
20090507:0930-1600;20090508:CLOSED.
string evRule Contains the Economic Value Rule name and the respective
optional argument. The two values should be separated by a
colon. For example, aussieBond:YearsToExpiration=3. When the
optional argument is not present, the first value will be followed
by a colon.
double evMultiplier Tells you approximately how much the market value of a con-
tract would change if the price were to change by 1. It cannot be
used to get market value by multiplying the price by the approx-
imate multiplier.
Vector<TagValue> secIdList() A list of contract identifiers that the customer is allowed to view
(CUSIP, ISIN, etc.)
Bond Values
string cusip For Bonds. The nine-character bond CUSIP or the 12-character
SEDOL.
string ratings For Bonds. Identifies the credit rating of the issuer. A higher
credit rating generally indicates a less risky investment. Bond rat-
ings are from Moody's and S&P respectively.
bool callable For Bonds. Values are True or False. If true, the bond can be
called by the issuer under certain conditions.
bool putable For Bonds. Values are True or False. If true, the bond can be
sold back to the issuer under certain conditions.
double coupon For Bonds. The interest rate used to calculate the amount you
will receive in interest payments over the course of the year.
bool convertible For Bonds. Values are True or False. If true, the bond can be con-
verted to stock under certain conditions.
string maturity For Bonds. The date on which the issuer must repay the face
value of the bond.
string issueDate For Bonds. The date the bond was issued.
string notes For Bonds, if populated for the bond in IB's database
ComboLeg
Attribute Description
int conId The unique contract identifier specifying the
security.
int ratio Select the relative number of contracts for the
leg you are constructing. To help determine the
ratio for a specific combination order, refer to
the Interactive Analytics section of the User's
Guide.
Attribute Description
string action The side (buy or sell) for the leg you are con-
structing.
string exchange The exchange to which the complete com-
bination order will be routed.
int openClose Specifies whether the order is an open or close
order. Valid values are:
Order
Attribute Description
Order Identifiers
int clientId The id of the client that placed this order.
int orderId The id for this order.
int permid The TWS id used to identify orders, remains the same over
TWS sessions.
Main Order Fields
string action Identifies the side. Valid values are: BUY, SELL, SSHORT
long totalQuantity The order quantity.
string orderType Identifies the order type.
Attribute Description
double lmtPrice This is 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.
double auxPrice This is the STOP price for stop-limit orders, and the offset
amount for relative orders. In all other cases, specify zero.
Extended Order Fields
string tif The time in force. Valid values are: DAY, GTC, IOC, GTD.
string activeStartTime For GTC orders.
string activeStopTime For GTC orders.
string ocaGroup Identifies an OCA (one cancels all) group.
int ocaType Tells how to handle remaining orders in an OCA group when
one order or part of an order executes. Valid values include:
Attribute Description
int triggerMethod Specifies how Simulated Stop, Stop-Limit and Trailing Stop
orders are triggered. Valid values are:
bool outsideRth If set to true, allows orders to also trigger or fill outside of reg-
ular trading hours.
bool hidden If set to true, the order will not be visible when viewing the
market depth. This option only applies to orders routed to the
ISLAND exchange.
string goodAfterTime The trade's "Good After Time," format
"YYYYMMDD hh:mm:ss (optional time zone)"
Use an empty string if not applicable.
string goodTillDate You must enter GTD as the time in force to use this string.
The trade's "Good Till Date," format "YYYYMMDD hh:m-
m:ss (optional time zone)"
Use an empty string if not applicable.
bool overridePercentageConstraints Precautionary constraints are defined on the TWS Presets page,
and help ensure tha tyour price and size order values are reas-
onable. Orders sent from the API are also validated against
these safety constraints, and may be rejected if any constraint
is violated. To override validation, set this parameter’s value
to True.
Valid values include:
l 0 = False
l 1 = True
Attribute Description
string rule80A Values include:
l Individual = 'I'
l Agency = 'A',
l AgentOtherMember = 'W'
l IndividualPTIA = 'J'
l AgencyPTIA = 'U'
l AgentOtherMemberPTIA = 'M'
l IndividualPT = 'K'
l AgencyPT = 'Y'
l AgentOtherMemberPT = 'N'
bool allOrNone 0 = no, 1 = yes
int minQty Identifies a minimum quantity order type.
double percentOffset The percent offset amount for relative orders.
TRAILLIMIT Order Fields
string faGroup The Financial Advisor group the trade will be allocated to --
use an empty string if not applicable.
Attribute Description
string faProfile The Financial Advisor allocation profile the trade will be alloc-
ated to -- use an empty string if not applicable.
string faMethod The Financial Advisor allocation function the trade will be
allocated with -- use an empty string if not applicable.
string faPercentage The Financial Advisor percentage concerning the trade's
allocation -- use an empty string if not applicable.
Institutional (non-cleared) Only
string openClose For institutional customers only. Valid values are O, C.
int origin The order origin. For institutional customers only. Valid values
are 0 = customer, 1 = firm
int shortSaleSlot Valid values are 1 or 2.
string designatedLocation Used only when shortSaleSlot = 2.
double discretionaryAmt The amount off the limit price allowed for discretionary orders.
l match = 1
l improvement = 2
l transparent = 3
For orders on BOX only.
double delta The stock delta. For orders on BOX only.
double startingPrice The auction starting price. For orders on BOX only.
double stockRefPrice The stock reference price. The reference price is used for VOL
orders to compute the limit price sent to an exchange (whether
or not Continuous Update is selected), and for price range mon-
itoring.
Attribute Description
Pegged-to-Stock and VOL Orders Only
double stockRangeLower The lower value for the acceptable underlying stock price
range. For price improvement option orders on BOX and VOL
orders with dynamic management.
double stockRangeUpper The upper value for the acceptable underlying stock price
range. For price improvement option orders on BOX and VOL
orders with dynamic management.
Volatility Orders Only
l 1 = Daily volatility
l 2 = Annual volatility
bool continuousUpdate VOL orders only. Specifies whether TWS will automatically
update the limit price of the order as the underlying price
moves.
int referencePriceType VOL orders only. Specifies how you want TWS to calculate
the limit price for options, and for stock range price mon-
itoring.
Valid values include:
l 1 = Average of NBBO
l 2 = NBB or the NBO depending on the action and
right.
string deltaNeutralOrderType VOL orders only. Enter an order type to instruct TWS to sub-
mit a delta neutral trade on full or partial execution of the VOL
order. For no hedge delta order to be sent, specify NONE.
int deltaNeutralAuxPrice VOL orders only. Use this field to enter a value if the value in
the deltaNeutralOrderType field is an order type that requires
an Aux price, such as a REL order.
string deltaNeutralOpenClose Specifies whether the order is an Open or a Close order and is
used when the hedge involves a CFD and the order is clearing
away.
int deltaNeutralConId
Attribute Description
string deltaNeutralSettlingFirm
string deltaNeutralClearingAccount
string deltaNeutralClearingIntent
string deltaNeutralOpenClose
bool deltaNeutralShortSale Used when the hedge involves a stock and indicates whether or
not it is sold short.
int scaleInitLevelSize For Scale orders: Defines the size of the first, or initial, order
component.
int scaleSubsLevelSize For Scale orders: Defines the order size of the subsequent scale
order components. Used in conjunction with scaleInitLevelSize
().
double scalePriceIncrement For Scale orders: Defines the price increment between scale
components. This field is required.
double scalePriceAdjustValue() For extended Scale orders.
Attribute Description
double scaleProfitOffset() For extended Scale orders.
l D = Delta
l B = Beta
l F = FX
l P = Pair
string hedgeParam Beta = x for Beta hedge orders, ratio = y for Pair hedge order
Clearing Information
string algoStrategy For information about API Algo orders, see IBAlgo
Parameters.
Attribute Description
What If
Solicited Orders
bool notHeld For IBDARK orders only. Orders routed to IBDARK are tagged
as “post only” and are held in IB's order book, where incoming
SmartRouted orders from other IB customers are eligible to
trade against them.
Vector<TagValue> For internal use only. Use the default value XYZ.
orderMiscOptions
OrderComboLeg
Attribute Description
double price Order-specific leg price.
OrderState
Attribute Description
string status Displays the order status.
string initMargin Shows the impact the order would have on your ini-
tial margin.
string maintMargin Shows the impact the order would have on your
maintenance margin.
string equityWithLoan Shows the impact the order would have on your
equity with loan value.
double commission Shows the commission amount on the order.
double minCommission Used in conjunction with the maxCommission field,
this defines the lowest end of the possible range into
which the actual order commission will fall.
double maxCommission Used in conjunction with the minCommission field,
this defines the highest end of the possible range
into which the actual order commission will fall.
string commissionCurrency Shows the currency of the commission value.
string warningText Displays a warning message if warranted.
ScannerSubscription
Attribute Description
int numberOfRows Defines the number of rows of data to return for a query.
Attribute Description
string moodyRatingAbove Filter out contracts with a Moody rating below this value. Can be left
blank.
string moodyRatingBelow Filter out contracts with a Moody rating above this value. Can be left
blank.
string spRatingAbove Filter out contracts with an S&P rating below this value. Can be left
blank.
string spRatingBelow Filter out contracts with an S&P rating above this value. Can be left
blank.
string maturityDateAbove Filter out contracts with a maturity date earlier than this value. Can be
left blank.
string maturityDateBelow Filter out contracts with a maturity date later than this value. Can be
left blank.
double couponRateAbove Filter out contracts with a coupon rate lower than this value. Can be
left blank.
double couponRateBelow Filter out contracts with a coupon rate higher than this value. Can be
left blank.
string excludeConvertible Filter out convertible bonds. Can be left blank.
string scannerSettingPairs Can leave empty. For example, a pairing "Annual, true" used on the
"top Option Implied Vol % Gainers" scan would return annualized
volatilities.
string stockTypeFilter Valid values are:
l CORP = Corporation
l ADR = American Depositary Receipt
l ETF = Exchange Traded Fund
l REIT = Real Estate Investment Trust
l CEF = Closed End Fund
UnderComp
Attribute Description
int conId The unique contract identifier specifying the security. Used for
Delta-Neutral Combo contracts.
double delta The underlying stock or future delta. Used for Delta-Neutral Combo
contracts.
double price The price of the underlying. Used for Delta-Neutral Combo contracts.
API FA functionality became significantly more powerful in TWS release 821 and higher, in that the now deprecated
"allocation string" method was replaced by the much more powerful Financial Advisor order allocation methods. Prior to
those new methods being used, TWS had to be configured to understand the desired FA order groups, profiles, and
account aliases. This can be done manually in TWS, or via the API, or via both.
You can place FA orders on the Advisors page in the most recent release of the TwsDde.xls DDE for Excel API spread-
sheet. For more information, see the Advisors Page topic.
l requestFA(int faDataType) is a method that is called by an API application to request one of those types of FA
configuration data.
l receiveFA(int faDataType, string XML) receives the requested data from TWS, via an event that TWS sends that
contains the data requested. The event includes an XML string containing the requested information.
l replaceFA(int faDataType, string XML) can be called from the API if the API application wishes to replace
the previous FA configuration information with a new XML string.
In accordance with the existence of this new functionality, all placeOrder methods, whether ActiveX, Java, or C++
based, have four new parameters pertaining to Financial Advisor order placement: faGroup, faMethod, faPercentage, and
faProfile. When one or more of these new values is not relevant to an order, simply pass in an empty string.
Assume that 100 shares of IBM is being bought on the NYSE by a Financial Advisor who has three sub-accounts, and
who wants them allocated with Equal Quantity to each. The following seven execution messages will occur:
EqualQuantity Method
Requires you to specify an order size. This method distributes shares equally between all accounts in the group.
Example: You transmit an order for 400 shares of stock ABC. If your Account Group includes four accounts, each
account receives 100 shares. If your Account Group includes six accounts, each account receives 66 shares, and then 1
share is allocated to each account until all are distributed.
NetLiq Method
Requires you to specify an order size. This method distributes shares based on the net liquidation value of each account.
The system calculates ratios based on the Net Liquidation value in each account and allocates shares based on these
ratios.
Example: You transmit an order for 700 shares of stock XYZ. The account group includes three accounts, A, B and C
with Net Liquidation values of $25,000, $50,000 and $100,000 respectively. The system calculates a ratio of 1:2:4 and
allocates 100 shares to Client A, 200 shares to Client B, and 400 shares to Client C.
AvailableEquity Method
Requires you to specify an order size. This method distributes shares based on the amount of equity with loan value cur-
rently available in each account. The system calculates ratios based on the Equity with Loan value in each account and
allocates shares based on these ratios.
Example: You transmit an order for 700 shares of stock XYZ. The account group includes three accounts, A, B and C
with available equity in the amounts of $25,000, $50,000 and $100,000 respectively. The system calculates a ratio of
1:2:4 and allocates 100 shares to Client A, 200 shares to Client B, and 400 shares to Client C.
PctChange Method
This method only works when you already hold a position in the selected instrument. Do not specify an order size. Since
the quantity is calculated by the system, the order size is displayed in the Quantity field after the order is acknowledged.
This method increases or decreases an already existing position. Positive percents will increase a position, negative per-
cents will decrease a position.
Example 1: Assume that three of the six accounts in this group hold long positions in stock XYZ. Client A has 100
shares, Client B has 400 shares, and Client C has 200 shares. You want to increase their holdings by 50%, so you enter
"50" in the percentage field. The system calculates that your order size needs to be equal to 350 shares. It then allocates
50 shares to Client A, 200 shares to Client B, and 100 shares to Client C.
Example 2: You want to close out all long positions for three of the five accounts in a group. You create a sell order
and enter "-100" in the Percentage field. The system calculates 100% of each position for every account in the group that
holds a position, and sells all shares to close the positions.
These handy charts make it easy to see how negative and positive percent values will affect long and short positions for
both buy and sell orders. Phew, that was a mouthful!
As an FA, you can place an order for any one of your managed accounts. The following code sample performs this task.
/** Stocks */
m_contract.m_symbol = "IBM";
m_contract.m_secType = "STK";
m_contract.m_exchange = "SMART";
m_contract.m_currency = "USD";
m_order.m_orderType = "MKT";
m_order.m_action = "BUY";
m_order.m_totalQuantity = 100;
m_order.m_transmit = true;
m_order.m_account = "DU74649";
As an FA, you can place an order for accounts that share an allocation profile. The following code sample performs the
task.
Note: Before trying this yourself, you must be familiar with setting up an allocation profile and pla-
cing an order in TWS.
m_order.m_faProfile = "USClients";
As an FA, you can place an order for accounts in an account group. Note that the method attribute is a mandatory field
when placing an order for account groups. The following code sample performs the task.
Note: Before trying this yourself, you must be familiar with setting up account groups and placing
an order in TWS.
m_order.m_faGroup = "USGroup";
m_order.m_faMethod = "PctChange";
m_order.m_faPercentage = "100";
As an FA, you can retrieve allocation information in XML format, and change or update allocation information by
passing an XML formatted configuration back.
The following code sample changes one of the groups' name by replacing the first occurrence of "TestGroup" in the con-
figuration file with "MyTestGroup" and passing it back.
switch (faDataType) {
case EClientSocket.GROUPS:
faGroupXML = xml ;
m_client.replaceFA(1, test);
break ;
case EClientSocket.PROFILES:
faProfilesXML = xml ;
break ;
case EClientSocket.ALIASES:
faAliasesXML = xml ;
break ;
The ActiveX for Excel sample spreadsheet, TwsActiveX.xls, duplicates the functionality of the ActiveX for Excel API
spreadsheet but internally uses an ActiveX component, Tws.ocx. One of the benefits of using this spreadsheet is that it
can connect to a TWS or IB Gateway session that is running on a remote PC. The DDE for Excel API spreadsheet cannot
do this.
Note: The methods, events and COM objects used in the code for the ActiveX for Excel sample
spreadsheet are the same as those used in the ActiveX API. See the ActiveX chapter for com-
plete details about the ActiveX API.
The following figure shows the Tickers page in the ActiveX for Excel API sample spreadsheet.
l Download the API components, which includes the ActiveX for Excel sample spreadsheet, TwsActiveX.xls.
l Ensure that:
o the application server is running and that it is configured to support ActiveX or
o the IB Gateway is running.
l Open the spreadsheet and start using the ActiveX for Excel API.
The sample spreadsheet currently comprises several pages complete with sample data and action buttons that make it
easy for you to get market data, send orders and view your activity.
We recommending using the sample Excel spreadsheet that we provide as a starting point toward creating your own Act-
iveX for Excel API. Follow the steps below to download the sample spreadsheet.
3. Save the installation program to your computer, and if desired, select a different directory. Click Save.
4. Close any versions of TWS and Excel that you have running.
5. Locate the installation program you just saved to your computer, then double-click the file to begin the API
installation.
6. Follow the instructions in the installation wizard.
Note: Before you can use the spreadsheet, you must have TWS running and configured to support
the ActiveX API. See Run the API through TWS for detailed instructions.
To run the ActiveX for Excel API on 64-bit Windows XP systems, do the following:
After you have downloaded the sample spreadsheet and configured the application to allow the ActiveX for Excel API
to link to it, open the spreadsheet and save it as your personal file.
Note: Note that not more than one API application can simultaneously access a single instance.
The API application does not need to be running on the same computer on which the applic-
ation is running.
Page Description
General Lets you connect to and disconnect from TWS, set the
server log level and request the current time.
Tickers Lets you set up your ticker lines and request market data.
You can view market data for all asset types including EFPs
and combination orders.
Bulletins Lets you subscribe to and view IB News Bulletins.
Market Depth Lets you view market depth for selected quotes.
Basic Orders Lets you send and modify orders, set up combination orders
and EFPs, and request open orders.
Conditional Orders Lets you create an order whose submission is contingent on
other conditions being met, for example an order based on a
prior fill.
Advanced Orders Lets you send and modify advanced orders types that
require the use of extended order attributes, such as Bracket,
Scale and Trailing Stop Limit orders.
Extended Order Attributes Used in conjunction with the Basic Orders, Advanced
Orders, Conditional Orders and Advisors pages, this page
lets you change the time in force, create Hidden or Iceberg
orders and apply many other order attributes.
Open Orders Shows you all transmitted orders, including those that have
been accepted by the IB system, and those that are working
at an exchange.
Account Provides up to date account information and displays your
portfolio.
Portfolio Displays all your current positions.
Executions Lets you view all execution reports, and includes a filtering
box so you can limit your results.
Commission Reports Lets you view commission details.
Historical Data Request historical data for an instrument based on data you
enter in a query.
Contract Details Lets you collect contract-specific information you will need
for other actions, including the conid and supported order
types for a contract
Bond Contract Details Lets you collect bond contract-specific information you will
need for other actions, including bond coupon and maturity
date.
Page Description
Real Time Bars Lets you request and view real time bars from TWS.
Market Scanner Lets you view market scanner parameters and subscribe to
TWS market scanners.
Fundamentals Lets you request and view Fundamentals data from TWS.
Advisors Lets Financial Advisors send and modify FA orders.
Log Lets you view all error messages.
General Page
l Connect to TWS.
l Disconnect from TWS.
l Set the level of log entry detail used by the server when processing API requests.
l Request the current server time.
To connect to TWS
Button Description
Connect to TWS Connects to TWS.
Disconnect from TWS Disconnects from TWS.
Set Server Log Level Sets the level of detail of entries in the log.txt log file.
Request Current Time Requests the current server time.
Global Cancel Cancels all requests.
The toolbar also includes the Show Errors Message Box check box, which when selected, displays error when con-
necting to TWS.
Bulletins Page
Use the Bulletins page to request and view IB news bulletins. Simply click Request News Bulletins in the toolbar. News
bulletins display in the table on the page. To request all the existing bulletins for the current day and any new ones,
select the All Day News check box on the toolbar. If this check box is not selected, you will receive only new bulletins.
Button Description
Request News Bulletins Requests all the new news bulletins.
Cancel News Bulletins Cancels receipt of all news bulletins.
Clear News Bulletins Clears all news bulletins from the page.
The toolbar also includes the All Day News check box, which when selected, requests all the existing bulletins for the
current day and any new ones.
Tickers Page
3. Optionally, click the Snapshot check box to request a single snapshot of market data.
4. Click Request Market Data on the toolbar.
To get market data for a group of tickers, select multiple ticker rows while holding down the Shift key, then click
Request Market Data multiple times until all rows are showing data.
l Enter the refresh rate value (in whole numbers, in seconds) in the Market Data Refresh Rate cell.
TWS market data updates every 3 seconds by default.
Button Description
Create Ticker Opens the Ticker box. Enter information to create a
market data line.
Combo Legs Opens the Combination Legs box. Enter contract
details to create legs of a combination order one by
one.
Request Market Data Select a line and click to get market data for the selec-
ted contract.
Cancel Market Data Cancel market data for the selected ticker.
Clear Market Data Clears all market data from the page.
The toolbar also includes the Snapshot check box, which when selected, requests only a single snapshot of market data.
Use the Market Depth page to view market depth for selected contracts. You can also view market depth for NYSE-listed
products through the Open Book Market Data Subscription, and NASDAQ-listed products through the TotalView Mar-
ket Data Subscriptions, if you have signed up for those subscriptions.
Button Description
Request Market Depth View bid/ask depth prices for the selected contract.
Cancel Market Depth Cancel market depth for the selected contract.
Clear Market Depth Clears all market depth data from the page.
The page also includes a Market Depth Refresh Rate cell, which lets you rest the market depth refresh rate in seconds, in
whole numbers from 1 - 9. The default refresh rate is 3 seconds.
l Create an order.
l Place a “what if” order, which shows you the margin and commission information before you place an order.
l Create a "basket" of orders.
l Modify and cancel orders.
l Create combination orders.
Placing Orders
This topic describes how to place the following types of orders on the Orders page:
Note: Ensure that TWS is running, and that you have connected the spreadsheet to TWS.
To place an order
1. Click the Basic Orders tab at the bottom of the spreadsheet.
2. Define a contract by typing a symbol in a blank Symbol field, then entering information in the relevant contract
description fields.
3. Select a contract and set up the order using the Order Description fields.
You must define the Action (Buy, Sell or Short Sell), Quantity, Order Type, Limit Price (unless it's a market order)
and if necessary, the Aux. Price for order types that require it.
4. If desired, select the contract (the ticker row) and apply extended order attributes by clicking the Apply Extended
Template button on the toolbar. This applies all attributes you have defined on the Extended Order
Attributes page to the selected contract.
5. Click the Place/Modify Order button on the toolbar.
1. Use the Contract Details page to get the contract id for both of the leg definitions.
o The conid for XYZ option JUL08 17.5 CALL on ISE is "12345678".
o The conid for XYZ option AUG08 17.5 CALL on ISE is "12345679".
2. Click the Basic Orders tab to build the combo leg definitions. Click the Combo Legs button on the Basic
Orders page toolbar and enter leg information. Your leg information is translated into the format:
[CMBLGS]_[NumOfLegs]_[Combo Leg Definitions]_[CMBLGS]
where:
o [CMBLGS] is the delimiter used to identify the start and end of the leg definitions
o [NumOfLegs] is the number of leg definitions
o [Combo Leg Definitions] defines N leg definitions, and each leg definition consists of [conid]_[ratio]_[action]_
[exchange]_[openClose], so the resulting combo substring looks as follows:
CMBLGS_2_17496957_1_BUY_EMPTY_0_15910089_1_SELL_EMPTY_0_CMBLGS
3. The combination leg definitions must occur before the extended order attributes. The full place order DDE
request string will look like this:
=acctName|ord!id12345?place?BUY_1_XYZ_BAG_ISE_LMT_1_CMBLGS_2_12345678_1_BUY_EMPTY_0_
12345679_1_SELL_EMPTY_0_CMBLGS_DAY_EMPTY_0_O_0_EMPTY_0_EMPTY_0_0_0EMPTY_0_0
If the order legs do not constitute a valid combination, one of the following errors will be returned:
2. The openClose leg definition value is always 'SAME' (i.e.0) for retail accounts. For insti-
tutional accounts, the value may be any of the following: (SAME, OPEN, CLOSE).
l Limit (LMT)
l Market (MKT)
l Limit if Touched (LIT)
l Market if Touched (MIT)
l Market on Close (MOC)
l Limit on Close (LOC)
l Pegged to Market (PEGMKT)
l Relative (REL)
l Stop (STP)
l Stop Limit (STPLMT)
l Trailing Stop (TRAIL)
l Trailing Stop Limit (TRAILLIMIT)
l Volume-Weighted Average Price (VWAP)
l Volatility orders (VOL)
Button Description
Create Ticker Opens the Ticker box. Enter information to create a market
data line.
Combo Legs Opens the Combination Legs box. Enter contract details
to create legs of a combination order one by one.
You can also enter Delta Neutral information.
Button Description
Apply Extended Template Applies the current values on the Extended Order Attrib-
utes page to the highlighted order row.
Place/Modify Orders After you have completed the Order Description fields, and
defined any extended attributes, click to create an order for
the selected contract.
Cancel Order This button cancels the selected order(s).
Smart Combo Routing Opens the Smart Combo Routing Parameters box, which
Params lets you add and remove parameter/value pairs to combo
orders. For more information, see Smart Combo Routing.
Clear Order Statuses Clears all order status information from the page.
There is also a WhatIf check box on the toolbar. When checked, you will receive margin and commission data as if the
order were placed, but the order will NOT be placed.
Use the Conditional Orders page to create an order whose submission is contingent on other conditions being met, for
example, an order based on a prior fill or a change in the bid or ask price.
To see the Conditional Statement fields, use the scroll bar on the bottom of the page to scroll to the right.
5. Complete the necessary fields on the Conditional Orders page according to the syntax in the following table.
Field Description
Statement An Excel function which returns a true or false. When true, the order will be sub-
mitted; when false, nothing happens.
ADD/MOD Use ADD for a one-time order. Use MOD to continue checking and modifying the
order until it is completely filled. This is the field that activates a conditional
order, and orders will be activated only with the "ADD" or "MOD" tags.
Action BUY
SELL
Quantity Enter the quantity of the order.
Order Type Refer to list of supported order types.
Lmt Price The limit price for Limit and Stop Limit order types.
Aux. Price The stop-election price for Stop and Stop Limit order types, or the offset for rel-
ative orders.
All of the fields described above may be variables that depend on other cells, so any type of conditional order may be
created.
If-Filled order
An if-filled order is an order that executes if a prior order executes. To create an if-filled order with the condition "If a
Buy order fully executes, enter a sell limit order at a price of $50.00":
Field Value
Statement Filled cell = 100
ADD/MOD ADD
Action SELL
Quantity 100
Order Type LMT
Lmt Price 50
Price-change order
A price-change order will be triggered if a specific bid or ask price is greater than, less than or equal to a specific price.
To create a price change order with the condition "If the bid price drops below 81.20, submit a buy limit order for 200
shares with a limit price of $81.10:
Field Value
Statement On the Tickers page, find the bid price field you want to use,
then enter the cell location in the standard Excel format
(=SheetName!CellAddress) in the formula bar (“=” entry field)
at the top of the Conditional Orders page. Add your qualifier,
"=" ">" or "<" followed by the price to the statement.
ADD/MOD ADD
Action BUY
Quantity 200
Order Type LMT
Lmt Price 81.10
Aux. Price Not used in this example.
Button Description
Combo Legs Opens the Combination Legs box. Enter contract details to create
legs of a combination order one by one.
Place/Modify After you have completed the Order Description fields, and defined
Order any extended attributes, click to create an order for the selected con-
tract.
Apply Extended Applies all attributes on the Extended Order Attributes page to the
Template selected order(s).
Button Description
Cancel Order This button cancels the order(s) you have highlighted.
Smart Combo Opens the Smart Combo Routing Parameters box, which lets you add
Routing Params and remove parameter/value pairs to combo orders. For more inform-
ation, see Smart Combo Routing.
Show Errors Jumps to the Error Code field and shows the error code.
l Bracket orders
l VOL orders
l Trailing Stop Limit Orders
l Scale Orders
l Relative Orders
This page includes several example orders with mouseover help to assist you in learning how to place these orders. Sim-
ply move your mouse over the red triangle of the corner of cells on the page to display pop-up help.
For more information about using extended order attributes for individual orders or groups of orders, see Apply Extended
Order Attributes to Individual Orders and Groups of Orders
4. Click the Advanced Orders tab, highlight the first order in the bracket order, then click the Place/Modify Order
button.
The order is not executed, but the system generates an Order ID.
5. Copy the Order ID for the first order, omitting the “id” prefix, then click the Extended Order Attributes tab and
paste the Order ID into the Value field for Parent Order Id (row 14). This value will be applied to all subsequent
orders until you remove it from the Extended Order Attributes page.
The first order of the bracket order is now the primary order.
6. Click the Advanced Orders tab, highlight the second order, then click the Place/Modify Order button.
The order is not executed but is now associated with the primary order by means of the Parent Order Id extended
order attribute.
7. Click the Extended Order Attributes tab and change the value for Transmit back to 1 (row 13).
8. Click the Advanced Orders tab, highlight the third order in the bracket order, then click the Place/Modify Order
button. The entire bracket order is transmitted.
9. When you are done placing your bracket order, go to the Extended Order Attributes page and delete the Parent
Order Id value you entered. If you do not, this value will be applied to all subsequent orders that you place in the
spreadsheet.
l Volatility
l Volatility Type
9. When you are done placing VOL orders, go to the Extended Order Attributes page and delete the VOL order val-
ues you entered. If you do not, these values will be applied to all subsequent orders that you place in the spread-
sheet.
l trailing amount
l stop price
l limit price
l limit offset
In the ActiveX for Excel API spreadsheet, you enter the trailing amount, stop price and limit price. There is no field or
extended order attribute for the limit offset value. You must include the limit offset in the stop price (the Trail Stop Price
extended order attribute).
5. On the Advanced Orders page, select the order row and click the Apply Extended Template button. The scale
order values are applied to the selected order and displayed in the Extended Order Attributes section of the page.
6. Click the Place/Modify Order button.
7. When you are done placing your order, go to the Extended Order Attributes page and delete the scale order val-
ues you entered. If you do not, these values will be applied to all subsequent orders that you place in the spread-
sheet.
5. On the Advanced Orders page, select the order row and click the Apply Extended Template button. The percent
offset value is applied to the selected order and displayed in the Extended Order Attributes section of the page.
6. Click the Place/Modify Order button.
7. When you are done placing your order, go to the Extended Order Attributes page and delete the Percent Offset
value you entered. If you do not, this value will be applied to all subsequent orders that you place in the spread-
sheet.
Button Description
Create Ticker Opens the Ticker box. Enter inform-
ation to create a market data line.
Combo Legs Opens the Combination Legs box.
Enter contract details to create legs of
a combination order one by one.
Apply Extended Template Applies the current values on the
Extended Order Attributes page to the
highlighted order row.
Place/Modify Orders After you have completed the Order
Description fields, and defined any
extended attributes, click to create an
order for the selected contract.
Cancel Order This button cancels the selected order
(s).
Smart Combo Routing Opens the Smart Combo Routing Para-
Params meters box, which lets you add and
remove parameter/value pairs to combo
orders. For more information, see Smart
Combo Routing.
Clear Order Statuses Clears all order status information from
the page.
There is also a WhatIf check box on the toolbar. When checked, you will receive margin and commission data as if the
order were placed, but the order will NOT be placed.
The Extended Order Attributes page includes all of the optional attributes you can use when you send an order, such as
setting a display size to create an iceberg order, adding orders to an OCA group, and setting the transmit date for a Good
After Time order. Once you define the attributes on this page, you can apply them to a single order or selected group of
orders using the Apply Extended Template button, which occurs on both the Orders page and the Conditional Orders
page. The attributes populate the extended order attributes fields that follow the Order Status fields to the far right of the
page.
For a complete list of extended order attributes supported by the API, see Extended Order Attributes.
l When appended to orderDescription, the number and order of attributes cannot be changed.
l For any attribute that is not defined, use the value 'EMPTY' or {}. Since a string length is limited to 255 char-
acters, we recommend using the open/close curly braces {}.
l A place order message for a simple stock limit day order looks as follows, with the primary exchange "ISLAND"
separating the extended attributes:
=psmith12|ord!'id1814454745?place?BUY_1_MSFT_STK_SMART_USD_LMT_26_{}_DAY_{}_{}_O_0_
{}_1_{}_0_0_
0_0_0_0_{}_{}_{}_{}_{}_{}_{}_{}_ISLAND_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_
{}_{}_1_2_3_4_5'
Note: You can also use this procedure to apply extended order attributes to orders on the Condi-
tional Orders page.
When you place the order or group of orders, the extended order attribute values you entered are applied to the
order.
For example, you might want to assign a unique Order Ref number to a group or basket of orders. To do this, you
would enter the number for the Order Ref attribute on the Extended Order Attributes page, then select all the
orders in the group on the Orders page and click Apply Extended Template.
4. Delete the value of the extended order attributes you used for the order from the Extended Order Attributes page.
These values will still apply to all subsequent orders that you place from the ActiveX for Excel API spreadsheet
unless you remove the value.
The Open Orders page shows you all transmitted orders, including those that have been accepted by the IB system, and
those that are working at an exchange. Once you have subscribed, the page is updated each time you submit a new order,
either through the API or in TWS.
Once an order executes, it remains on the Open Orders page for 30 seconds, with the Status value changed to FILLED.
Then the filled order is cleared and you can see it on the Executions page if you subscribed to real-time executions.
Button Description
Request Open Orders Queries TWS and returns all open
orders. Once you subscribe to open
orders, this page updates each time
there is a new open order.
Request All Open Orders Queries TWS and returns all open
orders from the current account. Once
you subscribe to open orders, this page
updates each time there is a new open
order.
Request Auto Open Orders Queries TWS and associate all newly
created TWS orders with the current cli-
ent, which must be Client ID 0.
Cancel Auto Open Orders Cancels association of newly created
TWS orders with the client
Clear Open Orders Removes all open orders from the page.
Account Page
l View account details including your current Equity with Loan Value and Available funds.
l View list of advisor-managed account codes.
l Financial Advisors can view FA information.
l View your current portfolio.
Button Description
Request Account Updates Each click gives you data for a specific account value. All blank
lines that precede the Account Portfolio section will hold data.
Continue to click until all lines are populated.
Cancel Account Updates Click this button one time for each position you hold. When you
get a line of "0's" you know you have downloaded all current pos-
itions. These values continue to update in real-time.
Request Managed For advisor accounts, receives a list of managed accounts and dis-
Accounts plays them as a comma-separated list in the Management Accounts
cell.
Button Description
Request FA For advisor accounts, displays FA data of the type specified in the
FA Data Type cell.
Clear Account Data Clears all information from the page. You must first cancel your
subscription before you can clear the data.
Portfolio Page
Note: Ensure that TWS is running, and that you have connected the spreadsheet to TWS.
Exercising Options
You can exercise options or let options lapse on the Portfolio page.
Button Description
Exercise Options Exercises the selected option or lets the
selected option lapse, depending on the
value in the Exercise Action cell.
Clear Portfolio Data Removes all data from the page.
Executions Page
When you subscribe to executions, the Executions page displays information about all completed trades.
Viewing Executions
Note: Ensure that TWS is running, and that you have connected the spreadsheet to TWS.
To view executions
1. Click the Executions tab at the bottom of the spreadsheet.
2. Optionally, filter your executions by entering values in the Execution Filter cells:
o Filter executions by client ID, account code, date/time, symbol, security type, exchange or side.
Button Description
Request Executions Queries TWS and returns information
about all valid executions. After you
subscribe to executions, this page
updates each time an order executes.
Clear Executions Table Removes all execution reports from the
page.
Commission Reports
The Commission Reports page displays commission details, including commission, currency, realized P&L, yield and
yield redemption date. When you request Executions on the Execution page, you also receive commission reports.
Button Description
Clear Commission Reports Removes all commission reports from the page.
Use the Historical Data page to request historical data for an instrument based on data you enter in query fields. The
query results display on a separate worksheet page and creates a new page for the results if the page doesn't currently
exist.
Note: For a information about historical data request limitations, see Historical Data Limitations.
In the Activate Page cell, enter TRUE to display the results page on top of the current window. Enter FALSE to
display the page on a separate tab in the spreadsheet without displaying on top of the current window.
The results are displayed on a new tabbed page in the spreadsheet, the name of which is specified in the Page
Name cell.
In the Activate Page cell, enter TRUE to display the results page on top of the current window. Enter FALSE to
display the page on a separate tab in the spreadsheet without displaying on top of the current window.
The results are displayed on a new tabbed page in the spreadsheet, the name of which is specified in the Page
Name cell.
5. Historical data queries on expired contracts are limited to the last year of the life of the contract.
The following figure shows a typical historical data results page.
Parameter Description
End Date/Time Use the format yyyymmdd {space}hh:mm:ss{space}tmz where the time
zone is allowed (optionally)after a space at the end.
Duration This is the time span the request will cover, and is specified using the
format integer {space} unit, where valid units are:
l S (seconds)
l D (days)
l W (weeks)
l Y (years)
This unit is currently limited to one. If no unit is specified, seconds are
used.
Parameter Description
Bar Size Specifies the size of the bars that will be returned. The following bar
sizes may be used, and are specified using the parametric value:
Bar
Integer
Size
Value
String
1 1
second
5 2
second-
s
15 3
second-
s
30 4
second-
s
1 5
minute
2 6
minute-
s
3 16
minute-
s
5 7
minute-
s
15 8
minute-
s
30 9
minute-
s
1 hour 10
1 day 11
Parameter Description
What to Show Determines the nature of the data extracted. Valid values include:
l Trades
l Midpoint
l Bid
l Ask
l Bid/Ask
All but the Bid/Ask data contain the start time, open, high, low, close,
volume and weighted average price during the time slice queried.
For the Bid/Ask query, the open and close values are the time-weighted
average bid and the time-weighted average offer, respectively. These
bars are identical to the TWS charts' candlestick bars.
Note that the new page is added to the right of the existing tabs on the worksheet.
Button Description
Create Ticker Opens the Ticker box. Enter information to create a mar-
ket data line.
Combo Legs Opens the Combination Legs box. Enter contract
details to create legs of a combination order one by
one.
Request Historical Submits your historical data query to TWS and displays
Data the results on a separate worksheet page.
Use the Contract Details page to request contract-specific information such as supported order types, valid exchanges, the
contract ID, and so on.
In the Activate Page cell, enter TRUE to display the results page on top of the current window. Enter FALSE to
display the page on a separate tab in the spreadsheet without displaying on top of the current window.
The results are displayed on a new tabbed page in the spreadsheet, the name of which is specified in the Page
Name cell.
The following figure shows a typical contract details page.
Button Description
Request Contract Details Returns information on the selected contract.
Use the Bond Contract Details page to request contract-specific information for bonds, including the coupon, ratings,
bond type, maturity date, and so on.
Note: Beginning with TWS Version 921, some bond contract data will be suppressed and will not
be available from the API. All bond contract data will continue to be available from Trader
Workstation, but only the following bond contract data will be available from the API:
- Contract ID
- Minimum Tick
- CUSIP (if you have subscribed to the CUSIP service)
- Rating (if you have subscribed to ratings)
In the Activate Page cell, enter TRUE to display the results page on top of the current window. Enter FALSE to
display the page on a separate tab in the spreadsheet without displaying on top of the current window.
The results are displayed on a new tabbed page in the spreadsheet, the name of which is specified in the Page
Name cell.
Note: Beginning with TWS Version 921, some bond contract data will be suppressed and will not
be available from the API. All bond contract data will continue to be available from Trader
Workstation, but only the following bond contract data will be available from the API:
- Contract ID
- Minimum Tick
- CUSIP (if you have subscribed to the CUSIP service)
- Rating (if you have subscribed to ratings)
Button Description
Request Bond Contract Details Gets bond information data for the selected contract.
Real time bars allow you to get a summary of real-time market data every five seconds, including the opening and clos-
ing price, and the high and the low within that five-second period (using TWS charting terminology, we call these five-
second periods "bars"). You can also get data showing trades, midpoints, bids or asks. You request real time bars on the
Real Time Bars page, which is shown below.
1. Click the Real Time Bars tab at the bottom of the spreadsheet to open the Real Time Bars page.
2. Select or enter the ticker symbol for which you want to request real time bars.
3. Enter the following information for the selected row:
o In the What to Show cell, enter TRADES, BID, ASK or MIDPOINT.
o In the RTH Only cell, enter 0 to return all data available during the time span requested, including time inter-
vals when the market in question was outside of regular trading hours. Enter 1 to return only data within the
regular trading hours for the product requested is returned, even if the time span falls partially or completely
outside.
4. Select the row, then click Request Real Time Bars on the toolbar. The status of your request displays in the Sub-
scription Status cell.
Results are displayed in the Real Time Bars cells on the right side of the page.
Button Description
Create Ticker Opens the Ticker box. Enter information to create a market data
line.
Request Real Time Bars Submits your real time bars request to TWS and displays the res-
ults in the dark gray cells the right side of the page.
Cancel Real Time Bars Cancels the real time bars request.
Clear Real Time Bars Clears all real time bar data from the page.
Table
Use the Market Scanner page to subscribe to TWS market scanners. These scanners allow you to define criteria and set fil-
ters that return the top x number of underlyings which meet all scan criteria. The scan is continually updated in real time.
You can also display market scanner parameters from this page.
Setting this cell to TRUE forces the scan results page to pop to the front of your application every time it
updates. To stop this behavior, set the value of this field to FALSE.
c. Type values for the rest of the scan parameters in the lightly shaded section of the page. You can get all of
the scan codes from the market scanner parameters.
3. Click Request Scanner Subscription on the toolbar. A new page for the scanner is created and is displayed after
the subscription is processed.
Note: Ensure that TWS is running, and that you have connected the spreadsheet to TWS.
3. To save the parameters in a convenient file on your computer, manually select part or all of the contents of the
XML file in the Scanner Parameters window, then copy and paste it into a separate text document.
4. Click OK to close the Scanner Parameters window.
The Scanner Parameters window is shown on the next page.
Button Description
Request Scanner Parameters Displays all scanner parameters in an XML file in a
separate window.
Request Scanner Subscription Creates and displays a new page for results of the
selected market scanner.
Cancel Scanner Subscription Cancels the market scanner.
Fundamentals Page
Use the Fundamentals page to receive Reuters global fundamental data and fundamental ratios. There must be a paid sub-
scription to Reuters Fundamental set up in Account Management before you can receive this data.
1. Click the Fundamentals tab at the bottom of the spreadsheet to display the Fundamentals page.
2. Enter information about the contract for which you want fundamentals data or ratios into the Contract Descrip-
tion cells.
3. In the Report Type cell, enter the type of report you wish to view:
o finstat - Financial Statement
o estimates - Estimates
o snapshot - Summary
4. In the Generic Tick Type cell, enter 258 as the tick type value. For details on generic tick type values, see Generic
Tick Types.
5. Enter the following information in the Fundamentals section of the page for fundamental data, or the Fun-
damental Ratios section for fundamental ratios:
a. Fundamental data and ratio results display on a new page in the spreadsheet. Type the name of the results
page in the Page Name cell.
Setting this cell to TRUE forces the results page to pop to the front of your application every time it
updates. To stop this behavior, set the value of this field to FALSE.
6. Do one of the following:
o Click Request Fundamentals on the toolbar to view fundamentals data. A new page for the results is created
and is displayed after the request is processed.
o Click Fundamentals Ratios on the toolbar to view fundamentals ratios. A new page for the results is created
and is displayed after the request is processed.
The status of your request appears in the Subscription Status cell.
Button Description
Request Fundamentals Requests fundamentals data, which displays on a
new page in the spreadsheet based on the inform-
ation you enter on the page.
Cancel Fundamentals Cancels fundamentals data.
Fundamental Ratios Requests fundamentals ratios, which displays on
a new page in the spreadsheet based on the
information you enter on the page.
Cancel Fundamental Cancels fundamentals ratios.
Ratios
Advisors Page
If you are a Financial Advisor and manage multiple accounts, use the Advisors page to create FA orders that:
Note: You must set up your managed accounts, account groups, methods and allocation profiles in
TWS before you can place FA orders in the ActiveX for Excel API sample spreadsheet.
You can use the Advisors page to set up an order and allocate all shares in the order to a single account.
Note: Ensure that TWS is running, and that you have connected the spreadsheet to TWS.
8. When you are done allocating shares to the account, delete the Account value from the Extended Order Attrib-
utes page. If you do not delete this value, it will be applied to all subsequent orders placed from the ActiveX for
Excel spreadsheet.
Optionally, you can receive margin and commission information that would result from the order if you placed it by
selecting the WhatIf check box on the toolbar. In this case, your order is not actually placed. Deselect the check box to
place your order without seeing the margin and commission information ahead of time.
You can also use the Advisors page to set up an order using an FA account group and FA method.
You can also use the Advisors page to set up an order using an FA allocation profile.
4. Click the Extended Order Attributes tab. Enter the name of the allocation profile in the Value field for the FA
Profile extended order attribute.
5. Click the Advisors tab.
6. Highlight the order row, then click the Apply Extended button to apply the extended order attribute value to the
order. The value for FA Profile is applied to the selected order and displayed in the Extended Order Attributes sec-
tion of the page.
7. Click the Place/Modify Order button.
8. When you are done allocating shares to the account, delete the FA Profile value you entered on the Extended
Order Attributes page. If you do not delete this value, it will be applied to all subsequent orders placed from the
ActiveX for Excel spreadsheet.
Optionally, you can receive margin and commission information that would result from the order if you placed it by
selecting the WhatIf check box on the toolbar. In this case, your order is not actually placed. Deselect the check box to
place your order without seeing the margin and commission information ahead of time.
Button Description
Create Ticker Opens the Ticker box. Enter information to create a market data line.
Combo Legs Opens the Combination Legs box. Enter contract details to create legs
of a combination order one by one.
Apply Extended Tem- Applies the current values on the Extended Order Attributes page to the
plate highlighted order row.
Place/Modify Orders After you have completed the Order Description fields, and defined any
extended attributes, click to create an order for the selected contract.
Cancel Order This button cancels the order(s) you have highlighted.
Clear Order Statuses Clears all information from the Order Status cells.
Log Page
The Log page displays all error messages received while logged into TWS and using the ActiveX for Excel spreadsheet.
You can clear all the information on the page by clicking Clear Log on the toolbar.
The POSIX API is based on our C++ API code. The C++ code was refactored so it could be built on any POSIX-com-
pliant platform. Use this new POSIX API to build a TWS API on Linux, and on Windows in non-MFC applications.
Note: Although the pre-existing public interface has been preserved, you must recompile your cli-
ent applications.
We also include a POSIX test client. The API installation directory includes these directories for the POSIX API:
PosixSocketClient and TestPosixSocketClient. The POSIX test client uses the same methods as the C++ Socket client,
plus it exposes several extra methods that clients must call when data is available on a socket for read/write. Refer to
TestPosixSocketClient as an example. Please note that this test client is greatly simplified. For real POSIX API applic-
ations, you will have to use a select system of some kind to manage several sockets and/or asynchronous events.
To run the POSIX test client on a Windows machine, see Running the POSIX Client on a Windows Machine.
2. If you ran vcvars32.bat successfully, the command prompt should look like this:
3. Navigate to C:\... \TestPosixSocketClient in the same command prompt window. In the example below,
TestPosixSocketClient is located in the C:\IB_API_963.
5. Now run the POSIX sample application by running PosixSocketClientTest.exe in the same C:\...\TestPosixSock-
etClient directory.
Reference
This chapter includes the following TWS API reference information:
Message codes shown below that end with a colon ( : ) display additional information.
Error Codes
Code Description
100 Max rate of messages per second has been exceeded.
101 Max number of tickers has been reached.
102 Duplicate ticker ID.
103 Duplicate order ID.
104 Can't modify a filled order.
105 Order being modified does not match original order.
106 Can't transmit order ID:
107 Cannot transmit incomplete order.
109 Price is out of the range defined by the Percentage setting at order defaults
frame. The order will not be transmitted.
110 The price does not conform to the minimum price variation for this contract.
111 The TIF (Tif type) and the order type are incompatible.
113 The Tif option should be set to DAY for MOC and LOC orders.
114 Relative orders are valid for stocks only.
115 Relative orders for US stocks can only be submitted to SMART, SMART_ECN,
INSTINET, or PRIMEX.
116 The order cannot be transmitted to a dead exchange.
117 The block order size must be at least 50.
118 VWAP orders must be routed through the VWAP exchange.
119 Only VWAP orders may be placed on the VWAP exchange.
120 It is too late to place a VWAP order for today.
121 Invalid BD flag for the order. Check "Destination" and "BD" flag.
Code Description
129 VWAP orders must be submitted at least three minutes before the start time.
131 The sweep-to-fill flag and display size are only valid for US stocks routed
through SMART, and will be ignored.
132 This order cannot be transmitted without a clearing account.
133 Submit new order failed.
134 Modify order failed.
135 Can't find order with ID =
136 This order cannot be cancelled.
137 VWAP orders can only be cancelled up to three minutes before the start time.
Code Description
161 Cancel attempted when order is not in a cancellable state. Order permId =
Code Description
200 No security definition has been found for the request.
201 Order rejected - Reason:
202 Order cancelled - Reason:
203 The security <security> is not available or allowed for this account.
Code Description
300 Can't find EId with ticker Id:
301 Invalid ticker action:
302 Error parsing stop ticker string:
303 Invalid action:
304 Invalid account value action:
305 Request parsing error, the request has been ignored.
306 Error processing DDE request:
307 Invalid request topic:
308 Unable to create the 'API' page in TWS as the maximum number of pages
already exists.
309 Max number (3) of market depth requests has been reached.
325 Discretionary orders are not supported for this combination of exchange and
order type.
326 Unable to connect as the client id is already in use. Retry with a unique client
id.
327 Only API connections with clientId set to 0 can set the auto bind TWS orders
property.
328 Trailing stop orders can be attached to limit or stop-limit orders only.
329 Order modify failed. Cannot change to the new order type.
330 Only FA or STL customers can request managed accounts list.
331 Internal error. FA or STL does not have any managed accounts.
332 The account codes for the order profile are invalid.
333 Invalid share allocation syntax.
334 Invalid Good Till Date order
335 Invalid delta: The delta must be between 0 and 100.
337 The date, time, or time-zone entered is invalid. The correct format is yyyym-
mdd hh:mm:ss xxx
where yyyymmdd and xxx are optional. E.g.: 20031126 15:59:00 EST
Note that there is a space between the date and time, and between the time
and time-zone.
If no date is specified, current date is assumed.
If no time-zone is specified, local time-zone is assumed.
338 Good After Time orders are currently disabled on this exchange.
339 Futures spread are no longer supported. Please use combos instead.
351 The "Regular Trading Hours only" flag is not valid for this order.
352 Short sale slot value of 2 (delivered from elsewhere) requires location.
374 If both are set, the lower stock range attribute must be less than the upper stock
range attribute.
375 Stock range attributes cannot be negative.
376 The order is not eligible for continuous update. The option must trade on a
cheap-to-reroute exchange.
377 Must specify valid delta hedge order aux. price.
378 Delta hedge order type requires delta hedge aux. price to be specified.
379 Delta hedge order type requires that no delta hedge aux. price be specified.
380 This order type is not allowed for delta hedge orders.
381 Your DDE.dll needs to be upgraded.
382 The price specified violates the number of ticks constraint specified in the
default order settings.
383 The size specified violates the size constraint specified in the default order set-
tings.
384 Invalid DDE array request.
385 Duplicate ticker ID for API scanner subscription.
386 Duplicate ticker ID for API historical data query.
387 Unsupported order type for this exchange and security type.
388 Order size is smaller than the minimum requirement.
389 Supplied routed order ID is not unique.
390 Supplied routed order ID is invalid.
391 The time or time-zone entered is invalid. The correct format is hh:mm:ss xxx
where xxx is an optionally specified time-zone. E.g.: 15:59:00 EST.
Note that there is a space between the time and the time zone.
If no time zone is specified, local time is assumed.
Code Description
400 Algo order error.
401 Length restriction.
405 The child order quantity should be equivalent to the parent order size.
423 Cross order RFQ has been expired. THI committed size is no longer avail-
able. Please open order dialog and verify liquidity allocation.
430 We are sorry, but fundamentals data for the security specified is not avail-
able.
431 What to show field is missing or incorrect.
432 Commission must not be negative.
433 Invalid "Restore size after taking profit" for multiple account allocation scale
order.
434 The order size cannot be zero.
435 You must specify an account.
436 You must specify an allocation (either a single account, group, or profile).
437 Order can have only one flag Outside RTH or Allow PreOpen.
438 The application is now locked.
439 Order processing failed. Algorithm definition not found.
440 Order modify failed. Algorithm cannot be modified.
441 Algo attributes validation failed:
442 Specified algorithm is not allowed for this order.
443 Order processing failed. Unknown algo attribute.
444 Volatility Combo order is not yet acknowledged. Cannot submit changes at
this time.
445 The RFQ for this order is no longer valid.
446 Missing scale order profit offset.
447 Missing scale price adjustment amount or interval.
448 Invalid scale price adjustment interval.
449 Unexpected scale price adjustment amount or interval.
40 Dividend schedule query failed.
Code Description
501 Already connected.
502 Couldn't connect to TWS. Confirm that API is enabled in TWS via the Con-
figure>API menu command.
503 Your version of TWS is out of date and must be upgraded.
504 Not connected.
505 Fatal error: Unknown message id.
506 Unsupported version. For Java clients only.
507 Bad message length. For Java clients only.
508 Bad message. For Java clients only.
Code Description
10000 Cross currency combo error.
10001 Cross currency vol error.
Code Description
1100 Connectivity between IB and TWS has been lost.
1101 Connectivity between IB and TWS has been restored-
data lost.*
1102 Connectivity between IB and TWS has been restored-
data maintained.
1300 TWS socket port has been reset and this connection is
being dropped.
Please reconnect on the new port - <port_num>
*Market and account data subscription requests must be resubmitted
Code Description
2100 New account data requested from TWS. API client has been unsub-
scribed from account data.
2101 Unable to subscribe to account as the following clients are subscribed to
a different account.
2102 Unable to modify this order as it is still being processed.
2103 A market data farm is disconnected.
l Historical data requests that use a bar size below 30 seconds can only go back six months.
l Historical data requests can go back one full calendar year or more, depending on the number of concurrent real-
time market data lines:
Market data lines can be increased based on monthly commission amounts, amount of equity and Quote Booster sub-
scriptions.
l For more information on how market data is affected by commissions and equity, see the second-to-the-last Note
(the long note with the examples) at the bottom of the Market Data page on our website.
l For more information on Quote Boosters, see the Quote Boosters page on our website. You subscribe to Quote
Boosters on the Market Data Subscriptions page in Account Management.
Pacing Violations
All of the API technologies support historical data requests. However, requesting the same historical data in a short
period of time can cause extra load on the backend and subsequently cause pacing violations. The error code and mes-
sage that indicates a pacing violation is:
162 - Historical Market Data Service error message: Historical data request pacing violation
l Do not make more than 60 historical data requests in any ten-minute period.
l If the whatToShow parameter in reqHistoricalData() is set to BID_ASK, then this counts as two requests and we
will call BID and ASK historical data separately.
Note: For more information about historical data requests, see Viewing Historical Data in the DDE
for Excel chapter, reqHistoricalDataEx() in the ActiveX chapter, reqHistoricalData() in the
C++ chapter, and reqHistoricalData() in the Java chapter.
1 week 10 minutes
2 weeks 15 minutes
1 month 30 minutes
3 months 1 day
Everything else 1 day
Valid Duration and Bar Size Settings for Historical Data Requests
The following table lists the minimum bar size settings for API historical data requests.
The following table lists valid duration and bar size settings for API historical data requests. Please note that these are
only guidelines.
Tick Types
The following table lists all possible values for the tickType parameter, which is used in the following ActiveX events,
C++ EWrapper functions, and Java EWrapper methods:
l tickPrice()
l tickSize()
l tickOptionComputation()
l tickGeneric()
l tickString()
l tickEFP
0 = Not halted
1 = Halted.
Beginning with TWS Version 939, possible values for the HALTED tick type are:
0 = Not halted
1 = General halt (trading halt is imposed for purely regulatory reasons) with/without volatility halt.
2 = Volatility only halt (trading halt is imposed by the exchange to protect against extreme volatility).
3. Applies to bond contracts only.
Starting with API version 9.0 (client version 30), version 6 of the REQ_MKT_DATA message is sent containing a new
field that specifies the requested ticks as a list of comma-delimited integer Ids (generic tick types). Requests for these
ticks will be answered if the tick type requested pertains to the contract at issue.
Note that Generic Tick Tags cannot be specified if you elect to use the Snapshot market data subscription.
Resulting
Integer ID Value Tick Type Tick
Value
100 Option Volume (currently for stocks) 29, 30
Resulting
Integer ID Value Tick Type Tick
Value
292 Receive top news for underlying contracts from TWS for news feeds to 62
which you have subscribed (in Account Management). Use secType =
NEWS in the Contract object. See Requesting News for examples.
You will receive at least one news tick regardless of its timeliness (it
could be new or it could be weeks old). Some news providers limit us
to maximum news retention of 30 days, so those limitations may affect
which news you see. Otherwise you will receive a maximum of five of
the most recent news items in the last 24 hours, and you will receive
additional news items as they come in.
411 Realtime Historical Volatility 58
456 IBDividends 59
In TWS, there is a SHORTABLE column, as shown below. The column describes number of shares with which the secur-
ity can be sold short.
The color GREEN indicates that at least 1000 shares are available to sell short. DARK GREEN indicates that this con-
tract can be sold short but that at the moment there are no shares available for short sale, and that the system is searching
for shares. RED indicates that no shares are available for short sale.
With API 9.30 or higher, the shorting indicator is supported for all socket connections. The functionality equates to the
SHORTABLE column in the TWS workstation.
When invoking the reqMktDataEx()/reqMktData() methods, you must include generic ticktype 236 in the argument to
obtain the shortable value. For example:
The Shortable tick determines if SHORT SELL orders for a contract will be accepted. Analyze the value returned from
tickGeneric(int tickerId, int tickType, double value) as follows:
The FUNDAMENTAL_RATIOS tickType (Tick Value 47) lets you request fundamental ratios in the form TAG-
G=VALUE, TAG2=VALUE2, and so on. This ratios are sent using the tickGeneric() callback. The following table lists
all the TAG values for FUNDAMENTAL_RATIOS.
TAG Description
NPRICE Closing Price
This is the closing price for the issue from the day it last traded. It is also referred to
as the Current Price. Note that some issues may not trade every day, and therefore it
is possible for this price to come from a date prior to the last business day.
TAG Description
MKTCAP Market capitalization
This value is calculated by multiplying the current Price by the current number of
shares outstanding.
TTMEPSXCLX EPS excluding extraordinary items
This is the Adjusted Income Available to Common Stockholders for the trailing
twelve months divided by the trailing twelve month Diluted Weighted Average
Shares Outstanding.
TAG Description
TTMDIVSHR Dividends per share
This is the sum of the Cash Dividends per share paid to common stockholders dur-
ing the last trailing twelve month period.
TAG Description
QCURRATIO Current ratio
This is the ratio of Total Current Assets for the most recent interim period divided
by Total Current Liabilities for the same period. NOTE: This item is Not Available
(NA) for Banks, Insurance companies and other companies that do not distinguish
between current and long term assets and liabilities.
QLTD2EQ LT debt/equity
This ratio is the Total Long Term Debt for the most recent interim period divided
by Total Shareholder Equity for the same period.
TTMREV Revenue
This is the sum of all revenue (sales) reported for all operating divisions for the
most recent TTM period. NOTE: Most banks and Insurance companies do not
report revenues when they announce their preliminary quarterly financial results in
the press. When this happens, the quarterly value will not be available (NA).
TTMEBITD EBITD
Earnings Before Interest, Taxes, Depreciation and Amortization (EBITDA) is EBIT
for the trailing twelve months plus the same period's Depreciation and Amortization
expenses (from the Statement of Cash Flows). NOTE: This item is only available for
Industrial and Utility companies.
TAG Description
TTMNIAC Net Income available to common
This is the trailing twelve month dollar amount accruing to common shareholders
for dividends and retained earnings. Income Available to Common Shareholders is
calculated as trailing twelve month Income After Taxes plus Minority Interest and
Equity in Affiliates plus Preferred Dividends, General Partner Distributions and US
GAAP Adjustments. NOTE: Any adjustment that is negative (ie. Preferred Stock
Dividends) would be subtracted from Income After Taxes.
TAG Description
TTMROEPCT Return on average equity
This value is the Income Available to Common Stockholders for the trailing
twelve months divided by the Average Common Equity and is expressed as a per-
centage. Average Common Equity is calculated by adding the Common Equity for
the 5 most recent quarters and dividing by 5.
TAG Description
DIVGRPCT Growth rate % - dividend
The Dividend Growth Rate is the compound annual growth rate in dividends per
share. DIVGR% is calculated for 3 years whenever 4 years of dividends are avail-
able.
The IBDividends generic tick returns a comma-separated list of dividends in the following order:
Example
0.83,0.92,20130219,0.23
Where
RTVolume
RTVolume is one of the generic tick tags that can be requested as part of a market data request. RTVolume returns the
following:
RTVolume is the API equivalent to opening the Time and Sales Window in Trader Workstation and viewing the updates
in real time. To implement this, you must include 233 in the genericTicklist parameter in your market data request.
You will receive the RTVolume update through the tickString() event within field value 48.
Example
RTVolume=701.28;1;1348075471534;67854;701.46918464;true
RTVolume=701.26;3;1348075476533;67857;701.46917554;false
RTVolume=701.27;3;1348075482034;67860;701.46916674;true
RTVolume=701.27;3;1348075482336;67863;701.46915809;false
RTVolume=701.25;1;1348075483534;67864;701.46915486;true
RTVolume=701.24;1;1348075487029;67865;701.46915151;true
RTVolume=701.25;1;1348075489787;67866;701.46914828;true
RTVolume=701.32;4;1348075490787;67870;701.46913949;true
RTVolume=701.32;2;1348075493802;67872;701.46913497;true
RTVolume=701.29;1;1348075494789;67873;701.46913233;true
API orders only mimic the behavior of Trader Workstation (TWS). Test each order type, ensuring that you can suc-
cessfully submit each one in TWS, before you submit the same order using the API.
IBAlgo Parameters
Beginning with TWS API Release 9.6, the ActiveX, C++ and Java APIs support the following IBAlgo orders for US
Stocks and US Options:
US Stocks
US Products
l Accumulate/Distribute (AD)
The following image lists all of the IBAlgo strategies and parameters supported by the API, except Accu-
mulate/Distribute, which is documented in Accumulate/Distribute (AD).
/** Stocks */
m_contract.m_symbol = "MSFT";
m_contract.m_secType = "STK";
m_contract.m_exchange = "SMART";
m_contract.m_currency = "USD";
m_order.m_action = "BUY";
m_order.m_totalQuantity = 1;
m_order.m_orderType = "LMT";
m_order.m_lmtPrice = 0.14
m_order.m_algoStrategy = "ArrivalPx";
m_order.m_algoParams = m_algoParams;
m_order.m_transmit = false;
TWAP (Twap)
l TWAP Algo
VWAP (Vwap)
l VWAP Algo
/** Options */
m_contract.m_symbol = "C";
m_contract.m_secType = "OPT";
m_contract.m_exchange = "SMART";
m_order.m_action = "BUY";
m_order.m_totalQuantity = 1;
m_order.m_orderType = "LMT";
m_order.m_lmtPrice = 0.14;
m_order.m_algoStrategy = "BalanceImpactRisk";
m_order.m_algoParams = m_algoParams;
m_order.m_transmit = false;
l Minimize Impact
Accumulate/Distribute (AD)
/** Stocks */
m_contract.m_symbol = "IBM";
m_contract.m_secType = "STK";
m_contract.m_exchange = "SMART";
m_contract.m_currency = "USD";
m_algoParams.add(newTagValue("componentSize", "100"));
m_algoParams.add(newTagValue("timeBetweenOrders", "60"));
m_algoParams.add(newTagValue("randomizeTime20", "1"));
m_algoParams.add(newTagValue("randomizeSize55", "1"));
m_algoParams.add(newTagValue("giveUp", "1"));
m_algoParams.add(newTagValue("catchUp", "1"));
m_algoParams.add(newTagValue("waitForFill", "1"));
m_order.m_action = "BUY";
m_order.m_totalQuantity = 700;
m_order.m_orderType = "LMT";
m_order.m_lmtPrice = 140.0;
m_order.m_algoStrategy = "AD";
m_order.m_tif = "DAY";
m_order.m_algoParams = m_algoParams;
m_order.m_transmit = false;
The ActiveX, C++ and Java APIs support the following CSFB algo strategies:
l Crossfinder
l Float
l Guerilla
l Work It IW
l Work It
l Pathfinder
l Reserve
l Strike
l 10B 18
l Tex
l TWAP
l VWAP
The following image lists all of the CSFB algo strategies and parameters supported by the API.
Crossfinder (CROS)
void onCrossFinderAlgo(){
con.m_symbol = "IBM";
con.m_secType = "STK";
con.m_exchange = "CSFBALGO";
con.m_currency = "USD";
order.m_action = "BUY";
order.m_totalQuantity = 100;
order.m_orderType = "LMT";
order.m_lmtPrice = 200.0;
order.m_algoStrategy = "CROS";
order.m_algoParams = m_algoParams;
order.m_transmit = false;
Float (FLT)
void onFloatCsfbAlgo(){
con.m_symbol = "IBM";
con.m_secType = "STK";
con.m_exchange = "CSFBALGO";
con.m_currency = "USD";
order.m_action = "BUY";
order.m_totalQuantity = 100;
order.m_orderType = "LMT";
order.m_lmtPrice = 200.0;
order.m_algoStrategy = "FLT";
order.m_algoParams = m_algoParams;
order.m_transmit = false;
Guerilla (GRRL)
void onGuerillaCsfbAlgo(){
con.m_symbol = "IBM";
con.m_secType = "STK";
con.m_exchange = "CSFBALGO";
con.m_currency = "USD";
order.m_action = "BUY";
order.m_totalQuantity = 100;
order.m_orderType = "LMT";
order.m_lmtPrice = 200.0;
order.m_algoStrategy = "GRRL";
order.m_algoParams = m_algoParams;
order.m_transmit = false;
Work It IW (INIW)
void onWorkItIwCsfbAlgo(){
con.m_symbol = "IBM";
con.m_secType = "STK";
con.m_exchange = "CSFBALGO";
con.m_currency = "USD";
order.m_action = "BUY";
order.m_totalQuantity = 100;
order.m_orderType = "LMT";
order.m_lmtPrice = 200.0;
order.m_algoStrategy = "INIW";
order.m_algoParams = m_algoParams;
order.m_transmit = false;
Work It (INLN)
void onWorkItCsfbAlgo(){
con.m_symbol = "IBM";
con.m_secType = "STK";
con.m_exchange = "CSFBALGO";
con.m_currency = "USD";
order.m_action = "BUY";
order.m_totalQuantity = 100;
order.m_orderType = "LMT";
order.m_lmtPrice = 200.0;
order.m_algoStrategy = "INLN";
order.m_algoParams = m_algoParams;
order.m_transmit = false;
Pathfinder (PTHF)
void onPathFinderCsfbAlgo(){
con.m_symbol = "IBM";
con.m_secType = "STK";
con.m_exchange = "CSFBALGO";
con.m_currency = "USD";
order.m_action = "BUY";
order.m_totalQuantity = 100;
order.m_orderType = "LMT";
order.m_lmtPrice = 200.0;
order.m_algoStrategy = "PTHF";
order.m_algoParams = m_algoParams;
order.m_transmit = false;
Reserve (RSRV)
void onReserveCsfbAlgo(){
con.m_symbol = "IBM";
con.m_secType = "STK";
con.m_exchange = "CSFBALGO";
con.m_currency = "USD";
order.m_action = "BUY";
order.m_totalQuantity = 100;
order.m_orderType = "LMT";
order.m_lmtPrice = 200.0;
order.m_algoStrategy = "RSRV";
order.m_algoParams = m_algoParams;
order.m_transmit = false;
Strike (SNPR)
void onStrikeCsfbAlgo(){
con.m_symbol = "IBM";
con.m_secType = "STK";
con.m_exchange = "CSFBALGO";
con.m_currency = "USD";
order.m_action = "BUY";
order.m_totalQuantity = 100;
order.m_orderType = "LMT";
order.m_lmtPrice = 200.0;
order.m_algoStrategy = "SNPR";
order.m_algoParams = m_algoParams;
order.m_transmit = false;
void on10BCsfbAlgo(){
con.m_symbol = "IBM";
con.m_secType = "STK";
con.m_exchange = "CSFBALGO";
con.m_currency = "USD";
order.m_action = "BUY";
order.m_totalQuantity = 100;
order.m_orderType = "LMT";
order.m_lmtPrice = 200.0;
order.m_algoStrategy = "TENB";
order.m_algoParams = m_algoParams;
order.m_transmit = false;
Tex (TEX)
void onTexCsfbAlgo(){
con.m_symbol = "IBM";
con.m_secType = "STK";
con.m_exchange = "CSFBALGO";
con.m_currency = "USD";
order.m_action = "BUY";
order.m_totalQuantity = 100;
order.m_orderType = "LMT";
order.m_lmtPrice = 200.0;
order.m_algoStrategy = "TEX";
order.m_algoParams = m_algoParams;
order.m_transmit = false;
TWAP (TWAP)
void onTwapCsfbAlgo(){
con.m_symbol = "IBM";
con.m_secType = "STK";
con.m_exchange = "CSFBALGO";
con.m_currency = "USD";
order.m_action = "BUY";
order.m_totalQuantity = 100;
order.m_orderType = "LMT";
order.m_lmtPrice = 200.0;
order.m_algoStrategy = "TWAP";
order.m_algoParams = m_algoParams;
order.m_transmit = false;
VWAP (VWAP)
void onVwapCsfbAlgo(){
con.m_symbol = "IBM";
con.m_secType = "STK";
con.m_exchange = "CSFBALGO";
con.m_currency = "USD";
order.m_action = "BUY";
order.m_totalQuantity = 100;
order.m_orderType = "LMT";
order.m_lmtPrice = 200.0;
order.m_algoStrategy = "VWAP";
order.m_algoParams = m_algoParams;
order.m_transmit = false;
int m_parentId The order ID of the parent, used for bracket, auto stop and trailing stop orders.
boolean m_blockOrder If set to true, specifies that the order is a block order.
boolean m_sweep- If set to true, specifies that the order is a Sweep-to-fill order.
ToFill
int m_displaySize The publicly disclosed order size to be used when placing iceberg orders.
l O - the default value. The "double bid/ask" method will be used for
orders for OTC stocks and US options. All other orders will use the
"last" method.
l 1 - use "double bid/ask" method, where stop orders are triggered based
on two consecutive bid or ask prices.
l 2 - "last" method, where stop orders are triggered based on the last price.
l 3 - "double-last" method, where stop orders are triggered based on last
two prices.
l 4 – “bid-ask” method. For a buy order, a single occurrence of the bid
price must be at or above the trigger price. For a sell order, a single
occurrence of the ask price must be at or below the trigger price.
l 7 – “last-or-bid-ask” method. For a buy order, a single bid price or the
last price must be at or above the trigger price. For a sell order, a single
ask price or the last price must be at or below the trigger price.
l 8 – “mid-point” method, where the midpoint must be at or above (for a
buy) or at or below (for a sell) the trigger price, and the spread between
the bid and ask must be less than 0.1% of the midpoint.
For a complete description of Trigger Methods, see Modify the Trigger Method
in the Trader Workstation Users' Guide.
boolean m_ignoreRth If set to true, allows triggering of orders outside of regular trading hours.
boolean m_hidden If set to true, the order will not be visible when viewing the market depth. The
only applies to orders routed to INet.
string m_goodAfter- Indicates that the trade should be submitted after the time and date set, with
Time format YYYYMMDD HH:MM:SS (seconds are optional). Use an empty string
if not applicable.
string m_goodTillDate Indicates that the trade should remain working until the time and date set, with
format YYYYMMDD HH:MM:SS (seconds are optional). You must set the tif
to GTD when using this string. Use an empty string if not applicable.
string m_faGroup The advisor group to which the trade will be allocated. Use an empty string if
not applicable.
string m_faProfile The advisor allocation profile to which the trade will be allocated. Use an
empty string if not applicable.
string m_faMethod The advisor allocation method with which the trade will be allocated. Use an
empty string if not applicable.
String clear- The true beneficiary of the order. This value must be sent on FUT/FOP orders
ingAccount for reporting the exchange.
double stockRefPrice The stock reference price. For BOX exchange only.
double stock- The lower value of the acceptable stock range. For BOX exchange only.
RangeLower
double stock- The upper value of the acceptable stock range. For BOX exchange only.
RangeUpper
double m_volatility The option price in volatility, as calculated by TWS' Option Analytics. This
value is expressed as a percent and is used to calculate the limit price sent to
the exchange.
int m_scaleCom- For Scale orders: Defines the number of units per component, backing into the
ponentSize number of components into which the parent order is split.
double m_scalePriceIn- For Scale orders: Defines the price increment per scale component.
crement
double m_basisPoints EFP orders
int basisPointsType EFP orders
You place an order for 1000 shares of XYZ stock. There are four separate executions before the order for 1000 total
shares is completed. The first partial fill executes with 200, then the second partial fill executes with 200 shares. The
third partial fill executes with another 200 shares and finally, the last partial fill executes with 400 shares.
In the orderStatus() event, here is the sequence of status messages that will be received by the API based on this example:
High Option Imp Vol Over Historical Shows the top underlying contracts (stocks or
(HIGH_OPT_IMP_VOLAT_OVER_ indices) with the largest divergence between
HIST)* implied and historical volatilities.
Low Option Imp Vol Over Historical Shows the top underlying contracts (stocks or
(LOW_OPT_IMP_VOLAT_OVER_ indices) with the smallest divergence between
HIST)* implied and historical volatilities.
Highest Option Imp Vol Shows the top underlying contracts (stocks or
(HIGH_OPT_IMP_VOLAT)* indices) with the highest vega-weighted
implied volatility of near-the-money options
with an expiration date in the next two
months.
Top Option Imp Vol % Gainers Shows the top underlying contracts (stocks or
(TOP_OPT_IMP_VOLAT_GAIN)* indices) with the largest percent gain between
current implied volatility and yesterday's clos-
ing value of the 15 minute average of implied
volatility.
Top Option Imp Vol % Losers Shows the top underlying contracts (stocks or
(TOP_OPT_IMP_VOLAT_LOSE)* indices) with the largest percent loss between
current implied volatility and yesterday's clos-
ing value of the 15 minute average of implied
volatility.
High Opt Volume P/C Ratio Put option volumes are divided by call option
(HIGH_OPT_VOLUME_PUT_CALL_ volumes and the top underlying symbols with
RATIO) the highest ratios are displayed.
Low Opt Volume P/C Ratio Put option volumes are divided by call option
(LOW_OPT_VOLUME_PUT_CALL_ volumes and the top underlying symbols with
RATIO) the lowest ratios are displayed.
Most Active by Opt Volume Displays the most active contracts sorted des-
(OPT_VOLUME_MOST_ACTIVE) cending by options volume.
Low Option Open Interest P/C Ratio Returns the top 50 contracts with the lowest
(LOW_OPT_OPEN_INTEREST_PUT_ put/call ratio of outstanding option contracts.
CALL_RATIO)
Lowest Option Imp Vol Shows the top underlying contracts (stocks or
(LOW_OPT_IMP_VOLAT) indices) with the lowest vega-weighted
implied volatility of near-the-money options
with an expiration date in the next two
months.
Market scanners in the TWS API support the following instruments and location codes:
Instruments
l STK - US stocks
l STOCK.HK - Asian stocks
l STOCK.EU - European stocks
Location Codes
l STK.US - US stocks
l STK.US.MAJOR - US stocks (without pink sheet)
l STK.US.MINOR - US stocks (only pink sheet)
l STK.HK.SEHK - Hong Kong stocks
l STK.HK.ASX - Australian Stocks
l STK.EU - European stocks
Smart Combo Routing is also supported in the Active X, C++ and Java APIs through the use of smartCom-
boRoutingParams, which requires TWS server version 57 or higher. smartComboRoutingParams is similar to
AlgoParams in that it makes use of tag/value pairs to add parameters to combo orders. The parameters cover the fol-
lowing capabilities:
Tag = LeginPrio
Values = -1, 0 or 1
l Discretionary Amount - When one leg is executed, we can adjust the other leg by up to a discretionary amount.
Tag = MaxSegSize
Value = An amount
l Market-If-Touched Timeout - For Market-If-Touched combo orders, we record the firstTradeTime of the first fill
of the first leg to execute, and the lastTradeTime of the last partial fill. For these kinds of orders, you can now spe-
cify timeout values of the last fill and the timeout since the first fill, in seconds.
Tags = ChangeToMktTime1 is the timeout after the last fill, and ChangeToMktTime2 is the timeout after the first
fill.
Value = Number of seconds
l Market-If-Touched Stop-Loss - Specify an absolute stop-loss amount per combo. If specified and if the implied
execution price of the combo (based on a leg that has already been executed and current market data) exceeds the
combo price plus the stop-loss amount, we convert the order from LMT to MKT immediately in order to finish
executing the combo order. If the stop-loss amount is specified but timeouts have not been specified, we will con-
tinue to try to execute the second leg at the calculated LMT price until it either executes or the stop-loss amount
is reached.
Tag = ChangeToMktOffset
Value = An amount.
l Maximum Leg-In Size - Specify the maximum allowed leg-in size per segment.
Tag = MaxSegSize
Value = Unit of combo size
l Discretionary Percentage - Specify a percentage of the combo price. This applies to scale combos in which the
discretionary amount is calculated from the current scale level. When the discretionary amount is entered as a per-
centage, the API converts it to a dollar amount based on the combo. This amount will be updated when the order
price changes or for scale orders for each level. You can enter a value for this parameter or for the Discretionary
Amt extended attribute one at a time, but not both at the same time.
Tag = DiscretionaryPct
Value = A value between 0 and 100.
API Logging
As client requests are processed (both system and API clients) it logs certain information to its 'log.txt' log file, which is
located in the installation directory. The purpose of this file is to help resolve problems by providing some insight into
the state of the program before the problem occurred.
API clients can specify how detailed they want these log entries to be by setting the log level. Log levels are:
l 1 = SYSTEM
l 2 = ERROR
l 3 = WARNING
l 4 = INFORMATION
l 5 = DETAIL
Note: Setting the log level to 5 will increase performance overhead. You should only use log level
5 when you are trying to resolve an issue.
[Cli-
entID:ClientVersion:ServerVersion:ClientType:Request:Response:Version:LogEntryType]
where:
From this example, we can tell that a socket client with clientId=0 connected and made a request for market data. The
version of the market data request, which was 3, implies what data should have been sent.
Note: This information, along with the various request/response message versions, can be found in
the EClientSocket implementation file supplied with the API installation.
RFQs from the IB Options Trading Desk are available only to users who have access to these specific areas. Please con-
tact the IB Options Trading Desk if you are interested in participating.
Market data for an RFQ is received until the user cancels the RFQ or the RFQ is canceled by the server. The server nor-
mally cancels an RFQ when it expires (approximately 1 minute) or if the RFQ request is invalid and/or for an unsup-
ported product.
Delta-Neutral RFQs
Submit Delta-Neutral RFQs by creating a combo order, even if a single contract must be hedged, and filling up and
attaching an UnderComp structure to a contract underComp field.
In the UnderComp structure, you must specify the conId of the hedge contract. The price and delta fields can be left
empty (0).
Upon accepting a Delta-Neutral DN RFQ, the server sends a deltaNeutralValidation() message with the UnderComp struc-
ture. If the delta and price fields are empty in the original request, the confirmation will contain the current values from
the server. These values are locked when the RFQ is processed and remain locked until the RFQ is canceled.
RFQ Samples
To learn more about submitting RFQs with the TWS API, look at the RFQ samples included in the 9.6 release of the API
software. The samples are located in the samples/rfq folder in your API software installation folder. The
SampleRFQ.java sample implements a small-state machine and shows how to submit RFQ's for:
l EU Stocks
l US Futures
l US Stock Options
l EU Stock Options
l Calendar Spread for Index Option (Delta-Neutral)
l US Stock Option (Delta-Neutral)
l US Index Option (Delta-Neutral)
l EU Index Option (Delta-Neutral)
You can identify mini options in the Active X, Java and C++ APIs by providing the multiplier or trading class in both
requests to TWS and responses from TWS.
The following requests and callbacks that include the Contract structure as a parameter can now use the tradingClass and
multiplier attributes to identify mini options. Also, some of these requests can now use the conId attribute to identify a
security (these are indicated below).
Requests
l reqMktData
l reqHistoricalData - also conId
l reqRealTimeBars - also conId
l reqContractDetails
l reqMktDepth - also conId
l exerciseOptions - also conId
l placeOrder
l calculateImpliedVolatility
l calculateOptionPrice
Callbacks
l openOrder
l updatePortfolio
l execDetails
l position
l multiplier is encoded/decoded after contract.right and before contract.exchange in all requests and callbacks.
l conId is encoded after tickerId/reqId and before contract.symbol in all requests and callbacks.
l tradingClass is encoded/decoded after contract.localSymbol in all requests and callbacks.
The reqFundamentalData request, available for stocks only, can also handle the conid attribute in the Contract structure
but not tradingClass or multiplier.
You can identify mini options in the DDE for Excel API by providing the multiplier or trading class in both requests to
TWS and responses from TWS. The DDE for Excel API spreadsheet (TwsDde.xls) released with API Version 9.69 was
updated to include the Trading Class column on most pages. You use this field to request mini options data from TWS.
Requirements
Mini-option support in the DDE for Excel API requires the following:
l The updated Excel spreadsheet requires ddedll.dll Version 16 and TWS Version 9.69 or higher.
l Previous versions of the Excel spreadsheet will not work with ddedll.dll Version 16 and TWS Version 9.69 or
higher.
l However, TWS Version 9.69 or higher will work with previous versions of the Excel spreadsheet if you are using
a previous version of the ddedll.dll file.
DDE syntax has been updated to support mini options data. The following examples show which requests for contract
data have been updated for mini options support. To check the DDE syntax in the Excel spreadsheet, look at the Ctrl
cells on the spreadsheet page for each data request.
l Place order:
topic=ord request=place (Place / Modify Order - Basic Orders, Conditional Orders, Advanced Orders, Advisors
pages)
=Salexd406|ord!'id424433486?place?AAPL_OPT_20130614_530_C_SMART_USD_~_AAPL7/BUY_1_LMT_
0.05_~_DAY_~_~_O_0_~_1_~_0_0_0_0_~_0_0_~...'
=Salexd406|ord!'id424433487?place?AAPL_BAG_SMART_USD_CMBLGS_2_126721266_1_BUY_SMART_0_
1236033_1_SELL_SMART_0_CMBLGS_~/BUY_1_LMT_0.05_~_DAY_~_~_O_0_~_1_~_0_0_0_0_~_0_0_~...'
Note that we use the Java API method/parameters in the examples below, but you can substitute the correct meth-
od/parameters for your API language of choice.
symbol=IBM
secType=STK
exchange=SMART
currency=USD
genericTicklist="mdoff,292"
Note: mdoff indicates that top market data will not tick.
or
conId=8314
secType=[empty]
exchange=SMART
currency=[empty]
genericTicklist="mdoff,292"
symbol=IBM
secType=STK
exchange=SMART
currency=USD
genericTicklist="mdoff,292:FLY"
To request only Fly On The Wall and Briefing.com (BRF) news for IBM
Request market data with the following parameters:
symbol=IBM
secType=STK
exchange=SMART
currency=USD
genericTicklist="mdoff,292:FLY+BRF"
symbol=IBM
secType=STK
exchange=SMART
currency=USD
genericTicklist="292"
symbol=*
secType=NEWS
exchange=FLY or NEWS:FLY
currency=[empty]
symbol=FLY:EU
secType=NEWS
exchange=FLY or NEWS:FLY
currency=[empty]
genericTicklist="292"
or
conId=6145497
symbol=[empty]
secType=[empty]
exchange=NEWS
currency=[empty]
genericTicklist="292"
I received the error "The DDEDLL.dll file required for Excel integration is either missing or out of date." -
(DDE for Excel API)
This error appears when you try to launch Trader Workstation (TWS) on a 64-bit Windows computer using a 32-bit
Java executable. To solve this issue, launch TWS using the 64-bit Java executable.
Why do I get I get all zeroes in a market data cell when using the DDE for Excel API?
This happens when the Excel DDE sheet has not been connected properly to TWS. To solve, restart both Excel and
TWS.
TWS does offer conditional orders that are held and monitored on IB's servers, albeit the range of conditions is limited
to a few variables like price and volume.
How many API clients can connect to Trader Workstation/IB Gateway simultaneously?
A single instance of Trader Workstation (or IB Gateway) can support a maximum of 8 API clients at the same time.
When receiving market data, does tickPrice() always come before tickSize()?
Yes.
When receiving market data, why do I receive two consecutive LAST_PRICE tick values?
TWS sends two LAST_PRICE tick values because one has the timestamp, which gives you the time of the last trade.
Is there any method in the Java API that gives me the close time for a particular financial product?
No, but we do send the opening and closing time of a particular exchange in the m_tradingHours (total trading hours)
and m_liquidHours (regular trading hours) attributes of the contractDetails() callback. These attributes send the current
trading day times and the following trading day times in this format:
YYYYMMDD:HHmm-HHmm;YYYYMMDD:HHmm-HHmm.
Is there away to get the minimum order size for Hong Kong stocks through the API?
No, but you can use the Contract Search on our website; search results include details such as minimum order size. Sim-
ply click Contract Search under the Help and Contacts menu located in the upper right corner of our website.
What is the best way to get real-time up-to-date quote information once for a series of tickers (up to 100)?
Subscribe to real-time market data with snapshot set to false so you get the latest up-to-date information. If snapshots are
old, it may be due to the market being closed; in that case, only the latest available information is sent to the API.
Can I receive news and events for currencies and futures in the Java API?
Not at this time. If this is a feature that you would like to see added to the API, use the New Feature Poll on our web-
site to request it.
Is there any method in the Java API that receives economic events as provided by the economic events calendar in
IBIS?
No, because we have not integrated the API with IBIS. If this is a feature that you would like to see added to the API,
use the New Feature Poll on our website to request it.
In the Java API beta version 9.69, why is the OPT value missing from com.ib.controller.Instrument?
There are no scans for Options in the API.
I'm using two separate machines to request FTSE futures tick data by calling reqMktData() and the two machines
receive similar but not identical data. Why is this happening?
We provide snapshots of the data based on what we receive from the exchange, and these snapshots can be generated at
a different pace for different users. This is why you are not getting the exact same data from both machines.
Why do I receive an error 200 - No security definition has been found for the request when I call reqContractDetails,
reqMktData, or addOrder() for a stock contract?
When using these methods for a stock contract, leave Global Symbol and Trading Class blank.
Is there a way to connect to your server directly, without connecting to TWS locally, in an authorized and secure
manner?
No. Any client application has to go through TWS or IB Gateway in order to reach our servers.
What is the easiest way to program a simple moving average in real time on a chart using the API?
While the API does not directly support chart indicators, you can construct your own indicators based raw data received
through the API. Try appending real-time bars to historical data requests.
When sending an order outside regular trading hours for the S&P Mini, I receive the following error message:
Order Event Warning:Attribute 'Outside Regular Trading Hours' is ignored based on the order type and destination.
PlaceOrder is now being processed.. even though I set the property m_outsideRth to True in the order object when
calling placeOrder() to ensure the order gets executed outside regular trading hours.
It is not necessary to set this for limit orders on Globex. The outsideRTH flag only applies to stop orders on Globex.
Why isn't it possible to send more than 20 orders or order-modifications per executed order with the API?
This is an Interactive Brokers policy. However, it is possible to adjust the order modification ratio. For more inform-
ation, see http://ibkb.interactivebrokers.com/article/1765.
Account page, using in ActiveX for Excel 482 Bulletins page 457
opening sample spreadsheet 453 place order for a single managed account 448
Real Time Bars page 497 place order for an allocation profile 448
Tickers page 458 advisors, Excel DDE support for 123-124, 443
ActiveX for Excel on 64-bit Windows 452 allocation methods for account groups 446
B C Sharp 367
basket orders, in ActiveX for Excel 463 Class EWrapper functions 254
requesting real-time market data 46-50, 52, 55 eDisconnect() 235, 302, 385
for market data requests 134 viewing in ActiveX for Excel 506
E Excel API 45
Excel DDE, extended order attributes 477 Execution 274, 343, 423
Excel DDE, Extended Order attributes page 477 Execution page toolbar 97
Excel DDE, financial advisor support 443 execution reporting, for financial advisors 445
Excel DDE, supported order types 466 execution reporting, in ActiveX for Excel 485
I J
IBDividends tick type example 538 Java EClient Socket methods 300
using DDE syntax 134 mini options - DDE for Excel 577
requesting in ActiveX for Excel 461 modifying orders in the DDE for Excel API 77
Market Depth page modifying orders, on Conditional Orders page 89, 470
toolbar buttons in ActiveX for Excel 461 Name Manager in Excel 128
Market Depth page toolbar 122 nextValidId() 169, 261, 330, 410
starting in Excel 111 open orders, viewing in ActiveX for Excel 480
order status for partial fills 565 placeOrder() 238, 305, 388
placing in ActiveX for Excel 463 portfolio data in FA managed accounts, in ActiveX for
Excel 484
orders and account configuration, for financial
advisors 442 Portfolio page
query specification fields for historical data in reqContractDetails() 245, 311, 394
Excel 108
reqContractDetailsEx() 148
query specification fields, on Historical Data page
in ActiveX for Excel 490 reqCurrentTime() 143, 235, 303, 386
R reqExecutionsEx() 148
receiveFA() 181, 270, 339, 419 reqGlobalCancel();C# EClient Socket methods 386,
390
recommendations for using API 37
reqGlobalCancel();C++ EClient Socket functions 240
reference 511
reqGlobalCancel();Java EClient Socket methods 307
refresh rate in Excel 73
reqHistoricalData() 247, 317, 397
refresh rate, for market depth in Excel 461
reqHistoricalDataEx() 155
refresh rate, on ActiveX for Excel Tickers
page 460 reqIds() 147, 240
relative orders, in ActiveX for Excel 476 reqMktData() 236, 303, 386
reqAccountUpdates() 149, 241, 307, 390 reqOpenOrders() 146, 239, 306, 389
requesting contract details in Excel 118 scannerParameters() 182, 271, 340, 420
requesting market data, in ActiveX for Excel 459 ScannerSubscription 289, 357, 438
running the API through IB Gateway 35 Socket Client Properties, in Java 345
starting market scanner in ActiveX for Excel 499 tickOptionComputation() 165, 256, 326, 406
tickEFP() 166, 258, 327, 407 on ActiveX for Excel Advanced Orders page 477
ticker, creating in ActiveX for Excel 459 on ActiveX for Excel Bond Contract Details
page 497
Tickers page
on ActiveX for Excel Contract Details page 494
in ActiveX for Excel 458
on ActiveX for Excel Executions page 487
in Excel 72
on ActiveX for Excel Fundamentals page 503
requesting market data in ActiveX for
Excel 459 on ActiveX for Excel Historical Data page 492
setting the refresh rate in ActiveX for on ActiveX for Excel Market Depth page 461
Excel 460
on ActiveX for Excel Market Scanner page 501
toolbar buttons in ActiveX for Excel 460
on ActiveX for Excel Open Orders page 481
using 72
on ActiveX for Excel Portfolio page 485
on ActiveX for Excel Real Time Bars TWS log file 573
page 498
TWS precautionary settings 38
on Conditional Orders page 470
TWS, configuring for API 34
on FA managed accounts, in ActiveX for Excel
Account page 483 TWS, linking using ActiveX 138
VOL orders
volatility orders
in Excel 91
winError() 255