APIprintable
APIprintable
January 2014
Updated through API Release 9.70
2014 Interactive Brokers LLC. All rights reserved.
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 rec-
ommendation.
Contents
Contents i
Overview 23
About the APIs 24
Installing the API Software 25
Run the API through TWS 26
Run the API through the IB Gateway 27
Recommendations 29
API Orders and TWS Precautionary Settings 30
API Order IDs 32
New Order Example 32
Modified Order Example 32
Trader Workstation API Settings 33
General 33
Trusted IP Addresses 34
Uninstalling and Re-installing the TWS API Software on Windows 35
CSharp API 36
DDEfor Excel 37
Getting Started with the DDE for Excel API 38
Download the API Components and Spreadsheet 39
Configure Trader Workstation to Support API Components 40
Open the Sample Spreadsheet 41
Using the DDE for Excel Sample Spreadsheet 42
Tickers Page 43
Using the Tickers Page 43
Tickers Page Toolbar Buttons 45
API Reference Guide i
Contents
Basic Orders Page 46
Placing Orders 47
Placing a Combination Order 48
Supported Order Types 50
Basic Orders Page Toolbar Buttons 50
Extended Order Attributes Page 50
Manually Program Extended Order Attributes 51
Apply Extended Order Attributes to Individual Orders and Groups of Orders 52
Extended Order Attributes 52
Conditional Orders Page 57
Setting Up Conditional Orders 57
Conditional Order Examples 59
If-Filled order 59
Price-change order 59
Conditional Orders Page Toolbar Buttons 60
Advanced Orders Page 60
Placing a Bracket Order 61
Placing a Volatility Order 62
Placing a Trailing Stop Limit Order 63
Placing a Scale Order 64
Placing a Relative Order 65
Advanced Orders Page Toolbar Buttons 65
Open Orders Page 65
Viewing Open Orders 66
Open Orders Tab Toolbar Buttons 67
Executions Page 67
Viewing Executions 68
API Reference Guide ii
Contents
Executions Page Toolbar Buttons 68
Executions Reporting Page 68
Running Execution Reports 69
Account Page 69
Using the Account Page 70
Account Page Toolbar Buttons 71
Account Page Values 71
Portfolio Page 75
Viewing Your Portfolio 76
Portfolio Page Toolbar Buttons 76
Historical Data Page 76
Viewing Historical Data 77
Historical Data Page Toolbar Buttons 78
Historical Data Page Query Specification Fields 79
Market Scanner Page 81
Starting a Market Scanner Subscription 82
Market Scanner Parameters 83
Market Scanner Page Toolbar Buttons 84
Available Market Scanners 84
Contract Details Page 88
Requesting Contract Details 89
Contract Details Page Toolbar Buttons 89
Bond Contract Details Page 90
Requesting Bond Contract Details 90
Bond Contract Details Page Toolbar Buttons 91
Market Depth Page 91
Using the Market Depth Page 92
API Reference Guide iii
Contents
Market Depth Page Toolbar Buttons 93
Advisors Page 93
Allocating Shares to a Single Account 94
Placing an Order using an FA Account Group and Method 95
Placing an Order using an Allocation Profile 95
Advisors Page Toolbar Buttons 96
DDE for Excel API Reference 97
Viewing the Code 97
Modules 98
Macros 98
Named Ranges 99
DDE Syntax for Excel 100
Active X 107
Linking to the Application using ActiveX 108
Registering Third-Party ActiveX Controls 109
Running the ActiveX API on 64-bit Windows XP Systems 110
Using the Visual Basic Sample Program 111
ActiveX Methods 112
connect() 113
disconnect() 113
reqCurrentTime() 113
setServerLogLevel() 113
reqMktDataEx() 114
cancelMktData() 114
calculateImpliedVolatility() 114
cancelCalculateImpliedVolatility() 114
calculateOptionPrice() 115
API Reference Guide iv
Contents
cancelCalculateOptionPrice() 115
reqMarketDataType() 115
placeOrderEx() 115
cancelOrder() 116
reqOpenOrders() 116
reqAllOpenOrders() 116
reqAutoOpenOrders() 116
reqIds() 117
exerciseOptionsEx() 117
reqGlobalCancel() 117
reqExecutionsEx() 118
reqContractDetailsEx() 118
reqMktDepthEx() 118
cancelMktDepth() 118
reqAccountUpdates() 119
reqNewsBulletins() 119
cancelNewsBulletins() 119
reqManagedAccts() 119
requestFA() 119
replaceFA() 120
reqAccountSummary() 120
cancelAccountSummary() 122
reqPositions() 122
cancelPositions() 122
reqHistoricalDataEx() 122
cancelHistoricalData() 124
reqScannerParameters() 124
API Reference Guide v
Contents
reqScannerSubscriptionEx() 125
cancelScannerSubscription() 125
reqRealTimeBarsEx() 125
cancelRealTimeBars() 126
createComboLegList() 126
createContract() 126
createExecutionFilter() 126
createOrder() 126
createScannerSubscription() 127
createTagValueList 127
createUnderComp() 127
reqFundamentalData() 127
cancelFundamentalData() 128
ActiveX Events 129
connectionClosed() 130
currentTime() 130
errMsg() 130
tickPrice() 130
tickSize() 131
tickOptionComputation() 131
tickGeneric() 132
tickString() 132
tickEFP() 132
tickSnapshotEnd() 133
marketDataType() 133
orderStatus() 134
openOrderEx() 135
API Reference Guide vi
Contents
nextValidId() 135
permId() 136
updateAccountValue() 136
updatePortfolioEx() 138
updateAccountTime() 139
accountDownloadEnd() 139
updateNewsBulletin() 139
contractDetailsEx() 140
contractDetailsEnd() 140
bondContractDetails() 140
execDetailsEx() 142
execDetailsEnd() 142
commissionReport() 142
updateMktDepth() 142
updateMktDepthL2() 143
managedAccounts() 144
receiveFA() 144
accountSummary() 145
accountSummaryEnd 147
position() 147
positionEnd() 148
historicalData() 148
scannerParameters() 148
scannerDataEx() 148
scannerDataEnd() 149
realtimeBar() 149
fundamentalData() 150
API Reference Guide vii
Contents
ActiveX COM Objects 151
IExecution 151
IExecutionFilter 152
ICommissionReport 153
IContract 153
IContractDetails 155
IComboLeg 156
IComboLegList 157
IOrder 157
OrderComboLeg 166
IOrderState 166
IScannerSubscription 166
ITagValueList 167
ITagValue 168
IUnderComp 168
ActiveX Properties 169
Placing a Combination Order 170
Example 170
C++ 173
Class EClientSocket Functions 174
EClientSocket() 175
eConnect() 175
eDisconnect() 175
isConnected() 175
reqCurrentTime() 175
serverVersion() 176
setLogLevel() 176
API Reference Guide viii
Contents
TwsConnectionTime() 176
checkMessages() 176
reqMktData() 176
cancelMktData() 177
calculateImpliedVolatility() 177
cancelCalculateImpliedVolatility() 177
calculateOptionPrice() 177
cancelCalculateOptionPrice() 178
reqMarketDataType() 178
placeOrder() 178
cancelOrder() 179
reqOpenOrders() 179
reqAllOpenOrders() 179
reqAutoOpenOrders() 179
reqIDs() 179
exerciseOptions() 180
reqGlobalCancel() 180
reqAccountUpdates() 180
reqExecutions() 181
reqContractDetails() 181
reqMktDepth() 181
cancelMktDepth() 182
reqNewsBulletins() 182
cancelNewsBulletins() 182
reqManagedAccts() 182
requestFA() 182
replaceFA() 183
API Reference Guide ix
Contents
reqAccountSummary() 183
cancelAccountSummary() 185
reqPositions() 185
cancelPositions() 185
reqHistoricalData() 185
cancelHistoricalData() 187
reqScannerParameters() 187
reqScannerSubscription() 187
cancelScannerSubscription() 187
reqRealTimeBars() 188
cancelRealTimeBars() 188
reqFundamentalData() 189
cancelFundamentalData() 189
Class EWrapper Functions 190
winError() 191
error() 191
connectionClosed() 191
currentTime() 191
tickPrice() 191
tickSize() 192
tickOptionComputation() 192
tickGeneric() 193
tickString() 193
tickEFP() 194
tickSnapshotEnd() 194
marketDataType() 195
orderStatus() 195
API Reference Guide x
Contents
openOrder() 197
nextValidId() 197
updateAccountValue() 197
updatePortfolio() 198
updateAccountTime() 199
accountDownloadEnd() 199
updateNewsBulletin() 199
contractDetails() 200
contractDetailsEnd() 200
bondContractDetails() 200
execDetails() 200
execDetailsEnd() 200
commissionReport() 201
updateMktDepth() 201
updateMktDepthL2() 202
managedAccounts() 202
receiveFA() 202
accountSummary() 203
accountSummaryEnd 205
position() 205
positionEnd() 205
historicalData() 205
scannerParameters() 206
scannerData() 206
scannerDataEnd() 206
realtimeBar() 207
fundamentalData() 207
API Reference Guide xi
Contents
SocketClient Properties 208
Execution 208
ExecutionFilter 209
Contract 210
ContractDetails 211
ComboLeg 213
Order 214
OrderState 222
ScannerSubscription 223
UnderComp 224
CommissionReport 224
Placing a Combination Order 225
Example 225
Java 227
Running the Java Test Client Sample Program 228
Running the Java Test Client Program with Eclipse 230
Java EClientSocket Methods 232
EClientSocket() 233
eConnect() 233
eDisconnect() 233
isConnected() 233
setServerLogLevel() 233
reqCurrentTime() 234
serverVersion() 234
TwsConnectionTime() 234
reqMktData() 234
cancelMktData() 234
API Reference Guide xii
Contents
calculateImpliedVolatility() 235
cancelCalculateImpliedVolatility() 235
calculateOptionPrice() 235
cancelCalculateOptionPrice() 235
reqMarketDataType() 236
placeOrder() 236
cancelOrder() 236
reqOpenOrders() 236
reqAllOpenOrders 237
reqAutoOpenOrders() 237
reqIDs() 237
exerciseOptions() 237
reqGlobalCancel() 238
reqAccountUpdates() 238
reqExecutions() 238
reqContractDetails() 239
reqMktDepth() 239
cancelMktDepth() 239
reqNewsBulletins() 239
cancelNewsBulletins() 240
reqManagedAccts() 240
requestFA() 240
replaceFA() 240
reqAccountSummary() 241
cancelAccountSummary() 243
reqPositions() 243
cancelPositions() 243
API Reference Guide xiii
Contents
reqScannerParameters() 243
reqScannerSubscription() 243
cancelScannerSubscription() 244
reqHistoricalData() 244
cancelHistoricalData() 246
reqRealTimeBars() 246
cancelRealTimeBars() 247
reqFundamentalData() 247
cancelFundamentalData() 247
Java EWrapper Methods 248
currentTime() 248
error() 249
connectionClosed() 249
tickPrice() 249
tickSize() 250
tickOptionComputation() 251
tickGeneric() 251
tickString() 252
tickEFP() 252
tickSnapshotEnd() 253
marketDataType() 253
orderStatus() 253
openOrder() 255
nextValidId() 255
updateAccountValue() 255
updatePortfolio() 256
updateAccountTime() 257
API Reference Guide xiv
Contents
accountDownloadEnd() 257
contractDetails() 257
contractDetailsEnd() 257
bondContractDetails() 258
execDetails() 258
execDetailsEnd() 258
commissionReport() 258
updateMktDepth() 259
updateMktDepthL2() 259
updateNewsBulletin() 260
managedAccounts() 260
receiveFA() 261
accountSummary() 261
accountSummaryEnd 263
position() 263
positionEnd() 263
historicalData() 263
scannerParameters() 264
scannerData() 264
scannerDataEnd() 264
realtimeBar() 265
fundamentalData() 265
Java SocketClient Properties 266
Execution 266
ExecutionFilter 267
CommissionReport 268
Contract 268
API Reference Guide xv
Contents
ContractDetails 269
ComboLeg 271
OrderComboLeg 272
Order 272
OrderState 282
ScannerSubscription 283
UnderComp 284
Placing a Combination Order 285
Example 285
Java Code Samples: Contract Parameters 288
How to Determine an Option Contract 288
How to Determine a Futures Contract 289
How to Determine a Stock 289
Advisors 291
Financial Advisor Orders and Account Configuration 292
Excel DDE Support 293
Support by Other API Technologies 294
Improved Financial Advisor Execution Reporting 295
Allocation Methods for Account Groups 296
EqualQuantity Method 296
NetLiq Method 296
AvailableEquity Method 296
PctChange Method 296
Java Code Samples for Financial Advisor API Orders 298
Place an Order for a Single Managed Account 298
Place an Order for an Allocation Profile 298
Place an Order for an Account Group 299
API Reference Guide xvi
Contents
Changing/Updating Allocation Information 299
ActiveXfor Excel 301
Getting Started with the ActiveX for Excel API 302
Download the API Components and Spreadsheet 302
Running the ActiveX for Excel API on 64-bit Windows XP Systems 302
Open the Sample Spreadsheet 303
Using the ActiveX for Excel Sample Spreadsheet 304
General Page 305
General Page Toolbar Buttons 306
Bulletins Page 307
Bulletins Page Toolbar Buttons 307
Tickers Page 308
Using the Tickers Page 309
Tickers Page Toolbar Buttons 310
Market Depth Page 310
Using the Market Depth Page 311
Market Depth Page Toolbar Buttons 311
Basic Orders Page 312
Placing Orders 313
Placing a Combination Order 314
Supported Order Types 315
Basic Orders Page Toolbar Buttons 316
Conditional Orders Page 316
Setting Up Conditional Orders 317
Conditional Order Examples 318
If-Filled order 318
Price-change order 319
API Reference Guide xvii
Contents
Conditional Orders Page Toolbar Buttons 319
Advanced Orders Page 320
Placing a Bracket Order 321
Placing a Volatility Order 322
Placing a Trailing Stop Limit Order 323
Placing a Scale Order 324
Placing a Relative Order 325
Advanced Orders Page Toolbar Buttons 325
Extended Order Attributes Page 326
Manually Program Extended Order Attributes 327
Apply Extended Order Attributes to Individual Orders and Groups of Orders 327
Open Orders Page 328
Viewing Open Orders 328
Open Orders Tab Toolbar 329
Account Page 329
Using the Account Page 330
Account Page Toolbar Buttons 331
Portfolio Page 332
Viewing Your Portfolio 332
Exercising Options 333
Portfolio Page Toolbar Buttons 333
Executions Page 333
Viewing Executions 334
Executions Page Toolbar Buttons 335
Commission Reports 335
Commission Reports Toolbar Buttons 336
Historical Data Page 336
API Reference Guide xviii
Contents
Viewing Historical Data 336
Historical Data Page Query Specification Fields 338
Historical Data Page Toolbar Buttons 340
Contract Details Page 341
Requesting Contract Details 341
Contract Details Page Toolbar Buttons 342
Bond Contract Details Page 343
Requesting Bond Contract Details 343
Bond Contract Details Page Toolbar Buttons 344
Real Time Bars Page 345
Real Time Bars Page Toolbar Buttons 346
Market Scanner Page 346
Starting a Market Scanner Subscription 347
Market Scanner Parameters 348
Market Scanner Page Toolbar Buttons 348
Fundamentals Page 349
Fundamentals Page Toolbar Buttons 350
Advisors Page 350
Allocating Shares to a Single Account 351
Placing an Order using an FA Account Group and Method 352
Placing an Order using an Allocation Profile 352
Advisors Page Toolbar Buttons 353
Log Page 353
POSIX 355
Running the POSIX Client on a Windows Machine 356
Reference 357
API Message Codes 358
API Reference Guide xix
Contents
Error Codes 358
System Message Codes 368
Warning Message Codes 368
Historical Data Limitations 370
Pacing Violations 370
Minimum Bar Size Settings for Historical Data Requests 371
Valid Duration and Bar Size Settings for Historical Data Requests 371
Tick Types 373
Generic Tick Types 376
Using the SHORTABLE Tick 377
TAG Values for FUNDAMENTAL_RATIOS tickType 378
IBDividends Tick Example 384
Example 384
RTVolume 384
Order Types and IBAlgos 386
Supported Order Types 386
IBAlgo Parameters 388
Arrival Price (ArrivalPx) 388
Dark Ice (DarkIce) 390
Percentage of Volume (PctVol) 390
TWAP (Twap) 391
VWAP (Vwap) 391
Balance Impact and Risk (BalanceImpactRisk) 391
Minimize Impact (MinImpact) 392
Accumulate/Distribute (AD) 393
CSFB Algo Parameters 394
Crossfinder (CROS) 395
API Reference Guide xx
Contents
Crossfinder (CROS) Java Code Sample 395
Float (FLT) 396
Float (FLT) Java Code Sample 396
Guerilla (GRRL) 397
Guerilla (GRRL) Java Code Sample 397
Work It IW (INIW) 398
Work It IW (INIW) Java Code Sample 398
Work It (INLN) 399
Work It (INLN) Java Code Sample 399
Pathfinder (PTHF) 400
Pathfinder (PTHF) Java Code Sample 400
Reserve (RSRV) 401
Reserve (RSRV) Java Code Sample 401
Strike (SNPR) 402
Strike (SNPR) Java Code Sample 402
10B 18 (TENB) Java Code Sample 402
10B 18 (TENB) Java Code Sample 403
Tex (TEX) 403
Tex (TEX) Java Code Sample 404
TWAP (TWAP) 404
TWAP (TWAP) Java Code Sample 405
VWAP (VWAP) 405
VWAP (VWAP) Java Code Sample 406
Extended Order Attributes 407
Order Status for Partial Fills 411
Available Market Scanners 412
Instruments and Location Codes for Market Scanners 415
API Reference Guide xxi
Contents
Supported Time Zones 417
Smart Combo Routing 418
API Logging 419
Example Log Entry 419
API Request/Server Response Message Identifiers 420
Requests for Quotes (RFQs) 421
Submitting RFQs using the API 421
Delta-Neutral RFQs 421
RFQ Samples 421
Support for Mini Options 422
Support for Mini Options - ActiveX, Java and C++ APIs 422
Support for Mini Options - DDEfor Excel 423
Requirements 423
DDESyntax Examples 423
Requests That Receive Contract Data from TWS 424
Requesting Real-Time Index Premium Data 425
Requesting News from an API Client 426
To request news for IBM 426
To request only Fly On The Wall (FLY) News for IBM 426
To request only Fly On The Wall and Briefing.com (BRF) news for IBM 426
To request top data and news for IBM 427
To request a list of news topics 427
To request Reuters European Union News 427
Frequently Asked Questions 428
Index 431
API Reference Guide xxii
Overview
This chapter provides an overview of the APIs (Application Programming Interfaces) available, including the following
topics:
l About the APIs
l Installing the API Software.htm
l Run the API through TWS
l Run the API through the IB Gateway
l Recommendations
l API Orders and TWS Precautionary Settings
l API Order IDs
l Trader Workstation API Settings
l Uninstalling and Re-installing the TWS API Software on Windows
l CSharp API
API Reference Guide 23
1
Chapter1 Overview
About the APIs
We provide several APIs which you can use to link to our system and trade your IB account. The API allows you to con-
nect through either the TWS or the IB Gateway.
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++or Javatopics in this guide. Customers
with no programming expertise should begin with the DDE for Excel section, which uses an everyday Excel spread-
sheet 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.
API Reference Guide 24
Chapter1 Overview
Installing the API Software
To install the APIsoftware
1. Download the latest API software from the IB website:
2. From the IB website menu, click Trading Technology > APISolutions.
3. Cick IB API, then click the APISoftware button.
4. In the popup window, read the license agreement then click I Agree.
5. Click the button corresponding to the Windows- or Mac/UNIX-based production or beta APIversion you want to
install.
6. Save the installation file to your computer.
7. Run the downloaded installation program to install the API software on your computer.
API Reference Guide 25
Chapter1 Overview
Run the API through TWS
To run the API through TWS, you must always have your system running and it must be configured to use any of the
API components.
To enable API connection through TWS
1. Log into TWS.
2. On the Edit menu, select Global Configuration.
3. Select APIin the left pane, then click Settings.
4. In the right pane, click the check box for Enable ActiveX and Socket Clients (ActiveX, C++ and Java API con-
nections), and/or Enable DDE Clients(for DDE for Excel API connections only) to configure TWS for the appro-
priate API connection. You must have these settings enabled to connect to the API through TWS.
Note: Multiple API clients with different client IDs can access a single instance of TWS on the
same computer. With the exception of DDE for Excel, the API application does not need to
be running on the same computer as TWS.
For a complete description of all Trader Workstations API settings, see the TWS Users Guide.
API Reference Guide 26
Chapter1 Overview
Run the API through the IB Gateway
The IB Gateway provides a low-resource alternative to TWS for connecting to the IB trading system via the API. The
gateway uses approximately 40% fewer system resources than TWS. However, the gateway is GUI-less, which means that
you cannot view the API activity as you can when running TWS.
To log into the IB Gateway
1. From the Loginmenu on the IB web site, select IB Gateway.
2. Select the API radio button.
3. Log in using your IB username and password, just as you would when logging into TWS.
4. Click Login. The Interactive Brokers Gateway box opens, displaying the connection status and gateway activity.
API Reference Guide 27
Chapter1 Overview
You must have the IB Gateway running while connected to the API.
API Reference Guide 28
Chapter1 Overview
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 TWSGlobal 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.
API Reference Guide 29
Chapter1 Overview
API Orders and TWS Precautionary Settings
By default, Trader Workstation includes precautionary settings as part of its Order Presets on the TWS Configuration
page. Precautionary settings are safety checks and include percentage, size limit, total value and number of ticks. They
can be modified in TWS for most instrument types (stocks, options, and so on) or for specific tickers.
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.
API Reference Guide 30
Chapter1 Overview
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.
API Reference Guide 31
Chapter1 Overview
API Order IDs
When you place a new order using the API, the order id number must be greater than the previously used numbers. For
example, if you place an order with an Order ID of 11, the next order you place should have an Order ID of at least 12.
So when you place a new order, the order id must be greater than the previously used order id number.
New Order Example
In this example, a user is going to place two orders for IBM stock. The first order is a BUY order for 200 shares and set
the limit price to $85.25. The second order will be an order to sell 100 shares with the limit price set to $84.25.
In this example, the first order is tagged with an Order ID of 1:
.placeOrder(1, IBM, BUY, $85.25, 200)
Now, user can place a second order. This order is assigned an Order ID of 2:
.placeOrder(2, IBM, SELL, $84.25, 100)
Modified Order Example
To modify an order using the API, resubmit the order you want to modify using the same order id, but with the price or
quantity modified as required. Only certain fields such as price or quantity can be altered using this method. If you want
to change the order type or action, you will have to cancel the order and submit a new order.
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:
.placeOrder(3, IBM, BUY, $85.25, 100)
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
.placeOrder(3, IBM, BUY, $86.25, 100)
API Reference Guide 32
Chapter1 Overview
Trader Workstation API Settings
In addition to configuring Trader Workstation (TWS) to communicate with the API, there are a number of other API-
related settings in TWS that you can configure.
To configure API settings in TWS
1. In TWS, select the Edit menu, then select Global Configuration.
2. Click API in the left pane, and select Settings.
3. Configure the API settings as required. These are described below.
Note: With the exception of DDE, the API application does not need to be running on the same
computer on which the application is running.
General
l Enable Active X and Socket Clients - Check to enable integration using ActiveX or socket clients including
Java and C++.
l Enable DDEclients - 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.
API Reference Guide 33
Chapter1 Overview
l Include FX positions when sending portfolio - If you have the Include FX Positions feature activated, all FX posi-
tions 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 sin-
gle ActiveX or socket API client will be able to access each of these instances. This does not apply to DDE
clients.
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 ver-
ification message asking if you are sure you want to make the connection.
l Click Create to add a new trusted IP address to the list.
l Click Edit to modify the selected address.
l Click Delete to remove the selected address.
API Reference Guide 34
Chapter1 Overview
Uninstalling and Re-installing the TWS API Software on
Windows
If you encounter problems running the TWS API software on the Windows platform, you can uninstall and re-install the
API software.
Note: This procedure is usually only necessary when troubleshooting the most extreme API prob-
lems.
To uninstall and re-install the TWS API software on Windows
1. Open the Windows Control Panel, then open Add or Remove Programs.
2. Select TWS Interoperability Componentsfrom the list of installed programs, then click Change/Remove.
3. Select Automatic, then click Next to uninstall the TWS API software.
4. In the Windows Explorer, delete the file TwsSocketClient.dllfrom the Windows\system32 folder.
5. Reboot your computer.
6. Re-install the TWS API software.
API Reference Guide 35
Chapter1 Overview
CSharp API
Beginning with APIVersion 9.70, a new CSharp API client is included with the API. After you install API software on
your computer, you can find CSharp API components in the following locations:
l CSharp API sample code - located in the samples/CSharp folder in your API installation directory (typically
TWS API X.XX, where X.XXis the current version number);
l CSharp source code - located in the source/CSharpClient folder in your API installation directory.
API Reference Guide 36
DDEfor Excel
This chapter describes the DDE for Excel API, including the following topics:
l Getting Started with the DDE for Excel API
l Using the DDE for Excel Sample Spreadsheet
l DDE for Excel API Reference
DDE is an acronym for Dynamic Data Exchange, a Microsoft-created communication method that allows multiple appli-
cations that are running simultaneously to exchange data and commands. We use this protocol to link Excel with your
running 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.
API Reference Guide 37
2
Chapter2 DDEfor Excel
Getting Started with the DDE for Excel API
We have created a sample DDE-linked Excel spreadsheet, TwsDde.xls, that you can use with your TWS to create a cus-
tom Excel application. It's easy to get started with the DDE for Excel API:
l Download the API components and sample Excel spreadsheet.
l Ensure that the DDE clients are enabled, either in Trader Workstation or IB Gateway, as described here here, or
that the IB Gateway is running.
l Open the spreadsheet and start using the DDE 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.
API Reference Guide 38
Chapter2 DDEfor Excel
Download the API Components and Spreadsheet
We recommending using the sample Excel spreadsheet that we provide as a starting point toward creating your own
DDE for Excel API. Follow the steps below to download the sample spreadsheet.
To install the sample DDE Spreadsheet
1. Download the latest API software from the IB website:
2. From the IB website menu, click Trading Technology > APISolutions.
3. Cick IB API, then click the APISoftware button.
4. In the popup window, read the license agreement then click I Agree.
5. Click the button corresponding to the Windows-based production, beta or previous APIversion you want to
install.
Note: Windows users can download the beta test version of the API by using the Windows
Betacolumn, 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, TWSAPI 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 sam-
ples\Excel folder in your APIinstallation 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 Gatewaybut we recommend you
start by running TWS.
API Reference Guide 39
Chapter2 DDEfor Excel
Configure Trader Workstation to Support API Com-
ponents
You must have your system running to use any of the API components.
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 APISettings.
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.
API Reference Guide 40
Chapter2 DDEfor Excel
Open the Sample Spreadsheet
After you have downloaded the sample spreadsheet and configured the application to allow the DDE for Excel API to
link to it, open the spreadsheet and save it as your personal file.
To open the sample spreadsheet
1. Go to the API installation folder in which the Excel API sample spreadsheet was installed (samples\Excel in your
APIInstallation folder), and double-click TwsDde.xls.
2. In the macro warning message box, click Enable Macros. If you receive a message asking if you want to link to
information in another worksheet, click Yes.
Note: To use the spreadsheet macros, your Excel macro security must be set to Medium or Low. If
you cannot open the spreadsheet or if the macros don't work, you need to modify your
macro security level.
In Microsoft Excel 2007, click the Microsoft Office Button, click Excel Options, and then
click Trust Centerin the Excel Options window. In the Trust Center, click Macro Settings,
then change your settings as required.
In previous versions of Excel, select Macrofrom the Toolsmenu, and then select Security.
Set security to Medium or Low.
3. In the User Namefield 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.
API Reference Guide 41
Chapter2 DDEfor Excel
Using the DDE for Excel Sample Spreadsheet
The DDE for Excel API sample spreadsheet, TwsDde.xls, includes the following pages (tabs):
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-
utes
Used in conjunction with the Basic Orders, Advanced Orders, Con-
ditional 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.
Portfolio Displays all your current positions.
Historical Data Request historical data for an instrument based on data you enter in a
query.
Market Scanner Subscribe to TWS market scanners.
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.
Market Depth Lets you view market depth for selected quotes.
Advisors Lets Financial Advisors send and modify FA orders.
API Reference Guide 42
Chapter2 DDEfor Excel
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
Use the Tickers page to:
l Create market data (ticker) lines.
l Request market data.
Using the Tickers Page
Note: Ensure that TWS is running, and that you have entered your user name in the User
Namefield in the Which Trader Workstation?section of all pages in the Excel spreadsheet
to properly connect to TWS.
To create a ticker using the Create Ticker button
1. Click the Tickers tab at the bottom of the spreadsheet.
2. Click the line number to the left of a blank row to select the row. You must have a blank row selected to create a
ticker line.
3. Click the Create Tickerbutton on the toolbar and enter information in the Tickers box.
4. Click OK.
API Reference Guide 43
Chapter2 DDEfor Excel
For stocks, you only need to specify the Symbol, Type, Exchange(usually SMART), and Currency.
To create a ticker on the spreadsheet
1. Select a blank cell in the Symbol column and enter a symbol.
2. Tab through the all contract description fields and enter data where necessary, for example if you are entering a
stock ticker, you don't need values in the Expiry, Strike, P/C and Multiplier fields.
The Exchangefield accepts the following values: SMART (for smart order routing), and any valid exchange acronym.
To request market data for a ticker
1. Select the ticker row for which you want to request market data by clicking the row number.
2. Press Ctrl+R, or click Request Market Data on the toolbar.
To get market data for a group of tickers, select multiple ticker rows while holding down the Shiftkey, then click
Request Market Datamultiple times until all rows are showing data.
To set the refresh rate
The refresh rate determines how often the DDE link to TWS is refreshed.
TWS market data updates every 300 milliseconds by default, so setting the refresh rate to 250 will get every tick to the
spreadsheet.
To set the processing rate
API Reference Guide 44
Chapter2 DDEfor Excel
The server processing rate affects the speed at which the DDE handles requests between TWS and the spreadsheet.
The allowed range is 100 ms- 2000 ms, inclusive.
To set the level of detail for logging of API client requests
1. In the Log Levelfield in the Which Trader Workstation?area, enter the desired log level value (1 =SYSTEM,
2=ERROR, 3=WARNING, 4=INFORMATION, 5=DETAIL).
2. Move your cursor out of the Log Levelfield, then click the Set Log Level button.
To remove all DDE links to TWS
The Clear All Linksbutton on the Tickers page lets you remove all DDE links from the TwsDde.xls spreadsheet to
TWS that the Visual Basic for Applications (VBA) code provided with the spreadsheet could create. You typically use
this button when you are preparing to save 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 clearLinksmacro; these are all called by the clearAllLinks macro.
Note: Clearing all links does NOT cancel orders.
Tickers Page Toolbar Buttons
The toolbar on the Tickers page includes the buttons described below.
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 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.
API Reference Guide 45
Chapter2 DDEfor Excel
Button Description
Set Log Level This specifies the level of log entry detail used when proc-
essing 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.
Basic Orders Page
Use the Basic Orders pageto:
l Create an order.
l Create a "basket" of orders.
l Modify and cancel orders.
l Create combination orders.
API Reference Guide 46
Chapter2 DDEfor Excel
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
Namefield 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 Symbolfield, then entering information in the relevant contract
description fields.
3. Select a contract and set up the order using the Order Descriptionfields.
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. Pricefor 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 Orderbutton in the Toolbar section of the page.
API Reference Guide 47
Chapter2 DDEfor Excel
To place a "basket" of orders
1. Click the Basic Orders tab at the bottom of the spreadsheet.
2. Define a contract by typing a symbol in a blank Symbolfield, then entering information in the relevant contract
description fields.
3. Select a contract and set up the order using fields in the Order Description section.
4. Repeat Steps 1 and 2 for additional orders.
5. Select a group of orders.
o
To select a group of contiguous orders, highlight the first order, hold down the Shift key, then highlight the
last order of the group.
o
To select a group of non-contiguous orders, hold the Ctrlkey down as you select each order.
6. Click the Place/Modify Orderbutton.
To modify an order (or group of orders)
1. On the Basic Orders page, change any necessary parameters in an order or group of orders.
2. Select the order or a group of orders.
o
To select a group of contiguous orders, highlight the first order, hold down the Shift key, then highlight the
last order of the group.
o
To select a group of non-contiguous orders, hold the Ctrlkey down as you select each order.
3. Click the Place/Modify Order button.
Note: You cannot modify orders in the DDEfor Excel API that were submitted from TWS .This is
because the DDEfor Excel API uses its own created order ID to modify the orders, not the
global customer order ID. All orders created in TWS have an internal order ID of 0. If you
try to modify an order in the DDE for Excel API with id = "id0" you will get the error
"duplicate order ID".
Placing a Combination Order
A combination order is a special type of order that is constructed of many separate legs but executed as a single trans-
action.
For example, to buy a calendar spread, you would:
l Buy 1 OPT JUL03 17.5 CALL (100)
l Sell 1 OPT AUG03 17.5 CALL (100)
The following example walks you through the process of placing a hypothetical calendar spread order for XYZ on ISE.
API Reference Guide 48
Chapter2 DDEfor Excel
To create a calendar spread order
1. Use theContract 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 Orderstab to build the combo leg definitions. Click the Combo Legsbutton 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.
API Reference Guide 49
Chapter2 DDEfor Excel
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).
Supported Order Types
The order types currently supported through the DDE for Excel API are:
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)
Basic Orders Page Toolbar Buttons
The toolbar on the Basic Orders page includes the following buttons:
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 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.
Extended Order Attributes Page
The Extended Order Attributespage 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
API Reference Guide 50
Chapter2 DDEfor Excel
orders using the Apply Extended Templatebutton, 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.
Manually Program Extended Order Attributes
Observe the following guidelines when you manually assign an attribute:
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'
API Reference Guide 51
Chapter2 DDEfor Excel
Apply Extended Order Attributes to Individual Orders and Groups of Orders
Normally, values that you enter on the Extended Order Attributes page apply to all subsequent orders. However, you
also can apply selected attributes to an individual order or a group of orders on the Orders page.
Note: You can also use this procedure to apply extended order attributes to orders on the Con-
ditional Orders page.
To apply extended order attributes to individual orders or a group of orders
1. Enter the value or values on the Extended Order Attributes page that you want to apply to an individual order or
group of orders.
2. On the Orders page, select the order or group of orders.
3. Click the Apply Extended Template button.
The extended order attributes are applied to the order(s) and the values you entered on the Extended Order Attrib-
utes page are added to the corresponding fields in the Extended Order Attributes section of the 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.
Extended Order Attributes
The following table shows the available extended order attributes.
Attribute Valid Values
timeInForce DAY
GTC
OPG
IOC
GTD
FOK
DTC
ocaGroup String that identifies an OCA (One Cancels All) group
account String (for institutions)
open/close O, C (for institutions)
origin 0, 1 (for institutions)
orderRef String
API Reference Guide 52
Chapter2 DDEfor Excel
Attribute Valid Values
transmit Specifies whether the order is transmitted immediately (set to 1) or not (set
to 0).
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 trig-
gered:
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 sin-
gle 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.
API Reference Guide 53
Chapter2 DDEfor Excel
Attribute Valid Values
hidden 0
1 (order not visible when viewing market depth)
Discretionary Amount
(SMART Routing)
Used in conjunction with a limit order to give the order a greater price
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).
API Reference Guide 54
Chapter2 DDEfor Excel
Attribute Valid Values
OCA Type Tells how to handle remaining orders in an OCA group when one order or
part of an order executes. Valid values include:
l 1 = Cancel all remaining orders with block
l 2 = Remaining orders are proportionately reduced in size with block
l 3 = Remaining orders are proportionately reduced in size with no
block
If you use a value, "with block" gives your order has overfill protection.
This means that only one order in the group will be routed at a time to
remove the possibility of an overfill.
Rule 80A 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'
Settling Firm Institutions only. Indicates the firm that will settle the trade.
All or None Indicates whether or not the order will remain at the exchange (or in the IB
system) until the entire quantity is available to be executed.
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 deter-
mine whether quote is automatically executable.
0 = false
1 = true
Firm Quote Only 0 = false
1 = true
API Reference Guide 55
Chapter2 DDEfor Excel
Attribute Valid Values
NBBO Price Cap Maximum SMART order distance from the NBBO. Can be used only if
either the Electronic Trade Only or Firm Quote Only extended order attrib-
ute is set to 1.
Auction Strategy match = 1
improvement = 2
transparent = 3
For BOX exchange only.
Starting Price The starting price. For BOX orders only.
Stock Ref Price Used for VOL orders to compute the limit price sent to an exchange
(whether or not Continuous Update is used), and for price range mon-
itoring. Also used for price improvement option orders.
Delta The stock delta. For BOX orders only.
Underlying Range
(Low)
The lower value for the acceptable underlying stock price range. For price
improvement option orders on BOX and VOL orders with dynamic man-
agement.
Underlying Range
(High)
The upper value for the acceptable underlying stock price range. For price
improvement option orders on BOX and VOL orders with dynamic man-
agement.
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.
Volatility Type 1 = daily
2 = annual
Reference Price Type 1 = average (NBBOmidpoint)
2 = BidOrAsk
Hedge Delta Order Type Enter an accepted order type such as: MKT, LMT, REL or MTL.
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.
API Reference Guide 56
Chapter2 DDEfor Excel
Attribute Valid Values
Scale Price Increment Used for Scale orders only, this value is used to calculate the per-unit price
of each component in the order. This cannot be a negative number.
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
Conditional Orders Page
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.
Setting Up Conditional Orders
Note: Ensure that TWS is running, and that you have entered your user name in the User
Namefield in the Which Trader Workstation?section of all pages in the Excel spreadsheet
to properly connect to TWS.
To set up a conditional order
API Reference Guide 57
Chapter2 DDEfor Excel
1. On the Conditional Orderspage, first create the order you want transmitted when a condition is met by defining
the contract in the Contract Descriptionfields, and then using the Order Description area to set up the order
parameters.
Note: Leave the Order Description fields blank if you plan to enter ADD in the ADD/MODfield
(see Step 3 below), because once the condition is TRUE, the Order Description fields will
be overwritten.
2. In the Condition Statementsarea, use the Statementfield 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 Filledfield) must
be equal to the value in M10 (the order Quantity field).
3. Type ADDin 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 Orderspage 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 mod-
ifying 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.
Aux. Price The stop-election price for Stop and Stop Limit order types, or the offset for
relative orders.
API Reference Guide 58
Chapter2 DDEfor Excel
All of the fields described above may be variables that depend on other cells, so any type of conditional order may be
created.
Conditional Order Examples
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 Tickerspage, 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
Quantity 200
Order Type LMT
Lmt Price 81.10
Aux. Price Not used in this example.
API Reference Guide 59
Chapter2 DDEfor Excel
To modify an order (or basket of orders)
1. Select the order or a group of orders.
o
To select a group of contiguous orders, highlight the first order, hold down the Shift key, then highlight the
last order of the group.
o
To select a group of non-contiguous orders, hold the Ctrlkey down as you select each order.
1. Click the Place/Modify Order button.
2. Change any necessary parameters, then click the Place/Modify Order button.
Conditional Orders Page Toolbar Buttons
The toolbar on the Conditional Orders page includes the following buttons:
Button Description
Combo Legs Opens the Combination Legs box. Enter contract details to
create legs of a combination orderone 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.
Advanced Orders Page
Use the Advanced Orderspageto 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
API Reference Guide 60
Chapter2 DDEfor Excel
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
Placing a Bracket Order
Bracket orders in the DDE for Excel sample spreadsheet require the use of the extended order attributes Transmit and Par-
ent Order Id. You must turn Transmitoff until the order is completely set up, and you must identify the first order in the
bracket as the Parent Order.
To place a Buy-Limit bracket order
1. Click the Advanced Orders tab at the bottom of the spreadsheet.
2. Enter the contract descriptions and order descriptions for all three orders on three contiguous rows:
o
The first order should be a BUY LMT order.
o
The second order should be a SELL STP order.
o
The third order should be a SELL LMT order.
2. Click the Extended Order Attributestab. Change the value for Transmitto 0 (row 13 on the Extended Order
Attributes page).
This ensures that your orders are not transmitted until you have completed the order setup.
3. Click the Advanced Orderstab, highlight the first order in the bracket order, then click the Place/Modify Order
button.
API Reference Guide 61
Chapter2 DDEfor Excel
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 Attributestab and
paste the Order ID into the Valuefield 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 Orderstab, 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 Attributestab and change the value for Transmitback to 1 (row 13).
7. Click the Advanced Orderstab, 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 Attributespage and delete the Parent
Order Idvalue you entered. If you do not, this value will be applied to all subsequent orders that you place in the
spreadsheet.
Placing a Volatility Order
In the DDE for Excel sample spreadsheet, you place volatility (VOL) orders by entering values for the following
extended order attributes:
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
To place a VOL order
1. Click the Advanced Orders tab at the bottom of the spreadsheet.
2. Define a contract by typing a symbol in a blank Symbolfield, then entering information in the relevant contract
description fields.
3. Select a contract and set up the order using the Order Description fields.
o
Enter VOLin the Order Type field.
4. Click the Extended Order Attributestab. Enter values in the Value field for the following extended order attrib-
utes:
o
Volatility - This value represents the volatility to use in calculating a limit price for the option. Enter this
value as a percentage, not as the market data is displayed. For example, enter 17.12 instead of .1712.
API Reference Guide 62
Chapter2 DDEfor Excel
o
Volatility Type - Enter 1for daily volatility or 2 for annual volatility.
o
Reference Price Type - This value is used to compute the limit price sent to an exchange and for stock range
price monitoring. Enter 1to use the average of the best bid and ask; or 2to use NBB (bid) when buying a call
or selling a put, or the NBO (ask) when selling a call or buying a put.
o
Continuous Update - Enter 1to automatically update the option price as the underlying stock price (or futures
price, for index options) moves. Enter 0if you do not want to use this feature.
5. On the Extended Order Attributespage, enter values in the Value field for the following optional extended order
attributes:
o
Underlying Range (Low) - Enter a low-end acceptable stock price relative to the selected option order. If the
price of the underlying instrument falls below the lower stock range price, the option order will be canceled.
o
Underlying Range (High) - Enter a high-end acceptable stock price relative to the selected option order. If the
price of the underlying instrument rises above the higher stock range price, the option order will be canceled.
o
Hedge Delta Order Type - Enter LMT, MKTor REL. Enter NONEif you do not want to use delta hedging.
o
Hedge Delta Aux Price - If you have entered LMT or REL as the Hedge Delta Order Type, enter the price as
the value for this attribute.
6. Click the Advanced Orders tab, then highlight the order row.
7. Click the Apply Extended Template button. The values you entered for the extended order attributes are applied
to the order row and displayed in the Extended Order Attributes section of the page.
8. With the order row highlighted, click the Place/Modify Order button.
9. When you are done placing VOL orders, go to the Extended Order Attributespage and delete the VOL order
values you entered. If you do not, these values will be applied to all subsequent orders that you place in the
spreadsheet.
Placing a Trailing Stop Limit Order
In TWS, there are four values that make up a trailing stop limit order:
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
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).
To create a Trailing Stop Limit Order
1. Click the Advanced Orders tab at the bottom of the spreadsheet.
2. Define a contract by typing a symbol in a blank Symbolfield, then entering information in the relevant contract
description fields.
3. Select a contract and set up the order using the Order Descriptionfields.
API Reference Guide 63
Chapter2 DDEfor Excel
o
Enter BUYor SELLin the Action field.
o
Enter the limit price in the Lmt Price field.
o
Enter TRAILLIMITin the Order Type field.
o
Enter the trailing amount in the Aux Price field.
4. Click the Extended Order Attributestab. Specify the trailing stop price as an extended order attribute. Type this
value in the Trail Stop Price Value field.
The Trail Stop Price value must include the limit offset.
o
For a sell order:
Trail Stop Price = Limit Price - Trailing Amount - Limit Offset
o
For a buy order:
Trail Stop Price = Limit Price + Trailing Amount + Limit Offset
5. On the Advanced Orderspage, select the order row and click the Apply Extended Templatebutton. The Trail
Stop Pricevalue is applied to the selected order and displayed in the Trail Stop Pricefield in the Extended Order
Attributessection of the page.
6. Click the Place/Modify Order button.
7. When you are done placing your order, go to the Extended Order Attributespage and delete the Trail Stop Price
value you entered. If you do not, this value will be applied to all subsequent orders that you place in the spread-
sheet.
Placing a Scale Order
In the DDE for Excel sample spreadsheet, you place scale orders by entering values for the following extended order
attributes:
To place a scale order
1. Click the Advanced Orders tab at the bottom of the spreadsheet.
2. Define a contract by typing a symbol in a blank Symbolfield, then entering information in the relevant contract
description fields.
3. Select a contract and set up the order using the Order Descriptionfields. The order type should be LMT or REL.
4. Click the Extended Order Attributestab. Enter values in the Value field for the following extended order attrib-
utes:
o
Scale Component Size - Enter the size of the first, or initial, order component. For example, if you submit a
10,000-share order with a Scale Component Size value of 1000, the first component will be fore 1000 shares.
o
Scale Price Increment - Enter the amount used to calculate the per-unit price of each component in the scale
ladder. This cannot be a negative number.
Note: As of API Release 9.41, the Scale Num Components not supported.
3. On the Advanced Orderspage, select the order row and click the Apply Extended Templatebutton. 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.
API Reference Guide 64
Chapter2 DDEfor Excel
5. When you are done placing your order, go to the Extended Order Attributespage and delete the scale order
values you entered. If you do not, these values will be applied to all subsequent orders that you place in the
spreadsheet.
Placing a Relative Order
In the DDE for Excel sample spreadsheet, you place relative orders by entering a value for the Percent Offset extended
order attribute.
To place a relative order
1. Click the Advanced Orders tab at the bottom of the spreadsheet.
2. Define a contract by typing a symbol in a blank Symbolfield, then entering information in the relevant contract
description fields.
3. Select a contract and set up the order using the Order Description fields.
o
Enter REL as the order type.
o
Enter the price cap in the Lmt Price cell.
4. Click the Extended Order Attributestab. Enter a percentage in decimal form in the Value field for the Percent
Offset extended order attribute.
5. On the Advanced Orderspage, select the order row and click the Apply Extended Templatebutton. 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 Attributespage 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.
Advanced Orders Page Toolbar Buttons
The toolbar on the Advanced Orders page includes the following buttons:
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 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.
Open Orders Page
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,
API Reference Guide 65
Chapter2 DDEfor Excel
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.
Viewing Open Orders
Note: Ensure that TWS is running, and that you have entered your user name in the User
Namefield in the Which Trader Workstation?section of all pages in the Excel spreadsheet
to properly connect to TWS.
To view open orders:
1. Click the Open Orders tab at the bottom of the spreadsheet.
2. Click Subscribe to Open Orders on the toolbar.
All of your open orders are displayed on the page, including orders you enter in the Excel API spreadsheet and in
TWS.
Orders that fill remain on the page for 30 seconds with a value of Fillin the Status field.
To remove open orders
1. Click the Cancel Open Orders Subscription button on the toolbar.
2. Click the Clear Open Orders button.
API Reference Guide 66
Chapter2 DDEfor Excel
Open Orders Tab Toolbar Buttons
The toolbar on the Open Orders page includes the following buttons:
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-
scription
Cancels the open orders subscription. The page will no longer
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
execution reports).
API Reference Guide 67
Chapter2 DDEfor Excel
Viewing Executions
Note: Ensure that TWS is running, and that you have entered your user name in the User
Namefield 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.
To remove execution reports
1. Click the Cancel Executions Subscription button on the toolbar.
2. Click the Clear Executions button.
Executions Page Toolbar Buttons
The toolbar on the Executions page includes the following buttons:
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-
scription
Click to cancel the execution subscription.
Clear Executions Removes all execution reports from the page.
Show Errors Jumps to the Error Code field and shows the error code.
Executions Reporting Page
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 rangesinto 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.
API Reference Guide 68
Chapter2 DDEfor Excel
Running Execution Reports
Note: Ensure that TWS is running, and that you have entered your user name in the User
Namefield in the Which Trader Workstation?section of all pages in the Excel spreadsheet
to properly connect to TWS.
To run execution reports
1. On the Executions page, click the Subscribe to Executions button on the toolbar.
2. Click the Executions Reporting tab at the bottom of the worksheet.
3. In the Type field select from:
o
Order ID - finds all executions resulting from orders with a specified PermID.
o
Order Ref- finds all executions resulting from orders with a given order reference; for example executions
from a specific basket order.
o
VOL order- finds all executions resulting from specific volatility order, including any hedge delta executions.
o
Strategy- in the Keyfield, enter a value to define the Type you selected. For example, if you selected Order
IDas the type, enter a specific order ID in the Key field.
Account Page
Use the Account page to:
API Reference Guide 69
Chapter2 DDEfor Excel
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.
Using the Account Page
Note: Ensure that TWS is running, and that you have entered your user name in the User
Namefield in the Which Trader Workstation?section of all pages in the Excel spreadsheet
to properly connect to TWS.
To view account information
1. Click the Account tab at the bottom of the spreadsheet.
2. Click the Subscribe to Account Updates button on the toolbar.
To remove account information
1. Click the Cancel Account Subscription button.
2. Click the Clear Account Data button.
To request the list of Financial Advisor (FA) managed account codes
API Reference Guide 70
Chapter2 DDEfor Excel
1. Click the Account tab at the bottom of the spreadsheet.
2. Click the Request Managed Accounts button.
To request details of a Financial Advisor (FA) managed account
1. Click the Account tab at the bottom of the spreadsheet.
2. In the Account Codefield in the Which Trader Workstation?area, type the account code for which you want
details.
3. Click the Request Managed Accounts button.
Account Page Toolbar Buttons
The toolbar on the Account page includes the following buttons.
Button Description
Subscribe to 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 Sub-
scription
Click this button one time for each position you hold. When
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
Accounts
For advisor accounts, click this button one time for each
account.
Show Errors Jumps to the Error Code field and shows the error code.
Account Page Values
The Account page displays the following values:
Field Description Notes
Account Code The account number.
Account Ready For internal use only.
Account Type Identifies the IB account type.
Accrued Cash Reflects the current month's accrued debit and
credit interest to date, updated daily.
At the beginning of
each month, the past
months accrual is
added to the cash bal-
ance and this field is
zeroed out.
API Reference Guide 71
Chapter2 DDEfor Excel
Field Description Notes
Available Funds For securities:
Equity with Loan Value - Initial margin
For commodities:
Net Liquidation Value - Initial margin
Buying Power Cash Account:
(Minimum (Equity with Loan Value, Previous
Day Equity with Loan Value)-Initial Margin)
Standard Margin Account:
Available Funds*4
Cash Balance For securities:
Settled cash + sales at the time of trade
For commodities:
Settled cash + sales at the time of trade +
futures PNL
Currency Shows the currency types that are listed in
the Market Value area.
Cushion Shows your current margin cushion.
Day Trades Remaining Number of day trades left for pattern day
trader period.
Day Trades Remaining
T+1, T+2, T+3, T+4
The number of day trades you have left for a
4-day pattern day-trader.
Equity With Loan
Value
For Securities:
Cash Account: Settled Cash
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.
API Reference Guide 72
Chapter2 DDEfor Excel
Field Description Notes
Full Available Funds For securities:
Equity with Loan Value - Initial margin
For commodities:
Net Liquidation Value - Initial margin
Full Excess Liquidity Equity with Loan Value - Maintenance mar-
gin
Full Init Margin Req Overnight initial margin requirement in the
base currency of the account.
Full Maint Margin
Req
Maintenance margin requirement as of next
period's margin change in the base currency
of the account.
Future Option Value Real-time mark-to-market value of futures
options.
Futures PNL Real-time change in futures value since last
settlement.
Gross Position Value Long Stock Value + Short Stock Value +
Long Option Value + Short Option Value.
Init Margin Req Initial margin requirement in the base cur-
rency of the account.
Leverage For Securities:
Gross Position value / Net Liquidation value
For Commodities:
Net Liquidation value - Initial margin
Look Ahead Available
Funds
For Securities:
Equity with loan value - look ahead initial
margin.
For Commodities:
Net Liquidation value - look ahead initial
margin.
Look Ahead Excess Liq-
uidity
Equity with loan value - look ahead main-
tenance margin.
Look Ahead Init Mar-
gin Req
Initial margin requirement as of next period's
margin change in the base currency of the
account.
Look Ahead Maint
Margin Req
Maintenance margin requirement as of next
period's margin change in the base currency
of the account.
Maint Margin Req Maintenance margin requirement in the base
currency of the account.
API Reference Guide 73
Chapter2 DDEfor Excel
Field Description Notes
Net Liquidation For Securities:
Total cash value + stock value + securities
options value + bond value
For Commodities:
Total cash value + commodities options value
Net Liquidation by
Currency
Same as above for individual currencies.
Option Market Value Real-time mark-to-market value of securities
options.
PNL The difference between the current market
value of your open positions and the average
cost, or Value - Average Cost.
Previous Day Equity
with Loan Value
Marginable Equity with Loan Value as of
16:00 ET the previous day, only applicable
to securities.
Realized PnL Shows your profit on closed positions, which
is the difference between your entry
execution cost and exit execution cost, or
(execution price + commissions to open the
positions) - (execution price + commissions
to close the position).
Reg T Equity Initial margin requirements calculated under
US Regulation T rules.
Reg T Margin For Securities:
Cash Account : Settled Cash
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 - futures
maintenance margin requirement
API Reference Guide 74
Chapter2 DDEfor Excel
Field Description Notes
SMA Max ((EWL - US initial margin require-
ments)*, (Prior Day SMA +/- change in day's
cash +/- US initial margin requirements** for
trades made during the day.))
*calculated end of day under US Stock rules,
regardless of country of trading.
**at the time of the trade
Only applicable for
securities.
Stock Market Value Real-time mark-to-market value of stock
Total Cash Balance Cash recognized at the time of trade + futures
PNL
Total Cash Value Total cash value of stock, commodities and
securities
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 Timefield in the Which Trader Workstation? area of the
page.
API Reference Guide 75
Chapter2 DDEfor Excel
Viewing Your Portfolio
Note: Ensure that TWS is running, and that you have entered your user name in the User
Namefield in the Which Trader Workstation?section of all pages in the Excel spreadsheet
to properly connect to TWS.
To view your portfolio
1. Click the Portfolio tab at the bottom of the worksheet.
2. Click the Subscribe to Portfolio Updates button.
To remove portfolio information
1. Click the Cancel Portfolio Subscription button.
2. Click the Clear Portfolio Data button.
Portfolio Page Toolbar Buttons
The toolbar on the Portfolio page includes the following buttons.
Button Description
Subscribe to Portfolio
Updates
Click to view all current portfolio data.
Cancel Portfolio Sub-
scription
Cancels the connection to TWS that updates your portfolio
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.
Historical Data 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 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.
API Reference Guide 76
Chapter2 DDEfor Excel
Note: For information about historical data request limitations, see Historical Data Limitations.
Viewing Historical Data
Note: Ensure that TWS is running, and that you have entered your user name in the User
Namefield in the Which Trader Workstation?section of all pages in the Excel spreadsheet
to properly connect to TWS.
To request historical data
1. Click the Historical Data tab at the bottom of the spreadsheet.
2. Create a ticker by filling in the fields in the Contract Descriptionsection of the page, or by clicking the Create
Tickerbutton on the toolbar and entering the required information in the Ticker box.
3. Enter the parameters of your query in the Query Specificationfields. For complete descriptions of the query fields,
Historical Data Page Query Specification Fields.
4. Select the line, then click the Request Historical Databutton. When the Ctrlfield displays "Finished," the results
are displayed on the specified page.
To request historical data for expired contracts
1. On the Historical Data page, create a ticker by filling in the fields in the Contract Descriptionsection of the
page, or by clicking the Create Tickerbutton on the toolbar and entering the required information in the Ticker
box.
2. Enter the parameters of your query in the Query Specification fields.
API Reference Guide 77
Chapter2 DDEfor Excel
3. In the Expiredfield in the Query Specificationsection, enter TRUE.
4. Select the line, then click the Request Historical Databutton. When the Ctrlfield displays "Finished," the results
are displayed on the specified page.
Note: Historical data queries on expired contracts are limited to the last year of the life of the con-
tract.
The following figure shows a typical historical data results page.
Historical Data Page Toolbar Buttons
The toolbar on the Historical Data page includes the following buttons.
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 Historical Data Submits your historical data query to TWS and displays the
results on a separate worksheet page.
Cancel Historical Data Cancels the historical data request.
API Reference Guide 78
Chapter2 DDEfor Excel
Button Description
Show Errors Jumps to the Error Code field and shows the error code.
Historical Data Page Query Specification Fields
Historical Data queries include the following fields:
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 for-
mat 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.
API Reference Guide 79
Chapter2 DDEfor Excel
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 Size String-Integer Value
l 1 second - 1
l 5 seconds - 2
l 15 seconds - 3
l 30 seconds - 4
l 1 minutes - 5
l 2 minutes - 6
l 3 minutes - 16
l 5 minutes - 7
l 15 minutes - 8
l 30 minutes - 9
l 1 hour - 10
l 1 day - 11
On the query return page, each "bar" is represented by a line in the spread-
sheet. If you specify a duration of 300 seconds, and a bar size of "1" (one
second) your return will include 300 lines, and the value in each line is
equal to one second, or is a one-second bar. Note that you can use either the
Integer value of the Bar Size String or the Integer Value to define the bar
sizes.
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, vol-
umeand weighted average priceduring the time slice queried.
For the Bid/Ask query, the openand closevalues are the time-weighted aver-
age bid and the time-weighted average offer, respectively. These bars are
identical to the TWS charts' candlestick bars.
API Reference Guide 80
Chapter2 DDEfor Excel
Parameter Description
RTH Only Regular Trading Hours only. Valid values include:
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
requested is returned, even if the time span falls partially or com-
pletely outside.
Date Format Style Valid values include:
l 1 - dates that apply to bars are returned in the format
yyyymmdd{space}{space}hh:mm:dd (the same format used when
reporting executions).
l 2 - the dates are returned as an integer specifying the number of sec-
onds since 1/1/1970 GMT.
Page Name The name of the results page. This appears in the tab for the results page at
the bottom of the worksheet.
Expired Valid values: TRUE, FALSE
If TRUE, the data query can be done on an expired futures contract, limited
to the last year of a contract's life.
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.
Market Scanner Page
Use the Market Scanner page to subscribe to TWS market scanners. These scanners allow you to define criteria and set
filters that return the top xnumber of underlyings which meet all scan criteria. The scan is continually updated in real
time.
API Reference Guide 81
Chapter2 DDEfor Excel
Starting a Market Scanner Subscription
Note: Ensure that TWS is running, and that you have entered your user name in the User
Namefield in the Which Trader Workstation?section of all pages in the Excel spreadsheet
to properly connect to TWS.
To start a scanner subscription
1. Click the Market Scannertab at the bottom of the spreadsheet.
2. Highlight an existing scanner row, or enter information for a different market scanner:
a. Type the name of the scan results page in the Page Name field.
b. Type TRUEor FALSEin the Activate Page field.
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 Subscriptionbutton in the toolbar. A new page for the scanner is created and is dis-
played after the subscription is processed.
API Reference Guide 82
Chapter2 DDEfor Excel
Market Scanner Parameters
The following table describes the market scanner parameters that make up a scanner subscription.
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
Above
Filters out returns with an average option volume below the
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.
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.
API Reference Guide 83
Chapter2 DDEfor Excel
Parameter Description
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.
Market Scanner Page Toolbar Buttons
The toolbar on the Market Scanner page includes the following buttons.
Button Description
Start Scanner Sub-
scription
Creates and displays a new page for results of the selected mar-
ket scanner.
Cancel Scanner Sub-
scription
Cancels the market scanner.
Show Errors Jumps to the Error Code field and shows the error code.
Available Market Scanners
The following table shows the available market scanners in the DDE for Excel API spreadsheet.
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.
Market Scanner (Scan Code) Description
Low Opt Volume P/C Ratio
(LOW_OPT_VOL_PUT_CALL_RATIO)*
Put option volumes are divided by call option vol-
umes and the top underlying symbols with the low-
est ratios are displayed.
High Option Imp Vol Over Historical
(HIGH_OPT_IMP_VOLAT_OVER_HIST)*
Shows the top underlying contracts (stocks or
indices) with the largest divergence between
implied and historical volatilities.
Low Option Imp Vol Over Historical
(LOW_OPT_IMP_VOLAT_OVER_HIST)*
Shows the top underlying contracts (stocks or
indices) with the smallest divergence between
implied and historical volatilities.
Highest Option Imp Vol
(HIGH_OPT_IMP_VOLAT)*
Shows the top underlying contracts (stocks or
indices) with the highest vega-weighted implied
volatility of near-the-money options with an expi-
ration date in the next two months.
API Reference Guide 84
Chapter2 DDEfor Excel
Market Scanner (Scan Code) Description
Top Option Imp Vol % Gainers
(TOP_OPT_IMP_VOLAT_GAIN)*
Shows the top underlying contracts (stocks or
indices) with the largest percent gain between cur-
rent implied volatility and yesterday's closing
value of the 15 minute average of implied vol-
atility.
Top Option Imp Vol % Losers
(TOP_OPT_IMP_VOLAT_LOSE)*
Shows the top underlying contracts (stocks or
indices) with the largest percent loss between cur-
rent implied volatility and yesterday's closing
value of the 15 minute average of implied vol-
atility.
High Opt Volume P/C Ratio
(HIGH_OPT_VOLUME_PUT_CALL_
RATIO)
Put option volumes are divided by call option vol-
umes and the top underlying symbols with the
highest ratios are displayed.
Low Opt Volume P/C Ratio
(LOW_OPT_VOLUME_PUT_CALL_
RATIO)
Put option volumes are divided by call option vol-
umes and the top underlying symbols with the low-
est ratios are displayed.
Most Active by Opt Volume
(OPT_VOLUME_MOST_ACTIVE)
Displays the most active contracts sorted descend-
ing by options volume.
Hot by Option Volume
(HOT_BY_OPT_VOLUME)
Shows the top underlying contracts for highest
options volume over a 10-day average.
High Option Open Interest P/C Ratio
(HIGH_OPT_OPEN_INTEREST_PUT_
CALL_RATIO)
Returns the top 50 contracts with the
highestput/call ratio of outstanding option con-
tracts.
Low Option Open Interest P/C Ratio
(LOW_OPT_OPEN_INTEREST_PUT_
CALL_RATIO)
Returns the top 50 contracts with the lowest
put/call ratio of outstanding option contracts.
Top % Gainers
(TOP_PERC_GAIN)
Contracts whose last trade price shows the highest
percent increase from the previous night's closing
price.
Most Active
(MOST_ACTIVE)
Contracts with the highest trading volume today,
based on units used by TWS (lots for US stocks;
contract for derivatives and non-US stocks).
The sample spreadsheet includes two Most Active
scans: Most Active List, which displays the most
active contracts in the NASDAQ, NYSE and
AMEX markets, and Most Active US, which dis-
plays the most active stocks in the United States.
Top % Losers
(TOP_PERC_LOSE)
Contracts whose last trade price shows the lowest
percent increase from the previous night's closing
price.
API Reference Guide 85
Chapter2 DDEfor Excel
Market Scanner (Scan Code) Description
Hot Contracts by Volume
(HOT_BY_VOLUME)
Contracts where:
l today's Volume/avgDailyVolume is highest.
l avgDailyVolume is a 30-day exponential
moving average of the contract's daily vol-
ume.
Top % Futures Gainers
(TOP_PERC_GAIN)
Futures whose last trade price shows the highest
percent increase from the previous night's closing
price.
Hot Contracts by Price
(HOT_BY_PRICE)
Contracts where:
l (lastTradePrice-prevClose)/avgDailyChange
is highest in absolute value (positive or neg-
ative).
l The avgDailyChange is defined as an expo-
nential moving average of the contract's (dai-
lyClose-dailyOpen)
Top Trade Count
(TOP_TRADE_COUNT)
The top trade count during the day.
Top Trade Rate
(TOP_TRADE_RATE)
Contracts with the highest number of trades in the
past 60 seconds (regardless of the sizes of those
trades).
Top Price Range
(TOP_PRICE_RANGE)
The largest difference between today's high and
low, or yesterday's close if outside of today's range.
Hot by Price Range
(HOT_BY_PRICE_RANGE)
The largest price range (from Top Price Range cal-
culation) over the volatility.
Top Volume Rate
(TOP_VOLUME_RATE)
The top volume rate per minute.
Lowest Option Imp Vol
(LOW_OPT_IMP_VOLAT)
Shows the top underlying contracts (stocks or
indices) with the lowest vega-weighted implied vol-
atility of near-the-money options with an expi-
ration date in the next two months.
Most Active by Opt Open Interest
(OPT_OPEN_INTEREST_MOST_
ACTIVE)
Returns the top 50 underlying contracts with the
(highest number of outstanding call contracts) +
(highest number of outstanding put contracts)
Not Open
(NOT_OPEN)
Contracts that have not traded today.
Halted
(HALTED)
Contracts for which trading has been halted.
API Reference Guide 86
Chapter2 DDEfor Excel
Market Scanner (Scan Code) Description
Top % Gainers Since Open
(TOP_OPEN_PERC_GAIN)
Shows contracts with the highest percent price
INCREASE between the last trade and opening
prices.
Top % Losers Since Open
(TOP_OPEN_PERC_LOSE)
Shows contracts with the highest percent price
DECREASE between the last trade and opening
prices.
Top Close-to-Open % Gainers
(HIGH_OPEN_GAP)
Shows contracts with the highest percent price
INCREASE between the previous close and today's
opening prices.
Top Close-to-Open % Losers
(LOW_OPEN_GAP)
Shows contracts with the highest percent price
DECREASE between the previous close and
today's opening prices.
Lowest Option Imp Vol
(LOW_OPT_IMP_VOLAT)*
Shows the top underlying contracts (stocks or
indices) with the lowest vega-weighted implied vol-
atility of near-the-money options with an expi-
ration date in the next two months.
Top Option Imp Vol % Gainers
(TOP_OPT_IMP_VOLAT_GAIN)*
Shows the top underlying contracts (stocks or
indices) with the largest percent gain between cur-
rent implied volatility and yesterday's closing
value of the 15 minute average of implied vol-
atility.
Top Option Imp Vol % Losers
(TOP_OPT_IMP_VOLAT_LOSE)*
Shows the top underlying contracts (stocks or
indices) with the largest percent loss between cur-
rent implied volatility and yesterday's closing
value of the 15 minute average of implied vol-
atility.
13-Week High
(HIGH_VS_13W_HL)
The highest price for the past 13 weeks.
13-Week Low
(LOW_VS_13W_HL)
The lowest price for the past 13 weeks.
26-Week High
(HIGH_VS_26W_HL)
The highest price for the past 26 weeks.
26-Week Low
(LOW_VS_26W_HL)
The lowest price for the past 26 weeks.
52-Week High
(HIGH_VS_52W_HL)
The highest price for the past 52 weeks.
52-Week Low
(LOW_VS_52W_HL)
The lowest price for the past 52 weeks.
API Reference Guide 87
Chapter2 DDEfor Excel
Market Scanner (Scan Code) Description
EFP - High Synth Bid Rev Yield
(HIGH_SYNTH_BID_REV_NAT_
YIELD)
Highlights the highest synthetic EFP interest rates
available. These rates are computed by taking the
price differential between the SSF and the under-
lying stock and netting dividends to calculate an
annualized synthetic implied interest rate over the
period of the SSF. The High rates may present an
investment opportunity.
EFP - Low Synth Bid Rev Yield
(LOW_SYNTH_BID_REV_NAT_
YIELD)
Highlights the lowest synthetic EFP interest rates
available. These rates are computed by taking the
price differential between the SSF and the under-
lying stock and netting dividends to calculate an
annualized synthetic implied interest rate over the
period of the SSF. The Low rates may present a bor-
rowing opportunity.
*30-day (V30) Implied Volatilities:
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 vol-
atilities 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 var-
iance. If there is no first expiration month with less than sixty calendar days to run, we do not cal-
culate a V30.
Contract Details Page
Use the Contract Details page to request contract-specific information such as supported order types, valid exchanges, the
contract ID, and so on.
API Reference Guide 88
Chapter2 DDEfor Excel
Requesting Contract Details
Note: Ensure that TWS is running, and that you have entered your user name in the User
Namefield in the Which Trader Workstation?section of all pages in the Excel spreadsheet
to properly connect to TWS.
To request details for a contract
1. Click the Contract Detailstab at the bottom of the spreadsheet to open the Contract Details page.
2. Select or enter the ticker symbol for which you want to request contract details.
3. To request contract details for an expired contract, type TRUEin the Expired field.
4. Click the Request Contract Details button on the toolbar.
Contract Details Page Toolbar Buttons
The toolbar on the Contract Details page includes the following buttons:
Button Description
Request Contract Details Returns information on the selected contract.
Show Errors Jumps to the Error Code field and shows the error code.
API Reference Guide 89
Chapter2 DDEfor Excel
Bond Contract Details Page
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)
Requesting Bond Contract Details
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 prop-
erly connect to TWS.
To request details for a bond contract
API Reference Guide 90
Chapter2 DDEfor Excel
1. Click the BondContract 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)
Bond Contract Details Page Toolbar Buttons
The toolbar on the Bond Contract Details page includes the following buttons:
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.
Market Depth Page
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.
API Reference Guide 91
Chapter2 DDEfor Excel
Using the Market Depth Page
Note: Ensure that TWS is running, and that you have entered your user name in the User
Namefield in the Which Trader Workstation?section of all pages in the Excel spreadsheet
to properly connect to TWS.
To request market depth for a contract
1. Click the Market Depthtab at the bottom of the spreadsheet to open the Market Depth page.
2. Select the ticker symbol for which you want to request the market depth, or enter a new ticker on a blank line.
3. Click the Request Market Depth button on the toolbar.
To reset the market data refresh rate for tickers and market depth
1. Click the Tickersor Market Depth tab at the bottom of the spreadsheet.
2. Type the desired market data refresh rate in milliseconds in the Refresh Ratefield 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.
To display more lines of market depth
You can edit the Request Market Depth macro to show more than the default 10 lines.
API Reference Guide 92
Chapter2 DDEfor Excel
1. From the Market Depth page, press Alt+F11.
The Visual Basic Editor (VBE) opens and displays the code for the Market Depth page.
2. In the Declarations section at the top of the code window for the page, change the number value in num-
DisplayRows = 10to a higher/lower value, then click the Save button on the VBE toolbar.
3. Close the Visual Basic Editor.
Market Depth Page Toolbar Buttons
The toolbar on the Market Depth page includes the following buttons:
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:
l allocate shares to a single managed account
l use FA account groups and methods
API Reference Guide 93
Chapter2 DDEfor Excel
l use allocation profiles
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.
Allocating Shares to a Single Account
You can use the Advisorspage to set up an order and allocate all shares in the order to a single account.
To allocate shares to a single account:
1. Create an account group in TWS.
2. Click the Advisors tab at the bottom of the spreadsheet.
3. Enter the contract information in the Contract Descriptioncells, then enter the order information in the Order
Descriptioncells.
4. Click the Extended Order Attributestab. Enter the account code in the Valuecell for the Account (Institutional
only) extended order attribute.
5. Click the Advisors tab.
6. Highlight the order row, then click the Apply Extendedbutton to apply the Accountorder attribute value to the
order. The Accountvalue is applied to the selected order and displayed in the Extended Order Attributes section
of the page.
7. Click the Place/Modify Orderbutton.
API Reference Guide 94
Chapter2 DDEfor Excel
8. When you are done allocating shares to the account, delete the Accountvalue from the Extended Order Attrib-
utespage. If you do not delete this value, it will be applied to all subsequent orders placed from the DDE for
Excel API spreadsheet.
Placing an Order using an FA Account Group and Method
You can also use the Advisorspage to set up an order using an FA account group and FA method.
To place an order using an FA account group and FA method:
1. Create the FA account group(s) and FA method(s) in TWS.
2. Click the Advisors tab at the bottom of the spreadsheet.
3. Enter the contract information in the Contract Descriptioncells, then enter the order information in the Order
Descriptioncells.
4. Click the Extended Order Attributestab. Enter values for the following extended order attributes:
o
FA Group - Enter the name of the account group.
o
FA Method - Enter the name of the allocation method to use for this order.
o
FA Percentage - Enter the percentage used by the PctChange allocation method to use for this order. This attrib-
ute applies only to FA groups that use this method.
5. Click the Advisors tab.
6. Highlight the order row, then click the Apply Extendedbutton to apply the extended order attribute values to the
order. The values for FA Group,FA Method and FA Percentage are applied to the selected order and displayed in
the Extended Order Attributes section of the page.
7. Click the Place/Modify Orderbutton.
8. When you are done allocating shares to the account, delete the values you entered on the Extended Order Attrib-
utespage. If you do not delete these values, they will be applied to all subsequent orders placed from the DDE
for Excel API spreadsheet.
Placing an Order using an Allocation Profile
You can also use the Advisorspage to set up an order using an FA allocation profile.
To place an order using an FA allocation profile:
1. Create the FA allocation profile in TWS.
2. Click the Advisors tab at the bottom of the spreadsheet.
3. Enter the contract information in the Contract Descriptioncells, then enter the order information in the Order
Descriptioncells.
4. Click the Extended Order Attributestab. 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 Extendedbutton 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.
API Reference Guide 95
Chapter2 DDEfor Excel
7. Click the Place/Modify Orderbutton.
8. When you are done allocating shares to the account, delete the FA Profile value you entered on the Extended
Order Attributespage. If you do not delete this value, it will be applied to all subsequent orders placed from the
DDE for Excel API spreadsheet.
Advisors Page Toolbar Buttons
The toolbar on the Basic Orders page includes the following buttons:
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.
API Reference Guide 96
Chapter2 DDEfor Excel
DDE for Excel API Reference
This section provides a variety of reference information about the DDE for Excel API, including the following topics:
l Viewing the Code
l Modules
l Named Ranges
l Macros
l DDE Syntax for Excel
Viewing the Code
To view the Visual Basic code behind the DDE for Excel API spreadsheet, press Alt+F11from any page. The Visual
Basic Editor opens:
The Visual Basic Editor contains three main components:
l Project Explorer
l Properties Window
l Code Window
API Reference Guide 97
Chapter2 DDEfor Excel
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 pages 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 appli-
cation. Using these constants instead of hard-coded values will make your application more robust and easier to main-
tain. 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,
placing 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.
API Reference Guide 98
Chapter2 DDEfor Excel
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:
API Reference Guide 99
Chapter2 DDEfor Excel
DDE Syntax for Excel
The table below defines possible cell values for DDE-supported functionality. The basic syntax, which appears in the
Excel formula bar (the "=" enterable 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:
Description Server Topic id reqType field2
Place an order server ord idn place orderDescription
Modify an order server ord idn modify orderModification
Cancel an order server ord idn cancel
Check order status server ord idn status
Request open orders server ord idn open
Request executions server ord idn executed
Check shares filled in order server ord idn sharesFilled
Check shares remaining in order server ord idn sharesRemaining
Execution (average) price server ord idn price
Underlying server ord idn symbol
Security type server ord idn secType Refer to Note 6
Expiry server ord idn expiry Refer to Note 7
Strike server ord idn strike Refer to Note 8
API Reference Guide 100
Chapter2 DDEfor Excel
Right server ord idn right Refer to Note 8
Specify contract multiplier for options
and futures
server ord idn multiplier Refer to Note 8
Order destination server ord idn exchange
Currency server ord idn currency
Order side server ord idn side
Order quantity server ord idn size
Order type server ord idn orderType
Limit price server ord idn limitPrice
Auxiliary price server ord idn auxPrice
Local symbol server ord idn localSymbol
Last fill price server ord idn lastFillPrice
Create ticker server tik idn req
Bid implied volatility server tik idn bidImpliedVol
Bid delta server tik idn bidDelta
Request bid size server tik idn bidSize
Request bid price server tik idn bid
Request ask price server tik idn ask
Request ask size server tik idn askSize
Ask implied volatility server tik idn askImpliedVol
Ask delta server tik idn askDelta
Request last price server tik idn last
Request last size server tik idn lastSize
Last implied volatility server tik idn lastImpliedVol
Last delta server tik idn lastDelta
Request today's high price server tik idn high
Request today's low price server tik idn low
Request today's volume size server tik idn volume
Request last close price server tik idn close
Request implied volatility calculated by
the TWS option modeler
server tik idn modelVolatility
API Reference Guide 101
Chapter2 DDEfor Excel
Request option delta calculated by the
TWS option modeler
server tik idn modelDelta
Request the model price server tik idn modelPrice
Request present value of dividends
expected on the options underlier
server tik idn pvDividend
Request number of hold days until the
expiry of the EFP
server tik idn holdDays
Request expiration date of the single
stock future
server tik idn futureExpiry
Request dividends expected until the
expiration of the single stock future
server tik idn dividendsToExpiry
Request annualized basis points server tik idn basisPoints
Request annualized basis points in per-
centage form
server tik idn formattedBasis
Points
Request implied futures price server tik idn impliedFuture
Request the dividend impact on the
annualized basis points interest rate
server tik idn dividendImpact
Account statement control key server acct idn acctv Account code (for Advi-
sor-managed accounts
only)
Request one account value string server acct idn key
Account value server acct idn value
Account currency server acct idn keyCurrency
Account portfolio control key server acct idn acctp Account code (for Advi-
sor-managed accounts
only)
Account portfolio underlying symbol server acct idn symbol
Account portfolio security type server acct idn secType
Account portfolio expiry server acct idn expiry
Account portfolio strike price server acct idn strike
API Reference Guide 102
Chapter2 DDEfor Excel
Account portfolio right server acct idn right
Account portfolio currency server acct idn currency
Account portfolio local symbol server acct idn localSymbol
Account portfolio market price server acct idn marketPrice
Account portfolio market value server acct idn marketValue
Account portfolio average cost server acct idn avgCost
Account portfolio realized PNL server acct idn realizedPNL
Account portfolio unrealized PNL server acct idn unrealizedPNL
Request contract details server contract idn req contractDescription
Valid order types server contract idn orderTypes
Valid exchanges server contract idn validExchanges
Contract identifier server contract idn conid
Minimum tick server contract idn minTick
Order multiplier server contract idn multiplier
Market name server contract idn marketName
Trading class server contract idn tradingClass
Execution order id server exec idn orderId
Underlying server exec idn symbol
Security type server exec idn secType
Expiry server exec idn expiry
Strike server exec idn strike
Right server exec idn right
Order destination server exec idn exchange
Currency server exec idn currency
Local symbol server exec idn localSymbol
Execution id server exec idn execId
Execution time server exec idn time
Account number server exec idn acctnNumber
Exchange where executed server exec idn eExchange
Side server exec idn side
API Reference Guide 103
Chapter2 DDEfor Excel
Number of shares filled in order server exec idn shares
Execution (average) price server exec idn price
Order ID server exec idn permId
Identifies position as one to be liq-
uidated last
server exec idn liquidation
Request execution details server exec idn Req executionFilter
Request list of Advisor-managed
accounts
server FAaccts idn Req
List of Advisor-managed accounts server FAaccts idn Value
Request market depth server mktDepth idn req contractDescripton? num_
display_rows
Refer to note (1)below.
Market maker server mktDepth idn mktMaker rowId_side
Refer to note (2)below.
Order price server mktDepth idn price rowId_side
Refer to note (2)below.
Order size server mktDepth idn size rowId_side
Refer to note (2)below.
Market data refresh rate server refreshRate idn millisec Number of milliseconds
Subscribe to news bulletins server news sub 0 Refer to note 3 below
News bulletin message ID server news newsID
News bulletin message type server news newsType Refer to note 4 below
News bulletin message text server news msg
Exchange from which news bulletins
originated
server news exchange
Set the server log level server logLevel <log_
level>
Refer to note 5 below.
Where:
API Reference Guide 104
Chapter2 DDEfor Excel
orderDescription = side_quantity_symbol_secType_exp_strike_right_exchange_orderType_lmtPrice_auxPrice
{_timeInForce_ocaGroup_account_open/close_origin_orderRef_transmit_parentId_blockOrder
_sweepToFill_displaySize_triggerMethod_ignoreRth_hidden_clientId_accountCode_goodAfterTime_
goodTillDate_faGroup_faMethod_faPercentage_faProfile_shortSaleSlot_
PRIMARYEXCHANGE
_shortSaleLocation_ocaType_rthOnly_rule80A_settlingFirm_allOrNone_minimumQty_percentOffset_
electronicTradeOnly_firmQuoteOnly_nbboPriceCap_auctionStrategy_startingPrice_stockRefPrice_
delta_stockRangeLower_stockRangeUpper_volatility_volatilityType_referencePriceType_hedgeDelta_
continuousUpdate}
Note:Attributes in brackets are extended order attributes and are described in the topic Extended Order Attributes.
contractDescription - symbol_secType_exp_strike_right_exchange
tickerDescription = symbol_secType_exp_strike_right_exchange
ExecutionFilter = clientId_accountCode_date_time_symbol_secType_exchange_side
Note 1:When requesting market depth you can specify the number of rows to display. If not supplied, the default
number of rows is five (5) rows. This parameter can be used to optimize performance, as a low number of display rows
requires less CPU overhead.
For example: =edemo|mktDepth!id0?req?MSFT_STK_SMART?10will request 10 rows of market depth orders.
Note 2:Field 2 of the market depth 'price'and 'size' reqTypes contain additional information to specify the order row
and side that the data applies to. Market depth orders are divided into two sides, BID and ASK, and order entries start
from the offset 0.
For example:
=edemo|mktDepth!id0?price?0_ASK will request the ASK price for the order entry 0.
=edemo|mktDepth!id0?size?2_BIDwill request the BID size for the order entry 2.
Note 3:When subscribing to news bulletins, the request should look like this:
=edemo|news!sub?0
where the request type is a zero. To unsubscribe simply clear the subscription cell.
Note 4:The valid news bulletin types are:
1 = Regular news bulletin
2 = Exchange no longer available for trading
3 = Exchange available for trading
Note 5:The valid log levels are:
1 = SYSTEM (least detailed)
2 = ERROR (default, if no level is specified)
API Reference Guide 105
Chapter2 DDEfor Excel
3 = WARNING
4 = INFORMATION
5 = DETAIL (most detailed)
Note 6:If the order is a combo, combo legs are inserted after the aux price. Here is a three-legged IBM combo descrip-
tion:
CMBLGS_3_8314_100_BUY_SMART_0_36930759_1_BUY_SMART_0_36930816_1_SELL_SMART_0_CMBLGS.
Each leg contains : contract ID, number of contracts, side, exchange, and open/close (0 or 1). Retail can always specify
0, institutional need to specify a 1 if the order being executed would close a position.
Note 7:If the order is an option or a future, the expiry is inserted after the sec type.
Note 8:If the order is an option, the strike and right (put or call) are inserted after the expiry. If the multiplier is spec-
ified, it follows the strike and right.
API Reference Guide 106
Active X
This chapter describes the ActiveX API, including the following topics:
l Linking to the Application using ActiveX
l Registering Third-Party ActiveX Controls
l Running the ActiveX API on 64-bit Windows XP Systems
l Using the Visual Basic Sample Program
l ActiveX Methods
l ActiveX Events
l ActiveX COM Objects
l ActiveX Properties
l Placing a Combination Order
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.
API Reference Guide 107
3
Chapter3 Active X
Linking to the Application using ActiveX
Before you can use third-party ActiveX controls, you must register them with Visual Basic.
To link using the ActiveX control and VB, VBA or C++
1. Drop the application control onto a form or dialog box.
2. Call the following methods:
o
Call the connect() method to connect to the running application.
o
Call the methods you need to perform whatever operations you require, such as the reqMktData() method to
request market data.
3. Call the placeOrder() method to place an order. Orders using extended attributes require that ActiveX properties
representing them be set first.
4. Handle the following events:
o
Handle the nextValidId() event to receive the next available valid order ID. Increment the ID by one for suc-
cessive orders.
o
Handle the tickPrice() and tickSize() events to receive the market data.
o
Handle the orderStatus() event to receive status information about orders.
o
Handle the error() event to receive error information.
o
Handle the connectionClosed() event to be notified in case the application stops communicating with the Acti-
veX control.
API Reference Guide 108
Chapter3 Active X
Registering Third-Party ActiveX Controls
To use a third-party ActiveX control in Visual Basic it must be registered first.
To register the ActiveX control with Visual Basic, follow these instructions:
1. From the Componentsmenu in your VB project, select the TWS ActiveX control (Tws.ocx, located in the bin/Ac-
tiveX folder in your APIInstallation folder).
2. Click Apply.
3. Verify that the TWS control appears in the toolbar with all standard controls.
API Reference Guide 109
Chapter3 Active X
Running the ActiveX API on 64-bit Windows XP Sys-
tems
To run the ActiveX API on 64-bit Windows XP systems, do the following:
1. Install Microsoft Visual C++ 2005 SP1 Redistributable Package (x86).
2. Install Microsoft Visual J# 2.0 Redistributable Package.
3. Download and install the API software.
API Reference Guide 110
Chapter3 Active X
Using the Visual Basic Sample Program
You can access the server through the ActiveX interface using the .NET sample application. To run the sample you must:
l Install the API sample programs
l Configure the application to support the API components
l Have MS Visual Studio (Visual Basic 6.0 or higher) installed on your PC.
The .NET program is a sample program that demonstrates use of the TWS ActiveX control to connect to the server from a
Visual Basic application.
Note: You can also run the Visual Basic version of the ActiveXsample program, but we rec-
ommend running the .NETversion.
To open the .net APIsample program:
1. Navigate to the samples\TestActiveX_VB.NET folder in your API installation folder, then rename the *.vbproj
file.
We recommend renaming the original *.vbproj file because Visual Studio will regenerate the project files to be
compatible with both 32- and 64-bit operating systems.
2. From the MS Visual Basic file menu, select Open Project, then select the *.vbproj file that you renamed in the
samples\TestActiveX_VB.NET folder of your API installation folder.
3. Press Ctrl+F5 to compile and run the project.
Note: If you have trouble getting the sample program to run, try re-registering the TWS ActiveX
component, Tws.ocx.
API Reference Guide 111
Chapter3 Active X
ActiveX Methods
ActiveX methods allow your application to call functions and request information from TWS.
Connection and Server
connect()
disconnect()
reqCurrentTime()
setServerLogLevel()
Market Data
reqMktDataEx()
cancelMktData()
calculateImpliedVolatility()
cancelCalculateImpliedVolatility()
calculateOptionPrice()
cancelCalculateOptionPrice()
reqMarketDataType()
Orders
placeOrderEx()
cancelOrder()
reqOpenOrders()
reqAllOpenOrders()
reqAutoOpenOrders()
reqIds()
exerciseOptionsEx()
reqGlobalCancel()
Executions
reqExecutionsEx()
Contract Details
reqContractDetailsEx()
Market Depth
reqMktDepthEx()
cancelMktDepth()
Account
reqAccountUpdates()
News Bulletins
reqNewsBulletins()
cancelNewsBulletins()
Financial Advisors
reqManagedAccts()
requestFA()
replaceFA()
reqAccountSummary()
cancelAccountSummary()
reqPositions()
cancelPositions()
Historical Data
reqHistoricalDataEx()
cancelHistoricalData()
Market Scanners
reqScannerParameters()
reqScannerSubscriptionEx()
cancelScannerSubscription()
Real Time Bars
reqRealTimeBarsEx()
cancelRealTimeBars()
Factory Methods
createComboLegList()
createContract()
createExecutionFilter()
createOrder()
createScannerSubscription()
createTagValueList()
createUnderComp()
Fundamental Data
reqFundamentalData()
cancelFundamentalData()
API Reference Guide 112
Chapter3 Active X
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
Parameter Type Description
host
String
The host name or IP address of the machine where TWS is running. Leave
blank to connect to the local host.
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.
Note: Each client MUST connect with a unique clientId.
disconnect()
Call this method to terminate the connections the host application. Calling this method does not cancel orders that have
already been sent.
Public Overridable Sub disconnect()
reqCurrentTime()
Returns the current system time on the server side.
Public Overridable Sub reqCurrentTime()
setServerLogLevel()
Public Overridable Sub setServerLogLevel(ByVal logLevel As Integer)
Parameter Type Description
logLevel Integer Specifies the level of log entry detail used by the server when processing
API requests. Valid values include:
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.
API Reference Guide 113
Chapter3 Active X
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
genericTicks As String, ByVal snapshot As Integer)
Parameter Type Description
tickerId Integer The ticker id. Must be a unique value. When the market data returns, it
will be identified by this tag. This is also used when canceling the mar-
ket data.
contract IContract This object contains a description of the contract for which market data
is being requested.
genericTicks String A comma delimited list of generic tick types. For more information
about tick types, see Generic Tick Types.
snapshot Integer Check to return a single snapshot of market data and have the market
data subscription cancel. Do not enter any genericTicklist values if you
use snapshot.
cancelMktData()
After calling this method, market data for the specified id will stop flowing.
Public Overridable Sub cancelMktData(ByVal id As Integer)
Parameter Type Description
id Integer The ID that was specified in the call to reqMktData().
calculateImpliedVolatility()
Call this function to calculate volatility for a supplied option price and underlying price.
Public Overridable Sub calculateImpliedVolatility(ByVal reqId As Integer, ByVal contract As TWSLib.IContract,
ByVal optionPrice As Double, ByVal underPrice As Double)
Parameter Type Description
reqId Integer The ticker ID.
contract IContract Describes the contract.
optionPrice Double The price of the option.
underPrice Double Price of the underlying.
cancelCalculateImpliedVolatility()
Call this function to cancel a request to calculate volatility for a supplied option price and underlying price.
Public Overridable Sub calculateImpliedVolatility(ByVal reqId As Integer)
API Reference Guide 114
Chapter3 Active X
Parameter Type Description
reqId Integer The ticker id.
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)
Parameter Type Description
reqId Integer The ticker ID.
contract IContract Describes the contract.
volatility Double The volatility.
underPrice Double Price of the underlying.
cancelCalculateOptionPrice()
Call this function to cancel a request to calculate option price and greek values for a supplied volatility and underlying
price.
Public Overridable Sub calculateOptionPrice(ByVal reqId As Integer)
Parameter Type Description
reqId Integer The ticker id.
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.
Public Overridable Sub reqMarketDataType(type As Integer)
Parameter Type Description
type Integer 1 for real-time streaming market data or 2 for frozen market data.
placeOrderEx()
Call this method to place an order. The order status will be returned by the orderStatus()event in dispinterface_DTwsE-
vents.
Public Overridable Sub placeOrderEx(ByVal orderId As Integer, ByVal contract As TWSLib.IContract, ByVal
order As TWSLib.IOrder)
API Reference Guide 115
Chapter3 Active X
Parameter Type Description
orderId Integer The order Id. You must specify a unique value. When the
order status returns, it will be identified by this tag. This tag
is also used when canceling the order.
contract IContract This object contains attributes used to describe the contract.
order IOrder This object contains the details of the order. Note: Each
client MUST connect with a unique clientId.
cancelOrder()
Call this method to cancel an order.
Public Overridable Sub cancelOrder(ByVal id As Integer)
Parameter Type Description
id Integer The order ID that was specified previously in the call to place-
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.
Public Overridable Sub reqOpenOrders()
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
Public Overridable Sub reqAllOpenOrders()
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.
Public Overridable Sub reqAutoOpenOrders(ByVal bAutoBind As Integer)
Parameter Type Description
bAutoBind Integer If set to TRUE, newly created application orders will be implic-
itly associated with the client. If set to FALSE, no association
will be made.
API Reference Guide 116
Chapter3 Active X
reqIds()
Call this function to request the next valid ID that can be used when placing an order. After calling this method, the next-
ValidId() 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).
Public Overridable Sub reqIds(ByVal numIds As Integer)
Parameter Type Description
numIds Integer Set to 1.
exerciseOptionsEx()
Call this method to exercise options.
Note: SMART is not an allowed exchange in exerciseOptionsEx()calls, and that TWS does a
request for the position in question whenever any API initiated exercise or lapse is
attempted.
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)
Parameter Type Description
tickerId Integer The Id for the exercise request
contract IContract This structure contains a description of the contract for which
market data is being requested.
exerciseAction Integer This can have two values:
1 = exercise
2 = lapse
exerciseQuantity Integer The number of contracts to be exercised
account String For institutional orders. Specifies the IB account.
override Integer Specifies whether your setting will override the system's nat-
ural action. For example, if your action is "exercise" and the
option is not in-the-money, by natural action the option
would not exercise. If you have override set to "yes" the nat-
ural action would be overridden and the out-of-the money
option would be exercised. Values are:
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.
API Reference Guide 117
Chapter3 Active X
Public Overridable Sub reqGlobalCancel()
reqExecutionsEx()
When this method is called, the execution reports that meet the filter criteria are downloaded to the client via the exec-
DetailsEx() 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.
Public Overridable Sub reqExecutionsEx(ByVal reqId As Integer, ByVal filter As TWSLib.IExecutionFilter)
Parameter Type Description
reqID Integer The ID of the data request. Ensures that responses are matched to
requests if several requests are in process.
filter IExecutionFilter The filter criteria used to determine which execution reports are
returned.
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.
Public Overridable Sub reqContractDetailsEx(ByVal reqId As Integer, ByVal contract As TWSLib.IContract)
Parameter Type Description
reqId Integer The ID of the data request. Ensures that responses are matched to
requests if several requests are in process.
contract IContract This object contains a description of the contract for which market
data is being requested.
reqMktDepthEx()
Call this method to request market depth for a specific contract. The market depth will be returned by the upda-
teMktDepth()and updateMktDepthL2() events.
Public Overridable Sub reqMktDepthEx(ByVal tickerId As Integer, ByVal contract As TWSLib.IContract, ByVal
numRows As Integer)
Parameter Type Description
tickerId Integer The ticker Id. Must be a unique value. When the market depth data
returns, it will be identified by this tag. This is also used when can-
celing the market depth.
contract IContract This object contains a description of the contract for which market data
is being requested.
numRows Integer Specifies the number of market depth rows to return.
cancelMktDepth()
After calling this method, market depth for the specified id will stop flowing.
API Reference Guide 118
Chapter3 Active X
Public Overridable Sub cancelMktDepth(ByVal id As Integer)
Parameter Type Description
id Integer The ID that was specified in the call to reqMktDepth() or
reqMktDepth2().
reqAccountUpdates()
Call this method to request account updates. The account data will be fed back through the updateAccountTime(), upda-
teAccountValue()and updatePortfolioEx() events.
Public Overridable Sub reqAccountUpdates(ByVal subscribe As Integer, ByVal acctCode As String)
Parameter Type Description
subscribe Integer If set to 1, the client will start receiving account and portfolio updates. If
set to 0, the client will stop receiving this information.
acctCode String The account code for which to receive account and portfolio updates.
reqNewsBulletins()
Call this method to start receiving news bulletins. Each bulletin will be returned by the updateNewsBulletin() event.
Public Overridable Sub reqNewsBulletins(ByVal allDaysMsgs As Integer)
Parameter Type Description
allDaysMsgs Integer If set to TRUE, returns all the existing bulletins for the current day
and any new ones. If set to FALSE, will only return new bulletins.
cancelNewsBulletins()
Call this method to stop receiving news bulletins.
Public Overridable Sub cancelNewsBulletins()
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.
Public Overridable Sub reqManagedAccts()
requestFA()
Call this method to request FA configuration information from the server. The data returns in an XML string via the
receiveFA() event.
Public Overridable Sub requestFA(ByVal faDataType As Integer)
API Reference Guide 119
Chapter3 Active X
Parameter Type Description
faDataType Integer Specifies the type of Financial Advisor configuration data being
requested. Valid values include:
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.
Public Overridable Sub replaceFA(ByVal faDataType As Integer, ByVal cxml As String)
Parameter Type Description
faDataType Integer Specifies the type of Financial Advisor configuration data being modified via
the API. Valid values include:
cxml String The XML string containing the new FA configuration 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().
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)
Parameter Type Description
messageType Integer Set this to 62.
version Integer Set this to 1.
reqId Integer
groupName String Set to All to return account summary data for all accounts, or set to a spe-
cific Advisor Account Group name that has already been created in
TWSGlobal Configuration.
API Reference Guide 120
Chapter3 Active X
Parameter Type Description
tags String A comma-separated list of account tags.
Available tags are:
l AccountType
l NetLiquidation
l TotalCashValue Total cash including futures pnl
l SettledCash For cash accounts, this is the same as Total-
CashValue
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 liq-
uidation
API Reference Guide 121
Chapter3 Active X
Parameter Type Description
l DayTradesRemaining The Number of Open/Close trades a user
could put on before Pattern Day Trading is detected. A value of "-1"
means that the user can put on unlimited day trades.
l Leverage GrossPositionValue / NetLiquidation
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)
Parameter Type Description
messageId Integer Set this to 63.
version Integer Set this to 1.
reqId Integer The ID of the data request being canceled.
reqPositions()
Requests real-time position data for all accounts.
Note: This request can only be made when connected to an FA managed account.
Public Overridable Sub reqPositions(ByVal messageId As Integer, ByVal version As Integer)
Parameter Type Description
messageId Integer Set this to 62
version Integer Set this to 1.
cancelPositions()
Cancels real-time position updates.
Note: This request can only be made when connected to an FA managed account.
Public Overridable Sub cancelPositions(ByVal messageId As Integer, ByVal version As Integer)
Parameter Type Description
messageId Integer Set this to 64.
version Integer Set this to 1.
reqHistoricalDataEx()
Call this method to start receiving historical data results through the historicalData() event.
API Reference Guide 122
Chapter3 Active X
Public Overridable Sub reqHistoricalDataEx(ByVal tickerId As Integer, ByVal contract As TWSLib.IContract,
ByVal endDateTime As String, ByVal duration As String, ByVal barSize As String, ByVal whatToShow As String,
ByVal useRTH As Integer, ByVal formatDate As Integer)
Parameter Type Description
tickerId Integer The Id for the request. Must be a unique value. When the data is
received, it will be identified by this Id. This is also used when can-
celing the historical data request.
contract IContract This structure contains a description of the contract for which market
data is being requested.
endDateTime String Use the format yyyymmdd hh:mm:ss tmz, where the time zone is
allowed (optionally) after a space at the end.
durationStr String This is the time span the request will cover, and is specified using the
format: <integer> <unit>, i.e., 1 D, where valid units are:
l S (seconds)
l D (days)
l W (weeks)
l M (months)
l Y (years)
Note:If no unit is specified, seconds are used. Also, note "years" is
currently limited to one.
barSize String The size of the bars that will be returned (within IB/TWS limits).
Valid values include:
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
API Reference Guide 123
Chapter3 Active X
Parameter Type Description
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 trading 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 completely outside of
the RTH.
formatDate Integer Determines the date format applied to returned bars. Valid values
include:
l 1 - dates applying to bars returned in the format:
yyyymmdd{space}{space}hh:mm:dd
l 2 - dates are returned as a long integer specifying the number of
seconds since 1/1/1970 GMT.
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.
Public Overridable Sub cancelHistoricalData(ByVal tickerId As Integer)
Parameter Type Description
tickerId Integer The ticker ID. Must be a unique value.
reqScannerParameters()
Requests an XML string that describes all possible scanner queries.
Public Overridable Sub reqScannerParameters()
API Reference Guide 124
Chapter3 Active X
reqScannerSubscriptionEx()
Call the reqScannerSubscriptionEX() method to start receiving market scanner results through the scannerDataEx() event.
Public Overridable Sub reqScannerSubscriptionEx(ByVal tickerId As Integer, ByVal subscription As TWSLib.I-
ScannerSubscription)
Parameter Type Description
tickerId Integer The Id for the subscription. Must be a unique value. When
the subscription data is received, it will be identified by
this Id. This is also used when canceling the scanner.
subscription IScannerSubscription Summary of the scanner subscription parameters including
filters.
cancelScannerSubscription()
Public Overridable Sub cancelScannerSubscription(ByVal tickerId As Integer)
Parameter Type Description
tickerId Integer The ticker ID. Must be a unique value.
reqRealTimeBarsEx()
Call the reqRealTimeBarsEx() method to start receiving real time bar results through the realtimeBar()event.
Public Overridable Sub reqRealTimeBarsEx(ByVal tickerId As Integer, ByVal contract As TWSLib.IContract,
ByVal barSize As Integer, ByVal whatToShow As String, ByVal useRTH As Integer)
Parameter Type Description
tickerId Integer The Id for the request. Must be a unique value. When the data is
received, it will be identified by this Id. This is also used when can-
celing the historical data request.
contract IContract This structure contains a description of the contract for which market
data is being requested.
barSize Integer Currently only 5 second bars are supported, if any other value is used,
an exception will be thrown.
whatToShow String Determines the nature of the data extracted. Valid values include:
l TRADES
l BID
l ASK
l MIDPOINT
API Reference Guide 125
Chapter3 Active X
Parameter Type Description
useRTH Integer Regular Trading Hours only. Valid values include:
l 0 = all data available during the time span requested is
returned, including 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
requested is returned, even if the time span falls partially or
completely outside.
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.
Public Overridable Sub cancelRealTimeBars(ByVal tickerId As Integer)
Parameter Type Description
tickerId Integer The ticker ID. Must be a unique value.
createComboLegList()
This factory method is used to create an IComboLegList COM object.
Public Overridable Sub createComboLegList() As TWSLib.IComboLegList
You must use the factory create methods to create the COM objects in this section. For example, the create-
ComboLegList() 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.
Public Overridable Sub createContract() As TWSLib.IContract
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.
Public Overridable Sub createExecutionFilter() As TWSLib.IExecutionFilter
You must use the factory create methods to create the COM objects described in this chapter. The crea-
teExecutionFilter() 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.
API Reference Guide 126
Chapter3 Active X
Public Overridable Sub createOrder() As TWSLib.IOrder
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.
Public Overridable Sub createScannerSubscription() As TWSLib.IScannerSubscription
You must use the factory create methods to create the COM objects described in this chapter. The crea-
teScannerSubscription() method creates an IScannerSubscription object, which contains a summary of the scanner sub-
scription parameters.
createTagValueList
This factory method is used to create ITagValueListand ITagValue objects.
Public Overridable Function createTagValueList() As TWSLib.ITagValueList
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.
Public Overridable Sub createUnderComp() As TWSLib.IScannerSubscription
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)
Parameter Type Description
reqId Integer The ID of the data request.
contract IContract This structure contains a description of the contract for which Reuters
Fundamental data is being requested.
reportType String Identifies the report type, which is one of the following:
l Estimates
l Financial Statements
l Summary
API Reference Guide 127
Chapter3 Active X
cancelFundamentalData()
Call this method to stop receiving Reuters global fundamental data.
Public Overridable Sub cancelFundamentalData(ByVal reqId As Integer)
Parameter Type Description
reqId Integer The ID of the data request.
API Reference Guide 128
Chapter3 Active X
ActiveX Events
ActiveX events receive information from the system and make it available to an application. This section defines the
ActiveX events you can receive via the DTwsEvents interface.
Connection and Server
connectionClosed()
currentTime()
errMsg()
Market Data
tickPrice()
tickSize()
tickOptionComputation()
tickGeneric()
tickString()
tickEFP()
tickSnapshotEnd()
marketDataType()
Orders
orderStatus()
openOrderEx()
nextValidId()
permId()
Account and Portfolio
updateAccountValue()
updatePortfolioEx()
updateAccountTime()
accountDownloadEnd()
News Bulletins
updateNewsBulletin()
Contract Details
contractDetailsEx()
contractDetailsEnd()
bondContractDetails()
Executions
execDetailsEx()
execDetailsEnd()
commissionReport()
Market Depth
updateMktDepth()
updateMktDepthL2()
Financial Advisors
managedAccounts()
receiveFA()
accountSummary()
accountSummaryEnd()
position()
positionEnd()
Historical Data
historicalData()
Market Scanners
scannerParameters()
scannerDataEx()
scannerDataEnd()
Real Time Bars
realtimebar()
Fundamental Data
fundamentalData()
API Reference Guide 129
Chapter3 Active X
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.
Sub currentTime(ByVal time As Integer)
Parameter Typle Description
time Integer 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.
Sub errMsg(ByVal id As Integer, ByVal errorCode As Integer, ByVal errorMsg As String)
Parameter Type Description
id Integer This is the orderId or tickerId of the request that generated the error
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.
Sub tickPrice(ByVal id As Integer, ByVal tickType As Integer, ByVal price As Double,
ByVal canAutoExecute As Integer)
Parameter Type Description
id Integer The ticker ID that was specified previously in the call to
reqMktData()
tickType Integer Specifies the type of price. Possible values are:
l 1 = bid
l 2 = ask
l 4 = last
l 6 = high
l 7 = low
l 9 = close
API Reference Guide 130
Chapter3 Active X
Parameter Type Description
price Double The bid, ask or last price, the daily high, daily low or last day
close, depending on tickType value.
canAutoExecute Integer Specifies whether the price tick is available for automatic
execution. Possible values are:
l 0 = not eligible for automatic execution
l 1 = eligible for automatic execution
tickSize()
This function is called when the market data changes. Sizes are updated immediately with no delay.
Sub tickSize(ByVal id As Integer, ByVal tickType As Integer, ByVal size As Integer)
Parameter Type Description
id Integer The ticker ID that was specified previously in the call to reqMktData()
tickType Integer Specifies the type of price. Possible values are:
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)
Parameter Type Description
id Integer The ticker ID that was specified previously in the call to reqMktData()
tickType Integer Specifies the type of tick. Possible values are:
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 calculated by the TWS option modeler.
optPrice Double The option price.
API Reference Guide 131
Chapter3 Active X
Parameter Type Description
pvDivdend 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.
Sub tickGeneric(ByVal id As Integer, ByVal tickType As Integer, ByVal value As Double)
Parameter Type Description
tickerId Integer The ticker Id that was specified previously in the call to reqMktData()
tickType Integer Specifies the type of tick.
Pass the field value into TickType.getField(int tickType) to retrieve the
field description. For example, a field value of 46 will map to shortable,
etc.
value Double The value of the specified field.
tickString()
This method is called when the market data changes. Values are updated immediately with no delay.
Sub tickString(ByVal id As Integer, ByVal tickType As Integer, ByVal value As String)
Parameter Type Description
tickerId Integer The ticker Id that was specified previously in the call to reqMktData()
tickType Integer Specifies the type of tick.
Pass the field value into TickType.getField(int tickType) to retrieve the
field description. For example, a field value of 45 will map to last-
Timestamp, etc.
value String The value of the specified field.
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 for-
mattedBasisPoints As String, ByVal totalDividends As Double, ByVal holdDays As Integer, ByVal futureExpiry As
String, ByVal dividendImpact As Double, ByVal dividendsToExpiry As Double))
API Reference Guide 132
Chapter3 Active X
Parameter Type Description
tickerId Integer The ticker Id that was specified previously in the call to
reqMktData().
field Integer 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 38
will map to bidEFP, etc.
basisPoints Double Annualized basis points, which is representative of the financing
rate that can be directly compared to broker rates.
formattedBasis
Points
String Annualized basis points as a formatted string that depicts them
in percentage form.
totalDividends Double The total expected dividends.
holdDays Integer 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 handled and there is nothing more to wait for.
This also covers the timeout case.
Sub tickSnapshotEnd(ByVal reqId As Integer)
Parameter Type Descrption
reqID Integer Id of the data request.
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.
Sub marketDataType(ByVal reqId As Integer, type As Integer)
Parameter Type Description
reqId Integer Id of the data request
type Integer 1 for real-time streaming market data or 2 for frozen market data..
API Reference Guide 133
Chapter3 Active X
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 Dou-
ble, 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.
Parameter Type Description
id Integer The order ID that was specified previously in the call to placeOrder()
status String The order status. Possible values include:
l PendingSubmit - indicates that you have transmitted the order,
but have not yet received confirmation that it has been accepted
by the order destination.
l PendingCancel - indicates that you have sent a request to cancel
the order but have not yet received cancel confirmation from the
order destination. At this point, your order is not confirmed can-
celed. You may still receive an execution while your cancellation
request is pending. PendingSubmit and PendingCancel order sta-
tuses are not sent by the system 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 system and that this order has yet to be elected.
The order is held in the 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 destination and is working.
l Cancelled - indicates that the balance of your order has been con-
firmed canceled by the system. This could occur unexpectedly
when the destination has rejected your order.
l Filled - indicates that he order has been completely filled.
l Inactive - indicates that the order has been accepted by the sys-
tem (simulated orders) or an exchange (native orders) but that cur-
rently the order is inactive due to system, exchange or other
issues.
filled Integer Specifies the number of shares that have been executed.
For more information about partial fills, see Order Status for Partial Fills.
API Reference Guide 134
Chapter3 Active X
Parameter Type Description
remaining Integer 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 filledparameter value is greater than zero. Otherwise,
the price parameter will be zero.
permId Integer The id used to identify orders. Remains the same over sessions.
parentId Integer The order ID of the parent order, used for bracket and auto trailing stop
orders.
lastFillPrice Double The last price of the shares that have been executed. Valid only if the
filled parameter value is greater than zero. Otherwise, the price parameter
will be zero.
clientId Integer - The ID of the client who placed the order. Note that application orders
have a fixed clientId and orderId of 0 that distinguishes them from API
orders.
whyHeld String Identifies an order held when TWS is trying to locate shares for a short
sell.
openOrderEx()
This method is called to feed in open orders.
Sub openOrderEx(ByVal orderId As Integer, ByVal contract As TWSLib.IContract, ByVal order As TWSLib.IO-
rder, ByVal orderState As TWSLib.IOrderState)
Parameter Type Description
orderId Integer The order Id assigned by TWS. Used to cancel or update the order.
contract IContract The Contract class attributes describe the contract.
order IOrder The Order class attributes define the details of the order.
orderState IOrderState The orderState attributes include margin and commissions fields for
both pre and post trade data.
nextValidId()
This event is called after a successful connection to TWS.
Sub nextValidId(ByVal id As Integer)
Parameter Type Description
id Integer The next available order ID received from TWS upon connection. Incre-
ment all successive orders by one based on this ID.
API Reference Guide 135
Chapter3 Active X
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.
Sub permId(ByVal id As Integer, ByVal permId As Integer)
Parameter Type Description
id Integer The next available order ID received from TWS upon connection. Incre-
ment all successive orders by one based on this ID.
permId Integer This id will remain the same from session to session
updateAccountValue()
This event updates a single account value.
Sub updateAccountValue(ByVal key As String, ByVal value As String, ByVal curency As String, ByVal account-
Name As String)
API Reference Guide 136
Chapter3 Active X
Parameter Type Description
key String A string that indicates one type of account value. Below are some of
the keys sent by TWS.
l Account Type
l Account Code
l Available Funds
l Buying Power
l CashBalance - Account cash balance
l Currency - Currency string
l updatePortfolioEx DayTradesRemaining - Number of day trades
left
l EquityWithLoanValue - Equity with Loan Value
l Excess Liquidity
l Full Available Funds
l Full Excess Liquidity
l Full Init Margin Req
l Full Maint Margin Req
l Future Option Value
l Futures PNL
l Gross Position Value
l InitMarginReq - Current initial margin requirement
l Leverage
l Look Ahead Available Funds
l Look Ahead Next Change
l Look Ahead Excess Liquidity
l Look Ahead Margin Req
l Look Ahead Maint Margin Req
l LongOptionValue - Long option value
l MaintMarginReq - Current maintenance margin
l NetLiquidation - Net liquidation value
l OptionMarketValue - Option market value
l Realized PNL
l Settled Cash
l ShortOptionValue - Short option value
API Reference Guide 137
Chapter3 Active X
Parameter Type Description
l StockMarketValue - Stock market value
l Total Cash Balance
l Total Cash Value
l UnalteredInitMarginReq - Overnight initial margin requirement
l UnalteredMaintMarginReq - Overnight maintenance margin
requirement
l Unrealized PNL
value String The value associated with the key.
curency String Defines the currency of the value, if the value is a monetary amount.
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.
API Reference Guide 138
Chapter3 Active X
Sub updatePortfolioEx(ByVal contract As TWSLib.IContract, ByVal position As Integer, ByVal marketPrice As
Double, ByVal marketValue As Double, ByVal averageCost As Double, ByVal unrealizedPNL As Double, ByVal
realizedPNL As Double, ByVal accountName As String)
Parameter Type Description
contract IContract This object contains a description of the contract which is being
traded. The exchange field in a contract is not set for portfolio
update.
position Integer This integer indicates the position on the contract. If the position is
0, it means the position has just cleared.
marketPrice Double The 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
(execution price + commission) by the quantity of your position.
unrealizedPNL Double The difference between the current market value of your open posi-
tions 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
Financial Advisor sub-account messages.
updateAccountTime()
This event sends the time at which the account values and portfolio market prices were calculated.
Sub updateAccountTime(ByVal timeStamp As String)
Parameter Type Description
timeStamp String This indicates the last update time of the account information.
accountDownloadEnd()
This event is called after a batch updateAccountValue() and updatePortfolioEx() is sent.
Sub accountDownloadEnd(ByVal accountName As String)
Parameter Type Description
accountName String The name of the account.
updateNewsBulletin()
This event is triggered for each new bulletin if the client has subscribed (i.e. by calling the reqNewsBulletins() method).
API Reference Guide 139
Chapter3 Active X
Sub updateNewsBulletin(ByVal msgId As Short, ByVal msgType As Short, ByVal message As String, ByVal orig-
Exchange As String)
Parameter Type Description
msgId Short The bulletin ID, increments for each new bulletin.
msgType Short Specifies the type of bulletin. Valid values include:
l 1 = Regular IB news bulletin
l 2 = Exchange no longer available for trading.
l 3 = Exchange is available for trading.
message String The bulletins message text.
origExchange String The exchange from which this message originated.
contractDetailsEx()
This event is called only in response to the reqContractDetailsEx() method having been called.
Sub contractDetailsEx(ByVal reqId As Integer, ByVal contractDetails As TWSLib.IContractDetails
Parameter Type Description
reqId Integer The ID of the data request. Ensures that responses are
matched to requests if several requests are in process.
contractDetails IContractDetails This object contains a full description of the contract being
looked up.
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.
Sub contractDetailsEnd(ByVal reqId As Integer)
Parameter Type Description
reqID
Integer
Id of the data request.
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)
API Reference Guide 140
Chapter3 Active X
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)
Parameter Type Description
symbol String The bond symbol.
secType String BOND
cusip String The nine-character bond CUSIP, or 12 character SEDOL.
coupon Double The interest rate used to calculate the amount you will receive
in interest payments over the course of the year.
maturity String The date on which the issuer must repay the face value of the
bond.
issueDate String he date on which the bond was issued.
ratings 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.
bondType String The type of the bond, such as "Corp" for corporate.
couponType String The type of the coupon, such as "FIXED."
convertible Integer Values are: True or False. If true, the bond can be converted to
stock under certain conditions.
callable Integer Values are: True or False. If true, the bond can be called by the
issuer under certain conditions.
putable Integer Values are: True or False. If true, the bond can be sold back to
the issuer under certain conditions.
descAppend String Description string containing further descriptive information
about the bond.
exchange String The exchange on which the BOND trades.
curency String The currency in which the bond trades.
marketName String The market name for this contract.
tradingClass String The trading class name for this contract.
conId Integer The IB contract ID of the bond.
minTick Double The minimum price increment of the bond.
orderTypes String The order types that apply to this bond.
validExchanges String A comma-delimited string of exchanges on which this bond
trades.
API Reference Guide 141
Chapter3 Active X
Parameter Type Description
nextOptionDate String Next option date. Applies only to bonds with embedded
options.
nextOptionType String Next option type. Applies only to bonds with embedded
options.
nextOptionPartial Integer Next option partial. Applies only to bonds with embedded
options (is the next option full or partial?).
notes String Bond notes, if populated for the bond in IBs database.
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.IE-
xecution)
Parameter Type Description
orderId Integer The order Id that was specified previously in the call to placeOrderEx().
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()
Sub execDetailsEnd(ByVal reqId As Integer)
Parameter Type Description
reqID Integer Id of the data request.
commissionReport()
The commissionReport() callback is triggered as follows:
l Immediately after a trade execution
l By calling reqExecutionsEx().
Sub commissionReport(ByVal commissionReport As TWSLib.ICommissionReport)
Parameter Type Description
commissionReport ICommissionReport The structure that contains com-
mission details.
updateMktDepth()
This function is called when the market depth changes.
API Reference Guide 142
Chapter3 Active X
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)
Parameter Type Description
id Integer The ticker ID that was specified previously in the call to reqMktDepth()
position Integer Specifies the row ID of this market depth entry.
operation Integer Identifies how this order should be applied to the market depth. Valid
values are:
l 0 = insert (insert this new order into the row identified by 'posi-
tion')
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 'posi-
tion')
side Integer The side of the book to which this order belongs. Valid values are:
l 0 = ask
l 1 = bid
price Double The order price.
size Integer The order size.
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)
Parameter Type Description
id Integer The ticker ID that was specified previously in the call to
reqMktDepth()
position Integer Specifies the row id of this market depth entry.
marketMaker String Specifies the exchange hosting this order.
API Reference Guide 143
Chapter3 Active X
Parameter Type Description
operation Integer Identifies the how this order should be applied to the market depth.
Valid values are:
l 0 = insert (insert this new order into the row identified by
'position')
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
price Double The order price.
size Integer The order size.
managedAccounts()
This event is fired when a successful connection is made to an account. It is also fired when the reqManagedAccts()
method is invoked.
Sub managedAccounts(ByVal accountsList As String)
Parameter Type Description
accountsList String The comma delimited list of FA-managed accounts.
receiveFA()
This event receives previously requested FA configuration information from TWS.
Sub receiveFA(ByVal faDataType As Integer, ByVal cxml As String)
Parameter Type Description
faDataType Integer Specifies the type of Financial Advisor configuration data being
received from TWS. Valid values include:
l 1 = GROUPS
l 2 = PROFILE
l 3 =ACCOUNT ALIASES
cxml String The XML string containing the previously requested FA configuration
information.
API Reference Guide 144
Chapter3 Active X
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)
Parameter Type Description
messageType Integer Set to 62.
version Integer Set to 1.
requestId Integer The ID of the data request.
account String The account ID.
API Reference Guide 145
Chapter3 Active X
Parameter Type Description
tag String The tag from the data request.
Available tags are:
l AccountType
l TotalCashValue Total cash including futures pnl
l SettledCash For cash accounts, this is the same as Total-
CashValue
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 liq-
uidation
l DayTradesRemaining The Number of Open/Close trades a user
could put on before Pattern Day Trading is detected. A value of "-1"
API Reference Guide 146
Chapter3 Active X
Parameter Type Description
means that the user can put on unlimited day trades.
l Leverage GrossPositionValue / NetLiquidation
value String The value of the tag.
currency String The currency of the tag.
accountSummaryEnd
This method is called once all account summary data for a given request are received.
Sub accountSummaryEnd(ByVal reqId As Integer)
Parameter Type Descrption
reqId Integer The ID of the data request.
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 currencyAs String, By Val
ibLocalSymbol As String, ByVal position As double)
Parameter Type Description
messageId Integer Set to 62.
version Integer Set to 1.
account String The account.
conid Integer Unique contract identifier.
underlying String The symbol of the underlying asset.
securityType String The security type.
expiry String The expiration date.
strike String The strike price.
right String Put or call.
multiplier String The multiplier.
exchange String The exchange.
currency String The currency.
ibLocalSymbol String The local symbol.
position double The position.
API Reference Guide 147
Chapter3 Active X
positionEnd()
This is called once all position data for a given request are received and functions as an end marker for the position()
data.
Sub positionEnd(ByVal reqId As Integer)
Parameter Type Descrption
reqId Integer The ID of the data request.
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)
Parameter Type Description
reqId integer The ticker ID of the request to which this bar is responding.
date String The date-time stamp of the start of the bar. The format is determined by
the reqHistoricalData() formatDate parameter.
open Double The bar opening price.
high Double The high price during the time covered by the bar.
low Double The low price during the time covered by the bar.
close Double The bar closing price.
barCount Integer The bar count.
volume Integer The volume during the time covered by the bar.
WAP Double The weighted average price during the time covered by the bar.
hasGaps Integer Identifies whether or not there are gaps in the data.
scannerParameters()
Sub scannerParameters(ByVal xml As String)
Parameter Type Description
xml String An XML document that describes the valid parameters that a scanner
parameter can have.
scannerDataEx()
This event receives the requested market scanner data results.
Sub scannerDataEx(ByVal reqId As Integer, ByVal rank As Integer, ByVal contractDetails As TWSLib.ICo-
ntractDetails, ByVal distance As String, ByVal benchmark As String, ByVal projection As String, ByVal legsStr As
String)
API Reference Guide 148
Chapter3 Active X
Parameter Type Description
reqId Integer The ID of the request to which this row is responding.
rank Integer The ranking within the response of this bar.
contractDetails IContractDetails This object contains a full description of the contract.
distance String Varies based on query.
benchmark String Varies based on query.
projection String Varies based on query.
legsStr String Describes combo legs when scan is returning EFP.
scannerDataEnd()
This function is called when the snapshot is received and marks the end of one scan.
Sub scannerDataEnd(ByVal reqId As Integer)
Parameter Type Description
reqId Integer The ID of the market data snapshot request being closed by this param-
eter.
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)
Parameter Type Description
reqId Integer The ticker Id of the request to which this bar is responding.
time Integer The date-time stamp of the start of the bar. The format is determined by
the reqHistoricalData() formatDate parameter.
open Double The bar opening price.
high Double The high price during the time covered by the bar.
low Double The low price during the time covered by the bar.
close Double The bar closing price.
volume Integer The volume during the time covered by the bar.
wap Double The weighted average price during the time covered by the bar.
count Integer When TRADES historical data is returned, represents the number of
trades that occurred during the time period the bar covers.
API Reference Guide 149
Chapter3 Active X
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.
Sub fundamentalData(ByVal reqId As Integer, ByVal data As String)
Parameter Type Description
reqId Integer The ID of the data request.
data String One of three XML reports:
l Estimates (estimates)
l Financial statements (finstat)
l Summary (snapshot)
API Reference Guide 150
Chapter3 Active X
ActiveX COM Objects
The tables below define properties for the following objects:
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
created 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. Includes commissions.
clientId() As Integer The id of the client that placed the order.
Note: TWS orders have a fixed
client id of "0."
cumQty() As Integer Cumulative quantity. Used in regular trades, combo
trades and legs of the combo.
exchange() As String Exchange that executed the order.
execId() As String Unique order execution id.
liquidation() As Integer Identifies the position as one to be liquidated last
should the need arise.
API Reference Guide 151
Chapter3 Active X
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 Finan-
cial 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.
Note: Refer to the Contract object
for the list of valid security
types.
API Reference Guide 152
Chapter3 Active X
Attribute Description
side() As String Filter the results of the reqExecutionsEx() method based
on the order action.
Note: Refer to the Order object for
the list of valid order actions.
symbol() As String Filter the results of the reqExecutionsEx() method based
on the order symbol.
time() As String Filter the results of the reqExecutionsEx() method based
on execution reports received after the specified time. The
format for timeFilter is "yyyymmdd-hh:mm:ss"
ICommissionReport
Attribute Description
commission() As Double The commission amount.
currency() As String The currency.
execId() As String Unique order execution id.
realizedPNL() As Double The amount of realized Profit and Loss.
yield() As Double The yield.
yieldRedemptionDate() As Double Takes the YYYYMMDD format.
IContract
Attribute Description
comboLegs() As Object Dynamic memory structure used to store the leg def-
initions 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 spec-
ify the currency.
exchange() As String The order destination, such as Smart.
expiry() As String The expiration date. Use the format YYYYMM.
API Reference Guide 153
Chapter3 Active X
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 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.
Exa
secType() As String This is the security type. Valid values 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.
API Reference Guide 154
Chapter3 Active X
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 prod-
uct. 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.
API Reference Guide 155
Chapter3 Active X
Attribute Description
evRule() As String Contains the Economic Value Rule name and the respec-
tive 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.
couponType() As String The type of bond coupon, such as "FIXED."
cusip() As String The nine-character bond CUSIP or the 12-character
SEDOL.
descAppend() As String A description string containing further descriptive infor-
mation about the bond.
issueDate() As String The date the bond was issued.
maturity() As String The date on which the issuer must repay the face value
of the bond.
nextOptionDate)_ As String Applies to bonds with embedded options.
nextOptionPartial() As Integer Applies to bonds with embedded options.
nextOptionType() As String Applies to bonds with embedded options.
notes() As String If populated for the bond in IB's database
putable() As Integer Values are True or False. If true, the bond can be sold
back to the issuer under certain conditions.
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.
API Reference Guide 156
Chapter3 Active X
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.
For Short Sale Stock Legs
designatedLocation() As String If shortSaleSlot == 2, the designatedLocation must be specified.
Otherwise leave blank or orders will be rejected.
shortSaleSlot() Integer For institutional customers only.
l 0 - inapplicable (i.e. retail customer or not short leg)
l 1 - clearing broker
l 2 - third party. If this value is used, you must enter a designated
location.
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.
API Reference Guide 157
Chapter3 Active X
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 spec-
ify zero.
orderType() As String Identifies the order type.
For more information about supported order types,
see Supported Order Types.
totalQuantity() As Integer The order quantity.
Extended Order Fields
allOrNone() As Integer 0 = no, 1 = yes
blockOrder() As Integer Specifies that the order is an ISE Block order.
displaySize() As Integer The publicly disclosed order size, used when plac-
ing Iceberg orders.
goodAfterTime() As String The trade's "Good After Time," format
"YYYYMMDD hh:mm:ss (optional time zone)"
Use an empty String if not applicable.
goodTillDate() As String You must enter GTD as the time in force to use
this string. The trade's "Good Till Date," format
"YYYYMMDD hh:mm:ss (optional time zone)"
Use an empty String if not applicable.
hidden() As Integer Specifies that the order will not be visible when
viewing the market depth. This option only
applies to orders routed to the ISLAND exchange.
minQty() As Integer Identifies a minimum quantity order type.
ocaGroup() As String Identifies an OCA (one cancels all) group.
API Reference Guide 158
Chapter3 Active X
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 1 = Cancel all remaining orders with
block
l 2 = Remaining orders are proportionately
reduced in size with block
l 3 = Remaining orders are proportionately
reduced in size with no block
If you use a value "with block" gives your order
has overfill protection. This means that only one
order in the group will be routed at a time to
remove the possibility of an overfill.
orderRef() As String The order reference. Intended for institutional cus-
tomers only, although all customers may use it to
identify the API client that sent the order when
multiple API clients are running.
outsideRth() As Integer Specifies whether orders can trigger or fill outside
of regular trading hours or not.
overridePercentageConstraints() As
Integer
Precautionary constraints are defined on the
TWS Presets page, and help ensure tha tyour
price and size order values are reasonable. Orders
sent from the API are also validated against
these safety constraints, and may be rejected if
any constraint is violated. To override val-
idation, set this parameters value to True.
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.
API Reference Guide 159
Chapter3 Active X
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:
l 0 - The default value. The "double
bid/ask" function will be used for orders
for OTC stocks and US options. All other
orders will used the "last" function.
l 1 - use "double bid/ask" function, where
stop orders are triggered based on two con-
secutive bid or ask prices.
l 2 - "last" function, where stop orders are
triggered based on the last price.
l 3 double last function.
l 4 bid/ask function.
l 7 last or bid/ask function.
l 8 mid-point function.
trailStopPrice() As Double For TRAILLIMIT orders only
API Reference Guide 160
Chapter3 Active X
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:
l This field is mutually exclusive with the
existing trailing amount. That is, the API
client can send one or the other but not
both.
l This field is read AFTER the stop price
(barrier price) as follows: del-
taNeutralAuxPrice
stopPrice
trailingPercent
scale order attributes
l The field will also be sent to the API in
the openOrder message if the API client
version is >= 56. It is sent after the stop-
Price field as follows:
stopPrice
trailingPct
basisPoint
activeStartTime As String For GTCorders.
activeStopTime As String For GTCorders.
Financial Advisor Fields
faGroup() As String The Financial Advisor group the trade will be
allocated to -- use an empty String if not appli-
cable.
faMethod() As String The Financial Advisor allocation function the
trade will be allocated with -- use an empty
String if not applicable.
faPercentage() As String The Financial Advisor percentage concerning the
trade's allocation-- use an empty String if not
applicable.
faProfile() As String The Financial Advisor allocation profile the trade
will be allocated to -- use an empty String if not
applicable.
Institutional (non-cleared) Only
designatedLocation() As String Used only when shortSaleSlot = 2.
openClose() As String For institutional customers only. Valid values are
O, C.
API Reference Guide 161
Chapter3 Active X
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.
SMARTRouting 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
directly to ASX orders WILL use SmartRouting.
notHeld() As Integer For IBDARKorders 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.
BOXor VOL Orders Only
auctionStrategy() As Integer Values include:
l match = 1
l improvement = 2
l transparent = 3
For orders on BOX only.
BOXExchange 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
API Reference Guide 162
Chapter3 Active X
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 deltaNeutralOrderTypefield 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.
API Reference Guide 163
Chapter3 Active X
Attribute Description
deltaNeutralShortSale () As Integer Used when the hedge involves a stock and indi-
cates whether or not it is sold short.
deltaNeutralShortSaleSlot() As Integer 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 del-
taNeutralDesignatedLocation.
deltaNeutralDesignatedLocation() As
String
Used only when deltaNeutralShortSaleSlot = 2.
Combo Orders Only
basisPoints() As Double For EFP orders only
basisPointsType() As Integer For EFP orders only
Scale Orders Only
scaleAutoReset() As Integer For extended Scale orders.
scaleInitFillQty() As Integer For extended Scale orders.
scaleInitLevelSize() As Integer For Scale orders: Defines the size of the first, or
initial, order component.
scaleInitPosition() As Integer For extended Scale orders.
scalePriceIncrement() As Double For Scale orders: Defines the price increment
between scale components. This field is required.
scalePriceAdjustInterval() As Integer For extended Scale orders.
scalePriceAdjustValue() As Double For extended Scale orders.
scaleProfitOffset() As Double For extended Scale orders.
scaleRandomPercent() 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.
Hedge Orders Only
API Reference Guide 164
Chapter3 Active X
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 ben-
eficiary 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.
algoParams() As Object Support for 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.
Order Combo Legs
OrderComboLegs() As Object Holds attributes for all legs in a combo order.
API Reference Guide 165
Chapter3 Active X
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.
couponRateAbove() As String Filter out contracts with a coupon rate lower
than this value. Can be left blank.
couponRateBelow() As String Filter out contracts with a coupon rate higher
than this value. Can be left blank.
excludeConvertible() As Integer Filter out convertible bonds. Can be left
blank.
instrument() As String Defines the instrument type for the scan.
locations() As String The location.
marketCapAbove() As Double Filter out contracts with a market cap lower
than this value. Can be left blank.
API Reference Guide 166
Chapter3 Active X
Attribute Description
marketCapBelow() As Double Filter out contracts with a market cap above
this value. Can be left blank.
maturityDateAbove() As String Filter out contracts with a maturity date ear-
lier than this value. Can be left blank.
maturityDateBelow() As String Filter out contracts with a maturity date later
than this value. Can be left blank.
moodyRatingAbove() As String Filter out contracts with a Moody rating
below this value. Can be left blank.
moodyRatingBelow() As String Filter out contracts with a Moody rating
above this value. Can be left blank.
numberOfRows() As Integer Defines the number of rows of data to return
for a query.
priceAbove() As Double Filter out contracts with a price lower than
this value. Can be left blank.
priceBelow() As Double Filter out contracts with a price higher than
this value. Can be left blank.
scanCode() As String Can be left blank.
scannerSettingPairs() As String Can leave empty. For example, a pairing
"Annual, true" used on the "top Option
Implied Vol % Gainers" scan would return
annualized volatilities.
spRatingAbove() As String Filter out contracts with an S&P rating below
this value. Can be left blank.
spRatingBelow() As String Filter out contracts with an S&P rating above
this value. Can be left blank.
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.
API Reference Guide 167
Chapter3 Active X
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.
API Reference Guide 168
Chapter3 Active X
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.
API Reference Guide 169
Chapter3 Active X
Placing a Combination Order
A combination order is a special type of order that is constructed of many separate legs but executed as a single trans-
action. Submit combo orders such as calendar spreads, conversions and straddles using the BAG security type (defined in
the Contractobject). The key to implementing a successful API combination order using the API is to knowing how to
place the same order using Trader Workstation. If you are familiar with placing combination orders in TWS, then it will
be easier to place the same order using the API, because the API only imitates the behavior of TWS.
Example
In this example, a customer places a BUY order on a calendar spread for GOOG. To buy one calendar spread means:
Leg 1: Sell 1 GOOG OPT SEP 18 '09 150.0 CALL (100)
Leg 2: Buy 1 GOOG OPT JAN 21 '11 150.0 CALL (100)
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.
To place this combo order
1. Get the Contract IDs for both leg definitions:
'First Leg
Dim con1 As TWSLib.IContract
con1 = Tws1.createContract
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"
API Reference Guide 170
Chapter3 Active X
con2.currency = "USD"
Tws1.reqContractDetailsEx(2, con2)
'All conId numbers are delivered by the ContractDetail()
Private Sub Tws1_contractDetailsEx(ByVal sender As Object, ByVal e As AxTW-
SLib._DTwsEvents_contractDetailsExEvent) Handles Tws1.contractDetailsEx
Dim contractDetails As TWSLib.IContractDetails
contractDetails = e.contractDetails
Dim contract As TWSLib.IContract
contract = contractDetails.summary
'reqId = 1 is corresponding to the first request or first leg
'reqId = 2 is corresponding to the second request or second leg
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
'First Combo leg
Dim Leg1 As TWSLib.IComboLeg
Leg1 = addAllLegs.Add()
Leg1.conId = leg1_conId
Leg1.ratio = 1
Leg1.action = "SELL"
Leg1.exchange = "SMART"
Leg1.openClose = 0
Leg1.shortSaleSlot = 0
Leg1.designatedLocation = ""
' Second Combo leg
Dim Leg2 As TWSLib.IComboLeg
Leg2 = addAllLegs.Add()
Leg1.conId = leg2_conId
Leg1.ratio = 1
Leg1.action = "BUY"
Leg1.exchange = "SMART"
Leg1.openClose = 0
API Reference Guide 171
Chapter3 Active X
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
Dim order As TWSLib.IOrder
order = Tws1.createOrder
order.action = "BUY"
order.totalQuantity = 1
order.orderType = "MKT"
Tws1.placeOrderEx(OrderId, contract, order)
API Reference Guide 172
C++
This chapter describes the C++ API, including the following topics:
l Class EClientSocket Functions
l Class EWrapper Functions
l SocketClient Properties
l Placing a Combination Order
API Reference Guide 173
4
Chapter4 C++
Class EClientSocket Functions
The list below define the class EClientSocket functions you can use when connecting to TWS. The list of functions
includes:
Connection and Server
EClientSocket()
eConnect()
eDisconnect()
isConnected()
reqCurrentTime()
serverVersion()
TwsConnectionTime()
setLogLevel()
checkMessages()
Market Data
reqMktData()
cancelMktData()
calculateImpliedVolatility()
cancelCalculateImpliedVolatility()
calculateOptionPrice()
cancelCalculateOptionPrice()
reqMarketDataType()
Orders
placeOrder()
cancelOrder()
reqOpenOrders()
reqAllOpenOrders()
reqAutoOpenOrders()
reqIDs()
exerciseOptions()
reqGlobalCancel()
Account
reqAccountUpdates()
Executions
reqExecutions()
Contract Details
reqContractDetails()
Market Depth
reqMktDepth()
cancelMktDepth()
News Bulletins
reqNewsBulletins()
cancelNewsBulletins()
Financial Advisors
reqManagedAccts()
requestFA()
replaceFA()
reqAccountSummary()
cancelAccountSummary()
reqPositions()
cancelPositions()
Historical Data
reqHistoricalData()
cancelHistoricalData()
Market Scanners
reqScannerParameters()
reqScannerSubscription()
cancelScannerSubscription()
Real Time Bars
reqRealTimeBars()
cancelRealTimeBars()
Fundamental Data
reqFundamentalData()
cancelFundamentalData()
API Reference Guide 174
Chapter4 C++
EClientSocket()
This is the constructor.
EClientSocket( EWrapper *ptr)
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."
bool eConnect( const char *host, UINT port, int clientId=0)
Parameter Type Description
host const The host name or IP address of the
machine where TWS is running. Leave
blank to connect to the local host.
port UINT Must match the port specified in TWS on
the Configure>API>Socket Port field.
clientId int A number used to identify this client con-
nection. All orders placed/modified from
this client will be associated with this
client identifier.
Note: Each client MUST connect with a
unique clientId.
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()
API Reference Guide 175
Chapter4 C++
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.
void setLogLevel(int logLevel)
Parameter Type Description
logLevel int Specifies the level of log entry
detail used by the server (TWS)
when processing API requests.
Valid values include:
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)
Parameter Type Description
id TickerId The ticker id. Must be a unique value.
When the market data returns, it will be
identified by this tag. This is also used
when canceling the market data.
contract Contract This structure contains a description of the
contract for which market data is being
requested.
API Reference Guide 176
Chapter4 C++
Parameter Type Description
genericTicks IBString A comma delimited list of generic tick
types. Tick types can be found in the
Generic Tick Types page.
snapshot bool Check to return a single snapshot of market
data and have the market data subscription
cancel. Do not enter any genericTicklist
values if you use snapshot.
cancelMktData()
After calling this function, market data for the specified id will stop flowing.
void cancelMktData(TickerId id)
Parameter Type Description
id TickerId The ID that was specified in the call to
reqMktData().
calculateImpliedVolatility()
Call this function to calculate volatility for a supplied option price and underlying price.
void calculateImpliedVolatility(TickerId reqId, Contract &contract, double optionPrice, double underPrice)
Parameter Type Description
reqId TickerId (long) The ticker id.
contract Contract Describes the contract.
optionPrice double The price of the option.
underPrice double Price of the underlying.
cancelCalculateImpliedVolatility()
Call this function to cancel a request to calculate volatility for a supplied option price and underlying price.
calculateImpliedVolatility(TickerId reqId)
Parameter Type Description
id TickerId The ticker ID.
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)
API Reference Guide 177
Chapter4 C++
Parameter Type Description
reqId TickerId The ticker ID.
contract Contract Describes the contract.
volatility double The volatility.
underPrice double Price of the underlying.
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)
Parameter Type Description
reqId TickerId The ticker id.
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)
Parameter Type Description
marketDataType int 1 for real-time streaming market data or 2 for frozen market data.
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)
Parameter Type Description
id OrderId The order id. You must specify a unique value.
When the order status returns, it will be identified
by this tag. This tag is also used when canceling
the order.
contract Contract This structure contains a description of the con-
tract which is being traded.
order Order This structure contains the details of the order.
Note: Each client MUST connect with a unique
clientId.
API Reference Guide 178
Chapter4 C++
cancelOrder()
Call this function to cancel an order.
void cancelOrder(OrderId id)
Parameter Type Description
id
OrderId
The order ID that was specified pre-
viously in the call to placeOrder()
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.
reqAutoOpenOrders (bool bAutoBind)
Note: This request can only be made from a client with clientId of 0.
Parameter Type Description
bAutoBind bool If set to TRUE, newly created TWS orders will
be implicitly associated with the client. If set to
FALSE, no association will be made.
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).
void reqIds(int numIds)
API Reference Guide 179
Chapter4 C++
Parameter Type Description
numIds int The number of ids you want to reserve.
exerciseOptions()
void exerciseOptions(TickerId id, const Contract &contract, int exerciseAction, int exerciseQuantity, const IBString
&account, int override)
Parameter Type Description
id TickerId The ticker id. Must be a unique value.
contract Contract This structure contains a description of the con-
tract for which market depth data is being
requested.
exerciseAction int Specifies whether you want the option to lapse
or be exercised. Values are 1 = exercise, 2 =
lapse.
exerciseQuantity int The quantity you want to exercise.
account IBString 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
exercise. If you have override set to "yes" the
natural action would be overridden and the out-
of-the money option would be exercised.
Values are: 0 = no, 1 = yes.
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.
void reqAccountUpdates(bool subscribe, const IBString& acctCode)
Parameter Type Description
subscribe bool If set to TRUE, the client will start receiving
account and portfolio updates. If set to FALSE,
the client will stop receiving this information.
acctCode IBString The account code for which to receive account
and portfolio updates.
API Reference Guide 180
Chapter4 C++
reqExecutions()
When this function is called, the execution reports that meet the filter criteria are downloaded to the client via the exec-
Details() 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.
void reqExecutions(int reqID, const ExecutionFilter& filter)
Parameter Type Description
reqId int The ID of the data request. Ensures that
responses are matched to requests if several
requests are in process.
filter ExecutionFilter This object contains attributes that describe
the filter criteria used to determine which
execution reports are returned.
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.
void reqContractDetails (int reqId, const Contract &contract)
Parameter Type Description
reqId int The ID of the data request. Ensures that responses
are matched to requests if several requests are in
process.
Contract Contract The summary description of the contract being
looked up.
reqMktDepth()
Call this function to request market depth for a specific contract. The market depth will be returned by the upda-
teMktDepth() and updateMktDepthL2() events.
void reqMktDepth (TickerID id, const Contract &contract, int numRows)
Parameter Type Description
id TickerId The ticker id. Must be a unique value. When
the market depth data returns, it will be iden-
tified by this tag. This is also used when can-
celing the market depth
contract Contact This structure contains a description of the con-
tract for which market depth data is being
requested.
numRows int Specifies the number of market depth rows to
display.
API Reference Guide 181
Chapter4 C++
cancelMktDepth()
After calling this function, market depth data for the specified id will stop flowing.
void cancelMktDepth (TickerId id)
Parameter Type Description
id TickerId The ID that was specified in the call to
reqMktDepth().
reqNewsBulletins()
Call this function to start receiving news bulletins. Each bulletin will be returned by the updatedNewsBulletin() event.
void reqNewsBulletins(bool allMsgs)
Parameter Type Description
allMsgs bool If set to TRUE, returns all the existing bulletins for
the current day and any new ones. If set to FALSE,
will only return new bulletins.
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)
Parameter Type Description
faDataType faDataType Specifies the type of Financial Advisor con-
figuration data being requested. Valid
values include:
l 1 = GROUPS
l 2 = PROFILE
l 3 = ACCOUNT ALIASES
API Reference Guide 182
Chapter4 C++
replaceFA()
Call this function to modify FA configuration information from the API. Note that this can also be done manually in
TWS itself.
replaceFA(faDataType faDataType, const IBString& cxml)
Parameter Type Description
faDataType faDataType Specifies the type of Financial Advisor con-
figuration data being modified via the API. Valid
values include:
l 1 = GROUPS
l 2 = PROFILE
l 3 =ACCOUNT ALIASES
cxml IBString 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().
Note: This request can only be made when connected to an FA managed account.
void reqAccountSummary(int reqID, const IBString& groupName, const IBString& tags)
Parameter Type Description
reqId int The ID of the data request. Ensures that responses are matched to
requests if several requests are in process.
groupName IBString Set to All to return account summary data for all accounts, or set to a
specific Advisor Account Group name that has already been created
in TWSGlobal Configuration.
API Reference Guide 183
Chapter4 C++
Parameter Type Description
tags IBString A comma-separated list of account tags.
Available tags are:
l AccountType
l NetLiquidation,
l TotalCashValue Total cash including futures pnl
l SettledCash For cash accounts, this is the same as Total-
CashValue
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,
API Reference Guide 184
Chapter4 C++
Parameter Type Description
l HighestSeverity A measure of how close the account is to
liquidation
l DayTradesRemaining The Number of Open/Close trades a
user could put on before Pattern Day Trading is detected. A
value of "-1" means that the user can put on unlimited day
trades.
l Leverage GrossPositionValue / NetLiquidation
cancelAccountSummary()
Cancels the request for Account Window Summary tab data.
void cancelAccountSummary(int reqId)
Parameter Type Description
reqId int The ID of the data request being canceled.
reqPositions()
Requests real-time position data for all accounts.
Note: This request can only be made when connected to an FA managed account.
void reqPositions()
cancelPositions()
Cancels real-time position updates.
void cancelPositions()
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)
Parameter Type Description
id TickerId The id of the request. Must be a unique value. When the market
data returns, it will be identified by this tag. This is also used
when canceling the market data.
contract Contract This object contains a description of the contract for which mar-
ket data is being requested.
API Reference Guide 185
Chapter4 C++
Parameter Type Description
endDateTime IBString Defines a query end date and time at any point during the past
6 mos. Valid values include any date/time within the past six
months in the format: yyyymmdd HH:mm:ss ttt
where "ttt" is the optional time zone.
durationStr IBString Set the query duration up to one week, using a time unit of sec-
onds, days or weeks. Valid values include any integer followed
by a space and then S (seconds), D (days) or W (week). If no unit
is specified, seconds is used.
barSizeSetting IBString Specifies the size of the bars that will be returned (within IB/TWS
limits). Valid 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 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
API Reference Guide 186
Chapter4 C++
Parameter Type Description
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:
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.
formatDate int Determines the date format applied to returned bars. Valid values
include:
l 1 - dates applying to bars returned in the format:
yyyymmdd{space}{space}hh:mm:dd
l 2 - dates are returned as a long integer specifying the
number of seconds since 1/1/1970 GMT.
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.
void cancelHistoricalData (TickerId tickerId)
Parameter Type Description
tickerId TickerId The ticker ID. Must be a unique value.
reqScannerParameters()
Requests an XML string that describes all possible scanner queries.
void reqScannerParameters()
reqScannerSubscription()
void reqScannerSubscription(int tickerId, const ScannerSubscription &subscription)
Parameter Type Description
tickerId int The ticker ID. Must be a unique
value.
ScannerSubscription ScannerSubscription This structure contains possible
parameters used to filter results.
cancelScannerSubscription()
void cancelScannerSubscription(int tickerId)
API Reference Guide 187
Chapter4 C++
Parameter Type Description
tickerId int The ticker ID. Must be a unique value.
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)
Parameter Type Description
id TickerId The Id for the request. Must be a unique value.
When the data is received, it will be identified by
this Id. This is also used when canceling the
request.
contract Contract This object contains a description of the contract
for which real time bars are being requested
barSize int Currently only 5 second bars are supported, if any
other value is used, an exception will be thrown.
whatToShow IBString Determines the nature of the data extracted. Valid
values include:
l TRADES
l BID
l ASK
l MIDPOINT
useRTH bool Regular Trading Hours only. Valid values include:
l 0 = all data available during the time span
requested is returned, including time inter-
vals when the market in question was out-
side of regular trading hours.
l 1 = only data within the regular trading
hours for the product requested is returned,
even if the time time span falls partially or
completely outside.
cancelRealTimeBars()
Call the cancelRealTimeBars() function to stop receiving real time bar results.
void cancelRealTimeBars (TickerId tickerId)
Parameter Type Description
tickerId TickerId The Id that was specified in the call to reqRealTimeBars().
API Reference Guide 188
Chapter4 C++
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.
void reqFundamentalData(TickerId reqId, const Contract &contract, const IBString& reportType)
Parameter Type Description
reqId TickerId The ID of the data request. Ensures that responses
are matched to requests if several requests are in
process.
contract Contract This structure contains a description of the con-
tract for which Reuters Fundamental data is being
requested.
reportType IBString Identifies the report type, which is one of the fol-
lowing:
l Estimates
l Financial Statements
l Summary
cancelFundamentalData()
Call this function to stop receiving Reuters global fundamental data.
void cancelFundamentalData(TickerId reqId)
Parameter Type Description
reqId TickerId The ID of the data request.
API Reference Guide 189
Chapter4 C++
Class EWrapper Functions
The tables below define the class EWrapper functions you can use when connecting to TWS. These functions receive
events from TWS.The list of functions includes:
Connection and Server
winError()
error()
connectionClosed()
currentTime()
Market Data
tickPrice()
tickSize()
tickOptionComputation()
tickGeneric()
tickString()
tickEFP()
tickSnapshotEnd()
marketDataType()
Orders
orderStatus()
openOrder()
nextValidId()
Account and Portfolio
updateAccountValue()
updatePortfolio()
updateAccountTime()
accountDownloadEnd()
News Bulletins
updateNewsBulletin()
Contract Details
contractDetails()
contractDetailsEnd()
bondContractDetails()
Executions
execDetails()
execDetailsEnd()
commissionReport()
Market Depth
updateMktDepth()
updateMktDepthL2()
Financial Advisors
managedAccounts()
receiveFA()
accountSummary()
accountSummaryEnd()
position()
positionEnd()
Historical Data
historicalData()
Market Scanners
scannerParameters()
scannerData()
scannerDataEnd()
Real Time Bars
realtimeBar()
Fundamental Data
fundamentalData()
API Reference Guide 190
Chapter4 C++
winError()
This event is called when there is an error on the client side.
virtual void winError(const IBString &str, int lastError)
Parameter Type Description
str IBString This is the error message text.
lastError int The error code returned by GetLastError().
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)
Parameter Type Description
Parameter Description
id int This is the orderId or tickerId of the
request that generated the error.
errorCode int Error codes are documented in the API
Message Codes topic.
errorString IBString This is the textual description of the
error, also documented in the Error Codes
topic.
connectionClosed()
This function is called when TWS closes the sockets connection with the ActiveX control, or when TWS is shut down.
virtual void connectionClosed()
currentTime()
This function receives the current system time on the server side.
virtual void currentTime(long time)
Parameter Type Description
time long 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)
API Reference Guide 191
Chapter4 C++
Parameter Type Description
id TickerId The ticker ID that was specified previously in the call to
reqMktData()
tickType TickeType Specifies the type of price. Possible values are:
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
execution. Possible values are:
l 0 = not eligible for automatic execution
l 1 = eligible for automatic execution
tickSize()
This function is called when the market data changes. Sizes are updated immediately with no delay.
virtual void tickSize(TickerId TickerId, TickType tickType, int size)
Parameter Type Description
id TickerId The ticker ID that was specified previously in the call to
reqMktData()
tickType TickType Specifies the type of size. Possible values are:
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. TWSs option model volatilities, prices, and
deltas, along with the present value of dividends expected on that options underlier are received.
API Reference Guide 192
Chapter4 C++
virtual void tickOptionComputation(TickerID tickerId, TickType tickType, double impliedVol, double delta, double
optPrice, double pvDividend, double gamma, double vega, double theta, double undPrice)
Parameter Type Description
id TickerId The ticker ID that was specified previously in the call to reqMktData()
tickType TickType Specifies the type of tick. Possible values are:
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.
virtual void tickGeneric(TickerId tickerId, TickType tickType, double value)
Parameter Type Description
tickerId TickerId The ticker Id that was specified previously in the call to
reqMktData().
tickType TickType 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 46
will map to shortable, etc.
value double The value of the specified field.
tickString()
This function is called when the market data changes. Values are updated immediately with no delay.
virtual void tickString(TickerId tickerId, TickType tickType, const IBString& value)
API Reference Guide 193
Chapter4 C++
Parameter Type Description
tickerId TickerId The ticker Id that was specified previously in the call to reqMktData().
field TickType 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 45 will map to last-
Timestamp, etc.
value IBString The value of the specified field.
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& for-
mattedBasisPoints, double totalDividends, int holdDays, const IBString& futureExpiry, double dividendImpact, dou-
ble dividendsToExpiry)
Parameter Type Description
tickerId TickerId The ticker Id that was specified previously in the call to
reqMktData()
field TickType 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 38
will map to bidEFP, etc.
basisPoints double Annualized basis points, which is representative of the financ-
ing rate that can be directly compared to broker rates.
formattedBasisPoints IBString Annualized basis points as a formatted string that depicts them
in percentage form.
impliedFuture double Implied futures price.
holdDays int Number of hold days until the expiry of the EFP.
futureExpiry IBString 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 handled and there is nothing more to wait for.
This also covers the timeout case.
virtual void tickSnapshotEnd(int reqId)
Parameter Type Description
reqID int Id of the data request.
API Reference Guide 194
Chapter4 C++
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.
virtual void marketDataType(TickerId reqId, int marketDataType)
Parameter Type Description
reqId TickerId ID of the data request
marketDataType int 1 for real-time streaming market data or 2 for frozen market data..
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.
Parameter Type Description
id OrderId The order ID that was specified previously in the call to placeOrder()
API Reference Guide 195
Chapter4 C++
Parameter Type Description
status IBString The order status. Possible values include:
l PendingSubmit - indicates that you have transmitted the
order, but have not yet received confirmation that it has been
accepted by the order destination. 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 can-
cel the order but have not yet received cancel confirmation
from the order destination. 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 destination and is working.
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 (simulated 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 param-
eter is valid only if the filledparameter 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.
API Reference Guide 196
Chapter4 C++
Parameter Type Description
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. Other-
wise, the price parameter will be zero.
clientId int The ID of the client (or TWS) that placed the order. Note that TWS
orders have a fixed clientId and orderId of 0 that distinguishes them
from API orders.
whyHeld IBString 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 function is called to feed in open orders.
virtual void openOrder(OrderId orderId, const Contract&, const Order&, const OrderState&)
For more information, see Extended Order Attributes.
Parameter Type Description
orderID
OrderId
The order ID assigned by TWS. Use to cancel or update the order.
contract
Contract
The Contract class attributes describe the contract.
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.
nextValidId()
This function is called after a successful connection to TWS.
virtual void nextValidId(OrderId orderId)
Parameter Type Description
orderId OrderId The next available order ID received from TWS upon connection. Incre-
ment all successive orders by one based on this ID.
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)
API Reference Guide 197
Chapter4 C++
Parameter Type Description
key IBString A string that indicates one type of account value. Below is a set of keys
sent by TWS.
l CashBalance - Account cash balance
l Currency - Currency string
l DayTradesRemaining - Number of day trades left
l EquityWithLoanValue - Equity with Loan Value
l InitMarginReq - Current initial margin requirement
l LongOptionValue - Long option value
l MaintMarginReq - Current maintenance margin
l NetLiquidation - Net liquidation value
l OptionMarketValue - Option market value
l ShortOptionValue - Short option value
l StockMarketValue - Stock market value
l UnalteredInitMarginReq - Overnight initial margin requirement
l UnalteredMaintMarginReq - Overnight maintenance margin require-
ment
value IBString The value associated with the key.
currency IBString Defines the currency type, in case the value is a currency type.
account IBString States the account to which the message applies. Useful for Financial
Advisor sub-account messages.
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)
Parameter Type Description
contract Contract This structure contains a description of the contract which is being
traded. The exchange field in a contract is not set for portfolio update.
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.
API Reference Guide 198
Chapter4 C++
Parameter Type Description
averageCost double The average cost per share is calculated by dividing your cost
(execution 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.
virtual void updateAccountTime(const IBString& timeStamp)
Parameter Type Description
timeStamp IBString This indicates the last update time of the account information.
accountDownloadEnd()
This is called after a batch updateAccountValue() and updatePortfolio() is sent.
virtual void accountDownloadEnd(const IBString& accountName)
Parameter Type Description
accountName IBString The name of the account.
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
Parameter Type Description
msgId int The bulletin ID, incrementing for each new bulletin.
msgType int Specifies the type of bulletin. Valid values include:
l 1 = Regular news bulletin
l 2 = Exchange no longer available for trading
l 3 = Exchange is available for trading
message IBString The bulletin's message text.
origExch IBString The exchange from which this message originated.
API Reference Guide 199
Chapter4 C++
contractDetails()
This function is called only when reqContractDetails function on the EClientSocket object has been called.
virtual void contractDetails(int reqId, const ContractDetails &contractDetails)
Parameter Type Description
reqId int The ID of the data request. Ensures that responses are
matched to requests if several requests are in process.
contractDetails ContractDetails This structure contains a full description of the contract
being looked up.
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.
void contractDetailsEnd(int reqId)
Parameter Type Description
reqID int The ID of the data request.
bondContractDetails()
This function is called only when reqContractDetails function on the EClientSocket object has been called for bonds.
virtual void bondContractDetails(int reqId, const ContractDetails& contractDetails)
Parameter Type Description
reqId int The ID of the data request.
contractDetails ContractDetails This structure contains a description of the contract which is
being traded. The exchange field in a contract is not set for
portfolio update.
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)
Parameter Type Description
reqId int The ID of the data request.
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().
API Reference Guide 200
Chapter4 C++
virtual void execDetailsEnd(int reqId)
Parameter Type Description
reqID
int
The Id of the data request.
commissionReport()
The commissionReport() callback is triggered as follows:
l Immediately after a trade execution
l By calling reqExecutions().
virtual void commissionReport(const CommissionReport &commissionReport)
Parameter Type Description
commissionReport CommissionReport The structure that contains com-
mission details.
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)
Parameter Type Description
id TickerId The ticker ID that was specified previously in the call to reqMktDepth()
position int Specifies the row id of this market depth entry.
operation int Identifies the how this order should be applied to the market depth.
Valid values are:
l 0 = insert (insert this new order into the row identified by 'posi-
tion')
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 'posi-
tion')
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.
API Reference Guide 201
Chapter4 C++
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)
Parameter Type Description
id TickerId The ticker ID that was specified previously in the
call to reqMktDepth()
position int Specifies the row id of this market depth entry.
marketMaker IBString Specifies the exchange hosting this order.
operation int Identifies the how this order should be applied to
the market depth. Valid values are:
l 0 = insert (insert this new order into the row
identified by 'position')
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 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.
managedAccounts()
This function is called when a successful connection is made to an account. It is also called when the reqManagedAccts()
function is invoked.
virtual void managedAccounts(const IBString& accountsList)
Parameter Type Description
accountsList IBString The comma delimited list of FA managed accounts.
receiveFA()
This event receives previously requested FA configuration information from TWS.
virtual receiveFA(faDataType pFaDataType, IBString cxml)
API Reference Guide 202
Chapter4 C++
Parameter Type Description
pFaDataType faDataType Specifies the type of Financial Advisor configuration data being
received from TWS. Valid values include:
l 1 = GROUPS
l 2 = PROFILE
l 3 =ACCOUNT ALIASES
cxml IBString The XML string containing the previously requested FA con-
figuration information.
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)
Parameter Type Description
reqId int The ID of the data request.
account IBString The account ID.
API Reference Guide 203
Chapter4 C++
Parameter Type Description
tag IBString The tag from the data request.
Available tags are:
l AccountType
l TotalCashValue Total cash including futures pnl
l SettledCash For cash accounts, this is the same as Total-
CashValue
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
API Reference Guide 204
Chapter4 C++
Parameter Type Description
liquidation
l DayTradesRemaining The Number of Open/Close trades a
user could put on before Pattern Day Trading is detected. A
value of "-1" means that the user can put on unlimited day
trades.
l Leverage GrossPositionValue / NetLiquidation
value IBString The value of the tag.
currency IBString The currency of the tag.
accountSummaryEnd
This method is called once all account summary data for a given request are received.
virtual void accountSummaryEnd(int reqId)
Parameter Type Description
reqId int The ID of the data request.
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)
Parameter Type Description
account IBString The account.
contract Contract The exchange.
position int The 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.
virtual void positionEnd()
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)
Parameter Type Description
reqId TickerId The ticker ID of the request to which this bar is responding.
API Reference Guide 205
Chapter4 C++
Parameter Type Description
date IBString The date-time stamp of the start of the bar. The format is determined
by the reqHistoricalData() formatDate parameter.
open double The bar opening price.
high double The high price during the time covered by the bar.
low double The low price during the time covered by the bar.
close double The bar closing price.
volume int The volume during the time covered by the bar.
barCount int When TRADES historical data is returned, represents the number of
trades that occurred during the time period the bar covers.
WAP double The weighted average price during the time covered by the bar.
hasGaps int Reports whether or not there are gaps in the data.
scannerParameters()
This function receives an XML document that describes the valid parameters that a scanner subscription can have.
virtual void scannerParameters(const IBString &xml)
Parameter Type Description
xml IBString An XML document that describes the valid parameters for que-
ries.
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)
Parameter Type Description
reqId int The ticker ID of the request to which this row is responding.
rank int The ranking within the response of this bar.
contractDetails ContractDetails This object contains a full description of the contract.
distance IBString Varies based on query.
benchmark IBString Varies based on query.
projection IBString Varies based on query.
legsStr IBString Describes combo legs when scan is returning EFP.
scannerDataEnd()
This function is called when the snapshot is received and marks the end of one scan.
virtual void scannerDataEnd(int reqId)
API Reference Guide 206
Chapter4 C++
Parameter Type Description
reqId int The ID of the market scanner request being closed by this parameter.
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)
Parameter Type Description
reqId TickerId The ticker Id of the request to which this bar is responding.
time long The date-time stamp of the start of the bar. The format is determined by the
reqHistoricalData() formatDate parameter.
open double The bar opening price.
high double The high price during the time covered by the bar.
low double The low price during the time covered by the bar.
close double The bar closing price.
volume long The volume during the time covered by the bar.
wap double The weighted average price during the time covered by the bar.
count int When TRADES historical data is returned, represents the number of trades
that occurred during the time period the bar covers.
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.
virtual void fundamentalData(TickerId reqId, IBString& data)
Parameter Type Description
reqId TickerId The ID of the data request.
data IBString One of three XML reports:
l Estimates (estimates)
l Financial statements (finstat)
l Summary (snapshot)
API Reference Guide 207
Chapter4 C++
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
values 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.
API Reference Guide 208
Chapter4 C++
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. Includes 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.
API Reference Guide 209
Chapter4 C++
Contract
Attribute Description
vector<ComboLeg> comboLegs Dynamic memory structure used to store the leg def-
initions for this contract.
IBString comboLegsDescrip Description for combo legs.
int conId The unique contract identifier.
IBString 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.
IBString exchange The order destination, such as Smart.
IBString expiry The expiration date. Use the format YYYYMM.
bool includeExpired 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 lim-
ited to the last year of the
contracts life, and are ini-
tially only supported for
expired futures contracts.
IBString localSymbol This is the local exchange symbol of the underlying
asset.
IBString multiplier Allows you to specify a futures or options multiplier.
This is only necessary when multiple possibilities
exist.;
IBString primaryExchange To clarify any ambiguity for Smart-routed contracts,
include the primary exchange, along with the Smart
designation, for the destination.
IBString right Specifies a Put or Call. Valid values are: P, PUT, C,
CALL.
IBString secId Unique identifier for the secIdType.
API Reference Guide 210
Chapter4 C++
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. Exam-
ple: 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 exam-
ple, 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.
API Reference Guide 211
Chapter4 C++
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 exam-
ple, 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.
API Reference Guide 212
Chapter4 C++
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-
ignatedLocation
If shortSaleSlot == 2, the designatedLocation must be specified.
Otherwise leave blank or orders will be rejected.
IBString exchange The exchange to which the complete combination order will be routed.
API Reference Guide 213
Chapter4 C++
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.
int shortSaleSlot For institutional customers only.
l 0 - inapplicable (i.e. retail customer or not short leg)
l 1 - clearing broker
l 2 - third party. If this value is used, you must enter a designated location.
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.
For more information about supported order types, see Supported
Order Types.
long totalQuantity The order quantity.
Extended Order Fields
API Reference Guide 214
Chapter4 C++
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.
IBString goodAfterTime The trade's "Good After Time," format
"YYYYMMDD hh:mm:ss (optional time zone)"
Use an empty String if not applicable.
IBString goodTillDate You must enter GTD as the time in force to use this string. The
trade's "Good Till Date," format "YYYYMMDD hh:mm: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 minQty Identifies a minimum quantity order type.
IBString 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:
l 1 = Cancel all remaining orders with block
l 2 = Remaining orders are proportionately reduced in size
with block
l 3 = Remaining orders are proportionately reduced in size
with no block
If you use a value "with block" gives your order has overfill pro-
tection. This means that only one order in the group will be routed
at a time to remove the possibility of an overfill.
IBString orderRef The order reference. Intended for institutional customers only,
although all customers may use it to identify the API client that
sent the order when multiple API clients are running.
boolean outsideRth() If set to true, allows orders to also trigger or fill outside of regular
trading hours.
bool over-
ridePercentageConstraints
Precautionary constraints are defined on the TWS Presets page, and
help ensure tha tyour price and size order values are reasonable.
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 parameters value to True.
Valid values include:
l 0 = False
l 1 = True
API Reference Guide 215
Chapter4 C++
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:
l This field is mutually exclusive with the existing trailing
amount. That is, the API client can send one or the other but
not both.
l This field is read AFTER the stop price (barrier price) as fol-
lows: deltaNeutralAuxPrice
stopPrice
trailingPercent
scale order attributes
l The field will also be sent to the API in the openOrder mes-
sage if the API client version is >= 56. It is sent after the
stopPrice field as follows:
stopPrice
trailingPct
basisPoint
double trailStopPrice For TRAILLIMIT orders only
bool 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.
API Reference Guide 216
Chapter4 C++
Attribute Description
int triggerfunction Specifies how Simulated Stop, Stop-Limit and Trailing Stop orders
are triggered. Valid values are:
l 0 - The default value. The "double bid/ask" function will be
used for orders for OTC stocks and US options. All other
orders will used the "last" function.
l 1 - use "double bid/ask" function, where stop orders are trig-
gered based on two consecutive bid or ask prices.
l 2 - "last" function, where stop orders are triggered based on
the last price.
l 3 double last function.
l 4 bid/ask function.
l 7 last or bid/ask function.
l 8 mid-point function.
API Reference Guide 217
Chapter4 C++
Attribute Description
IBString activeStartTime For GTCorders.
IBString activeStopTime For GTCorders.
Financial Advisor Fields
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 allo-
cated 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.
IBString 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.
SMARTRouting Only
double discretionaryAmt The amount off the limit price allowed for discretionary orders.
bool eTradeOnly Trade with electronic quotes.
0 = no, 1 = yes
API Reference Guide 218
Chapter4 C++
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 Smar-
tRouting. When set to true, orders routed directly to ASX orders
WILL use SmartRouting.
BOXor VOL Orders Only
int auctionStrategy Values include:
l match = 1
l improvement = 2
l transparent = 3
For orders on BOX only.
BOXExchange 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.
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
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
deltaNeutralOrderTypefield 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.
API Reference Guide 219
Chapter4 C++
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 del-
taNeutralDesignatedLocation.
IBString del-
taNeutralDesignatedLocation
Used only when deltaNeutralShortSaleSlot = 2.
Combo Orders Only
double basisPoints For EFP orders only
int basisPointsType For EFP orders only
Scale Orders Only
bool scaleAutoReset() For extended Scale orders.
int scaleInitFillQty() For extended Scale orders.
int scaleInitLevelSize For Scale orders: Defines the size of the first, or initial, order com-
ponent.
int scaleInitPosition() For extended Scale orders.
API Reference Guide 220
Chapter4 C++
Attribute Description
int scalePriceAdjustInterval() For extended Scale orders.
double scalePriceAdjustValue() 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.
bool scaleRandomPercent() 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 scaleTable Manual table for Scale orders.
Hedge Orders Only
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 account The account. For institutional customers only.
IBString clearingAccount For IBExecution customers: Specifies the true beneficiary of the
order. This value is required for FUT/FOP orders for reporting to the
exchange.
IBString clearingIntent For IBExecution customers: Valid values are: IB, Away, and PTA
(post trade allocation).
IBString settlingFirm Institutional only.
Algo Orders Only
IBString algoStrategy For information about API Algo orders, see IBAlgo Parameters.
Vector<TagValue> algoParams Support for IBAlgo parameters.
What If
API Reference Guide 221
Chapter4 C++
Attribute Description
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
Vector<TagValue> Order-
ComboLegs
Holds attributes for all legs in a combo order.
Not Held
bool m_notHeld For IBDARKorders only. Orders routed to IBDARK are tagged as
post only and are held in IB's order book, where incoming Smar-
tRouted orders from other IB customers are eligible to trade against
them.
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.
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.
API Reference Guide 222
Chapter4 C++
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-
ageOptionVolumeAbove
Can leave empty.
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.
IBString instrument Defines the instrument type for the scan.
IBString locationCode The location.
double marketCapAbove Filter out contracts with a market cap lower than this value. Can be left
blank.
double marketCapBelow Filter out contracts with a market cap above this value. Can be left
blank.
IBString maturityDateAbove Filter out contracts with a maturity date earlier than this value. Can be
left blank.
IBString maturityDateBelow Filter out contracts with a maturity date later than this value. Can be
left blank.
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 vol-
atilities.
IBString spRatingAbove Filter out contracts with an S&P rating below this value. Can be left
blank.
API Reference Guide 223
Chapter4 C++
Attribute Description
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.
IBString currency() The currency.
IBString execId() Unique order execution id.
double realizedPNL() The amount of realized Profit and Loss.
double yield() The yield.
int yieldRedemptionDate() Takes the YYYYMMDD format.
API Reference Guide 224
Chapter4 C++
Placing a Combination Order
A combination order is a special type of order that is constructed of many separate legs but executed as a single trans-
action. Submit combo orders such as calendar spreads, conversions and straddles using the BAG security type (defined in
the Contractobject). The key to implementing a successful API combination order using the API is to knowing how to
place the same order using Trader Workstation. If you are familiar with placing combination orders in TWS, then it will
be easier to place the same order using the API, because the API only imitates the behavior of TWS.
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.
Leg 1: Buy 1 CLK9 futures contract
Leg 2: Sell 1 CLM9 futures contract
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.
To place this combo order
1. Get the Contract IDs for both leg definitions. Request 1 is assigned to CLK9 and Request 2 is assigned to CLM9.
con1.localSymbol = "CLK9";
con1.secType = "FUT";
con1.exchange = "NYMEX";
con1.currency = "USD";
m_client->reqContractDetails(1, con1->getContract()); // request 1
con2.m_localSymbol = "CLM9";
con2.m_secType = "FUT";
con2.m_exchange = "NYMEX";
con2.m_currency = "USD";
m_client->reqContractDetails(2, con2->getContract()); // request 2
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.
::contractDetails( int reqId, const ContractDetails &contractDetails)
{
// to obtain conId for CLK9
if (reqId == 1)