API Reference Guide September 2010 Updated through API Release 9.64 © 2010 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 recommendation.

Contents
1 Overview .................................................................................. 13
About the APIs ................................................................................................ 14 Run the API through TWS ................................................................................. 15 Run the API through the IB Gateway .................................................................. 16 Recommendations ........................................................................................... 18 API Logging .................................................................................................... 19 Example Log Entry ............................................................................. 20 API Request/Server Response Message Identifiers........................................... 20 Historical Data Limitations ................................................................................ 21 Valid Duration and Bar Size Settings for Historical Data Requests .............. 22 API Orders and TWS Precautionary Settings ........................................................ 23 API Order IDs.................................................................................................. 25 New Order Example ............................................................................. 25 Modified Order Example ....................................................................... 25 Requests for Quotes (RFQs) .............................................................................. 26 Submitting RFQs using the API.............................................................. 26 Delta-Neutral RFQs.............................................................................. 26 RFQ Samples ...................................................................................... 26 Requesting Real-Time Index Premium Data ......................................................... 27 Uninstalling and Re-installing the TWS API Software on Windows ........................... 28

2

DDE for Excel............................................................................ 29
Getting Started with the DDE for Excel API.......................................................... 30 Download the API Components and Spreadsheet............................................. 30 Configure the Application to Support API Components ..................................... 31 Open the Sample Spreadsheet...................................................................... 33 Using the DDE for Excel Sample Spreadsheet ...................................................... 34 Tickers Page ................................................................................................... 35 Using the Tickers Page ................................................................................ 35 Tickers Page Toolbar Buttons........................................................................ 38 Basic Orders Page............................................................................................ 39 Placing Orders ............................................................................................ 40

API Reference Guide

i

Contents

Placing a Combination Order ........................................................................ 41 Supported Order Types................................................................................ 43 Order Attributes ......................................................................................... 44 Basic Orders Page Toolbar Buttons ................................................................ 45 Extended Order Attributes Page ......................................................................... 46 Manually Program Extended Order Attributes.................................................. 47 Apply Extended Order Attributes to Individual Orders and Groups of Orders........ 47 Extended Order Attributes............................................................................ 48 Conditional Orders Page ................................................................................... 52 Setting Up Conditional Orders....................................................................... 52 Conditional Order Examples ......................................................................... 53 If-Filled order ..................................................................................... 53 Price-change order .............................................................................. 54 Conditional Orders Page Toolbar Buttons........................................................ 55 Advanced Orders Page ..................................................................................... 56 Placing a Bracket Order ............................................................................... 57 Placing a Volatility Order.............................................................................. 58 Placing a Trailing Stop Limit Order ................................................................ 59 Placing a Scale Order .................................................................................. 60 Placing a Relative Order............................................................................... 61 Advanced Orders Page Toolbar Buttons.......................................................... 62 Open Orders Page............................................................................................ 63 Viewing Open Orders................................................................................... 64 Open Orders Tab Toolbar ............................................................................. 64 Executions Page .............................................................................................. 65 Viewing Executions ..................................................................................... 65 Executions Page Toolbar Buttons .................................................................. 66 Executions Reporting Page ................................................................................ 67 Running Execution Reports .......................................................................... 68 Account Page .................................................................................................. 69 Using the Account Page ............................................................................... 70 Account Page Values ................................................................................... 71 Account Page Toolbar Buttons ...................................................................... 75 ................................................................................................................ 75 Portfolio Page.................................................................................................. 76 Viewing Your Portfolio ................................................................................. 76

API Reference Guide

ii

Contents

Portfolio Page Toolbar Buttons ...................................................................... 77 Historical Data Page ......................................................................................... 78 Viewing Historical Data ................................................................................ 79 Historical Data Page Query Specification Fields ............................................... 81 Historical Data Page Toolbar Buttons ............................................................. 83 Market Scanner Page ....................................................................................... 84 Starting a Market Scanner Subscription ......................................................... 85 Market Scanner Parameters ......................................................................... 85 Available Market Scanners ........................................................................... 87 Market Scanner Page Toolbar Buttons............................................................ 91 Contract Details Page ....................................................................................... 92 Requesting Contract Details ......................................................................... 92 Contract Details Page Toolbar Buttons ........................................................... 93 Bond Contract Details Page ............................................................................... 94 Requesting Bond Contract Details ................................................................. 94 Bond Contract Details Page Toolbar Buttons ................................................... 95 Market Depth Page .......................................................................................... 96 Using the Market Depth Page ....................................................................... 97 Market Depth Page Toolbar Buttons............................................................... 98 Advisors Page ................................................................................................. 99 Allocating Shares to a Single Account .......................................................... 100 Placing an Order using an FA Account Group and Method ............................... 101 Placing an Order using an Allocation Profile .................................................. 102 Advisors Page Toolbar Buttons.................................................................... 103 DDE for Excel API Reference ........................................................................... 104 Viewing the Code...................................................................................... 104 Modules................................................................................................... 105 Named Ranges ......................................................................................... 105 Macros .................................................................................................... 106 DDE Syntax for Excel ................................................................................ 107

3

ActiveX ................................................................................... 113
Linking to the Application using ActiveX ............................................................ 114 Registering Third-Party ActiveX Controls ........................................................... 115 Running the ActiveX API on 64-bit Windows XP Systems ..................................... 115 Using the Visual Basic Sample Program ............................................................ 116

API Reference Guide

iii

Contents

ActiveX Methods ............................................................................................ 117 connect()................................................................................................. 119 disconnect()............................................................................................. 119 reqMktDataEx() ........................................................................................ 119 reqMktData() ........................................................................................... 120 reqMktData2() ......................................................................................... 121 cancelMktData() ....................................................................................... 122 calculateImpliedVolatility()......................................................................... 122 cancelCalculateImpliedVolatility()................................................................ 122 calculateOptionPrice() ............................................................................... 122 cancelCalculateOptionPrice() ...................................................................... 123 placeOrderEx() ......................................................................................... 123 placeOrder() ............................................................................................ 123 placeOrder2() .......................................................................................... 126 cancelOrder() ........................................................................................... 127 reqOpenOrders() ...................................................................................... 128 reqAllOpenOrders() ................................................................................... 128 reqAutoOpenOrders() ................................................................................ 128 reqExecutionsEx()..................................................................................... 128 reqExecutions() ........................................................................................ 128 reqIds() .................................................................................................. 129 reqContractDetailsEx() .............................................................................. 129 reqContractDetails().................................................................................. 130 reqContractDetails2() ................................................................................ 131 reqMktDepthEx() ...................................................................................... 131 reqMktDepth() ......................................................................................... 132 reqMktDepth2()........................................................................................ 133 cancelMktDepth() ..................................................................................... 133 addComboLeg()........................................................................................ 134 clearComboLegs()..................................................................................... 135 reqNewsBulletins().................................................................................... 135 cancelNewsBulletins() ............................................................................... 135 setServerLogLevel() .................................................................................. 135 reqManagedAccts() ................................................................................... 136 reqAccountUpdates()................................................................................. 136 requestFA() ............................................................................................. 136

API Reference Guide

iv

Contents

replaceFA() .............................................................................................. 137 reqHistoricalDataEx() ................................................................................ 138 reqHistoricalData() ................................................................................... 141 exerciseOptionsEx() .................................................................................. 143 exerciseOptions() ..................................................................................... 144 reqScannerParameters()............................................................................ 144 reqScannerSubscriptionEx() ....................................................................... 145 reqScannerSubscription() .......................................................................... 145 cancelHistoricalData() ............................................................................... 147 cancelScannerSubscription() ...................................................................... 147 reqRealTimeBarsEx()................................................................................. 147 reqRealTimeBars() .................................................................................... 148 cancelRealTimeBars() ................................................................................ 149 reqCurrentTime()...................................................................................... 149 createComboLegList() ............................................................................... 149 createContract() ....................................................................................... 150 createExecutionFilter() .............................................................................. 150 createOrder() ........................................................................................... 150 createScannerSubscription() ...................................................................... 150 createTagValueList.................................................................................... 150 createUnderComp() .................................................................................. 151 reqFundamentalData() .............................................................................. 151 cancelFundamentalData() .......................................................................... 151 ActiveX Events .............................................................................................. 152 tickPrice()................................................................................................ 153 tickSize()................................................................................................. 153 tickOptionComputation()............................................................................ 154 tickGeneric() ............................................................................................ 154 tickString() .............................................................................................. 154 tickEFP() ................................................................................................. 155 tickSnapshotEnd() .................................................................................... 155 orderStatus() ........................................................................................... 157 errMsg() .................................................................................................. 158 connectionClosed() ................................................................................... 158 openOrderEx() ......................................................................................... 159 openOrder1() ........................................................................................... 159

API Reference Guide

v

Contents

openOrder2() ........................................................................................... 160 openOrder3() ........................................................................................... 161 openOrder4() ........................................................................................... 163 updateAccountValue() ............................................................................... 168 updatePortfolioEx() ................................................................................... 169 updatePortfolio() ...................................................................................... 170 updateAccountTime() ................................................................................ 171 nextValidId()............................................................................................ 171 permId() ................................................................................................. 171 contractDetailsEx() ................................................................................... 172 contractDetails()....................................................................................... 172 contractDetailsEnd() ................................................................................. 173 execDetailsEx() ........................................................................................ 173 execDetails()............................................................................................ 174 execDetailsEnd() ...................................................................................... 175 updateMktDepth() .................................................................................... 175 updateMktDepthL2() ................................................................................. 176 updateNewsBulletin() ................................................................................ 176 managedAccounts() .................................................................................. 177 receiveFA() .............................................................................................. 177 historicalData() ........................................................................................ 177 bondContractDetails() ............................................................................... 179 scannerParameters()................................................................................. 180 scannerDataEx()....................................................................................... 180 scannerData() .......................................................................................... 180 scannerDataEnd() ..................................................................................... 181 realtimeBar() ........................................................................................... 181 currentTime()........................................................................................... 182 fundamentalData() ................................................................................... 182 ActiveX COM Objects...................................................................................... 183 IExecution ............................................................................................... 184 IExecutionFilter ........................................................................................ 184 IContract ................................................................................................. 186 IContractDetails ....................................................................................... 188 IComboLeg .............................................................................................. 189 IComboLegList ......................................................................................... 190

API Reference Guide

vi

.................................. 204 Example...................................................dll ............................... 220 reqContractDetails().................................................. 213 To run the pre-built sample application ................... 216 eDisconnect()...................................................................................................................................................... 217 cancelMktData() ............................................................................................................. 220 cancelMktDepth() .......... 219 reqOpenOrders() ............................................................................. 208 Using the C++ TestSocketClient Sample Program .......................................................................................................................................................................................................................................................................................................... 198 IUnderComp ......................................... 219 reqAccountUpdates()...................................................................................... 218 cancelCalculateOptionPrice() ....................................................... 218 calculateOptionPrice() .............................................................................................................. 190 IOrderState ............ 217 cancelCalculateImpliedVolatility()........................................................................................................... 196 IScannerSubscription ................................................................................................. 217 calculateImpliedVolatility()...................................................................................................................................... 218 cancelOrder() .......................................................................... 220 reqIDs() ............................................................................. 213 To run the TestSocketClient program from Microsoft Visual Studio 2008 ........................................ 213 Class EClientSocket Functions .......................................................... 199 Placing a Combination Order ... 215 EClientSocket() ............................................. 218 placeOrder() .......................................................... 216 isConnected()................................................................................................................................................................ 216 reqMktData() ......................................... 204 4 C++ ................................. 219 checkMessages() ..................................... 198 ITagValue ......................................................................................................................................... 220 reqMktDepth() .......................................................................................................................... 221 API Reference Guide vii ........................................................ 198 ActiveX Properties...................................... 215 eConnect() ..........................................................................................................................................................................................................................Contents IOrder..................................................... 197 ITagValueList ................................................. 207 Linking to TWS using the TwsSocketClient.......................................................... 219 reqExecutions() ...............

........................................................................... 228 Class EWrapper Functions ................................. 234 error() .............................................................................................................................................................................................................................................................................................................................................................. 233 orderStatus() ........................... 232 tickEFP() ........................................................................................................................................................................................................................................................................................................................ 223 reqHistoricalData() .............................. 221 reqAllOpenOrders() ............... 227 serverVersion() ....................................................................................................... 221 cancelNewsBulletins() ............................................................................................................................................................... 223 exerciseOptions() ................................................................................... 230 tickOptionComputation()..............................................................................Contents reqNewsBulletins()........................................ 236 openOrder()....................................................................................................................................................... 237 API Reference Guide viii .............................................................................. 227 cancelFundamentalData() .............................................................. 235 connectionClosed() ........................................ 230 tickSize().......................................... 225 reqScannerSubscription() ..................................................... 222 reqManagedAccts() .............................................................. 236 updateAccountValue() .................................................................................. 235 winError()........................................................ 226 reqRealTimeBars() ............................................... 231 tickString() ............................................................................................................................................................................................................................................ 225 reqScannerParameters()............................................................................................................................................................... 222 replaceFA() ................................... 231 tickGeneric() ............................................................................. 236 managedAccounts() ......... 227 TwsConnectionTime() .............................. 222 requestFA() ...................................................................................... 225 cancelHistoricalData() ............................... 226 cancelRealTimeBars() ......... 221 setLogLevel() ........................................................................................... 226 cancelScannerSubscription() ..................................................................... 232 tickSnapshotEnd() ........ 227 reqFundamentalData() ...................................................................... 221 reqAutoOpenOrders() ..... 227 reqCurrentTime()...................................................................................................... 229 tickPrice().....................................................................

....... 250 ComboLeg .................................................................................................................... 265 Java Test Client Overview ....................................................................... 257 UnderComp........................................................................................... 243 scannerDataEnd() ........................................................................................................................................................................ 261 Linking to TWS using the Java API ................ 238 nextValidId().................................................................. 252 OrderState........................................................................................ 269 API Reference Guide ix .............................................................................................................................................................................. 246 ExecutionFilter ....................................................................................................................................................................................................................................................................................................................................................... 256 ScannerSubscription .... 240 updateMktDepth() .............................................................................................................................................. 242 scannerParameters()............................ 238 updateAccountTime() ........................................................................... 240 updateNewsBulletin() ..........................................................................................................................Contents updatePortfolio() ................................................................................. 239 execDetails()........... 243 realtimeBar() .... 241 receiveFA() ...................................... 258 Placing a Combination Order ...................... 239 contractDetails().................. 244 SocketClient Properties................................................................................................................. 248 ContractDetails............................ 244 currentTime()....................... 239 contractDetailsEnd() .......................... 243 scannerData() ............................................ 245 Execution ..................... 244 fundamentalData() ....................................................................................................................................................................................................................... 242 historicalData() ..................................................................................................... 259 Example........................................................................................................................................................................................................................................................................................... 259 5 Java...................................................................................................................................................................... 240 updateMktDepthL2() ........ 239 execDetailsEnd() ...................................................................................................................................................... 251 Order ...................... 242 bondContractDetails() ............... 262 Running the Java Test Client Sample Program .................................................................................................... 246 Contract .....

.. 279 requestFA() ...................................................... 273 eDisconnect().................................................................................................................... 276 reqExecutions() ................................................................................................ 277 reqMktDepth() ................................................................................. 269 TestJavaClient Classes...................................................................................... 276 reqAccountUpdates()............................................................................................................................................................................................. 273 reqMktData() ................... 275 calculateOptionPrice() ................................................................................................................................................................................................................................................................................................................................................................................................................................. 274 cancelMktData() ................................................................................................................................................................................................. 279 reqScannerParameters()....... 272 EClientSocket() .......... 275 cancelOrder() ............................ 276 reqContractDetails()........................................................................................................ 275 placeOrder() ......... 278 setServerLogLevel() .................................................................................................................................................................................. 269 Java API Overview ........................................................................................................................................................................................................ 275 reqOpenOrders() ............................................................................Contents Package ........................................................................ 275 cancelCalculateOptionPrice() ........................................................................................................ 274 cancelCalculateImpliedVolatility()............................................................................................................................................................................................... 279 replaceFA() ........................... 277 cancelNewsBulletins() ....... 282 reqRealTimeBars() ....... 281 cancelHistoricalData() ............................................................................................... 280 cancelScannerSubscription() ..................................................................................................................... 280 reqScannerSubscription() ................ 278 reqManagedAccts() .......................................................................................... 277 cancelMktDepth() ................................................................ 278 reqAutoOpenOrders() ................................................... 274 calculateImpliedVolatility().......... 283 API Reference Guide x .. 273 isConnected()........................................................................... 273 eConnect() ........................................................................................................ 280 reqHistoricalData() .. 277 reqNewsBulletins()....................................................................... 278 reqAllOpenOrders .......... 271 Java EClientSocket Methods ........................

................................................ 288 tickGeneric() ................................................................... 284 TwsConnectionTime() ...................................................................... 284 reqCurrentTime()....................................................................................................................................................................................................................................... 288 tickOptionComputation().................................................................................................. 286 tickPrice()........................ 295 updateAccountTime() ............................................................................................................... 292 connectionClosed() ...................................... 289 tickEFP() ............................................................. 300 scannerData() ........................................................................................................................................................ 291 error() ....................................... 299 historicalData() ............................................... 289 tickSnapshotEnd() .................................................................. 290 orderStatus() ................................................................................................... 289 tickString() ............................................................................................................................................................................. 285 Java EWrapper Methods.................................................................................................................. 299 scannerParameters()........................................................................................................................... 295 contractDetails().................................................................... 287 tickSize()................................................................................................................................................................................. 284 reqFundamentalData() ......................................................................................................... 300 API Reference Guide xi ...................................................................................................................... 285 cancelFundamentalData() ........................................................................................................................................................................................................................................................................................................................... 298 receiveFA() ............................................ 283 exerciseOptions() .............................. 284 serverVersion() ......................... 296 bondContractDetails() ............ 296 contractDetailsEnd() ...... 293 openOrder().................................. 298 updateNewsBulletin() ....................................... 297 updateMktDepthL2() ..............................................Contents cancelRealTimeBars() ............................. 295 nextValidId()........................................................................ 294 updatePortfolio() .............................................. 296 execDetails()..... 293 managedAccounts() ................................................................................................................. 293 updateAccountValue() ........................................................................ 297 updateMktDepth() .............. 296 execDetailsEnd() ........................................................................................................................................................................

.......................... 300 realtimeBar() .......................................................... 303 Contract ............... 307 Order ... 316 Placing a Combination Order ................................................................................................................................................................................................................................................................................ 322 Excel DDE Support................................................................................................ 329 Open the Sample Spreadsheet....................................................................................................................................................... 330 General Page .............................................................................................................. 322 Improved Financial Advisor Execution Reporting ........................................................................................................................................................................................................................... 331 General Page Toolbar Buttons..................................................................................................Contents scannerDataEnd() ............................ 328 Download the API Components and Spreadsheet. 324 AvailableEquity Method ..................................................................... 328 Running the ActiveX for Excel API on 64-bit Windows XP Systems .............................................................................................................................................................................................................................................................. 322 Support by Other API Technologies ................................ 323 Allocation Methods for Account Groups ................................... 324 7 ActiveX for Excel ...... 324 EqualQuantity Method ................................ 329 Using the ActiveX for Excel Sample Spreadsheet ................................................................................................................... 324 NetLiq Method ......................... 301 Java SocketClient Properties .............................................................................................................. 327 Getting Started with the ActiveX for Excel API ............ 309 OrderState..... 303 ExecutionFilter .................................................... 301 fundamentalData() ............................................................................................. 333 API Reference Guide xii ............................. 324 PctChange Method........ 302 Execution ..................................... 305 ContractDetails...................................................................................................................................................................... 314 ScannerSubscription ......................................................................................... 317 Example......................................... 317 6 Advisors ........................... 301 currentTime()....................................................................................... 315 UnderComp.......................................... 306 ComboLeg .................................................................... 321 Financial Advisor Orders and Account Configuration........................................................................

................... 358 Viewing Open Orders............... 339 Market Depth Page Toolbar Buttons........................ 359 Account Page .............................................................................................. 342 Supported Order Types..................................................................................... 354 Placing a Relative Order.......................................................................... 360 Using the Account Page ...............................Contents Tickers Page ............................................ 355 Advanced Orders Page Toolbar Buttons.................... 357 Open Orders Page................................................................................................................................... 339 Basic Orders Page.................................................................................. 336 Bulletins Page ................................................................................................................. 348 Advanced Orders Page ..................................................................................................................................... 340 Placing Orders ........................................................................................ 345 Conditional Order Examples ............................................................. 357 Apply Extended Order Attributes to Individual Orders and Groups of Orders................................................................................ 363 API Reference Guide xiii .................. 362 Portfolio Page.............................................................................................................................. 337 Market Depth Page ........................................................... 352 Placing a Trailing Stop Limit Order ......................................... 346 If-Filled order .......................................................... 346 Price-change order ..................................................................................................................................... 337 Bulletins Page Toolbar Buttons..................................... 355 Extended Order Attributes Page ..................... 359 Open Orders Tab Toolbar ...................................................................................................................................................................................................................................................................... 334 Using the Tickers Page ......................................................................... 356 Manually Program Extended Order Attributes......................................................................................... 353 Placing a Scale Order ............... 360 Account Page Toolbar Buttons .............................................................................................. 349 Placing a Bracket Order ..................................................................... 344 Conditional Orders Page ............................................................................................ 341 Placing a Combination Order .................................................................................................. 345 Setting Up Conditional Orders.. 334 Tickers Page Toolbar Buttons................... 347 Conditional Orders Page Toolbar Buttons............................................................................................................................. 344 Basic Orders Page Toolbar Buttons .............................. 351 Placing a Volatility Order......................................................................................................... 338 Using the Market Depth Page ..........

................................ 367 Viewing Historical Data ......................................................... 379 Starting a Market Scanner Subscription ....... 373 Requesting Contract Details ............................................ 396 API Reference Guide xiv ...................... 390 Placing an Order using an FA Account Group and Method ......................................................................................................................................................................................................... 363 Exercising Options ............................................................................................................................... 395 Running the POSIX Client on a Windows Machine ................................................................ 387 Fundamentals Page Toolbar Buttons ................................................................................................... 375 Requesting Bond Contract Details ....... 368 Historical Data Page Query Specification Fields ...... 393 Log Page .......................................................................................................................................................................... 372 Contract Details Page ................................................... 365 Viewing Executions ............... 376 Real Time Bars Page . 391 Placing an Order using an Allocation Profile ........................................................................................................................................................ 375 Bond Contract Details Page Toolbar Buttons ...... 388 Advisors Page .................................................... 373 Contract Details Page Toolbar Buttons ......................................................................................................................................................................................................... 392 Advisors Page Toolbar Buttons..................................... 394 8 POSIX.................................................. 382 Market Scanner Page Toolbar Buttons.......................................................... 378 Market Scanner Page ............................... 364 Executions Page ............................................................................................................................................................................. 377 Real Time Bars Page Toolbar Buttons ................................................... 374 Bond Contract Details Page ..................... 389 Allocating Shares to a Single Account .........................................................................................................................................................................Contents Viewing Your Portfolio .................................................... 366 Historical Data Page ............ 386 Fundamentals Page........................................................................................................................ 380 Available Market Scanners ................................................................. 380 Market Scanner Parameters ........................................................................... 363 Portfolio Page Toolbar Buttons ........... 366 Executions Page Toolbar Buttons ................................................................... 370 Historical Data Page Toolbar Buttons ......

..................................................................................................................................................................................................................................................................... 413 Supported Order Types...................................................... 407 Tick Types ................... 412 TAG Values for FUNDAMENTAL_RATIOS tickType ........... 419 Extended Order Attributes ....................................................................................Contents 9 Reference Tables .................................................................................. 429 API Reference Guide xv .................................................. 397 API Message Codes ..................................................................................... 398 Error Codes ...................................................................................................................................................... 421 Available Market Scanners .. 408 Generic Tick Types........... 411 Using the SHORTABLE Tick....................... 425 IBAlgo Parameters ................................................................................... 407 Warning Message Codes........................................................................................... 398 System Message Codes .............

Contents API Reference Guide xvi .

Overview 1 This chapter provides an overview of the APIs (Application Programming Interfaces) available. including the following topics: • • • • • • • • • • • About the APIs Run the API through TWS Run the API through the IB Gateway Recommendations API Logging Historical Data Limitations API Orders and TWS Precautionary Settings API Order IDs Requests for Quotes (RFQs) Requesting Real Time Premium Data Uninstalling the API Software API Reference Guide 13 .

Customers with no programming expertise should begin with the DDE for Excel section. The API allows you to connect through either the TWS or the IB Gateway. Connecting through the TWS requires that you have the application running. 2 3 4 API Reference Guide 14 . • • Note: To develop and test your API program. and cancel basic and advanced orders. View market data. Customize the sample applications to meet your needs. Use the sample application to learn how to request market data. modify. you can use the GUI-less IB Gateway to connect. Click Download latest version under the appropriate OS column and install the program on your computer. To view syntax for specific functionality. The Java API to link from a Java application (for all platforms). Once you are satisfied that the API works as designed. To use the API components and view sample source code and spreadsheets 1 Install or upgrade the latest API and sample files from the IB website. select API Solutions. On the Trading menu. the API allows you to: • • • • • • Run multiple sessions off the same IB login. or create your own application using described syntax and functionality. including: • • The DDE component to link through Excel (for Windows platforms only). View historical data and run market scanners.NET application (on Windows platforms only). The API provides multiple development methods to connect. submit orders. Configure the application to support the API. but also allows you to test and confirm that your API orders are working correctly. we recommend that you use the sample application and connect via TWS. The ActiveX control to link through a Visual Basic and . ActiveX. etc. then click the IB API button. see the DDE for Excel. API topics are written for experienced programmers and provide little guidance for non-technical users. but does not provide an interface for you to test and confirm API activity. Connecting through the IB Gateway allows you to use the AIP without a large GUI application running. View open orders. Regardless of the connection method you use. Submit. if you desire. View updated status of your account balance and portfolio. C++ or Java topics in this guide. The Windows C++ socket client component to link through a C++ application (for Windows platforms).Overview About the APIs About the APIs We provide several APIs which you can use to link to our system and trade your IB account. which uses an everyday Excel® spreadsheet to link to TWS via the API.

C++ and Java API connections). With the exception of DDE for Excel. Only one API application can access a single instance at a time. 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 2 Log into TWS. select API then select the check box for either Enable ActiveX and Socket Clients (ActiveX.Overview Run the API through TWS Run the API through TWS To run the API through TWS. the API application does not need to be running on the same computer on which the application is running. then make your selections and click OK. On the Configure menu. You must have these settings enabled to connect to the API through TWS • You can also select Global Configuration from the Configure menu to display the TWS API Configuration window. and/or Enable DDE Clients (for DDE for Excel API connections only) to configure TWS for the appropriate API connection. Note: API Reference Guide 15 .

Select the API radio button. the gateway is GUI-less. which means that you cannot view the API activity as you can when running TWS. Click Login.Overview Run the API through the IB Gateway 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. just as you would when logging into TWS. select IB Gateway. The Interactive Brokers Gateway box opens. displaying the connection status and gateway activity. To log into the IB Gateway 1 2 3 4 From the Login menu on the IB web site. Log in using your IB username and password. The gateway uses approximately 40% fewer system resources than TWS. However. API Reference Guide 16 .

Overview Run the API through the IB Gateway You must have the IB Gateway running while connected to the API. API Reference Guide 17 .

the order may not work. • • API Reference Guide 18 . Please test your API application with an IB Paper Trading account to catch and avoid any errors.Each order you place must have a unique Order ID. Order IDs .When you place an order by conid. We recommend that you increment your own Order IDs to avoid conflicts between orders placed from your API application. You can request a Paper Trading account from Account Management. you must provide the conid AND the exchange. If you provide extra fields when placing an order by conid.Overview Recommendations Recommendations Before you use our TWS API to create your own customized trading application. you should consider the following important recommendations: • Placing Orders by Conid .

ServerVersion identifies the server's response stream (for internal use). the log level as listed above) • • • API Reference Guide 19 .Overview API Logging API Logging As client requests are processed (both system and API clients) it logs certain information to its 'log. LogEntryLevel identifies the type of log entry (i. if no level is specified) 3 = WARNING 4 = INFORMATION 5 = DETAIL (most detailed) Setting the log level to 5 will have a performance overhead. Log levels are: • • • • • 1 = SYSTEM (least detailed) 2 = ERROR (default. The number shown is the response identifier as listed in the "Incoming Response Identifiers" section below. Note: The log entries for API requests have the format: [ClientID:ClientVersion:ServerVersion:ClientType:Request:Response:Versio n:LogEntryType] where: • • • • • ClientID is the clientId used when connecting.txt' log file. The version changes when the message format changes. Version identifies the version of the request or response message. indicates that the log entry is the result of an API client request. Response: If greater than 0. and should only be used when trying to resolve an issue. Request: If greater than 0. indicates that the log entry is the result of a server response to the API. which is located in the installation directory. The number shown is the request identifier as listed in the "Outgoing Request Identifiers" section below. Socket = 1.e. ClientType is the type of API connection: DDE = 0. ClientVersion identifies the client's request stream (for internal use). The purpose of this file is to help resolve problems by providing some insight into the state of the program before the problem occurred. API clients can specify how detailed they want these log entries to be by setting the log level.

0.null] From this example.2.52. The version of the market data request.null.SMART. API Reference Guide 20 .STK. API Request/Server Response Message Identifiers Outgoing Request Identifiers 1 = Request Market Data 2 = Cancel Market Data 3 = Place Order 4 = Cancel Order 5 = Request Open Orders 6 = Request Account Data 7 = Request Execution Reports 8 = Request Next Order Id 9 = Request Contract Details 10 = Request Market Depth 11 = Cancel Market Depth 12 = Request News Bulletins 13 = Cancel News Bulletins 14 = Set Server Log Level Note: Incoming Response Identifiers 1 = Ticker Price 2 = Ticker Size 3 = Order Status 4 = Error Message 5 = Open Order 6 = Account Value 7 = Portfolio Value 8 = Account Update Time 9 = Next Valid Order Id 10 = Contract Details 11 = Execution Report Details 12 = NYSE Open Book Row Entry 13 = Level II Quotes Row Entry 14 = News Bulletin This information. can be found in the EClientSocket implementation file supplied with the API installation. which was 3.0.IBM. along with the various request/response message versions. we can tell that a socket client with clientId=0 connected and made a request for market data.implies what data should have been sent.null.Overview API Logging Example Log Entry [0:9:9:1:1:0:3:DET]Socket request [3.

However. For more information about historical data requests. reqHistoricalDataEx() in the ActiveX chapter. Making six or more historical data requests for the same Contract. Each request is restricted to duration and bar size values that return no more than 2000 bars (2000 bars per request). see Viewing Historical Data in the DDE for Excel chapter. All of the API technologies support historical data requests. reqHistoricalData() in the C++ chapter. Exchange and Tick Type within two seconds.Overview Historical Data Limitations Historical Data Limitations Historical data requests are subject to the following limitations: • • Historical data requests can go back one full calendar year. The error code and message that indicates a pacing violation is: 162 . Note: API Reference Guide 21 . observe the following limitation when requesting historical data: • Do not make more than 60 historical data requests in any ten-minute period. requesting the same historical data in a short period of time can cause extra load on the backend and subsequently cause pacing violations. Also. and reqHistoricalData() in the Java chapter.Historical Market Data Service error message: Historical data request pacing violation The following conditions can cause a pacing violation: • • Making identical historical data requests within 15 seconds.

Please note that these are only guidelines. 15 secs. 1 secs API Reference Guide 22 . 30 secs. 15 mins. 15 mins. 3 mins. 5 secs. 5 mins 3 mins. 30 mins. 5mins 3 mins. 15 mins 1 hour. 1 hour. 15 mins. 30 secs. 2 mins. 1 min. 30 mins. 2 mins. 2 mins.Overview Historical Data Limitations Valid Duration and Bar Size Settings for Historical Data Requests The following table lists valid duration and bar size settings for API historical data requests. Duration 1Y 6M 3M 1M 1W 2D 1D 14400 S (4 hrs) 7200 S (2 hrs) 3600 S (1 hr) 1800 S (30 mins) 960 S (15 mins. 30 secs. 2 mins. 5 secs. 15 secs. 5 mins 3 mins.) 300 S (5 mins) 60 S ( 1 min) Bar Size 1 day 1 day 1 day 1 day. 1 min. 1 min. 2 mins. 5 secs 15 mins. 30 secs. 2 mins. 30 secs. 15 secs. 5 secs. 2 mins. 30 mins. 5 mins 3 mins. 1 secs 30 secs. 1 hour 1 day. 15 secs 5 secs 1 secs 3 mins. 5 secs. 2 mins. 30 secs. 30 secs 1 hour. 1 min 1 hour. 1 min. 15 secs. 15 secs 1 hour. 15 secs. 5 mins 3 mins. 1 min. 30 mins. 1 min. 15 mins. 1 secs 5 mins 3 mins. 1 min. 30 mins. 15 mins.

select Order then select Order Presets. options. then click OK. select API then All API Settings. TWS precautionary settings apply to API orders placed from ALL API technologies. For example. If you place an order for 1000 shares of stock. and so on) or for specific tickers.Overview API Orders and TWS Precautionary Settings API Orders and TWS Precautionary Settings By default. enter higher precautionary setting limits for the desired instrument types and or tickers. total value and number of ticks. • API Reference Guide 23 . You can override the precautionary settings by doing one of the following: In TWS: • On the Configure menu. In the Order Presets. All of your API orders will ignore the precautionary settings in TWS. then click OK. Trader Workstation includes precautionary settings as part of its Order Presets on the TWS Configuration page. If your API order violates these settings. Precautionary settings are safety checks and include percentage. you will receive an error message. Select the instrument type or ticker on the left. They can be modified in TWS for most instrument types (stocks. On the Configure menu. the default precautionary setting for order size is 500. you will receive an error message indicating that the size specified violates the constraints specified in the default order settings. enter the desired limits in the Precautionary Settings section of the page. Select the Bypass Order Precautions for API Orders check box. size limit.

Overview API Orders and TWS Precautionary Settings In the IB Gateway: • From the Configure menu. select Settings. All of your API orders will ignore the precautionary settings you had set via a TWS session. API Reference Guide 24 . Select the Bypass Order Precautions for API Orders checkbox and click OK.

customer wants to modify the same order and change the limit price to $86.placeOrder(2. IBM. 100…) API Reference Guide 25 . if you place an order with an Order ID of 11. IBM. user can place a second order. IBM. the order id must be greater than the previously used order id number.25. 100…) Modified Order Example To modify an order using the API. $85. the order id number must be greater than the previously used numbers.25. 200…) Now.25. resubmit the order you want to modify using the same order id. The second order will be an order to sell 100 shares with the limit price set to $84. a user initially decides to buy 100 shares and sets the limit price to $85.25. For example. If you want to change the order type or action. IBM. Only certain fields such as price or quantity can be altered using this method. In this example. BUY. In this example.25.25 . Then.Overview API Order IDs API Order IDs When you place a new order using the API. Note that the first order is assigned an Order ID of 3: . $84. 100…) You can now modify the limit price for this order by calling the same . The first order is a BUY order for 200 shares and set the limit price to $85. $86. New Order Example In this example. $85.placeOrder(3.25. the next order you place should have an Order ID of at least 12. the first order is tagged with an Order ID of 1: .placeOrder(1. SELL.placeOrder method and using the same Order ID of 3. This order is assigned an Order ID of 2: .25. So when you place a new order. BUY. but with the price or quantity modified as required. you will have to cancel the order and submit a new order. with the limit price modified to $86. a user is going to place two orders for IBM stock. BUY.placeOrder(3.25.

The SampleRFQ. the server sends a deltaNeutralValidation() message with the UnderComp structure. These values are locked when the RFQ is processed and remain locked until the RFQ is canceled. The samples are located in the samples/rfq folder in your API software installation folder. Upon accepting a Delta-Neutral DN RFQ. the confirmation will contain the current values from the server. In the response. Additional space is required for non-RFQ tickerIds. The price and delta fields can be left empty (0). Market data for an RFQ is received until the user cancels the RFQ or the RFQ is canceled by the server. even if a single contract must be hedged. you must specify the conId of the hedge contract. and filling up and attaching an UnderComp structure to a contract underComp field. Quotes are available for US equity and index options. please contact the IB Options Trading Desk.6 release of the API software. If the delta and price fields are empty in the original request. Use orderId's with a relatively high number to avoid clashes. RFQ Samples To learn more about submitting RFQs with the TWS API. RFQs from the IB Options Trading Desk are available only to users who have access to these specific areas.java sample implements a small-state machine and shows how to submit RFQ's for: • • • • • • • • EU Stocks US Futures US Stock Options EU Stock Options Calendar Spread for Index Option (Delta-Neutral) US Stock Option (Delta-Neutral) US Index Option (Delta-Neutral) EU Index Option (Delta-Neutral) API Reference Guide 26 . tickPrice()/tickSize() are called with the tickerId matching the orderId of the RFQ. The server normally cancels an RFQ when it expires (approximately 1 minute) or if the RFQ request is invalid and/or for an unsupported product. In the UnderComp structure.Overview Requests for Quotes (RFQs) Requests for Quotes (RFQs) RFQs from the IB Options Trading Desk allow you to get quotes for large orders from IB affiliate Timber Hill. For a complete list. Submitting RFQs using the API Submit an RFQ by submitting an order with an order type of QUOTE. look at the RFQ samples included in the 9. Please contact the IB Options Trading Desk if you are interested in participating. and major European and Asian index options and combinations. Delta-Neutral RFQs Submit Delta-Neutral RFQs by creating a combo order.

API Reference Guide 27 . you must do the following: • Specify the Symbol.Overview Requesting Real-Time Index Premium Data Requesting Real-Time Index Premium Data You can request real-time Index Premium market data using the following APIs and API sample applications: • • • • ActiveX (including the ActiveX API sample application) C++ (including the C++ API sample application) Java (including the Java API sample application) ActiveX for Excel To request real-time Index Premium data. For example. • • The exchange must match the index for which you want data. You must use the generic tick type 162 (for Index Future Premium). Security Type and Exchange. IND and NYSE would get you Index Premium data for the Dow Jones Industrial Average. INDU.

In the Windows Explorer. then click Change/Remove.Overview Uninstalling and Re-installing the TWS API Software on Windows Uninstalling and Re-installing the TWS API Software on Windows If you encounter problems running the TWS API software on the Windows platform. Re-install the TWS API software. Reboot your computer.dll from the Windows\system32 folder. To uninstall and re-install the TWS API software on Windows 1 2 3 4 5 6 Open the Windows Control Panel. Select TWS Interoperability Components from the list of installed programs. then click Next to uninstall the TWS API software. then open Add or Remove Programs. Note: This procedure is usually only necessary when troubleshooting the most extreme API problems. Select Automatic. API Reference Guide 28 . delete the file TwsSocketClient. you can uninstall and re-install the API software.

API Reference Guide 29 .DDE for Excel This chapter describes the DDE for Excel API. The following figure shows the Tickers page in the Excel DDE API sample spreadsheet. allowing you to view real-time market data (including market depth) manage orders and monitor your executions and account information using an Excel spreadsheet. a Microsoft-created communication method that allows multiple applications 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. including the following topics: • • • • 2 Getting Started with the DDE for Excel API Using the DDE for Excel Sample Spreadsheet Viewing the Code DDE for Excel API Reference DDE is an acronym for Dynamic Data Exchange.

It's easy to get started with the DDE for Excel API: • • Download the API components and sample Excel spreadsheet. TwsDde. 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. Click the IB API icon. select a different directory. • Open the spreadsheet and start using the DDE for Excel API. 3 Save the installation program to your computer. API Reference Guide 30 . Locate the API installation program you just saved to your computer. Note: Windows users can download the beta test version of the API by using the Windows Beta column. find the column appropriate to your operating system. You can also run the sample against the IB Gateway but we recommend you start by running TWS. By default. and on the API Software page.xls.DDE for Excel Getting Started with the DDE for Excel API Getting Started with the DDE for Excel API We have created a sample DDE-linked Excel spreadsheet. InstallAX_960. Click Save. or revert to the previous production version by selecting Downgrade to Previous Version. 4 5 6 Before you can use the spreadsheet. Note that the API installation file is named for the API version. Ensure that either: • • the application server is running and that it is configured to support DDE. click Download latest version. the sample DDE spreadsheet is saved to C:\IB_API_X_XX\Excel\TwsDde. The sample spreadsheet currently comprises several pages complete with sample data and action buttons that make it easy for you to get market data. Follow the instructions in the installation wizard.xls. select API Solutions from the Software menu. then double-click the file to begin the API installation. Follow the steps below to download the sample spreadsheet. the IB Gateway and Excel that you have running. that you can use with your TWS to create a custom Excel application. Close any versions of TWS. where X_XX is the API version number. for example. send orders and view your activity. or the IB Gateway is running. To install the sample DDE Spreadsheet 1 2 From the IB homepage. you must have TWS running and configured to support the DDE API. and if desired.

DDE for Excel Getting Started with the DDE for Excel API Configure the Application to Support API Components You must have your system running to use any of the API components. API Reference Guide 31 . • You can also select Global Configuration from the Configure menu to display the TWS API Configuration window. then make your selections and click OK. To configure the application to support accessing its functionality via the API 1 2 Run the application. select API then select the check box for Enable DDE Clients (for DDE for Excel API connections only) to configure TWS. On the Configure menu.

the API application does not need to be running on the same computer on which the application is running.DDE for Excel Getting Started with the DDE for Excel API Note: Note that not more than one API application can simultaneously access a single instance. With the exception of DDE. API Reference Guide 32 .

In Microsoft Excel 2007. you need to modify your macro security level. Note that you must type your User Name on each page of the worksheet to properly connect. click Enable Macros. If you cannot open the spreadsheet or if the macros don't work.xls. 3 In the User Name field in the Which Trader Workstation? area. click the Microsoft Office Button. then change your settings as required. and resave the application as your own.DDE for Excel Getting Started with the DDE for Excel API 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. you will need to cut and paste your information from your Excel spreadsheet to the newly released sample spreadsheet. click Excel Options. In the macro warning message box. click Macro Settings. API Reference Guide 33 . open the spreadsheet and save it as your personal file. In the Trust Center. and then select Security. To open the sample spreadsheet 1 Go to the API installation folder in which the Excel API sample spreadsheet was installed (typically C:\IB_API_X_XX\Excel. Set security to Medium or Low. click Yes. Note: To use the spreadsheet macros. and then click Trust Center in the Excel Options window. your Excel macro security must be set to Medium or Low. In previous versions of Excel. This means that when new features are added. type your account user name. where X_XX is the API version number) and double-click TwsDde. If you receive a message asking if you want to link to information in another worksheet. 2 We recommend using this spreadsheet as the starting point for your API application. select Macro from the Tools menu.

such as Bracket. for example an order based on a prior fill.xls sample spreadsheet. Subscribe to TWS market scanners. Advanced Orders. Basic Orders Extended Order Attributes Conditional Orders Open Orders Advanced Orders Executions Executions Reporting Account Portfolio Historical Data Market Scanner Contract Details Bond Contract Details Market Depth Advisors Note: Two additional pages.DDE for Excel Using the DDE for Excel Sample Spreadsheet Using the DDE for Excel Sample Spreadsheet The DDE for Excel API sample spreadsheet. Provides up to date account information and displays your portfolio. You can view market data for all asset types including EFPs and combination orders. and request open orders. Lets you view market depth for selected quotes. Displays all your current positions. and includes a filtering box so you can limit your results. Conditional Orders and Advisors pages. they are no longer documented in this API Users’ Guide and you should not use them. Used in conjunction with the Basic Orders. and those that are working at an exchange. While these older pages are still included in the TswDde. Lets you view all execution reports. Lets Financial Advisors send and modify FA orders. Lets you create an order whose submission is contingent on other conditions being met. Request historical data for an instrument based on data you enter in a query. this page lets you run four different types of execution reports. API Reference Guide 34 . including those that have been accepted by the IB system. Scale and Trailing Stop Limit orders.xls. Lets you send and modify advanced orders types that require the use of extended order attributes. Linked to the Executions page. represent functionality that has been replaced by other pages in the spreadsheet (Executions. includes the following pages (tabs): Page Tickers Description Lets you set up your ticker lines and request market data. Lets you send and modify orders. including bond coupon and maturity date. including the conid and supported order types for a contract Lets you collect bond contract-specific information you will need for other actions. set up combination orders and EFPs. this page lets you change the time in force. Lets you collect contract-specific information you will need for other actions. create Hidden or Iceberg orders and apply many other order attributes. Shows you all transmitted orders. Old Style Executions and Old Style Account-Portfolio. TwsDde. Account and Portfolio pages).

DDE for Excel Tickers Page Tickers Page Use the Tickers page to: • • • Create market data (ticker) lines. To create a ticker using the Create Ticker button 1 2 3 4 Click the Tickers tab at the bottom of the spreadsheet. Click the Create Ticker button on the toolbar and enter information in the Tickers box. • Using the Tickers Page Note: Ensure that TWS is running. and that you have entered your user name in the User Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet to properly connect to TWS. API Reference Guide 35 . 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. Create a combination order for options. Click OK. Request market data. Create market data line for Exchange for Physical (EFP) combination orders.

Strike. To create a ticker on the spreadsheet 1 2 Select a blank cell in the Symbol column and enter a symbol. and any valid exchange acronym. select multiple ticker rows while holding down the Shift key. and Currency. Press Ctrl+R. To request market data for a ticker 1 2 Select the ticker row for which you want to request market data by clicking the row number. you don't need values in the Expiry. for example if you are entering a stock ticker. Tab through the all contract description fields and enter data where necessary. Exchange (usually SMART). Note: The Exchange field accepts the following values: SMART (for smart order routing). you only need to specify the Symbol. or click Request Market Data on the toolbar. API Reference Guide 36 . Type. P/C and Multiplier fields. To get market data for a group of tickers.DDE for Excel Tickers Page For stocks. then click Request Market Data multiple times until all rows are showing data.

You typically use this button when you are preparing to save the spreadsheet. • Type the processing rate value (in milliseconds) in the Processing Rate field.DDE for Excel Tickers Page To set the refresh rate The refresh rate determines how often the DDE link to TWS is refreshed. To remove all DDE links to TWS The Clear All Links button on the Tickers page lets you remove all DDE links from the TwsDde. and other data requests. 4=INFORMATION. TWS market data updates every 300 milliseconds by default. If you add your own links to existing or new pages. API Reference Guide 37 . inclusive. these are all called by the clearAllLinks macro. 2=ERROR. historical data. Clicking this button cancels all market data. enter the desired log level value (1 =SYSTEM.200 ms. 5=DETAIL). market scanner subscriptions. The allowed range is 100 ms. Note: Clearing all links does NOT cancel orders. update the clearAllLinks macro to clear those links as well. • Type the refresh rate value (in milliseconds) in the Refresh Rate field. To set the level of detail for logging of API client requests 1 2 In the Log Level field in the Which Trader Workstation? area. then click the Set Log Level button. Move your cursor out of the Log Level field. then click Set Refresh Rate on the toolbar.xls spreadsheet to TWS that the Visual Basic for Applications (VBA) code provided with the spreadsheet could create. 3=WARNING. To set the processing rate The server processing rate affects the speed at which the DDE handles requests between TWS and the spreadsheet. Each page in the spreadsheet contains its own clearLinks macro. so setting the refresh rate to 250 will get every tick to the spreadsheet. then click Set Processing Rate on the toolbar.

DDE for Excel Tickers Page Tickers Page Toolbar Buttons The toolbar on the Tickers page includes the buttons described below. Enter information to create a market data line. Enter contract details to create legs of a combination order one by one. This specifies the level of log entry detail used when processing API requests. inclusive. The Refresh Rate value is in milliseconds. and determines how often the DDE link to TWS is refreshed. Button Create Ticker Combo Legs Request Market Data Set Refresh Rate Description Opens the Ticker box. inclusive. Clears all DDE links to the TWS. Valid values include: 1 = SYSTEM 2 = ERROR 3 = WARNING 4 = INFORMATION 5 = DETAIL Jumps to the Error Code field and shows the error code. A Refresh Rate of 250 will get every tick to the spreadsheet. If you subscribe to bulletins. Opens the Combination Legs box. This means the default "every 1 second" rate will only show 30% of the ticks. Select a line and click to get market data for the selected contract. Set Processing Rate Set Log Level Show Errors Show Bulletins Clear All Links API Reference Guide 38 . Note that the TWS market data updates every 300 milliseconds. Set the TWS/DDE server message processing rate (also in milliseconds) to affect the speed at which DDE will handle requests between the spreadsheet and TWS. news will appear in the RED box in the upper right corner of the spreadsheet. The allowed range is 100ms to 2000ms. The default refresh rate is 1000 (updates every 1 second). Opens the News Bulletins message. and the allowed range is 100ms to 2000ms.

API Reference Guide 39 . Create a "basket" of orders. Create combination orders.DDE for Excel Basic Orders Page Basic Orders Page Use the Basic Orders page to: • • • • Create an order. Modify and cancel orders.

You must define the Action (Buy. Quantity. highlight the first order. 4 If desired. and that you have entered your user name in the User Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet to properly connect to TWS. Limit Price (unless it's a market order) and if necessary. This applies all attributes you have defined on the Extended Order Attributes page. API Reference Guide 40 . apply extended order attributes by clicking the Apply Extended Template button on the toolbar. hold the Ctrl key down as you select each order. Sell or Short Sell). Define a contract by typing a symbol in a blank Symbol field. Select a contract and set up the order using the Order Description fields. Define a contract by typing a symbol in a blank Symbol field. Repeat Steps 1 and 2 for additional orders. then highlight the last order of the group. the Aux. 5 To place a "basket" of orders 1 2 3 4 5 Click the Basic Orders tab at the bottom of the spreadsheet. then entering information in the relevant contract description fields. hold down the Shift key. • 6 Click the Place/Modify Order button.DDE for Excel Basic Orders Page Placing Orders This topic describes how to place the following types of orders on the Orders page: • • • Simple orders Basket orders Modified orders Ensure that TWS is running. Select a group of orders. Order Type. Click the Place/Modify Order button in the Toolbar section of the page. then entering information in the relevant contract description fields. Note: To place an order 1 2 3 Click the Basic Orders tab at the bottom of the spreadsheet. Price for order types that require it. Select a contract and set up the order using fields in the Order Description section. • To select a group of contiguous orders. To select a group of non-contiguous orders.

5 CALL (100) Sell 1 OPT AUG03 17. • To select a group of contiguous orders.5 CALL on ISE is "12345679". you would: • • Buy 1 OPT JUL03 17. 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 transaction. To select a group of non-contiguous orders. hold the Ctrl key down as you select each order. The conid for XYZ option AUG08 17. • • The conid for XYZ option JUL08 17. 2 Click the Basic Orders tab to build the combo leg definitions. Select the order or a group of orders.DDE for Excel Basic Orders Page To modify an order (or group of orders) 1 2 On the Basic Orders page. • 3 Click the Place/Modify Order button. Click the Combo Legs button on the Basic Orders page toolbar and enter leg information. hold down the Shift key. then highlight the last order of the group. change any necessary parameters in an order or group of orders. To buy a calendar spread. 1 Use the Contract Details page to get the contract id for both of the leg definitions. Your leg information is translated into the format: API Reference Guide 41 . highlight the first order.5 CALL on ISE is "12345678".5 CALL (100) To create a calendar spread order The following example walks you through the process of placing a hypothetical calendar spread order for XYZ on ISE.

one of the following errors will be returned: • • • • 312 = The combo details are invalid. The full place order DDE request string will look like this: =acctName|ord!id12345?place?BUY_1_XYZ_BAG_ISE_LMT_1_CMBLGS_2_1234 5678_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. the value may be any of the following: (SAME. 313 = The combo details for '<leg number>' are invalid. which must specify the SMART exchange. CLOSE). 314 = Security type 'BAG' requires combo leg details. 315 = Stock combo legs are restricted to SMART exchange.0) for retail accounts.DDE for Excel Basic Orders Page [CMBLGS]_[NumOfLegs]_[Combo Leg Definitions]_[CMBLGS] where: • [CMBLGS] is the delimiter used to identify the start and end of the leg definitions [NumOfLegs] is the number of leg definitions [Combo Leg Definitions] defines N leg definitions. The exception is for a STK leg definition. API Reference Guide 42 . and each leg definition consists of [conid]_[ratio]_[action]_[exchange]_[openClose]. Notes: 1. For institutional accounts.e. The openClose leg definition value is always 'SAME' (i. so the resulting combo substring looks as follows: CMBLGS_2_17496957_1_BUY_EMPTY_0_15910089_1_SELL_EMPTY_0_CMBL GS • • 3 The combination leg definitions must occur before the extended order attributes. OPEN. 2. The exchange for the leg definition must match that of the combination order.

DDE for Excel Basic Orders Page Supported Order Types The order types currently supported through the DDE for Excel API are: • • • • • • • • • • • • • Limit (LMT) Market (MKT) Limit if Touched (LIT) Market if Touched (MIT) Market on Close (MOC) Limit on Close (LOC) Pegged to Market (PEGMKT) Relative (REL) Stop (STP) Stop Limit (STPLMT) Trailing Stop (TRAIL) Trailing Stop Limit (TRAILLIMIT) Volume-Weighted Average Price (VWAP) Volatility orders (VOL) • API Reference Guide 43 .

3. etc) any valid underlying symbol STK OPT FUT use the format: YYYYMM number value (120. 2. 65. etc.DDE for Excel Basic Orders Page Order Attributes Field side quantity symbol secType Valid Values Buy Sell number value (1.) P C for put or call Smart any valid exchange/ECN symbol LMT LMTCLS MKT MKTCLS PEGMKT STP STPLMT TRAIL VWAP REL number value number value exp strike right exchange orderType lmtPrice auxPrice API Reference Guide 44 .

and defined any extended attributes. Cancel Order Apply Extended Template Show Errors API Reference Guide 45 . After you have completed the Order Description fields. click to create an order for the selected contract. Jumps to the Error Code field and shows the error code. Applies the current values on the Extended Order Attributes page to the highlighted order row.DDE for Excel Basic Orders Page Basic Orders Page Toolbar Buttons The toolbar on the Basic Orders page includes the following buttons: Button Combo Legs Place/Modify Orders Description Opens the Combination Legs box. This button cancels the order(s) you have highlighted. Enter contract details to create legs of a combination order one by one.

DDE for Excel Extended Order Attributes Page

Extended Order Attributes Page
The Extended Order Attributes page includes all of the optional attributes you can use when you send an order, such as setting a display size to create an iceberg order, adding orders to an OCA group, and setting the transmit date for a Good After Time order. Once you define the attributes on this page, you can apply them to a single order or selected group of orders using the Apply Extended Template button, which occurs on both the Orders page and the Conditional Orders page. The attributes populate the extended order attributes fields that follow the Order Status fields to the far right of the page.

API Reference Guide

46

DDE for Excel Extended Order Attributes Page

Manually Program Extended Order Attributes
Observe the following guidelines when you manually assign an attribute:

When appended to orderDescription, the number and order of attributes cannot be changed. For any attribute that is not defined, use the value 'EMPTY' or {}. Since a string length is limited to 255 characters, we recommend using the open/close curly braces {}. 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_{}_{}_{}_{}_{}_{}_{}_{}_SUP ERSOES_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_1_2_3_4 _5'

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 Conditional Orders page.

To apply extended order attributes to individual orders or a group of orders 1 2 3 Enter the value or values on the Extended Order Attributes page that you want to apply to an individual order or group of orders. On the Orders page, select the order or group of orders. 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 Attributes 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.

API Reference Guide

47

DDE for Excel Extended Order Attributes Page

Extended Order Attributes
The following table shows the available extended order attributes: Attribute timeInForce Valid Values DAY GTC OPG IOC String String (for institutions) O, C (for institutions) 0, 1 (for institutions) String 0 (don't transmit) 1 (transmit) String (the order ID used for the parent order, use for bracket and auto trailing stop orders) 0 (not a block order) 1 (this is a block order) 0 (not a sweep-to-fill order) 1 (this is a sweep-to-fill order) String (publicly disclosed order size)

ocaGroup account open/close origin orderRef transmit

parentId blockOrder sweepToFill displaySize

API Reference Guide

48

DDE for Excel Extended Order Attributes Page

Attribute triggerMethod

Valid Values Specifies how simulated Stop, Stop-Limit, and Trailing Stop orders are triggered. • O - the default value. The "double bid/ask" method will be used for orders for OTC stocks and US options. All other orders will used the "last" method. 1 - use "double bid/ask" method, where stop orders are triggered based on two consecutive bid or ask prices. 2 - "last" method, where stop orders are triggered based on the last price. 3 - "double-last" method, where stop orders are triggered based on last two prices. 4 – “bid-ask” method. For a buy order, a single occurrence of the bid price must be at or above the trigger price. For a sell order, a single occurrence of the ask price must be at or below the trigger price. 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. 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. 0 1 (order not visible when viewing market depth)

• • •

hidden

Only valid for orders routed to Island. • •

Discretionary Amount (SMART Routing) Good After Time Good 'Till Date

Used in conjunction with a limit order to give the order a greater price range over which to execute. Enter the date and time after which the order will become active. Use the format YYYYMMDD hh:mm:ss 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. For Advisor accounts only. The name of the Account Group.

FA Group

API Reference Guide

49

DDE for Excel Extended Order Attributes Page

Attribute FA Method

Valid Values For Advisor accounts only. The share allocation method. • • • • EqualQuantity NetLiq AvailableEquity PctChange

FA Percentage FA Profile Short Sale Slot

For Advisor accounts only. The share allocation percentage. For Advisor accounts only. The name of the Share Allocation profile. For institutions only. Valid values are: • • 1 2

Short Sale Location OCA Type

Institutional accounts only. 1 = Cancel on Fill with Block 2 = Reduce on Fill with Block 3 = Reduce on Fill without Block Individual = 'I' Agency = 'A', AgentOtherMember = 'W' IndividualPTIA = 'J' AgencyPTIA = 'U' AgentOtherMemberPTIA = 'M' IndividualPT = 'K' AgencyPT = 'Y' AgentOtherMemberPT = 'N' Institutions only 0 = false 1 = true Identifies the order as a minimum quantity order. The percent offset for relative orders. 0 = false 1 = true 0 = false 1 = true Maximum SMART order distance from the NBBO. match = 1 improvement = 2 transparent = 3 For BOX exchange only. The starting price. For BOX orders only.

Rule 80A

Settling Firm All or None Minimum Qty Percent Offset Electronic Trade Only Firm Quote Only NBBO Price Cap Auction Strategy

Starting Price

API Reference Guide

50

DDE for Excel Extended Order Attributes Page

Attribute Stock Ref Price

Valid Values Used for VOL orders to compute the limit price sent to an exchange (whether or not Continuous Update is used), and for price range monitoring. Also used for price improvement option orders. The stock delta. For BOX orders only. The lower value for the acceptable underlying stock price range. For price improvement option orders on BOX and VOL orders with dynamic management. The upper value for the acceptable underlying stock price range. For price improvement option orders on BOX and VOL orders with dynamic management. 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. 1 = daily 2 = annual 1 = average 2 = BidOrAsk Prior to TWS Release 859, use "1" to send a market order, "0" for no order. After TWS 859, enter an accepted order type such as: MKT, LMT, REL or MTL. 0 = false 1 = true Enter the Aux Price for Hedge Delta order types that require one. Used for Trailing Stop Limit orders only. This is the stop trigger price for TRAILLMT orders. Used for Scale orders only, this value defines the order size of the each order component. 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. 0 = false 1 = true

Delta Underlying Range (Low) Underlying Range (High) Volatility

Volatility Type Reference Price Type Hedge Delta Order Type

Continuous Update Hedge Delta Aux Price Trail Stop Price Scale Component Size Scale Price Increment

Outside RTH

API Reference Guide

51

DDE for Excel Conditional Orders Page

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 Conditional Statement fields (in blue), 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 Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet to properly connect to TWS.

To set up a conditional order 1 On the Conditional Orders page, first create the order you want transmitted when a condition is met by defining the contract in the Contract Description fields, and then using the Order Description area to set up the order parameters. In the blue Condition Statements area, use the Statement field to set the criteria which must be met to trigger the order. When the Statement = TRUE, your order will be submitted. The sample spreadsheet includes a pair of orders, with the second orders transmission depending on the first order being completely filled. In this case, the Statement field
API Reference Guide 52

2

DDE for Excel Conditional Orders Page

trigger is that the value in cell T10 (the Filled field) must be equal to the value in M10 (the order Quantity field). 3 4 Type ADD in the ADD/MOD field because you are creating a one-time order. Define the remaining order parameters just as you did in the Order Description area.

5

Complete the necessary fields on the Conditional Orders page according to the syntax in the following table. Description An Excel function which returns a true or false. When true, the order will be submitted; when false, nothing happens. Use ADD for a one-time order. Use MOD to continue checking and modifying the order until it is completely filled. This is the field that activates a conditional order, and orders will be activated only with the "ADD" or "MOD" tags. BUY SELL Enter the quantity of the order. Refer to list of supported order types. The limit price for Limit and Stop Limit order types. The stop-election price for Stop and Stop Limit order types, or the offset for relative orders.

Field Statement ADD/MOD

Action Quantity Order Type Lmt Price Aux. Price

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 Statement ADD/MOD Action Quantity Value Filled cell = 100 ADD SELL 100

API Reference Guide

53

Price Price-change order Value LMT 50 empty A price-change order will be triggered if a specific bid or ask price is greater than. then highlight the last order of the group. Change any necessary parameters. "=" ">" or "<" followed by the price. To select a group of non-contiguous orders. then click the Place/Modify Order button. less than or equal to a specific price. In this example. Price To modify an order (or basket of orders) 1 Select the order or a group of orders. hold down the Shift key. highlight the first order. Paste this in the formula bar ("=" entry field) for the Statement.DDE for Excel Conditional Orders Page Field Order Type Lmt Price Aux. ADD/MOD Action Quantity Order Type Lmt Price Aux. hold the Ctrl key down as you select each order. • To select a group of contiguous orders. put your cursor in the bid price field you want to use.10 Not used in this example. and add your qualifier. then copy the value that appears in the formula 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.20 ADD BUY 200 LMT 81. submit a buy limit order for 200 shares with a limit price of $81. To create a price change order with the condition "If the bid price drops below 81. API Reference Guide 54 . the formula would be: =username|tik!id4?bid<81. • 2 3 Click the Place/Modify Order button.20.10: Field Statement Value On the Tickers page.

DDE for Excel Conditional Orders Page Conditional Orders Page Toolbar Buttons The toolbar on the Conditional Orders page includes the following buttons: Button Combo Legs Description Opens the Combination Legs box. Jumps to the Error Code field and shows the error code. Enter contract details to create legs of a combination order one by one. and defined any extended attributes. After you have completed the Order Description fields. Applies all attributes on the Extended Order Attributes page to the selected order(s). This button cancels the order(s) you have highlighted. click to create an order for the selected contract. Place/Modify Order Apply Extended Template Cancel Order Show Errors API Reference Guide 55 .

DDE for Excel Advanced Orders Page Advanced Orders Page Use the Advanced Orders page to: • Create complex orders that require the use of extended order attributes. see Apply Extended Order Attributes to Individual Orders and Groups of Orders API Reference Guide 56 . including: • • • • Bracket orders VOL orders Trailing Stop Limit Orders Scale Orders Relative Orders • For more information about using extended order attributes for individual orders or groups of orders.

highlight the second order. The third order should be a SELL LMT order. but the system generates an Order ID. this value will be applied to all subsequent orders that you place in the spreadsheet. go to the Extended Order Attributes page and delete the Parent Order Id value you entered. API Reference Guide 57 . then click the Place/Modify Order button. The order is not executed. The second order should be a SELL STP order. Enter the contract descriptions and order descriptions for all three orders on three contiguous rows: • • • The first order should be a BUY LMT order. 4 Click the Advanced Orders tab. omitting the “id” prefix. Click the Advanced Orders tab. then click the Place/Modify Order button.DDE for Excel Advanced Orders Page Placing a Bracket Order Bracket orders in the DDE for Excel sample spreadsheet require the use of the extended order attributes Transmit and Parent Order Id. You must turn Transmit off until the order is completely set up. This ensures that your orders are not transmitted until you have completed the order setup. and you must identify the first order in the bracket as the Parent Order. The order is not executed but is now associated with the primary order by means of the Parent Order Id extended order attribute. 5 Copy the Order ID for the first order. To place a Buy-Limit bracket order 1 2 Click the Advanced Orders tab at the bottom of the spreadsheet. then click the Extended Order Attributes tab and paste the Order ID into the Value field for Parent Order Id (row 14). This value will be applied to all subsequent orders until you remove it from the Extended Order Attributes page. When you are done placing your bracket order. 6 Click the Advanced Orders tab. The entire bracket order is transmitted. 3 Click the Extended Order Attributes tab. 7 8 9 Click the Extended Order Attributes tab and change the value for Transmit back to 1 (row 13). Change the value for Transmit to 0 (row 13 on the Extended Order Attributes page). then click the Place/Modify Order button. highlight the first order in the bracket order. highlight the third order in the bracket order. If you do not. The first order of the bracket order is now the primary order.

Enter a low-end acceptable stock price relative to the selected option order.This value represents the volatility to use in calculating a limit price for the option.12 instead of . Enter 1 to use the average of the best bid and ask. Enter 0 if you do not want to use this feature. • Enter VOL in the Order Type field.Enter 1 for daily volatility or 2 for annual volatility. Volatility Type .This value is used to compute the limit price sent to an exchange and for stock range price monitoring. Enter values in the Value field for the following extended order attributes: • Volatility . If the price of the underlying instrument falls below the lower stock range price. API Reference Guide 58 . Enter this value as a percentage. Reference Price Type .DDE for Excel Advanced Orders Page Placing a Volatility Order In the DDE for Excel sample spreadsheet.optional Hedge Delta Order Type . you place VOL orders by entering values for the following extended order attributes: • • • • • • • • Volatility Volatility Type Reference Price Type Continuous Update Underlying Range (Low) . • • • 5 On the Extended Order Attributes page. 4 Click the Extended Order Attributes tab. Select a contract and set up the order using the Order Description fields. Continuous Update .optional To place a VOL order 1 2 3 Click the Advanced Orders tab at the bottom of the spreadsheet.Enter 1 to automatically update the option price as the underlying stock price (or futures price. for index options) moves. enter values in the Value field for the following optional extended order attributes: • Underlying Range (Low) . Define a contract by typing a symbol in a blank Symbol field. then entering information in the relevant contract description fields. or 2 to use NBB (bid) when buying a call or selling a put. or the NBO (ask) when selling a call or buying a put. enter 17. not as the market data is displayed.optional Underlying Range (High) .optional Hedge Delta Aux Price .1712. the option order will be canceled. For example.

MKT or REL. the option order will be canceled. Click the Apply Extended Template button. there are four values that make up a trailing stop limit order: • • • trailing amount stop price limit price limit offset • In the DDE for Excel API spreadsheet. Hedge Delta Order Type . Enter NONE if you do not want to use delta hedging.If you have entered LMT or REL as the Hedge Delta Order Type. Select a contract and set up the order using the Order Description fields. click the Place/Modify Order 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. then highlight the order row. Enter TRAILLIMIT in the Order Type field. then entering information in the relevant contract description fields. You must include the limit offset in the stop price (the Trail Stop Price extended order attribute). There is no field or extended order attribute for the limit offset value. If the price of the underlying instrument rises above the higher stock range price. you enter the trailing amount. • • • • Enter BUY or SELL in the Action field. With the order row highlighted. enter the price as the value for this attribute. go to the Extended Order Attributes page and delete the VOL order values you entered. Enter the trailing amount in the Aux Price field. To create a Trailing Stop Limit Order 1 2 3 Click the Advanced Orders tab at the bottom of the spreadsheet. these values will be applied to all subsequent orders that you place in the spreadsheet. Enter the limit price in the Lmt Price field.Enter LMT. API Reference Guide 59 . Define a contract by typing a symbol in a blank Symbol field. When you are done placing VOL orders. Hedge Delta Aux Price . stop price and limit price.Enter a high-end acceptable stock price relative to the selected option order. • • 6 7 Click the Advanced Orders tab. 8 9 Placing a Trailing Stop Limit Order In TWS. If you do not.DDE for Excel Advanced Orders Page • Underlying Range (High) .

select the order row and click the Apply Extended Template button. if you submit a 10. As of API Release 9. the first component will be fore 1000 shares. order component. Click the Extended Order Attributes tab. Scale Price Increment . • The Trail Stop Price value must include the limit offset.Trailing Amount . The order type should be LMT or REL. 6 7 Placing a Scale Order In the DDE for Excel sample spreadsheet.41. the Scale Num Components not supported. go to the Extended Order Attributes page and delete the Trail Stop Price value you entered. then entering information in the relevant contract description fields. or initial. Select a contract and set up the order using the Order Description fields. Specify the trailing stop price as an extended order attribute.DDE for Excel Advanced Orders Page 4 Click the Extended Order Attributes tab. • Note: API Reference Guide 60 . For example. For a sell order: Trail Stop Price = Limit Price . you place scale orders by entering values for the following extended order attributes: • • Scale Component Size Scale Price Increment To place a scale order 1 2 3 4 Click the Advanced Orders tab at the bottom of the spreadsheet. Type this value in the Trail Stop Price Value field. this value will be applied to all subsequent orders that you place in the spreadsheet. This cannot be a negative number. The Trail Stop Price value is applied to the selected order and displayed in the Trail Stop Price field in the Extended Order Attributes section of the page. Click the Place/Modify Order button. Enter values in the Value field for the following extended order attributes: • Scale Component Size .Enter the amount used to calculate the per-unit price of each component in the scale ladder.Limit Offset For a buy order: Trail Stop Price = Limit Price + Trailing Amount + Limit Offset 5 On the Advanced Orders page. When you are done placing your order.Enter the size of the first. If you do not. Define a contract by typing a symbol in a blank Symbol field.000-share order with a Scale Component Size value of 1000.

6 7 API Reference Guide 61 . Enter the price cap in the Lmt Price cell. Select a contract and set up the order using the Order Description fields. Enter a percentage in decimal form in the Value field for the Percent Offset extended order attribute. go to the Extended Order Attributes page and delete the Percent Offset value you entered. If you do not. When you are done placing your order. On the Advanced Orders page. Define a contract by typing a symbol in a blank Symbol field. Click the Place/Modify Order button. 4 5 Click the Extended Order Attributes tab. select the order row and click the Apply Extended Template button. then entering information in the relevant contract description fields. To place a relative order 1 2 3 Click the Advanced Orders tab at the bottom of the spreadsheet. go to the Extended Order Attributes page and delete the scale order values you entered. The scale order values are applied to the selected order and displayed in the Extended Order Attributes section of the page. The percent offset value is applied to the selected order and displayed in the Extended Order Attributes section of the page. 6 7 Placing a Relative Order In the DDE for Excel sample spreadsheet.DDE for Excel Advanced Orders Page 5 On the Advanced Orders page. this value will be applied to all subsequent orders that you place in the spreadsheet. When you are done placing your order. select the order row and click the Apply Extended Template button. If you do not. Click the Place/Modify Order button. these values will be applied to all subsequent orders that you place in the spreadsheet. you place relative orders by entering a value for the Percent Offset extended order attribute. • • Enter REL as the order type.

Jumps to the Error Code field and shows the error code. click to create an order for the selected contract. Applies the current values on the Extended Order Attributes page to the highlighted order row. Enter contract details to create legs of a combination order one by one. This button cancels the order(s) you have highlighted. After you have completed the Order Description fields. Cancel Order Apply Extended Template Show Errors API Reference Guide 62 .DDE for Excel Advanced Orders Page Advanced Orders Page Toolbar Buttons The toolbar on the Advanced Orders page includes the following buttons: Button Combo Legs Place/Modify Orders Description Opens the Combination Legs box. and defined any extended attributes.

it remains on the Open Orders page for 30 seconds. with the Status value changed to FILLED. either through the API or in TWS. API Reference Guide 63 . and those that are working at an exchange. Once you have subscribed. the page is updated each time you submit a new order. Then the filled order is cleared and you can see it on the Executions page if you subscribed to real-time executions.DDE for Excel Open Orders Page Open Orders Page The Open Orders page shows you all transmitted orders. including those that have been accepted by the IB system. Once an order executes.

Open Orders Tab Toolbar The toolbar on the Open Orders page includes the following buttons: Button Subscribe to Open Orders Description Once you enter a valid user name. Jumps to the Error Code field and shows the error code. Click Subscribe to Open Orders on the toolbar. To view open orders: 1 2 Click the Open Orders tab at the bottom of the spreadsheet. clicking this button queries TWS and returns all open orders. To remove open orders 1 2 Click the Cancel Open Orders Subscription button on the toolbar. Cancel Open Orders Subscription Clear Open Orders Show Errors API Reference Guide 64 . Orders that fill remain on the page for 30 seconds with a value of Fill in the Status field. Click the Clear Open Orders button. The page will no longer show your open orders. All of your open orders are displayed on the page. and that you have entered your user name in the User Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet to properly connect to TWS. Once you subscribe to open orders. Removes all open orders from the page.DDE for Excel Open Orders Page Viewing Open Orders Note: Ensure that TWS is running. including orders you enter in the Excel API spreadsheet and in TWS. this page updates each time there is a new open order. Cancels the open orders subscription.

To view executions 1 2 Click the Executions tab at the bottom of the spreadsheet. API Reference Guide 65 . Click the Subscribe to Executions button in the toolbar. Click the Clear Executions button.DDE for Excel Executions Page Executions Page When you subscribe to executions. To remove execution reports 1 2 Click the Cancel Executions Subscription button on the toolbar. Viewing Executions Note: Ensure that TWS is running. and that you have entered your user name in the User Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet to properly connect to TWS. the Executions page displays information about all completed trades (also called “execution reports”).

DDE for Excel Executions Page Executions Page Toolbar Buttons The toolbar on the Executions page includes the following buttons: Button Subscribe to Executions Description After you have entered a valid user name. Removes all execution reports from the page. Jumps to the Error Code field and shows the error code. this page updates each time an order executes. Click to cancel the execution subscription. After you subscribe to executions. this button queries TWS and returns information about all valid executions. Cancel Executions Subscription Clear Executions Show Errors API Reference Guide 66 .

and how such data can be used in your own custom DDE for Excel API applications. Order Reference number. you can use the Executions Reporting page to run reports based on an Order ID. the Executions Reporting page is a practical example of how you can extract array subscription data from the named ranges into which the data is put when it is received.DDE for Excel Executions Reporting Page Executions Reporting Page Once you have subscribed to executions on the Executions page. or strategy From a programming point of view. VOL order key. API Reference Guide 67 .

Order Ref . including any hedge delta executions. and that you have entered your user name in the User Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet to properly connect to TWS. In the Type field select from: • • Order ID .DDE for Excel Executions Reporting Page Running Execution Reports Note: Ensure that TWS is running. enter a value to define the Type you selected. Click the Executions Reporting tab at the bottom of the worksheet.in the Key field. VOL order . for example executions from a specific basket order. To run execution reports 1 2 3 On the Executions page.finds all executions resulting from specific volatility order.finds all executions resulting from orders with a given order reference. enter a specific order ID in the Key field. Strategy . • • API Reference Guide 68 . click the Subscribe to Executions button on the toolbar. if you selected Order ID as the type. For example.finds all executions resulting from orders with a specified PermID.

View list of advisor-managed account codes. • • API Reference Guide 69 .DDE for Excel Account Page Account Page Use the Account page to: • View account details including your current Equity with Loan Value and Available funds. View your current portfolio.

To request the list of Financial Advisor (FA) managed account codes 1 2 Click the Account tab at the bottom of the spreadsheet. Click the Request Managed Accounts button. Click the Subscribe to Account Updates button on the toolbar. To view account information 1 2 Click the Account tab at the bottom of the spreadsheet. Click the Request Managed Accounts button. To remove account information 1 2 Click the Cancel Account Subscription button.DDE for Excel Account Page Using the Account Page Note: Ensure that TWS is running. In the Account Code field in the Which Trader Workstation? area. API Reference Guide 70 . type the account code for which you want details. Click the Clear Account Data button. and that you have entered your user name in the User Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet to properly connect to TWS. To request details of a Financial Advisor (FA) managed account 1 2 3 Click the Account tab at the bottom of the spreadsheet.

the past month’s accrual is added to the cash balance and this field is zeroed out.Initial margin • Buying Power Cash Account: (Minimum (Equity with Loan Value. Identifies the IB account type. updated daily.Initial margin For commodities: • Net Liquidation Value . The number of day trades you have left for a 4-day pattern day-trader. API Reference Guide 71 . Notes Available Funds For securities: Equity with Loan Value . Reflects the current month's accrued debit and credit interest to date. For internal use only. 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 Cushion Day Trades Remaining Day Trades Remaining T+1. At the beginning of each month. T+4 Shows the currency types that are listed in the Market Value area. T+2.DDE for Excel Account Page Account Page Values The Account page displays the following values: Field Account Code Account Ready Account Type Accrued Cash Description The account number. T+3. Number of day trades left for pattern day trader period. Shows your current margin cushion.

S. futures PNL) Margin Account: • Total cash value + commodities option value futures maintenance margin requirement • • Notes Excess Liquidity Exchange Rate Full Available Funds Equity with Loan Value . & Canada securities options value) For Commodities: Cash Account: Total cash value + commodities option value .Initial margin For commodities: • Net Liquidation Value .Maintenance margin The exchange rate of the currency to your base currency. Real-time mark-to-market value of futures options.DDE for Excel Account Page Field Equity With Loan Value Description For Securities: • Cash Account: Settled Cash Margin Account: Total cash value + stock value + bond value + (non-U. Initial margin requirement in the base currency of the account. Real-time change in futures value since last settlement.Initial margin • Full Excess Liquidity Full Init Margin Req Full Maint Margin Req Future Option Value Futures PNL Gross Position Value Init Margin Req Equity with Loan Value . Maintenance margin requirement as of next period's margin change in the base currency of the account. API Reference Guide 72 . Long Stock Value + Short Stock Value + Long Option Value + Short Option Value.futures maintenance margin requirement + minimum (0.Maintenance margin Overnight initial margin requirement in the base currency of the account. For securities: Equity with Loan Value .

Initial margin • Notes Look Ahead Available Funds For Securities: Equity with loan value . Previous Day Equity with Loan Value API Reference Guide 73 . Maintenance margin requirement in the base currency of the account. The difference between the current market value of your open positions and the average cost. For Securities: Total cash value + stock value + securities options value + bond value For Commodities: • Total cash value + commodities options value • Net Liquidation by Currency Option Market Value PNL Same as above for individual currencies. Real-time mark-to-market value of securities options. Marginable Equity with Loan Value as of 16:00 ET the previous day.Average Cost. Initial margin requirement as of next period's margin change in the base currency of the account.look ahead initial margin. Maintenance margin requirement as of next period's margin change in the base currency of the account. For Commodities: • Net Liquidation value . only applicable to securities. • Look Ahead Excess Liquidity Look Ahead Init Margin Req Look Ahead Maint Margin Req Maint Margin Req Net Liquidation Equity with loan value .look ahead initial margin. or Value .DDE for Excel Account Page Field Leverage Description For Securities: Gross Position value / Net Liquidation value For Commodities: • Net Liquidation value .look ahead maintenance margin.

(execution price + commissions to close the position).)) *calculated end of day under US Stock rules. Stock Market Value Total Cash Balance Total Cash Value API Reference Guide 74 . which is the difference between your entry execution cost and exit execution cost. or (execution price + commissions to open the positions) . **at the time of the trade Real-time mark-to-market value of stock Cash recognized at the time of trade + futures PNL Total cash value of stock. futures PNL) Margin Account : Total cash value .futures maintenance margin requirement + minimum (0. & Canada securities options value) Cash Account : Total cash value + commodities option value . For Securities: • • Cash Account : Settled Cash Margin Account : Total cash value + stock value + bond value + (non-U.DDE for Excel Account Page Field Realized PnL Description Shows your profit on closed positions.US initial margin requirements)*. Initial margin requirements calculated under US Regulation T rules. commodities and securities Only applicable for securities. regardless of country of trading. (Prior Day SMA +/change in day's cash +/.futures maintenance margin requirement Notes Reg T Equity Reg T Margin For Commodities: • • SMA Max ((EWL .US initial margin requirements** for trades made during the day.S.

All blank lines that precede the Account Portfolio section will hold data. Button Subscribe to Account Updates Description Each click gives you data for a specific account value. Click this button one time for each position you hold. Jumps to the Error Code field and shows the error code. Continue to click until all lines are populated. Cancel Account Subscription Clear Account Data Request Managed Accounts Show Errors API Reference Guide 75 . When you get a line of "0's" you know you have downloaded all current positions. You must first cancel your subscription before you can clear the data.DDE for Excel Account Page Account Page Toolbar Buttons The toolbar on the Account page includes the following buttons. For advisor accounts. These values continue to update in real-time. click this button one time for each account. Clears all information from the page.

To view your portfolio 1 2 Click the Portfolio tab at the bottom of the worksheet. API Reference Guide 76 . To remove portfolio information 1 2 Click the Cancel Portfolio Subscription button. which you can see in the Last Update Time field in the Which Trader Workstation? area of the page. Click the Subscribe to Portfolio Updates button. Viewing Your Portfolio Note: Ensure that TWS is running. and that you have entered your user name in the User Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet to properly connect to TWS. Click the Clear Portfolio Data button. This page communicates with TWS and updates the values every three minutes.DDE for Excel Portfolio Page Portfolio Page The Portfolio page displays all of your current positions.

Removes all data from the page. Show Errors API Reference Guide 77 . You must cancel your subscription before you can clear all data. Cancels the connection to TWS that updates your portfolio information. Jumps to the Error Code field and shows the error code. Button Subscribe to Portfolio Updates Cancel Portfolio Subscription Clear Portfolio Data Description Click to view all current portfolio data.DDE for Excel Portfolio Page Portfolio Page Toolbar Buttons The toolbar on the Portfolio page includes the following buttons.

and you can chart and sort the data in Excel. see Historical Data Limitations. Note that since the query returns in a named range of cells.DDE for Excel Historical Data Page Historical Data Page Use the Historical Data page to request historical data for an instrument based on data you enter in query fields. Note: For a information about historical data request limitations. you can write VBA macros to perform computations on it. The query results display on a separate worksheet page and creates a new page for the results if the page doesn't currently exist. API Reference Guide 78 .

Enter the parameters of your query in the Query Specification fields. Create a ticker by filling in the fields in the Contract Description section of the page. or by clicking the Create Ticker button on the toolbar and entering the required information in the Ticker box. Historical Data Page Query Specification Fields. and that you have entered your user name in the User Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet to properly connect to TWS. enter TRUE. To request historical data 1 2 Click the Historical Data tab at the bottom of the spreadsheet. When the Ctrl field displays "Finished. 2 3 4 API Reference Guide 79 . create a ticker by filling in the fields in the Contract Description section of the page. Enter the parameters of your query in the Query Specification fields. When the Ctrl field displays "Finished." the results are displayed on the specified page. or by clicking the Create Ticker button on the toolbar and entering the required information in the Ticker box." the results are displayed on the specified page. For complete descriptions of the query fields. Select the line. Select the line. 3 4 To request historical data for expired contracts 1 On the Historical Data page. In the Expired field in the Query Specification section. then click the Request Historical Data button. then click the Request Historical Data button. Note: Historical data queries on expired contracts are limited to the last year of the life of the contract.DDE for Excel Historical Data Page Viewing Historical Data Note: Ensure that TWS is running.

API Reference Guide 80 .DDE for Excel Historical Data Page The following figure shows a typical historical data results page.

seconds are used. If no unit is specified. Note that you can use either the Integer value of the Bar Size String or the Integer Value to define the bar sizes. and is specified using the format integer {space} unit. and the value in each line is equal to one second. API Reference Guide 81 . and are specified using the parametric value: Bar Size String Integer Value 1 second 1 5 seconds 2 15 seconds 3 30 seconds 4 1 minutes 5 2 minutes 6 3 minutes 16 5 minutes 7 15 minutes 8 30 minutes 9 1 hour 10 1 day 11 1 week 12 1 month 13 3 months 14 1 year 15 On the query return page. where valid units are: • • • S (seconds) D (days) W (weeks) Duration • Y (years) This unit is currently limited to one. Bar Size Specifies the size of the bars that will be returned. each "bar" is represented by a line in the spreadsheet. The following bar sizes may be used. and a bar size of "1" (one second) your return will include 300 lines. or is a one-second bar.DDE for Excel Historical Data Page Historical Data Page Query Specification Fields Historical Data queries include the following fields: Parameter End Date/Time Description Use the format yyyymmdd {space}hh:mm:ss{space}tmz where the time zone is allowed (optionally)after a space at the end. If you specify a duration of 300 seconds. This is the time span the request will cover.

low. Valid values: TRUE. close. Valid values include: • 0 . These bars are identical to the TWS charts' candlestick bars.all data available during the time span requested is returned. This appears in the tab for the results page at the bottom of the worksheet. Valid values include: • • • • Trades Midpoint Bid Ask • Bid/Ask All but the Bid/Ask data contain the start time. volume and weighted average price during the time slice queried. even if the time span falls partially or completely outside.the dates are returned as an integer specifying the number of seconds since 1/1/1970 GMT.only data within the regular trading hours for the product requested is returned. FALSE If TRUE. high. respectively. the open and close values are the time-weighted average bid and the time-weighted average offer. API Reference Guide 82 . Note that the new page is added to the right of the existing tabs on the worksheet. 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). For the Bid/Ask query.DDE for Excel Historical Data Page Parameter What to Show Description Determines the nature of the data extracted. 1 . including time intervals when the market in question was outside of regular trading hours. 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 data query can be done on an expired futures contract.dates that apply to bars are returned in the format yyyymmdd{space}{space}hh:mm:dd (the same format used when reporting executions). • Date Format Style Valid values include: • • Page Name Expired The name of the results page. 1 . 2 . RTH Only Regular Trading Hours only. open.

Cancels the historical data request. Enter contract details to create legs of a combination order one by one. Button Create Ticker Combo Legs Description Opens the Ticker box. Jumps to the Error Code field and shows the error code. Request Historical Data Cancel Historical Data Show Errors API Reference Guide 83 . Enter information to create a market data line. Submits your historical data query to TWS and displays the results on a separate worksheet page.DDE for Excel Historical Data Page Historical Data Page Toolbar Buttons The toolbar on the Historical Data page includes the following buttons. Opens the Combination Legs box.

These scanners allow you to define criteria and set filters that return the top x number of underlyings which meet all scan criteria. API Reference Guide 84 .DDE for Excel Market Scanner Page Market Scanner Page Use the Market Scanner page to subscribe to TWS market scanners. The scan is continually updated in real time.

Filters out returns with an average volume below the named price. Highlight an existing scanner row. The instrument type used in the scan. The number of rows of data to return in the results. Scan Code Instrument Location code Stock type filter Number of rows Price Above Price Below Average volume above API Reference Guide 85 . or both. or enter information for a different market scanner: a b Type the name of the scan results page in the Page Name field. To stop this behavior. US Stocks) for the scan. Type TRUE or FALSE in the Activate Page field.e. Setting these field to TRUE forces the scan results page to pop to the front of your application every time it updates. The type of scan. Click the Start Scanner Subscription button in the toolbar. A new page for the scanner is created and is displayed after the subscription is processed. This could be as often as every minute. Market Scanner Parameters The following table describes the market scanner parameters that make up a scanner subscription. Can be left empty. Can be left empty. Filters out returns with prices below the named price. Parameter Page name Activate Page? Description The name that will be given to the new page that is created with the scanner data. If set to true. Allows you to specify just stocks. The market used (i. c 3 Type values for the rest of the scan parameters in the lightly shaded section of the page. Can be left empty. just ETFs.DDE for Excel Market Scanner Page Starting a Market Scanner Subscription Note: Ensure that TWS is running. the new scanner page will display on top of the worksheet every time the scan results update. and that you have entered your user name in the User Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet to properly connect to TWS. set the value of this field to FALSE. Filters out returns with prices above the named price. To start a scanner subscription 1 2 Click the Market Scanner tab at the bottom of the spreadsheet.

Filters out returns with a market capitalization value below the named price. Can be left empty. Can be left empty. Delimit setting pairs by slashes. Filters out convertible bonds. Can be left empty. Filters out returns with an S&P rating below the named price. API Reference Guide 86 . Can be left empty. Can be left empty.DDE for Excel Market Scanner Page Parameter Average Option Volume Above Market Cap Above Market Cap Below Moody Rating Above Moody Rating Below S & P Rating Above S & P Rating Below Maturity Date Above Maturity Date Below Coupon Rate Above Coupon Rate Below Exclude Convertible Scanner Settings Pairs Description Filters out returns with an average option volume below the named price. Filters out returns with an S&P rating above the named price. Filters out returns with a Moody rating above the named price. Can be left empty. Can be left empty. Filters out returns with a coupon rate below the named price. Can be left empty. Filters out returns with a Moody rating below the named price. Can be left empty. Can be left empty. Filters out returns with a market capitalization value above the named price. Filters out returns with a maturity date below the named price. Filters out returns with a maturity date above the named price. Can be left empty. Filters out returns with a coupon rate above the named price. For example "Annual/True" used on the Top Option Implied Vol% Gainers would instruct the scan to return annualized volatilities. Can be left empty.

Shows the top underlying contracts for highest options volume over a 10-day average. Top Option Imp Vol % Gainers (TOP_OPT_IMP_VOLAT_GAIN)* Top Option Imp Vol % Losers (TOP_OPT_IMP_VOLAT_LOSE)* High Opt Volume P/C Ratio (HIGH_OPT_VOLUME_PUT_CALL_ RATIO) Low Opt Volume P/C Ratio (LOW_OPT_VOLUME_PUT_CALL_ RATIO) Most Active by Opt Volume (OPT_VOLUME_MOST_ACTIVE) Hot by Option Volume (HOT_BY_OPT_VOLUME) High Option Open Interest P/C Ratio (HIGH_OPT_OPEN_INTEREST_PUT_ CALL_RATIO) Low Option Open Interest P/C Ratio (LOW_OPT_OPEN_INTEREST_PUT_ CALL_RATIO) API Reference Guide 87 . Displays the most active contracts sorted descending by options volume. run the Market Scanners in TWS. Returns the top 50 contracts with the highest put/call ratio of outstanding option contracts. Shows the top underlying contracts (stocks or indices) with the largest percent gain between current implied volatility and yesterday's closing value of the 15 minute average of implied volatility. Shows the top underlying contracts (stocks or indices) with the largest divergence between implied and historical volatilities. Market Scanner (Scan Code) Low Opt Volume P/C Ratio (LOW_OPT_VOL_PUT_CALL_RATIO)* High Option Imp Vol Over Historical (HIGH_OPT_IMP_VOLAT_OVER_HIST)* Low Option Imp Vol Over Historical (LOW_OPT_IMP_VOLAT_OVER_HIST)* Highest Option Imp Vol (HIGH_OPT_IMP_VOLAT)* Description Put option volumes are divided by call option volumes and the top underlying symbols with the lowest ratios are displayed.DDE for Excel Market Scanner Page Available Market Scanners The following table shows the available market scanners in the DDE for Excel API spreadsheet. Shows the top underlying contracts (stocks or indices) with the smallest divergence between implied and historical volatilities. Returns the top 50 contracts with the lowest put/call ratio of outstanding option contracts. Put option volumes are divided by call option volumes and the top underlying symbols with the lowest ratios are displayed. Shows the top underlying contracts (stocks or indices) with the highest vega-weighted implied volatility of near-the-money options with an expiration date in the next two months. Note: To get more detailed market scan results than are available in the DDE for Excel API spreadsheet. Put option volumes are divided by call option volumes and the top underlying symbols with the highest ratios are displayed. Shows the top underlying contracts (stocks or indices) with the largest percent loss between current implied volatility and yesterday's closing value of the 15 minute average of implied volatility.

The sample spreadsheet includes two Most Active scans: Most Active List. The largest price range (from Top Price Range calculation) over the volatility. based on units used by TWS (lots for US stocks. which displays the most active stocks in the United States. The top volume rate per minute. contract for derivatives and non-US stocks). Contracts where: • • today's Volume/avgDailyVolume is highest. Top % Losers (TOP_PERC_LOSE) Hot Contracts by Volume (HOT_BY_VOLUME) Top % Futures Gainers (TOP_PERC_GAIN) Hot Contracts by Price (HOT_BY_PRICE) Futures whose last trade price shows the highest percent increase from the previous night's closing price.DDE for Excel Market Scanner Page Market Scanner (Scan Code) Top % Gainers (TOP_PERC_GAIN) Most Active (MOST_ACTIVE) Description Contracts whose last trade price shows the highest percent increase from the previous night's closing price. which displays the most active contracts in the NASDAQ. or yesterday's close if outside of today's range. NYSE and AMEX markets. Contracts whose last trade price shows the lowest percent increase from the previous night's closing price. The largest difference between today's high and low. API Reference Guide 88 . avgDailyVolume is a 30-day exponential moving average of the contract's daily volume. Contracts with the highest trading volume today. Contracts with the highest number of trades in the past 60 seconds (regardless of the sizes of those trades). Contracts where: • (lastTradePrice-prevClose)/avgDailyChan ge is highest in absolute value (positive or negative). and Most Active US. The avgDailyChange is defined as an exponential moving average of the contract's (dailyClose-dailyOpen) • Top Trade Count (TOP_TRADE_COUNT) Top Trade Rate (TOP_TRADE_RATE) Top Price Range (TOP_PRICE_RANGE) Hot by Price Range (HOT_BY_PRICE_RANGE) Top Volume Rate (TOP_VOLUME_RATE) The top trade count during the day.

The lowest price for the past 13 weeks. Shows contracts with the highest percent price DECREASE between the last trade and opening prices. Contracts for which trading has been halted. Shows the top underlying contracts (stocks or indices) with the largest percent gain between current implied volatility and yesterday's closing value of the 15 minute average of implied volatility. Returns the top 50 underlying contracts with the (highest number of outstanding call contracts) + (highest number of outstanding put contracts) Contracts that have not traded today. The highest price for the past 13 weeks. Shows contracts with the highest percent price INCREASE between the previous close and today's opening prices. The lowest price for the past 26 weeks. Most Active by Opt Open Interest (OPT_OPEN_INTEREST_MOST_ ACTIVE) Not Open (NOT_OPEN) Halted (HALTED) Top % Gainers Since Open (TOP_OPEN_PERC_GAIN) Top % Losers Since Open (TOP_OPEN_PERC_LOSE) Top Close-to-Open % Gainers (HIGH_OPEN_GAP) Top Close-to-Open % Losers (LOW_OPEN_GAP) Lowest Option Imp Vol (LOW_OPT_IMP_VOLAT)* Top Option Imp Vol % Gainers (TOP_OPT_IMP_VOLAT_GAIN)* Top Option Imp Vol % Losers (TOP_OPT_IMP_VOLAT_LOSE)* 13-Week High (HIGH_VS_13W_HL) 13-Week Low (LOW_VS_13W_HL) 26-Week High (HIGH_VS_26W_HL) 26-Week Low (LOW_VS_26W_HL) API Reference Guide 89 . Shows contracts with the highest percent price DECREASE between the previous close and today's opening prices. Shows the top underlying contracts (stocks or indices) with the largest percent loss between current implied volatility and yesterday's closing value of the 15 minute average of implied volatility. The highest price for the past 26 weeks. Shows the top underlying contracts (stocks or indices) with the lowest vega-weighted implied volatility of near-the-money options with an expiration date in the next two months.DDE for Excel Market Scanner Page Market Scanner (Scan Code) Lowest Option Imp Vol (LOW_OPT_IMP_VOLAT) Description Shows the top underlying contracts (stocks or indices) with the lowest vega-weighted implied volatility of near-the-money options with an expiration date in the next two months. Shows contracts with the highest percent price INCREASE between the last trade and opening prices.

The IB 30-day volatility is the at-market volatility estimated for a maturity thirty calendar days forward of the current trading day. A linear interpolation (or extrapolation.Low Synth Bid Rev Yield (LOW_SYNTH_BID_REV_NAT_ YIELD) *30-day (V30) Implied Volatilities: Implied volatility is calculated using a 100-step binary tree for American style options. Highlights the highest synthetic EFP interest rates available. If there is no first expiration month with less than sixty calendar days to run.DDE for Excel Market Scanner Page Market Scanner (Scan Code) 52-Week High (HIGH_VS_52W_HL) 52-Week Low (LOW_VS_52W_HL) EFP . Interest rates are calculated using the settlement prices from the day's Eurodollar futures contracts. The Low rates may present a borrowing opportunity. The lowest price for the past 52 weeks. These rates are computed by taking the price differential between the SSF and the underlying stock and netting dividends to calculate an annualized synthetic implied interest rate over the period of the SSF. EFP . The High rates may present an investment opportunity. and a Black-Scholes model for European style options. Highlights the lowest synthetic EFP interest rates available. 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 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. The implied volatilities are fit to a parabola as a function of the strike price for each expiry. as required) of the 30-day variance based on the squares of the at-market volatilities is performed. API Reference Guide 90 . V30 is then the square root of the estimated variance. It is based on option prices from two consecutive expiration months. These rates are computed by taking the price differential between the SSF and the underlying stock and netting dividends to calculate an annualized synthetic implied interest rate over the period of the SSF. we do not calculate a V30.High Synth Bid Rev Yield (HIGH_SYNTH_BID_REV_NAT_ YIELD) Description The highest price for the past 52 weeks. and dividends are based on historical payouts.

Cancels the market scanner. Button Start Scanner Subscription Cancel Scanner Subscription Show Errors Description Creates and displays a new page for results of the selected market scanner.DDE for Excel Market Scanner Page Market Scanner Page Toolbar Buttons The toolbar on the Market Scanner page includes the following buttons. Jumps to the Error Code field and shows the error code. API Reference Guide 91 .

Requesting Contract Details Note: Ensure that TWS is running. type TRUE in the Expired field. To request contract details for an expired contract. the contract ID. valid exchanges. and so on. Click the Request Contract Details button on the toolbar. Select or enter the ticker symbol for which you want to request contract details.DDE for Excel Contract Details Page Contract Details Page Use the Contract Details page to request contract-specific information such as supported order types. and that you have entered your user name in the User Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet to properly connect to TWS. API Reference Guide 92 . To request details for a contract 1 2 3 4 Click the Contract Details tab at the bottom of the spreadsheet to open the Contract Details page.

API Reference Guide 93 .DDE for Excel Contract Details Page Contract Details Page Toolbar Buttons The toolbar on the Contract Details page includes the following buttons: Button Request Contract Details Show Errors Description Returns information on the selected contract. Jumps to the Error Code field and shows the error code.

DDE for Excel Bond Contract Details Page Bond Contract Details Page Use the Bond Contract Details page to request contract-specific information for bonds. API Reference Guide 94 . Click the Request Bond Contract Details button on the toolbar. and so on. To request details for a bond contract 1 2 3 Click the Bond Contract Details tab at the bottom of the spreadsheet. bond type. including the coupon. Enter the ticker symbol for which you want to request contract details. maturity date. ratings. and that you have entered your user name in the User Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet to properly connect to TWS. Requesting Bond Contract Details Note: Ensure that TWS is running.

Jumps to the Error Code field and shows the error code.DDE for Excel Bond Contract Details Page Bond Contract Details Page Toolbar Buttons The toolbar on the Bond Contract Details page includes the following buttons: Button Request Bond Contract Details Show Errors Description Gets bond information data for the selected contract. API Reference Guide 95 .

and NASDAQ-listed products through the TotalView Market Data Subscriptions. You can also view market depth for NYSE-listed products through the Open Book Market Data Subscription. API Reference Guide 96 .DDE for Excel Market Depth Page Market Depth Page Use the Market Depth page to view market depth for selected contracts. if you have signed up for those subscriptions.

Click the Request Market Depth button on the toolbar. then click the Save button on the VBE toolbar. The Visual Basic Editor (VBE) opens and displays the code for the Market Depth page. 1 From the Market Depth page. or enter a new ticker on a blank line. 2 In the Declarations section at the top of the code window for the page. Select the ticker symbol for which you want to request the market depth. change the number value in numDisplayRows = 10 to a higher/lower value. Close the Visual Basic Editor. To request market depth for a contract 1 2 3 Click the Market Depth tab at the bottom of the spreadsheet to open the Market Depth page. Move your cursor out of the Refresh Rate field. To display more lines of market depth You can edit the Request Market Depth macro to show more than the default 10 lines.DDE for Excel Market Depth Page Using the Market Depth Page Note: Ensure that TWS is running. Type the desired market data refresh rate in milliseconds in the Refresh Rate field in the Which Trader Workstation? area. 3 API Reference Guide 97 . Click the Set Refresh Rate button on the toolbar. To reset the market data refresh rate for tickers and market depth 1 2 3 4 Click the Tickers or Market Depth tab at the bottom of the spreadsheet. press Alt+F11. and that you have entered your user name in the User Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet to properly connect to TWS.

Cancel market depth for the selected contract. Resets the refresh rate (in milliseconds) for market data.DDE for Excel Market Depth Page Market Depth Page Toolbar Buttons The toolbar on the Market Depth page includes the following buttons: Button Request Market Depth Cancel Market Depth Set Refresh Rate Show Errors Description View bid/ask depth prices for the selected contract. API Reference Guide 98 . Jumps to the Error Code field and shows the error code.

account groups. methods and allocation profiles in TWS before you can place FA orders in the DDE for Excel API sample spreadsheet. API Reference Guide 99 .DDE for Excel Advisors Page Advisors Page If you are a Financial Advisor and manage multiple accounts. use the Advisors page to create FA orders that: • • • allocate shares to a single managed account use FA account groups and methods use allocation profiles Note: You must set up your managed accounts.

Enter the account code in the Value cell for the Account (Institutional only) extended order attribute. delete the Account value from the Extended Order Attributes page. Click the Extended Order Attributes tab. Click the Advisors tab at the bottom of the spreadsheet. Highlight the order row. To allocate shares to a single account: 1 2 3 4 5 6 Create an account group in TWS. When you are done allocating shares to the account.DDE for Excel Advisors Page Allocating Shares to a Single Account You can use the Advisors page to set up an order and allocate all shares in the order to a single account. then enter the order information in the Order Description cells. then click the Apply Extended button to apply the Account order attribute value to the order. it will be applied to all subsequent orders placed from the DDE for Excel API spreadsheet. 7 8 API Reference Guide 100 . Click the Place/Modify Order button. Click the Advisors tab. Enter the contract information in the Contract Description cells. If you do not delete this value. The Account value is applied to the selected order and displayed in the Extended Order Attributes section of the page.

delete the values you entered on the Extended Order Attributes page. Click the Place/Modify Order button. To place an order using an FA account group and FA method: 1 2 3 4 Create the FA account group(s) and FA method(s) in TWS. Click the Extended Order Attributes tab. then click the Apply Extended button to apply the extended order attribute values to the order. then enter the order information in the Order Description cells. Highlight the order row.Enter the name of the account group. Enter values for the following extended order attributes: • • • FA Group . FA Method and FA Percentage are applied to the selected order and displayed in the Extended Order Attributes section of the page. If you do not delete these values. This attribute applies only to FA groups that use this method. FA Method . Click the Advisors tab at the bottom of the spreadsheet. 5 6 Click the Advisors tab.DDE for Excel Advisors Page Placing an Order using an FA Account Group and Method You can also use the Advisors page to set up an order using an FA account group and FA method. 7 8 API Reference Guide 101 . The values for FA Group.Enter the name of the allocation method to use for this order. When you are done allocating shares to the account.Enter the percentage used by the PctChange allocation method to use for this order. Enter the contract information in the Contract Description cells. they will be applied to all subsequent orders placed from the DDE for Excel API spreadsheet. FA Percentage .

The value for FA Profile is applied to the selected order and displayed in the Extended Order Attributes section of the page. Click the Extended Order Attributes tab. Highlight the order row. Enter the name of the allocation profile in the Value field for the FA Profile extended order attribute. If you do not delete this value. then click the Apply Extended button to apply the extended order attribute value to the order. 7 8 API Reference Guide 102 . Click the Place/Modify Order button. To place an order using an FA allocation profile: 1 2 3 4 5 6 Create the FA allocation profile in TWS. Click the Advisors tab. it will be applied to all subsequent orders placed from the DDE for Excel API spreadsheet. Click the Advisors tab at the bottom of the spreadsheet. Enter the contract information in the Contract Description cells.DDE for Excel Advisors Page Placing an Order using an Allocation Profile You can also use the Advisors page to set up an order using an FA allocation profile. When you are done allocating shares to the account. then enter the order information in the Order Description cells. delete the FA Profile value you entered on the Extended Order Attributes page.

and defined any extended attributes. This button cancels the order(s) you have highlighted. After you have completed the Order Description fields. Jumps to the Error Code field and shows the error code. Enter contract details to create legs of a combination order one by one. Applies the current values on the Extended Order Attributes page to the highlighted order row. Cancel Order Apply Extended Show Errors API Reference Guide 103 . click to create an order for the selected contract.DDE for Excel Advisors Page Advisors Page Toolbar Buttons The toolbar on the Basic Orders page includes the following buttons: Button Combo Legs Place/Modify Orders Description Opens the Combination Legs box.

press Alt+F11 from any page. The Visual Basic Editor opens: The Visual Basic Editor contains three main components: • • Project Explorer Properties Window Code Window • API Reference Guide 104 .DDE for Excel DDE for Excel API Reference DDE for Excel API Reference This section provides a variety of reference information about the DDE for Excel API. including the following topics: • • • • Viewing the Code Modules Named Ranges Macros DDE Syntax for Excel • Viewing the Code To view the Visual Basic code behind the DDE for Excel API spreadsheet.

you can view the named ranges by selecting Name > Define from the Tools menu. The Name Manager displays every named range used in the spreadsheet. composeControlLink – put together a link that causes operations to occur. to view the code for a particular page. double-click the page’s corresponding object in the Project Explorer. Specifically. the value of the range.xls sample spreadsheet used named ranges extensively. such as subscribing to market data. It also makes important data available to your own custom macros and worksheets. Using these constants instead of hard-coded values will make your application more robust and easier to maintain. you can see a complete list of all named ranges used in the spreadsheet by clicking Formulas then clicking Name Manager. option model volatility. Modules The Visual Basic code includes the following modules (visible in the VBE Project Explorer): • • • ArrayQueries ErrorDisplay Orders util • The util module contains many pre-defined constants that you can use when you program your own DDE API application. Named ranges help you to move data around on worksheets without breaking existing logic.DDE for Excel DDE for Excel API Reference The Project Explorer contains a list of objects used in the spreadsheet. or subscribing to the market scanner. • • 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. depending on which version of Excel you are using: • In Excel 2007. The TwsDde. and build the DDE string representing it. or execution id. You can also download a free Name Manager from Microsoft that has additional functionality for these earlier versions of Excel. composeContractReq – Read a contract description out of a page like Tickers or Orders. In earlier versions of Excel. These object correspond to the pages in the spreadsheet. the following util functions are particularly useful in building new Visual Basic functionality: • composeLink – put together a link that receives data. placing orders. and the page and range of cells covered by the range. You can view all the named ranges used in the spreadsheet by doing the following. such as a market data bid size. • API Reference Guide 105 .

You can see all the macros used in the sample spreadsheet by opening the Excel Macro dialog. For example. which opens macro code in the Visual Basic Editor. refer to your Microsoft Excel documentation. From there you can choose to edit the macro. you are actually running a macro called requestMarketData. when you click the Request Market Data button on the Tickers page. editing and viewing macros. Note: You must enable macros when you open Excel or none of the macros in the spreadsheet will function.DDE for Excel DDE for Excel API Reference The following screen shows the Name Manager for the DDE for Excel API sample spreadsheet: Macros The DDE API sample spreadsheet uses Microsoft Excel macros extensively. API Reference Guide 106 . For information about recording. Each toolbar button on every page in the spreadsheet runs a macro when you click it.

For orders. which appears in the Excel formula bar (the "=" enterable field at the top of the spreadsheet) when you put your cursor in a cell. such as place or cancel field2 = additional information as noted below Server server server server server server server server server server server server server server server server Topic ord ord ord ord ord ord ord ord ord ord ord ord ord ord ord id idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn reqType place modify cancel status open executed sharesFilled sharesRemaining price symbol secType expiry strike right multiplier Refer to Note 6 Refer to Note 7 Refer to Note 8 Refer to Note 8 Refer to Note 8 field2 orderDescription orderModification • • Description Place an order Modify an order Cancel an order Check order status Request open orders Request executions Check shares filled in order Check shares remaining in order Execution (average) price Underlying Security type Expiry Strike Right Specify contract multiplier for options and futures Order destination Currency Order side Order quantity Order type server server server server server ord ord ord ord ord idn idn idn idn idn exchange currency side size orderType API Reference Guide 107 . where n is some integer. The basic syntax. reqType = the request type. even from session to session.DDE for Excel DDE for Excel API Reference DDE Syntax for Excel The table below defines possible cell values for DDE-supported functionality. such as orders (ord) or tickers (tik) id = idn. is: =server|topic!id?reqType?field2 or =server|error!error (for an optional tag that will display errors) where: • • • server = the username topic = the function category. n must always increase.

DDE for Excel DDE for Excel API Reference Description Limit price Auxiliary price Local symbol Last fill price Create ticker Bid implied volatility Bid delta Request bid size Request bid price Request ask price Request ask size Ask implied volatility Ask delta Request last price Request last size Last implied volatility Last delta Request today's high price Request today's low price Request today's volume size Request last close price Request implied volatility calculated by the TWS option modeler Request option delta calculated by the TWS option modeler Request the model price Request present value of dividends expected on the options underlier Request number of hold days until the expiry of the EFP Request expiration date of the single stock future Server server server server server server server server server server server server server server server server server server server server server server server Topic ord ord ord ord tik tik tik tik tik tik tik tik tik tik tik tik tik tik tik tik tik tik id idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn reqType limitPrice auxPrice localSymbol lastFillPrice req bidImpliedVol bidDelta bidSize bid ask askSize askImpliedVol askDelta last lastSize lastImpliedVol lastDelta high low volume close modelVolatility field2 server tik idn modelDelta server server tik tik idn idn modelPrice pvDividend server tik idn holdDays server tik idn futureExpiry API Reference Guide 108 .

DDE for Excel DDE for Excel API Reference Description Request dividends expected until the expiration of the single stock future Request annualized basis points Request annualized basis points in percentage form Request implied futures price Request the dividend impact on the annualized basis points interest rate Account statement control key Request one account value string Account value Account currency Account portfolio control key Account portfolio underlying symbol Account portfolio security type Account portfolio expiry Account portfolio strike price Account portfolio right Account portfolio currency Account portfolio local symbol Account portfolio market price Account portfolio market value Account portfolio average cost Account portfolio realized PNL Server server Topic tik id idn reqType dividendsToExpiry field2 server server tik tik idn idn basisPoints formattedBasis Points impliedFuture dividendImpact server server tik tik idn idn server acct idn acctv Account code (for Advisor-managed accounts only) server server server server acct acct acct acct idn idn idn idn key value keyCurrency acctp Account code (for Advisor-managed accounts only) server server server server server server server server server server server acct acct acct acct acct acct acct acct acct acct acct idn idn idn idn idn idn idn idn idn idn idn symbol secType expiry strike right currency localSymbol marketPrice marketValue avgCost realizedPNL API Reference Guide 109 .

DDE for Excel DDE for Excel API Reference Description Account portfolio unrealized PNL Request contract details Valid order types Valid exchanges Contract identifier Minimum tick Order multiplier Market name Trading class Execution order id Underlying Security type Expiry Strike Right Order destination Currency Local symbol Execution id Execution time Account number Exchange where executed Side Number of shares filled in order Execution (average) price Order ID Identifies position as one to be liquidated last Request execution details Request list of Advisor-managed accounts List of Advisor-managed accounts Server server server server server server server server server server server server server server server server server server server server server server server server server server server server Topic acct contract contract contract contract contract contract contract contract exec exec exec exec exec exec exec exec exec exec exec exec exec exec exec exec exec exec id idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn idn reqType unrealizedPNL req orderTypes validExchanges conid minTick multiplier marketName tradingClass orderId symbol secType expiry strike right exchange currency localSymbol execId time acctnNumber eExchange side shares price permId liquidation field2 contractDescription server server exec FAaccts idn idn Req Req executionFilter server FAaccts idn Value API Reference Guide 110 .

rowId_side Refer to note (2) below. Where: • orderDescription = side_quantity_symbol_secType_exp_strike_right_exchange_orderType_lmtPrice_auxPrice {_timeInForce_ocaGroup_account_open/close_origin_orderRef_transmit_parentId_blockOr der _sweepToFill_displaySize_triggerMethod_ignoreRth_hidden_clientId_accountCode_goodAft erTime_ goodTillDate_faGroup_faMethod_faPercentage_faProfile_shortSaleSlot_ PRIMARYEXCHANGE _shortSaleLocation_ocaType_rthOnly_rule80A_settlingFirm_allOrNone_minimumQty_perce ntOffset_ electronicTradeOnly_firmQuoteOnly_nbboPriceCap_auctionStrategy_startingPrice_stockRef Price_ delta_stockRangeLower_stockRangeUpper_volatility_volatilityType_referencePriceType_hed geDelta_ continuousUpdate} Attributes in brackets are extended order attributes and are described in the topic Extended Order Attributes.DDE for Excel DDE for Excel API Reference Description Request market depth Server server Topic mktDepth id idn reqType req field2 contractDescripton? num_display_rows Refer to note (1) below. Note: API Reference Guide 111 . Number of milliseconds Refer to note 3 below Market maker server mktDepth idn mktMaker Order price server mktDepth idn price Order size server mktDepth idn size Market data refresh rate Subscribe to news bulletins News bulletin message ID News bulletin message type News bulletin message text Exchange from which news bulletins originated Set the server log level server server server server server server refreshRate news news news news news idn sub newsID newsType msg exchange millisec 0 Refer to note 4 below server logLevel <log_level> Refer to note 5 below. rowId_side Refer to note (2) below. rowId_side Refer to note (2) below.

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 2 3 4 5 = = = = = SYSTEM (least detailed) ERROR (default. Market depth orders are divided into two sides. exchange. it follows the strike and right. as a low number of display rows requires less CPU overhead. the strike and right (put or call) are inserted after the expiry. API Reference Guide 112 . institutional need to specify a 1 if the order being executed would close a position. Each leg contains : contract ID. If the order is an option. the default number of rows is five (5) rows. side. number of contracts. 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. To unsubscribe simply clear the subscription cell. If not supplied. This parameter can be used to optimize performance. If the multiplier is specified. BID and ASK. and open/close (0 or 1). combo legs are inserted after the aux price. =edemo|mktDepth!id0?size?2_BID will request the BID size for the order entry 2.symbol_secType_exp_strike_right_exchange tickerDescription = symbol_secType_exp_strike_right_exchange ExecutionFilter = clientId_accountCode_date_time_symbol_secType_exchange_side When requesting market depth you can specify the number of rows to display. Note 7: Note 8: If the order is an option or a future. Here is a three-legged IBM combo description: CMBLGS_3_8314_100_BUY_SMART_0_36930759_1_BUY_SMART_0_36930816_1_SELL_SMA RT_0_CMBLGS. For example: =edemo|mktDepth!id0?price?0_ASK will request the ASK price for the order entry 0. and order entries start from the offset 0. Note 1: Note 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. For example: =edemo|mktDepth!id0?req?MSFT_STK_SMART?10 will request 10 rows of market depth orders.DDE for Excel DDE for Excel API Reference • • • contractDescription . Retail can always specify 0. the expiry is inserted after the sec type. if no level is specified) WARNING INFORMATION DETAIL (most detailed) Note 6: If the order is a combo.

ocx. which duplicates most of the functionality of the DDE for Excel sample spreadsheet but is based on the ActiveX control.ActiveX This chapter describes the ActiveX API. including the following topics: • • • • • • • • • 3 Linking to the Application using ActiveX Registering Third-Party ActiveX Controls Running the ActiveX API on 64-bit Windows XP Systems Using the Visual Basic Sample Program ActiveX Methods ActiveX Events ActiveX COM Objects ActiveX Properties Placing a Combination Order The API software also includes an ActiveX for Excel sample spreadsheet. Tws. See ActiveX for Excel for details. Note: API Reference Guide 113 .

Handle the error() event to receive error information. 3 4 Call the placeOrder() method to place an order. Handle the following events: • Handle the nextValidId() event to receive the next available valid order ID. Increment the ID by one for successive orders. To link using the ActiveX control and VB. VBA or C++ 1 2 Drop the application control onto a form or dialog box. Call the following methods: • • Call the connect() method to connect to the running application. you must register them with Visual Basic.ActiveX Linking to the Application using ActiveX Linking to the Application using ActiveX Before you can use third-party ActiveX controls. Handle the orderStatus() event to receive status information about orders. such as the reqMktData() method to request market data. Orders using extended attributes require that ActiveX properties representing them be set first. Call the methods you need to perform whatever operations you require. Handle the tickPrice() and tickSize() events to receive the market data. Handle the connectionClosed() event to be notified in case the application stops communicating with the ActiveX control. • • • • API Reference Guide 114 .

ocx). select the TWS ActiveX control (Tws. API Reference Guide 115 . follow these instructions: 1 2 3 From the Components menu in your VB project. Running the ActiveX API on 64-bit Windows XP Systems To run the ActiveX API on 64-bit Windows XP systems. Click Apply. To register the ActiveX control with Visual Basic.ActiveX Registering Third-Party ActiveX Controls Registering Third-Party ActiveX Controls To use a third-party ActiveX control in Visual Basic it must be registered first. Verify that the TWS control appears in the toolbar with all standard controls.0 Redistributable Package. do the following: 1 2 3 Install Microsoft Visual C++ 2005 SP1 Redistributable Package (x86). Install Microsoft Visual J# 2. Download and install the API software.

0 or higher) installed on your PC. select Components. API Reference Guide 116 . To open the VB_API_sample program: 1 2 From the MS Visual Basic file menu. for example. and select VB_API_sample.60. try re-registering the TWS ActiveX component. • The Visual Basic program is a sample program that demonstrates use of the TWS ActiveX control to connect to the server from a Visual Basic application. Press Ctrl+F5 to compile and run the project. If you have trouble getting the sample program to run. select the TWS ActiveXControl module and click OK. To run the sample you must: • • Install the API sample programs Configure the application to support the API components Have MS Visual Studio (Visual Basic 6.vbp. 9.ActiveX Using the Visual Basic Sample Program Using the Visual Basic Sample Program You can access the server through the ActiveX interface using the Visual Basic sample application. If you are using Visual Studio 2008. Navigate to the \TestActiveXClient_VB directory in your API installation folder.ocx. Tws. In the Components dialog box. select Open Project. 3 4 5 Note: On the Projects menu. you will have to upgrade your project before it can be opened. Visual Basic presents an Upgrade Wizard to walk you through this simple process. X_XX represents the API version number.

ActiveX ActiveX Methods ActiveX Methods ActiveX methods allow your application to call functions and request information from TWS. Please update your software to use the "Ex" counterparts to these deprecated methods. The new "Ex" methods have been API Reference Guide 117 . Note: Please note that methods in red have been deprecated as of API release 9.4 (December 2007) and will soon be removed.

ActiveX ActiveX Methods grouped with their deprecated counterparts for easy identification. Connection and Server connect() disconnect() reqCurrentTime() setServerLogLevel() Account reqAccountUpdates() News Bulletins reqNewsBulletins() cancelNewsBulletins() Market Data reqMktDataEx() reqMktData() reqMktData2() cancelMktData() Financial Advisors reqManagedAccts() requestFA() replaceFA() calculateImpliedVolatility() cancelCalculateImpliedVolatility() calculateOptionPrice() cancelCalculateOptionPrice() Orders placeOrderEx() placeOrder() placeOrder2() cancelOrder() reqOpenOrders() reqAllOpenOrders() reqAutoOpenOrders() reqIds() exerciseOptionsEx() exerciseOptions() addComboLeg() clearComboLegs() Historical Data reqHistoricalDataEx() requestHistoricalData() cancelHistoricalData() Market Scanners reqScannerParameters() reqScannerSubscriptionEx() reqScannerSubscription() cancelScannerSubscription() Real Time Bars reqRealTimeBarsEx() reqRealTimeBars() cancelRealTimeBars() Factory Methods createComboLegList() createContract() createExecutionFilter() createOrder() createScannerSubscription() createTagValueList() createUnderComp() Executions reqExecutionsEx() reqExecutions() Contract Details reqContractDetailsEx() reqContractDetails() reqContractDetails2() Fundamental Data reqFundamentalData() cancelFundamentalData() Market Depth reqMktDepthEx() reqMktDepth() reqMktDepth2() cancelMktDepth() API Reference Guide 118 .

When the market data returns. it will be identified by this tag. Public Overridable Sub reqMktDataEx(ByVal tickerId As Integer. Check to return a single snapshot of market data and have the market data subscription cancel.IContract. This is also used when canceling the market data. Must be a unique value. Must match the port specified in TWS on the Configure>API>Socket Port field. ByVal contract As TWSLib. ByVal port as Integer. ByVal snapshot As Integer) Parameter tickerId Description The ticker id. Public Overridable Sub disconnect() reqMktDataEx() Call this method to request market data. A comma delimited list of generic tick types. ByVal genericTicks As String. seeGeneric Tick Types. Leave blank to connect to the local host. contract genericTicks snapshot API Reference Guide 119 . tickString() and tickEFP() events in dispinterface_DTwsEvents. A number used to identify this client connection. tickSize(). Do not enter any genericTicklist values if you use snapshot.ActiveX ActiveX Methods connect() Call this method to connect to the host application. All orders placed/modified from this client will be associated with this client identifier. Note: Each client MUST connect with a unique clientId. tickOptionComputation(). For more information about tick types. This object contains a description of the contract for which market data is being requested. disconnect() Call this method to terminate the connections the host application. ByVal clientID as Integer Parameter host port clientID Description The host name or IP address of the machine where TWS is running. Calling this method does not cancel orders that have already been sent. Public Overridable Sub connect(ByVal host as String. tickGeneric(). The market data will be returned by the tickPrice().

This is also used when canceling the market data. Ambiguities may require that this field be specified. ByVal snapshot As Integer) Parameter id Description The ticker id. ByVal multiplier As String. The strike price. . Check to return a single snapshot of market data and have the market data subscription cancel.ActiveX ActiveX Methods reqMktData() Call this method to request market data. CALL. ByVal secType As String. Valid values are: • • • • • • expiry strike right multiplier exchange primaryExchange STK OPT FUT IND FOP CASH symbol secType The expiration data. To clarify any ambiguity for Smart-routed contracts. The order destination. ByVal currency As String. C. The market data will be returned by the tickPrice() and tickSize() events. include the primary exchange. ByVal exchange As String. ByVal expiry As String. currency snapshot API Reference Guide 120 .allows you to specify a futures or options multiplier in cases where multiple possibilities exist. Specifies a Put or Call. it is a good idea to always specify the currency. Given the existence of this kind of ambiguity. along with the Smart designation. Public Overridable Sub reqMktData(ByVal id As Integer. Specifies the currency. The security type. Must be a unique value.4 (December 2007) and will soon be removed. ByVal strike As Double. ByVal genericTicks As String. The primary exchange on which the product trades. ByVal symbol As String. The symbol of the underlying for which you are requesting market data. ByVal right As String. for the destination. Do not enter any genericTicklist values if you use snapshot. ByVal primaryExchange As String. Use the format YYYYMM. when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). Note: This method has been deprecated as of API release 9. used to definitively identify a product. such as Smart. it will be identified by this tag. for example. Please update your software to use the "Ex" counterparts to these deprecated methods. When the market data returns. PUT. Valid values are: P.

The local exchange symbol of the underlying for which you are requesting market data. The security type. ByVal currency As String. ByVal secType As String. ByVal snapshot As Integer) Parameter id Description The ticker id. for example. Check to return a single snapshot of market data and have the market data subscription cancel. such as SMART. ByVal localSymbol As String. when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). genericTicklist snapshot API Reference Guide 121 . Public Overridable Sub reqMktData2(ByVal id As Integer.ActiveX ActiveX Methods reqMktData2() Call this method to request market data using the exchange symbol. ByVal exchange As String. Ambiguities may require that this field be specified. it will be identified by this tag. The market data will be returned by the tickPrice() and tickSize() events. used to definitively identify a product. Note: This method has been deprecated as of API release 9. Given the existence of this kind of ambiguity. The primary exchange on which the product trades. Do not enter any genericTicklist values if you use snapshot. When the market data returns. ByVal genericTicks As String.4 (December 2007) and will soon be removed. Must be a unique value. ByVal primaryExchange As String. This is also used when canceling the market data. A comma delimited list of generic tick types. it is a good idea to always specify the currency. Specifies the currency. Tick types can be found in the Generic Tick Types page. Valid values are: • • • • • • exchange primaryExchange currency STK OPT FUT IND FOP CASH localSymbol secType The order destination. Please update your software to use the "Ex" counterparts to these deprecated methods.

ByVal volatility As Double. ByVal optionPrice As Double. Public Overridable Sub calculateImpliedVolatility(ByVal reqId As Integer) Parameter reqId Description The ticker id. The volatility. calculateImpliedVolatility() Call this function to calculate volatility for a supplied option price and underlying price.IContract. Describes the contract. Public Overridable Sub cancelMktData(ByVal id As Integer) Parameter id Description The ID that was specified in the call to reqMktData(). ByVal underPrice As Double) Parameter reqId contract volatility underPrice Description The ticker ID. Public Overridable Sub calculateOptionPrice(ByVal reqId As Integer. The price of the option. cancelCalculateImpliedVolatility() Call this function to cancel a request to calculate volatility for a supplied option price and underlying price. Describes the contract. ByVal contract As TWSLib. calculateOptionPrice() Call this function to calculate option price and greek values for a supplied volatility and underlying price. Price of the underlying. ByVal underPrice As Double) Parameter reqId contract optionPrice underPrice Description The ticker ID. ByVal contract As TWSLib. Public Overridable Sub calculateImpliedVolatility(ByVal reqId As Integer. market data for the specified id will stop flowing.IContract. API Reference Guide 122 .ActiveX ActiveX Methods cancelMktData() After calling this method. Price of the underlying.

ByVal goodAfterTime As String. it will be identified by this tag. ByVal group As String. You must specify a unique value. API Reference Guide 123 . ByVal faMethod As String. When the order status returns. When the order status returns. ByVal strike As Double. This object contains the details of the order.4 (December 2007) and will soon be removed. ByVal faPercentage As String. This tag is also used when canceling the order. Note: Each client MUST connect with a unique clientId. Public Overridable Sub placeOrder(ByVal id As Integer. placeOrderEx() Call this method to place an order. The order status will be returned by the orderStatus() event in dispinterface_DTwsEvents. ByVal right As String. Please update your software to use the "Ex" counterparts to these deprecated methods. contract order placeOrder() Call this method to place an order. ByVal symbol As String. Note: This method has been deprecated as of API release 9. ByVal goodTillDate As String) Parameter id Description The order id. ByVal order As TWSLib. The order status will be returned by the orderStatus() event. ByVal orderType As String. ByVal action As String. ByVal secType As String. ByVal price As Double. ByVal faProfile As String. ByVal exchange As String. ByVal expiry As String. For more details see Active X Properties. ByVal auxPrice As Double. This object contains attributes used to describe the contract. Public Overridable Sub placeOrderEx(ByVal orderId As Integer. ByVal multiplier As String. ByVal quantity As Integer. This tag is also used when canceling the order. ByVal curency As String.ActiveX ActiveX Methods 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 reqId Description The ticker id. ByVal primaryExchange As String. it will be identified by this tag. You must specify a unique value. ByVal contract As TWSLib.IOrder) Parameter orderId Description The order Id.IContract.

C. used to definitively identify a product. PUT. it is a good idea to always specify the currency. Valid values are: • • • • • • • • • • • MKT MKTCLS LMT LMTCLS PEGMKT SCALE STP STPLMT TRAIL REL VWAP orderType API Reference Guide 124 . Use the format YYYYMM. such as Smart.ActiveX ActiveX Methods Parameter action Description Identifies the side. The order destination. Allows you to specify a futures or options multiplier in cases where multiple possibilities exist. CALL. The symbol of the underlying asset. Valid values are: P. The primary exchange on which the product trades. Ambiguities may require that this field be specified. Given the existence of this kind of ambiguity. Valid values are: • • • • • STK OPT FUT FOP CASH expiry strike right multiplier exchange primaryExchange curency The expiration date. Specifies the currency. for example. The strike price Specifies a Put or Call. Identifies the order type. Valid values are: • • • BUY SELL SSHORT quantity symbol secType The order quantity. The security type. when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD).

" Send an empty string if not an FA. specify zero. also specify zero. Specifies that the order becomes active after the time set. Specifies the order's "Financial Advisor Group. In all other cases. and the offset amount for relative orders. Specifies the order's "Financial Advisor Profile. Specifies the order's "Financial Advisor Allocation Method." Send an empty string if not applicable." Send an empty string if not an FA. lmtPrice goodAfterTime group faMethod faPercentage faProfile goodTillDate API Reference Guide 125 . Send an empty string if not applicable. Identifies the STOP price for stop-limit orders. used for limit." Send an empty string if not an FA. Specifies the order's "Financial Advisor Percentage. In all other cases specify zero. stop-limit and relative orders.ActiveX ActiveX Methods Parameter lmtPrice Description The LIMIT price." Send an empty string if not an FA. Specifies the order's "Good Till Date. For relative orders with no limit price.

ByVal orderType As String. API Reference Guide 126 . ByVal lmtPrice As Double. Specifies the currency. Note: This method has been deprecated as of API release 9. The order status will be returned by the orderStatus() event. it will be identified by this tag.4 (December 2007) and will soon be removed. ByVal primaryExchange As String. The security type. Public Overridable Sub placeOrder2(ByVal id As Integer. Given the existence of this kind of ambiguity. ByVal exchange As String. This tag is also used when canceling the order. ByVal goodTillDate As String) Parameter id Description The order id. ByVal faMethod As String. when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). such as Smart. The local exchange symbol of the underlying asset. ByVal faPercentage As String. ByVal faProfile As String. When the order status returns. The primary exchange on which the product trades. You must specify a unique value. ByVal goodAfterTime As String.ActiveX ActiveX Methods placeOrder2() Call this method to place an order using the exchange symbol. ByVal auxPrice As Double. ByVal group As String. Ambiguities may require that this field be specified. ByVal action As String. ByVal quantity As Integer. ByVal secType As String. for example. ByVal curency As String. used to definitively identify a product. Valid values are: • • • quantity localSymbol secType BUY SELL SSHORT action The order quantity. it is a good idea to always specify the currency. Valid values are: • • • • • STK OPT FUT FOP CASH exchange primaryExchange curency The order destination. Please update your software to use the "Ex" counterparts to these deprecated methods. Identifies the side. ByVal localSymbol As String.

and the offset amount for relative orders. Specifies that the order becomes active after the time set. stop-limit and relative orders." Send an empty string if not applicable." Send an empty string if not an FA. auxPrice goodAfterTime group faMethod faPercentage faProfile goodTillDate cancelOrder() Call this method to cancel an order. Specifies the order's "Good Till Date.ActiveX ActiveX Methods Parameter orderType Description Identifies the order type. specify zero. For relative orders with no limit price." Send an empty string if not an FA. Send an empty string if not applicable. In all other cases specify zero. In all other cases. Specifies the order's "Financial Advisor Profile. used for limit. Identifies the STOP price for stop-limit orders." Send an empty string if not an FA. Specifies the order's "Financial Advisor Allocation Method. Valid values are: • • • • • • • • • • • MKT MKTCLS LMT LMTCLS PEGMKT SCALE STP STPLMT TRAIL REL VWAP lmtPrice The LIMIT price. Public Overridable Sub cancelOrder(ByVal id As Integer) Parameter id Description The order ID that was specified previously in the call to placeOrder() API Reference Guide 127 . Specifies the order's "Financial Advisor Group. also specify zero. Specifies the order's "Financial Advisor Percentage." Send an empty string if not an FA.

Public Overridable Sub reqExecutions() API Reference Guide 128 .Each open order will be fed back through the orderStatus() event. reqExecutions() When this method is called. openOrder2. newly created application orders will be implicitly associated with the client. If set to FALSE. Note: The client with a clientId of 0 will also receive the application-owned open orders.ActiveX ActiveX Methods reqOpenOrders() Call this method to request the open orders that were placed from this client.IExecutionFilter) Parameter filter Description The filter criteria used to determine which execution reports are returned. openOrder3. When a new application order is created. Each open order will be fed back through the openOrder1. This association will persist over multiple API and application sessions. Public Overridable Sub reqAutoOpenOrders(ByVal bAutoBind As Integer) Parameter bAutoBind Description If set to TRUE. ByVal filter As TWSLib. no association will be made. Public Overridable Sub reqExecutionsEx(ByVal reqId As Integer. and fed back through the orderStatus() event. Note: This request can only be made from a client with a clientId of 0. the execution reports that meet the filter criteria are downloaded to the client via the execDetailsEx() event in dispinterface_DTwsEvents. openOrder4 or openOrderEx() events. all execution reports are downloaded to the client via the execDetails() event. the order will be associated with the client. reqExecutionsEx() When this method is called. 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. Public Overridable Sub reqOpenOrders() reqAllOpenOrders() Call this method to request the open orders that were placed from all clients and also from the application. These orders will be associated with the client and a new orderId will be generated.

the nextValidId() event will be triggered. API Reference Guide 129 . Public Overridable Sub reqIds(ByVal numIds As Integer) Parameter numIds Description Set to 1. The contract details will be received via the contractDetailsEx() callback in dispinterface_DTwsEvents. reqContractDetailsEx() Call this method to download all details for a particular contract. After calling this method. and the id returned is that next valid ID. Public Overridable Sub reqContractDetailsEx(ByVal reqId As Integer. This object contains a description of the contract for which market data is being requested.ActiveX ActiveX Methods reqIds() Call this function to request the next valid ID that can be used when placing an order. ByVal contract As TWSLib.IContract) Parameter reqId contract Description The ID of the data request. Ensures that responses are matched to requests if several requests are in process. That ID will reflect any autobinding that has occurred (which generates new IDs and increments the next valid ID therein).

The contract details data will be returned by the contractDetails() event. Valid values are: • • • • • • expiry strike right multiplier exchange curency STK OPT FUT IND FOP CASH The expiration data. Ambiguities may require that this field be specified. Please update your software to use the "Ex" counterparts to these deprecated methods. Use the format YYYYMM. for example. Note: This method has been deprecated as of API release 9. Allows you to specify a futures or options multiplier in cases where multiple possibilities exist. ByVal secType As String. such as SMART. ByVal includeExpired As Integer) Parameter symbol secType Description The symbol of the underlying for which you are requesting market data. ByVal strike As Double. PUT. ByVal exchange As String. Given the existence of this kind of ambiguity. Public Overridable Sub reqContractDetails(ByVal symbol As String. Valid values are: P.ActiveX ActiveX Methods reqContractDetails() Call this method to request details for a particular underlying or security. The order destination. The security type.4 (December 2007) and will soon be removed. it is a good idea to always specify the currency. API Reference Guide 130 . ByVal expiry As String. when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). C. The strike price. ByVal multiplier As String. ByVal right As String. ByVal curency As String. Specifies a Put or Call. Specifies the currency. CALL.

ByVal exchange As String.ActiveX ActiveX Methods reqContractDetails2() Call this method to request details for a particular security using the exchange symbol. Given the existence of this kind of ambiguity. contract numRows API Reference Guide 131 . This is also used when canceling the market depth. reqMktDepthEx() Call this method to request market depth for a specific contract. The market depth will be returned by the updateMktDepth() and updateMktDepthL2() events. such as SMART. This object contains a description of the contract for which market data is being requested. when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). for example. it will be identified by this tag. ByVal contract As TWSLib. it is a good idea to always specify the currency. Valid values are: • • • • • • exchange curency STK OPT FUT IND FOP CASH The order destination. ByVal numRows As Integer) Parameter tickerId Description The ticker Id. ByVal includeExpired As Integer) Parameter localSymbol secType Description The local exchange symbol of the underlying for which you are requesting market data. When the market depth data returns. ByVal secType As String. Public Overridable Sub reqContractDetails2(ByVal localSymbol As String.IContract. The contract details data will be returned by the contractDetails() event. Ambiguities may require that this field be specified. Public Overridable Sub reqMktDepthEx(ByVal tickerId As Integer. ByVal curency As String. The security type. Specifies the number of market depth rows to return. Specifies the currency. Must be a unique value.

it is a good idea to always specify the currency. such as SMART. Public Overridable Sub reqMktDepth(ByVal id As Integer. Specifies the number of market depth rows you want to display. Specifies the currency. Valid values are: P. Specifies a Put or Call. ByVal exchange As String. Ambiguities may require that this field be specified. C. CALL. The order destination. ByVal numRows As Integer) Parameter id Description The ticker id. ByVal curency As String. Note: This method has been deprecated as of API release 9. Must be a unique value. when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). ByVal expiry As String. The security type. When the market data returns. it will be identified by this tag. ByVal multiplier As String. Use the format YYYYMM. ByVal symbol As String. Please update your software to use the "Ex" counterparts to these deprecated methods. ByVal right As String. Given the existence of this kind of ambiguity. The market depth data will be returned by the updateMktDepth() and updateMktDepthL2() events.ActiveX ActiveX Methods reqMktDepth() Call this method to request market depth details for a particular underlying or security. for example. Allows you to specify a futures or options multiplier in cases where multiple possibilities exist. The symbol of the underlying for which you are requesting market data. This is also used when canceling the market data. numRows API Reference Guide 132 . The strike price. ByVal strike As Double. ByVal secType As String.4 (December 2007) and will soon be removed. Valid values are: • • • • • • expiry strike right multiplier exchange curency STK OPT FUT IND FOP CASH symbol secType The expiration data. PUT.

ByVal numRows As Integer) Parameter id Description The ticker id. This is also used when canceling the market data. ByVal secType As String. when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). The security type. market depth for the specified id will stop flowing. Specifies the currency.4 (December 2007) and will soon be removed. Ambiguities may require that this field be specified. Public Overridable Sub reqMktDepth2(ByVal id As Integer. Valid values are: • • • • • • exchange curency STK OPT FUT IND FOP CASH localSymbol secType The order destination. Public Overridable Sub cancelMktDepth(ByVal id As Integer) Parameter id Description The ID that was specified in the call to reqMktDepth() or reqMktDepth2(). Must be a unique value. for example. ByVal curency As String. it is a good idea to always specify the currency. numRows cancelMktDepth() After calling this method. Given the existence of this kind of ambiguity. When the market data returns. ByVal exchange As String. ByVal localSymbol As String. such as SMART. Specifies the number of market depth rows you want to display. Note: This method has been deprecated as of API release 9. The local exchange symbol of the underlying for which you are requesting market data. Please update your software to use the "Ex" counterparts to these deprecated methods. The market depth data will be returned by the updateMktDepth() and updateMktDepthL2() events.ActiveX ActiveX Methods reqMktDepth2() Call this method to request market depth details for a particular underlying or security. it will be identified by this tag. API Reference Guide 133 .

ByVal action As String. API Reference Guide 134 .4 (December 2007) and will soon be removed.clearing broker 2 . This is the only option for retail customers. Close . Public Overridable Sub addComboLeg(ByVal conId As Integer. • • • designatedLocation If shortSaleSlot == 2. retail customer or not short leg) 1 .third party. The exchange to which the complete combination order will be routed.(0) same as the parent security. you must enter a designated location. To help determine the ratio for a specific combination order. exchange openClose For institutional customers only. 0 .(2) This option is for Institutional Customers only. ByVal exchange As String. If this value is used. Combination orders must have a secType of 'BAG. Specifies whether the order is an open or close order.inapplicable (i. Select the relative number of contracts for the leg you are constructing. the designatedLocation must be specified. Select the side (buy or sell) for the leg you are constructing. Open . ByVal ratio As Integer. ByVal openClose As Integer. use Interactive Analytics (see Interactive Analytics in the User's Guide). Otherwise leave blank or orders will be rejected. Valid values are: • • • shortSaleSlot Same ." Note: This method has been deprecated as of API release 9. ByVal shortSaleSlot As Integer. ByVal designatedLocation As String) Parameter conid action ratio Description The unique contract identifier specifying the security.e.ActiveX ActiveX Methods addComboLeg() This method adds a leg definition to an order and must be called for each leg before the combination order can be placed.(1) This option is for Institutional Customers only.

cancelNewsBulletins() Call this method to stop receiving news bulletins. Public Overridable Sub reqNewsBulletins(ByVal allDaysMsgs As Integer) Parameter allDaysMsgs Description If set to TRUE.ActiveX ActiveX Methods clearComboLegs() This method must be called to remove all leg definitions from a combination order before constructing a new combination order. Valid values include: • • • • • 1 = SYSTEM 2 = ERROR 3 = WARNING 4 = INFORMATION 5 = DETAIL API Reference Guide 135 . If set to FALSE. Public Overridable Sub clearComboLegs() reqNewsBulletins() Call this method to start receiving news bulletins. returns all the existing bulletins for the current day and any new ones. Public Overridable Sub setServerLogLevel(ByVal logLevel As Integer) Parameter logLevel Description Specifies the level of log entry detail used by the server when processing API requests. See API Logging for more details.4 (December 2007) and will soon be removed. Each bulletin will be returned by the updateNewsBulletin() event. Note: This method has been deprecated as of API release 9. will only return new bulletins. Public Overridable Sub cancelNewsBulletins() setServerLogLevel() The default level is ERROR.

Public Overridable Sub reqAccountUpdates(ByVal subscribe As Integer. The account data will be fed back through the updateAccountTime(). ByVal acctCode As String) Parameter subscribe Description If set to 1. Note: This request can only be made when connected to a Financial Advisor account. The data returns in an XML string via the receiveFA() event. acctCode requestFA() Call this method to request FA configuration information from the server. updateAccountValue() and updatePortfolio() events. The account code for which to receive account and portfolio updates. Public Overridable Sub requestFA(ByVal faDataType As Integer) Parameter faDataType Description Specifies the type of Financial Advisor configuration data being requested. The list will be returned by the managedAccounts() event.ActiveX ActiveX Methods reqManagedAccts() Call this method to request the list of managed accounts. If set to 2. Valid values include: • • • 1 = GROUPS 2 = PROFILE 3 =ACCOUNT ALIASES API Reference Guide 136 . the client will stop receiving this information. Public Overridable Sub reqManagedAccts() reqAccountUpdates() Call this method to request account updates. the client will start receiving account and portfolio updates.

Public Overridable Sub replaceFA(ByVal faDataType As Integer.ActiveX ActiveX Methods replaceFA() Call this method to modify FA configuration information from the API. ByVal cxml As String) Parameter faDataType Description Specifies the type of Financial Advisor configuration data being modified via the API. API Reference Guide 137 . Note that this can also be done manually. Valid values include: • • • cxml 1 = GROUPS 2 = PROFILE 3 =ACCOUNT ALIASES The XML string containing the new FA configuration information.

Also. Public Overridable Sub reqHistoricalDataEx(ByVal tickerId As Integer. ByVal duration As String. ByVal contract As TWSLib. where valid units are: • • • • S (seconds) D (days) W (weeks) M (months) contract endDateTime durationStr • Y (years) Note: If no unit is specified. i. This is also used when canceling the historical data request. This is the time span the request will cover. and is specified using the format: <integer> <unit>. 1 D. ByVal formatDate As Integer) Parameter tickerId Description The Id for the request. ByVal useRTH As Integer. When the data is received. API Reference Guide 138 ..ActiveX ActiveX Methods reqHistoricalDataEx() Call this method to start receiving historical data results through the historicalData() event. This structure contains a description of the contract for which market data is being requested. Use the format yyyymmdd hh:mm:ss tmz. ByVal endDateTime As String. it will be identified by this Id. where the time zone is allowed (optionally) after a space at the end. note "years" is currently limited to one. Must be a unique value.e. ByVal whatToShow As String. seconds are used. see Historical Data Limitations.IContract. Note: For a information about historical data request limitations. ByVal barSize As String.

Valid values include: Bar Size 1 sec 5 secs 15 secs 30 secs 1 min 2 mins 3 mins 5 mins 15 mins 30 mins 1 hour 1 day 1 week 1 month 3 months 1 year Determines the nature of data being extracted. 1 .ActiveX ActiveX Methods Parameter barSize Description The size of the bars that will be returned (within IB/TWS limits).only data within the regular trading hours is returned. Valid values include: • • 0 . API Reference Guide 139 . or only data that falls within regular trading hours.all data is returned even where the market in question was outside of its regular trading hours. even if the requested time span falls partially or completely outside of the RTH. Valid values include: • • • • • • • • TRADES MIDPOINT BID ASK BID_ASK HISTORICAL_VOLATILITY OPTION_IMPLIED_VOLATILITY OPTION_VOLUME whatToShow useRTH Determines whether to return all data available during the requested time span.

dates applying to bars returned in the format: yyyymmdd{space}{space}hh:mm:dd 2 .ActiveX ActiveX Methods Parameter formatDate Description Determines the date format applied to returned bars. API Reference Guide 140 .dates are returned as a long integer specifying the number of seconds since 1/1/1970 GMT. Valid values include: • • 1 .

Specifies the currency. ByVal formatDate As Integer) Parameter id Description The ticker id. Use the format YYYYMM. When the market data returns. ByVal useRTH As Integer. ByVal whatToShow As String. ByVal expiry As String. Specifies a Put or Call. ByVal symbol As String. Please update your software to use the "Ex" counterparts to these deprecated methods. endDateTime durationStr API Reference Guide 141 . Valid values include any date/time within the past six months in the format: yyyymmdd HH:mm:ss zzz where "zzz" is the optional time zone. If no unit is specified. This is also used when canceling the market data. when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). Valid values are: • • • • • • expiry strike right multiplier exchange curency STK OPT FUT IND FOP CASH symbol secType The expiration data. Valid values include any integer followed by a space and then S (seconds). it will be identified by this tag. ByVal barSizeSetting As String. ByVal secType As String. ByVal exchange As String. ByVal isExpired As Integer. The strike price. Must be a unique value. D (days) or W (week). C. PUT. ByVal strike As Double. days or weeks. Ambiguities may require that this field be specified.4 (December 2007) and will soon be removed. such as Smart. Set the query duration up to one week. using a time unit of seconds. Given the existence of this kind of ambiguity. for example. Valid values are: P. Defines a query end date and time at any point during the past 6 mos. ByVal right As String. it is a good idea to always specify the currency. The symbol of the underlying for which you are requesting market data. The order destination. CALL. seconds is used. The security type. ByVal durationStr As String. Public Overridable Sub reqHistoricalData(ByVal id As Integer.ActiveX ActiveX Methods reqHistoricalData() This method has been deprecated as of API release 9. ByVal curency As String. ByVal endDateTime As String. Allows you to specify a futures or options multiplier in cases where multiple possibilities exist. ByVal multiplier As String.

Valid values include: • • 1 . Valid values include: • • 0 . formatDate Determines the date format applied to returned bars. 1 . Valid values include: Bar Size Parametric Value 1 sec 1 5 secs 2 15 secs 3 30 secs 4 1 min. 5 2 mins 6 5 mins 7 15 mins 8 30 mins 9 1 hour 10 1 day 11 1 week 12 1 month 13 3 months 14 1 year 15 Determines the nature of data being extracted.only data within the regular trading hours is returned. or only data that falls within regular trading hours. Valid values include: Specifies the size of the bars that will be returned (within IB/TWS limits).dates applying to bars returned in the format: yyyymmdd{space}{space}hh:mm:dd 2 . API Reference Guide 142 .dates are returned as a long integer specifying the number of seconds since 1/1/1970 GMT. Valid values include: • • • • • TRADES MIDPOINT BID ASK BID_ASK whatToShow useRTH Determines whether to return all data available during the requested time span.all data is returned even where the market in question was outside of its regular trading hours.ActiveX ActiveX Methods Parameter barSizeSetting Description Specifies the size of the bars that will be returned (within IB/TWS limits). even if the requested time span falls partially or completely outside of the RTH.

ByVal exerciseAction As Integer. ByVal override As Integer) Parameter tickerId contract exerciseAction Description The Id for the exercise request This structure contains a description of the contract for which market data is being requested. For example. by natural action the option would not exercise.IContract. Public Overridable Sub exerciseOptionsEx(ByVal tickerId As Integer. ByVal exerciseQuantity As Integer. ByVal contract As TWSLib. Values are: • • 0 = do not override 1 = override API Reference Guide 143 . Specifies the IB account. If you have override set to "yes" the natural action would be overridden and the out-of-the money option would be exercised. This can have two values: • • exerciseQuantity account override 1 = exercise 2 = lapse The number of contracts to be exercised For institutional orders. ByVal account As String. Specifies whether your setting will override the system's natural action.ActiveX ActiveX Methods exerciseOptionsEx() Call this method to exercise options. Note: Please note that 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. if your action is "exercise" and the option is not in-the-money.

2 = lapse. when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). C. Public Overridable Sub reqScannerParameters() API Reference Guide 144 . a default value of "100" is assumed. Must be a unique value. If you have override set to "yes" the natural action would be overridden and the out-of-the money option would be exercised. exchange curency exerciseAction exerciseQuantity override reqScannerParameters() Requests an XML string that describes all possible scanner queries. Given the existence of this kind of ambiguity. Specifies whether you want the option to lapse or be exercised. 1 = yes. ByVal exchange As String. The order destination. Please update your software to use the "Ex" counterparts to these deprecated methods. The quantity you want to exercise. use values P. or CALL Allows you to specify a futures or option multiplier in cases where more than one possibility exists. Values are 1 = exercise. Specifies the currency. ByVal symbol As String.ActiveX ActiveX Methods exerciseOptions() Note: This method has been deprecated as of API release 9. ByVal exerciseQuantity As Integer. PUT. ByVal secType As String. ByVal exerciseAction As Integer. ByVal multiplier As String. for example. The symbol of the underlying The option type. Ambiguities may require that this field be specified. ByVal curency As String. ByVal strike As Double. Public Overridable Sub exerciseOptions(ByVal id As Integer. ByVal right As String. ByVal expiry As String. Values are: 0 = no. Values include: OPT. If no multiplier is specified. by natural action the option would not exercise. Specifies whether your setting will override the system's natural action. ByVal override As Integer) Parameter id symbol secType expiry strike right multiplier Description The ticker id. For example. if your action is "exercise" and the option is not in-the-money.4 (December 2007) and will soon be removed. it is a good idea to always specify the currency. Use the format YYYYMM The strike price The option right. FOP. WAR The expiration date.

ByVal moodyRatingBelow As String. ByVal scannerSettingPairs As String. ByVal marketCapBelow As Double. Public Overridable Sub reqScannerSubscriptionEx(ByVal tickerId As Integer. ByVal spRatingAbove As String. ByVal marketCapAbove As Double. Please update your software to use the "Ex" counterparts to these deprecated methods. ByVal moodyRatingAbove As String. AMEX. and OTCBB being sub-types. it will be identified by this Id. ByVal scanCode As String. Values include STK. ByVal numberOfRows As Integer. Must be a unique value.IScannerSubscription) Parameter tickerId Description The Id for the subscription. ByVal subscription As TWSLib. Can be left blank. Filter out contracts with a price lower than this value. ByVal averageOptionVolumeAbove As Integer. Available values are listed in the scanner parameters XML document. ByVal instrument As String. NASDAQ. ByVal spRatingBelow As String.US is a legal value for this parameter. ByVal aboveVolume As Integer. ByVal maturityDateBelow As String. Defines the number or rows to display. ByVal couponRateBelow As Double. such as HIGH_OPT_VOLUME_PUT_CALL_RATIO. ByVal excludeConvertible As Integer.4 (December 2007) and will soon be removed.ActiveX ActiveX Methods reqScannerSubscriptionEx() Call the reqScannerSubscriptionEX() method to start receiving market scanner results through the scannerDataEx() event. ByVal stockTypeFilter As String) Parameter tickerId numberOfRows instrument locationCode Description The ticker ID. Available values are listed in the scanner parameters XML document. This is also used when canceling the scanner. Currently limited to US Stocks. Public Overridable Sub reqScannerSubscription(ByVal tickerId As Integer. The type of the scan. 145 scanCode abovePrice belowPrice API Reference Guide . When the subscription data is received. Can be left blank. ByVal locationCode As String. ByVal belowPrice As Double. Filter out contracts with a price above than this value. STK. ByVal couponRateAbove As Double. ByVal abovePrice As Double. ByVal maturityDateAbove As String. subscription reqScannerSubscription() Note: This method has been deprecated as of API release 9. Summary of the scanner subscription parameters including filters. Must be a unique value. with NYSE. Defines the instrument type used in the scan.

Can be left blank. Filter out contracts with a coupon rate higher than this value. Filter out convertible bonds. defines the stock type to be returned with respect to stocks and ETFs. Filter out contracts with a maturity date later than this value.excludes nothing STOCK . Scanner Setting Pairs are delimited by slashes. Can be left blank. Filter out contracts with a moody rating above this value. Filter out contracts with a maturity date earlier than this value. Can be left blank. Can be left blank. making this parameter open ended.true" which when used with Top Option Implied Vol % Gainers scan would return annualized volatilities. Filter out contracts with a market cap above this value. Filter out contracts with an S&P rating higher than this value. Used with the scanCode to help further narrow your query return. Filter out contracts with a volume above this value. Can be left blank. Valid values include: • • • ALL .which excludes ETFs ETF .which includes ETFs stockTypeFilter averageOptionVolume Above Filter out contracts with an average volume lower than this value. API Reference Guide 146 . Filter out contracts with a moody rating below this value. Can be left blank.ActiveX ActiveX Methods Parameter aboveVolume marketCapAbove marketCapBelow moodyRatingAbove moodyRatingBelow spRatingAbove spRatingBelow maturityDateAbove maturityDateBelow couponRateAbove couponRateBelow excludeConvertible scannerSettingPairs Description Filter out contracts with a volume below this value. A pair example is "Annual. Can be left blank. Can be left blank. Can be left blank. Can be left blank. Can be left blank. Filter out contracts with an S&P rating lower than this value. Filter out contracts with a coupon rate lower than this value. Can be left blank.

Public Overridable Sub cancelHistoricalData(ByVal tickerId As Integer) Parameter tickerId Description The ticker ID. ByVal useRTH As Integer) Parameter tickerId Description The Id for the request. ByVal barSize As Integer.ActiveX ActiveX Methods 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. Valid values include: • API Reference Guide 147 . it will be identified by this Id. 1 = only data within the regular trading hours for the product requested is returned. This structure contains a description of the contract for which market data is being requested. Determines the nature of the data extracted.IContract. Public Overridable Sub reqRealTimeBarsEx(ByVal tickerId As Integer. Must be a unique value. reqRealTimeBarsEx() Call the reqRealTimeBarsEx() method to start receiving real time bar results through the realtimeBar() event. if any other value is used. an exception will be thrown. including time intervals when the market in question was outside of regular trading hours. ByVal contract As TWSLib. Must be a unique value. ByVal whatToShow As String. Valid values include: • • • • useRTH • TRADES BID ASK MIDPOINT 0 = all data available during the time span requested is returned. Currently only 5 second bars are supported. cancelScannerSubscription() Public Overridable Sub cancelScannerSubscription(ByVal tickerId As Integer) Parameter tickerId Description The ticker ID. Must be a unique value. even if the time span falls partially or completely outside. When the data is received. This is also used when canceling the historical data request. contract barSize whatToShow Regular Trading Hours only.

ByVal barSize As Integer.4 (December 2007) and will soon be removed. The order destination. ByVal multiplier As String. Specifies the currency. if any other value is used. ByVal whatToShow As String. When the data is received. Specifies that the contract has expired.ActiveX ActiveX Methods reqRealTimeBars() Call the reqRealTimeBars() method to start receiving real time bar results through the realtimeBar() event. Public Overridable Sub reqRealTimeBars(ByVal tickerId As Integer. ByVal exchange As String. ByVal primaryExchange As String. ByVal useRTH As Integer) Parameter tickerId Description The Id for the request. ByVal isExpired As Integer. ByVal right As String. ByVal strike As Double. PUT. isExpired barSize API Reference Guide 148 . it is a good idea to always specify the currency. Allows you to specify a future or option contract multiplier. it will be identified by this Id. for example. Identifies the listing exchange for the contract (do not list SMART). ByVal currency As String. such as Smart. ByVal expiry As String. Must be a unique value. Use the format YYYYMM. Currently only 5 second bars are supported. CALL. ByVal secType As String. Specifies a Put or Call. Valid values are: • • • • • • • expiry strike right multiplier exchange primaryExchange currency STK OPT FUT IND FOP CASH BAG symbol secType The expiration date. ByVal symbol As String. The strike price. Note: This method has been deprecated as of API release 9. Ambiguities may require that this field be specified. This is the security type. C. when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). This is the symbol of the underlying asset. This is also used when canceling the historical data request. an exception will be thrown. Valid values are: P. This is only necessary when multiple possibilities exist. Please update your software to use the "Ex" counterparts to these deprecated methods. Given the existence of this kind of ambiguity.

Valid values include: • • 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.ActiveX ActiveX Methods Parameter whatToShow Description Determines the nature of the data extracted. including time intervals when the market in question was outside of regular trading hours. API Reference Guide 149 . For example. 1 = only data within the regular trading hours for the product requested is returned. Must be a unique value. useRTH Regular Trading Hours only. even if the time span falls partially or completely outside. Public Overridable Sub createComboLegList() As TWSLib. Valid values include: • • • • TRADES BID ASK MIDPOINT 0 = all data available during the time span requested is returned. Public Overridable Sub cancelRealTimeBars(ByVal tickerId As Integer) Parameter tickerId Description The ticker ID.IComboLegList You must use the factory “create” methods to create the COM objects in this section. reqCurrentTime() Returns the current system time on the server side. The IComboLeg object contains the definition of the leg list. Public Overridable Sub reqCurrentTime() createComboLegList() This factory method is used to create an IComboLegList COM object. the createComboLegList() method creates an IComboLeg object.

IExecutionFilter 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.IContract You must use the factory “create” methods to create the COM objects described in this chapter. The createScannerSubscripion() method creates an IScannerSubscription object. The createContract() method creates an IContract object. Public Overridable Sub createScannerSubscription() As TWSLib. which contains the filter criteria used to determine which execution reports are returned. which contains a description of the contract for which market data is being requested. createScannerSubscription() This factory method is used to create an IScannerSubscription COM object. Public Overridable Sub createContract() As TWSLib. createOrder() This factory method is used to create an IOrder COM object.IScannerSubscription You must use the factory “create” methods to create the COM objects described in this chapter. createTagValueList This factory method is used to create ITagValueList and ITagValue objects. Public Overridable Sub createExecutionFilter() As TWSLib.ITagValueList You must use the factory “create” methods to create the COM objects described in this chapter. Public Overridable Sub createOrder() As TWSLib.ActiveX ActiveX Methods createContract() This factory method is used to create an IContract COM object.IOrder You must use the factory “create” methods to create the COM objects described in this chapter. Public Overridable Function createTagValueList() As TWSLib. createExecutionFilter() This factory method is used to create an IExecutionFilter COM object. The createExecutionFilter() method creates an IExecutionFilter object. API Reference Guide 150 . which contains a summary of the scanner subscription parameters.

IScannerSubscription You must use the factory “create” methods to create the COM objects described in this chapter. The createUnderComp() method creates an IUnderComp object. ByVal reportType As String) Parameter reqId contract reportType Description The ID of the data request. This structure contains a description of the contract for which Reuters Fundamental data is being requested. Identifies the report type. which is used to define a Delta-Neutral Combo contract. reqFundamentalData() Call this method to receive Reuters global fundamental data. Public Overridable Sub reqFundamentalData(ByVal reqId As Integer. Public Overridable Sub createUnderComp() As TWSLib.ActiveX ActiveX Methods createUnderComp() This factory method is used to create an IUnderComp COM object.IContract. There must be a subscription to Reuters Fundamental set up in Account Management before you can receive this data. API Reference Guide 151 . Public Overridable Sub cancelFundamentalData(ByVal reqId As Integer) Parameter reqId Description The ID of the data request. ByVal contract As TWSLib. which is one of the following: • • • Estimates Financial Statements Summary cancelFundamentalData() Call this method to stop receiving Reuters global fundamental data.

This section defines the ActiveX events you can receive via the DTwsEvents interface.4 (December 2007) and will soon be removed.ActiveX ActiveX Events ActiveX Events ActiveX events receive information from the system and make it available to an application. Contract Details contractDetailsEx() contractDetails() contractDetailsEnd() bondContractDetails() Executions execDetailsEx() execDetails() execDetailsEnd() Market Depth updateMktDepth() updateMktDepthL2() Financial Advisors managedAccounts() receiveFA() Historical Data historicalData() Market Scanners scannerParameters() scannerDataEx() scannerData() scannerDataEnd() Real Time Bars realtimebar() Fundamental Data fundamentalData() Connection and Server connectionClosed() currentTime() errMsg() Market Data tickPrice() tickSize() tickOptionComputation() tickGeneric() tickString() tickEFP() tickSnapshotEnd() Orders orderStatus() openOrderEx() openOrder1() openOrder2() openOrder3() openOrder4() nextValidId() permId() Account and Portfolio updateAccountValue() updatePortfolioEx() updatePortfolio() updateAccountTime() News Bulletins updateNewsBulletin() API Reference Guide 152 . Note: Please note that events in red have been deprecated as of API release 9. Please update your software to use the "Ex" counterparts to these deprecated events. The new "Ex" events have been grouped with their deprecated counterparts for easy identification.

depending on the tickType value. last size or trading volume. Possible values are: • • • • • • price canAutoExecute 1 = bid 2 = ask 4 = last 6 = high 7 = low 9 = close The bid. ask size. Prices are updated immediately with no delay. the daily high. ByVal price As Double. daily low or last day close. Sub tickSize(ByVal id As Integer. API Reference Guide 153 . depending on tickType value. Possible values are: • • 0 = not eligible for automatic execution 1 = eligible for automatic execution tickSize() This function is called when the market data changes. ByVal size As Integer) Parameter id tickType Description The ticker ID that was specified previously in the call to reqMktData() Specifies the type of price. Sub tickPrice(ByVal id As Integer. ByVal tickType As Integer. Sizes are updated immediately with no delay. ByVal canAutoExecute As Integer) Parameter id tickType Description The ticker ID that was specified previously in the call to reqMktData() Specifies the type of price. Possible values are: • • • • size 0 = bid size 3 = ask size 5 = last size 8 = volume The bid size. Specifies whether the price tick is available for automatic execution. ByVal tickType As Integer.ActiveX ActiveX Events tickPrice() This function is called when the market data changes. ask or last price.

ActiveX ActiveX Events tickOptionComputation() Sub tickOptionComputation(ByVal id As Integer. The value of the specified field. The option gamma value. Sub tickGeneric(ByVal id As Integer. Possible values are: • • • ImpliedVol delta optPrice pvDivdend gamma vega theta undPrice 10 = Bid 11 = Ask 12 = Last The implied volatility calculated by the TWS option modeler.getField(int tickType) to retrieve the field description. using the specified ticktype value. Pass the field value into TickType. The option theta value. etc. The present value of dividends expected on the options underlier. The option delta calculated by the TWS option modeler. The option price. For example. The price of the underlying. ByVal value As Double) Parameter tickerId tickType Description The ticker Id that was specified previously in the call to reqMktData() Specifies the type of tick. ByVal vega As Double. ByVal pvDividend As Double. Values are updated immediately with no delay. ByVal impliedVol As Double. The option vega value. API Reference Guide 154 . ByVal optPrice As Double. ByVal tickType As Integer. ByVal delta As Double. Values are updated immediately with no delay. ByVal gamma As Double. ByVal theta As Double. a field value of 46 will map to shortable. tickGeneric() This method is called when the market data changes. value tickString() This method is called when the market data changes. ByVal tickType As Integer. ByVal undPrice As Double) Parameter id tickType Description The ticker ID that was specified previously in the call to reqMktData() Specifies the type of tick.

For example. etc. ByVal value As String) Parameter tickerId tickType Description The ticker Id that was specified previously in the call to reqMktData() Specifies the type of tick. ByVal totalDividends As Double.getField(int tickType) to retrieve the field description. Annualized basis points. Pass the field value into TickType. ByVal dividendsToExpiry As Double)) Parameter tickerId field Description The ticker Id that was specified previously in the call to reqMktData(). value tickEFP() This method is called when the market data changes. ByVal formattedBasisPoints As String. Annualized basis points as a formatted string that depicts them in percentage form. ByVal field As Integer. The dividends expected until the expiration of the single stock future. a field value of 38 will map to bidEFP. ByVal holdDays As Integer. basisPoints formattedBasis Points totalDividends holdDays futureExpiry dividendImpact dividendsToExpiry tickSnapshotEnd() This is called when a snapshot market data subscription has been fully handled and there is nothing more to wait for. The value of the specified field. ByVal tickType As Integer.getField(int tickType) to retrieve the field description. The expiration date of the single stock future. For example. The total expected dividends. Sub tickEFP(ByVal tickerId As Integer. a field value of 45 will map to lastTimestamp. ByVal futureExpiry As String. This also covers the timeout case. ByVal dividendImpact As Double. The dividend impact upon the annualized basis points interest rate.ActiveX ActiveX Events Sub tickString(ByVal id As Integer. Pass the field value into TickType. Values are updated immediately with no delay. The number of hold days until the expiry of the EFP. which is representative of the financing rate that can be directly compared to broker rates. Specifies the type of price. etc. API Reference Guide 155 . ByVal basisPoints As Double.

ActiveX ActiveX Events

Sub tickSnapshotEnd(ByVal reqId As Integer) Parameter reqID Description Id of the data request.

API Reference Guide

156

ActiveX ActiveX Events

orderStatus()
This event is called whenever the status of an order changes. It is also fired after reconnecting if the client has any open orders. Sub orderStatus(ByVal id As Integer, ByVal status As String, ByVal filled As Integer, ByVal remaining As Integer, ByVal avgFillPrice As Double, ByVal permId As Integer, ByVal parentId As Integer, ByVal lastFillPrice As Double, ByVal clientId As Integer, ByVal whyHeld As String) Parameter id status Description The order ID that was specified previously in the call to placeOrder() The order status. Possible values include: • PendingSubmit - indicates that you have transmitted the order, but have not yet received confirmation that it has been accepted by the order destination. 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 canceled. You may still receive an execution while your cancellation request is pending. Note: PendingSubmit and PendingCancel order statuses are not sent by the system and should be explicitly set by the API developer when an order is canceled. • 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. Submitted - indicates that your order has been accepted at the order destination and is working. Cancelled - indicates that the balance of your order has been confirmed canceled by the system. This could occur unexpectedly when the destination has rejected your order. Filled - indicates that he order has been completely filled. 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.

• •

• •

API Reference Guide

157

ActiveX ActiveX Events

Parameter filled remaining avgFillPrice

Description Specifies the number of shares that have been executed. Specifies the number of shares still outstanding. The average price of the shares that have been executed. This parameter is valid only if the filled parameter value is greater than zero. Otherwise, the price parameter will be zero. The id used to identify orders. Remains the same over sessions. The order ID of the parent order, used for bracket and auto trailing stop orders. 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. - 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.

permId parentId lastFilledPrice

clientId

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 id errorCode errorString Description This is the orderId or tickerId of the request that generated the error Error codes are documented in the Error Codes topic. This is the textual description of the error, also documented in the Error Codes topic.

connectionClosed()
This event is triggered when TWS closes the sockets connection with the ActiveX control, or when TWS is shut down. Sub connectionClosed()

API Reference Guide

158

ActiveX ActiveX Events

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.IOrder, ByVal orderState As TWSLib.IOrderState) Parameter orderId contract order orderState Description The order Id assigned by TWS. Used to cancel or update the order. The Contract class attributes describe the contract. The Order class attributes define the details of the order. The orderState attributes include margin and commissions fields for both pre and post trade data.

openOrder1()
This event sends the contract description of the open order. Note: This event has been deprecated as of API release 9,4 (December 2007) and will soon be removed. Please update your software to use the “Ex” counterparts to these deprecated events.

Sub openOrder1(ByVal id As Integer, ByVal symbol As String, ByVal secType As String, ByVal expiry As String, ByVal strike As Double, ByVal right As String, ByVal exchange As String, ByVal curency As String, ByVal localSymbol As String) Parameter id symbol secType Description The assigned order id. Use this id to cancel or modify the order. The underlying symbol. The security type. Valid values are: • • • • • • expiry strike right exchange currency STK OPT FUT IND FOP CASH

The expiration date. Use the format YYYYMM. The strike price. Specifies a Put or Call. Valid values are: P, PUT, C, CALL. The order destination, such as Smart. Specifies the currency. This field is only required when the secType = CASH. Otherwise it is ignored.

API Reference Guide

159

ActiveX ActiveX Events

Parameter local symbol

Description The local exchange symbol for the underlying asset.

openOrder2()
This event sends the order description of the open order. Note: This event has been deprecated as of API release 9,4 (December 2007) and will soon be removed. Please update your software to use the “Ex” counterparts to these deprecated events.

Sub openOrder2(ByVal id As Integer, ByVal action As String, ByVal quantity As Integer, ByVal orderType As String, ByVal lmtPrice As Double, ByVal auxPrice As Double, ByVal tif As String, ByVal ocaGroup As String, ByVal account As String, ByVal openClose As String, ByVal origin As Integer, ByVal orderRef As String, ByVal clientId As Integer) Parameter id action quantity orderType Description The order id. This is the same value that was passed in openOrder1. Identifies the side. Valid values are: BUY, SELL, SSHORT The order quantity. Identifies the order type. Valid values are: • • • • • • • • • • lmtPrice MKT MKTCLS LMT LMTCLS PEGMKT STP STPLMT TRAIL REL VWAP

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. This is the STOP price for stop limit orders and the offset amount for relative orders. In all other cases, specify 0. The time in force. Valid values are DAY, GTC, IOC Identifies a one-cancels-all group. The account. For institutional customers only. Specifies whether the order is an open or close order. For institutional customers only.

auxPrice tif ocaGroup account openClose

API Reference Guide

160

ActiveX ActiveX Events

Parameter origin orderRef clientId

Description The order origin. For institutional customers only. Valid values are: 0 = Customer, 1 = Firm. The order reference. For institutional customers only. The ID of the requesting 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.

openOrder3()
This event sends the contract description of the open order. Note: This event has been deprecated as of API release 9,4 (December 2007) and will soon be removed. Please update your software to use the “Ex” counterparts to these deprecated events.

Sub openOrder3(ByVal id As Integer, ByVal symbol As String, ByVal secType As String, ByVal expiry As String, ByVal strike As Double, ByVal right As String, ByVal exchange As String, ByVal curency As String, ByVal localSymbol As String, ByVal action As String, ByVal quantity As Integer, ByVal orderType As String, ByVal lmtPrice As Double, ByVal auxPrice As Double, ByVal tif As String, ByVal ocaGroup As String, ByVal account As String, ByVal openClose As String, ByVal origin As Integer, ByVal orderRef As String, ByVal clientId As Integer, ByVal permId As Integer, ByVal sharesAllocation As String, ByVal faGroup As String, ByVal faMethod As String, ByVal faPercentage As String, ByVal faProfile As String, ByVal goodAfterTime As String, ByVal goodTillDate As String) Parameter id symbol secType Description The assigned order id. Use this id to cancel or modify the order. The underlying symbol. The security type. Valid values are: • • • • • • expiry strike right exchange currency local symbol STK OPT FUT IND FOP CASH

The expiration date. Use the format YYYYMM. The strike price. Specifies a Put or Call. Valid values are: P, PUT, C, CALL. The order destination, such as Smart. Specifies the currency. This field is only required when the secType = CASH. Otherwise it is ignored. The local exchange symbol for the underlying asset.

API Reference Guide

161

ActiveX ActiveX Events

Parameter action quantity orderType

Description Identifies the side. Valid values are: BUY, SELL, SSHORT The size of the order. Identifies the order type. Valid values are: • • • • • • • • • • MKT MKTCLS LMT LMTCLS PEGMKT STP STPLMT TRAIL REL VWAP

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. This is the STOP price for stop limit orders, and the offset amount for relative orders. In all other cases, specify zero.

AuxPrice

API Reference Guide

162

ActiveX ActiveX Events

openOrder4()
This event sends the contract description of the open order. Note: This event has been deprecated as of API release 9,4 (December 2007) and will soon be removed. Please update your software to use the “Ex” counterparts to these deprecated events.

Sub openOrder4(ByVal id As Integer, ByVal symbol As String, ByVal secType As String, ByVal expiry As String, ByVal strike As Double, ByVal right As String, ByVal exchange As String, ByVal curency As String, ByVal localSymbol As String, ByVal action As String, ByVal quantity As Integer, ByVal orderType As String, ByVal lmtPrice As Double, ByVal auxPrice As Double, ByVal tif As String, ByVal ocaGroup As String, ByVal account As String, ByVal openClose As String, ByVal origin As Integer, ByVal orderRef As String, ByVal clientId As Integer, ByVal permId As Integer, ByVal sharesAllocation As String, ByVal faGroup As String, ByVal faMethod As String, ByVal faPercentage As String, ByVal faProfile As String, ByVal goodAfterTime As String, ByVal goodTillDate As String, ByVal ocaType As Integer, ByVal rule80A As String, ByVal settlingFirm As String, ByVal allOrNone As Integer, ByVal minQty As Integer, ByVal percentOffset As Double, ByVal eTradeOnly As Integer, ByVal firmQuoteOnly As Integer, ByVal nbboPriceCap As Double, ByVal auctionStrategy As Integer, ByVal startingPrice As Double, ByVal stockRefPrice As Double, ByVal delta As Double, ByVal stockRangeLower As Double, ByVal stockRangeUpper As Double, ByVal blockOrder As Integer, ByVal sweepToFill As Integer, ByVal ignoreRth As Integer, ByVal hidden As Integer, ByVal discretionaryAmt As Double, ByVal displaySize As Integer, ByVal parentId As Integer, ByVal triggerMethod As Integer, ByVal shortSaleSlot As Integer, ByVal designatedLocation As String, ByVal volatility As Double, ByVal volatilityType As Integer, ByVal deltaNeutralOrderType As String, ByVal deltaNeutralAuxPrice As Double, ByVal continuousUpdate As Integer, ByVal referencePriceType As Integer, ByVal trailStopPrice As Double, ByVal basisPoints As Double, ByVal basisPointsType As Integer, ByVal legsStr As String, ByVal scaleInitLevelSize As Integer, ByVal scaleSubsLevelSize As Integer, ByVal scalePriceIncrement As Double) Parameter id symbol secType Description The assigned order id. Use this id to cancel or modify the order. The underlying symbol. The security type. Valid values are: • • • • • • STK OPT FUT IND FOP CASH

API Reference Guide

163

For institutional customers only. For institutional customers only. C. For institutional customers only. also specify zero. This is the STOP price for stop limit orders. Valid values are: BUY. The local exchange symbol for the underlying asset. PUT. Cancel on Fill with Block = 1 Reduce on Fill with Block = 2 Reduce on Fill without Block = 3 The account to which the order is allocated. Identifies the order type. Valid values are: P. For institutional customers only. used for Limit. and the offset amount for relative orders.ActiveX ActiveX Events Parameter expiry strike right exchange curency local symbol action quantity orderType Description The expiration date. The time in force. specify zero. The order origin. In all other cases. The order destination. In all other cases specify zero. For relative orders with no limit price. The strike price. The order reference. Otherwise it is ignored. such as Smart. 1 = firm. Valid values are: 0 = customer. SELL. SSHORT The size of the order. This field is only required when the secType = CASH. Identifies the order as part of a one-cancels-all group. Identifies the side. The ID of the client who placed the order. NOTE: TWS orders have a fixed client ID of "0. Specifies whether the order is to open or close a position. Valid values are: • • • • • • • • • • MKT MKTCLS LMT LMTCLS PEGMKT STP STPLMT TRAIL REL VWAP lmtPrice This is the limit price." AuxPrice tif ocaGroup ocaType account openClose origin orderRef clientId API Reference Guide 164 . Specifies a Put or Call. Specifies the currency. Stop Limit and Relative orders. Use the format YYYYMM. CALL.

" format "YYYYMMDD hh:mm:ss (optional time zone)" Use an empty String if not applicable. minQty percentOffset eTradeOnly firmQuoteOnly nbboPriceCap API Reference Guide 165 . Trade with electronic quotes. Values are: 0 = no. The advisor group to which the trade will be allocated. Valid values include: The advisor method which will be used to allocate the trade. which means the entire quantity must execute or the order will be cancelled. Use an empty string if not applicable. 2 = no Values are: • • • • • • • • • Individual = 'I' Agency = 'A'. Use an empty string if not applicable. Upgrade to new FA functionality must be done. This value remains the same over TWS sessions. 1 = yes. You must enter GTD as the time in force to use this string. Identifies the order as having the all or none attribute.ActiveX ActiveX Events Parameter permId sharesAllocation faGroup faMethod faPercentage faProfile goodAfterTime Description The TWS ID used to identify orders. Deprecated. AgentOtherMember = 'W' IndividualPTIA = 'J' AgencyPTIA = 'U' AgentOtherMemberPTIA = 'M' IndividualPT = 'K' AgencyPT = 'Y' AgentOtherMemberPT = 'N' goodTillDate rthOnly rule80A settlingFirm allOrNone Institution only. 1 = yes Identifies a minimum quantity order type. The advisor profile which will be used to allocate the trade. Values are: 0 = no. Valid values include: The trade's "Good After Time. 1 = yes Maximum smart order distance from the NBBO. Values are: 0 = no." format "YYYYMMDD hh:mm:ss (optional time zone)" Use an empty String if not applicable. Use an empty string if not applicable. The percentage of the order for trade allocation. The percent offset amount for relative orders. 1 = yes Trade with firm quotes. The trade's "Good Till Date.

For price improvement option orders on BOX and VOL orders with dynamic management. allows triggering of orders outside of regular trading hours. delta stockRangeLower stockRangeUpper blockOrder sweepToFill ignoreRth hidden discretionaryAmt displaySize parentId triggerMethod • • shortSaleSlot designatedLocation Valid values are 1 or 2. 2 .The default value. The reference price is used for VOL orders to compute the limit price sent to an exchange (whether or not Continuous Update is selected). 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."last" method. If set to true. The amount off the limit price allowed for discretionary orders. specifies that the order is a Sweep-to-Fill order. All other orders will used the "last" method. Valid values are: • O . Specifies how Simulated Stop. Use only when shortSaleSlot value = 2. For price improvement option orders on BOX and VOL orders with dynamic management. If set to true. The publicly disclosed order size. Stop-Limit and Trailing Stop orders are triggered. used when placing Iceberg orders. For orders on BOX only. The lower value for the acceptable underlying stock price range. The stock delta. where stop orders are triggered based on the last price. where stop orders are triggered based on two consecutive bid or ask prices. The order ID of the parent order. specifies that the order is an ISE Block order.ActiveX ActiveX Events Parameter auctionStrategy Description Values are: • • match = 1 improvement = 2 • transparent = 3 For orders on BOX only. and for price range monitoring. API Reference Guide 166 . The "double bid/ask" method will be used for orders for OTC stocks and US options. 1 .use "double bid/ask" method. The stock reference price. used for bracket and auto trailing stop orders. For orders on BOX only. The upper value for the acceptable underlying stock price range. startingPrice stockRefPrice The auction starting price. If set to true.

referencePriceType API Reference Guide 167 . as calculated by TWS' Option Analytics. Valid values include: • • 1 = Average of NBBO 2 = NBB or the NBO depending on the action and right. specify NONE. Specifies whether TWS will automatically update the limit price of the order as the underlying price moves. and for stock range price monitoring. Specifies how you want TWS to calculate the limit price for options. VOL orders only. For no hedge delta order to be sent. Use this field to enter a value if the value in the deltaNeutralOrderType field is an order type that requires an Aux price. This value is expressed as a percent and is used to calculate the limit price sent to the exchange. such as a REL order.ActiveX ActiveX Events Parameter volatility Description The option price in volatility. Values are: • • 1 = Daily volatility 2 = Annual volatility volatilityType deltaNeutralOrder Type deltaNeutralAux Price continuousUpdate VOL orders only. VOL orders only. 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.

ActiveX ActiveX Events updateAccountValue() This event updates a single account value. Sub updateAccountValue(ByVal key As String. Below are some of the keys sent by TWS.Number of day trades left EquityWithLoanValue .Current initial margin requirement Leverage Look Ahead Available Funds Look Ahead Next Change Look Ahead Excess Liquidity Look Ahead Margin Req Look Ahead Maint Margin Req LongOptionValue .Account cash balance Currency . ByVal curency As String. ByVal value As String. ByVal accountName As String) Parameter key Description A string that indicates one type of account value. • • • • • • • • • • • • • • • • • • • • • • • • Account Type Account Code Available Funds Buying Power CashBalance .Equity with Loan Value Excess Liquidity Full Available Funds Full Excess Liquidity Full Init Margin Req Full Maint Margin Req Future Option Value Futures PNL Gross Position Value InitMarginReq .Currency string DayTradesRemaining .Long option value API Reference Guide 168 .

IContract. ByVal position As Integer. If the position is 0.Option market value Realized PNL Settled Cash ShortOptionValue . position marketPrice marketValue averageCost API Reference Guide 169 .ActiveX ActiveX Events Parameter key Description Values. The average cost per share is calculated by dividing your cost (execution price + commission) by the quantity of your position.Overnight initial margin requirement UnalteredMaintMarginReq .Stock market value Total Cash Balance Total Cash Value UnalteredInitMarginReq . The unit price of the instrument.Net liquidation value OptionMarketValue . continued: • • • • • • • • • • • • MaintMarginReq . ByVal realizedPNL As Double. This integer indicates the position on the contract. Useful for Financial Advisor sub-account messages.Overnight maintenance margin requirement Unrealized PNL value curency account The value associated with the key. updatePortfolioEx() This callback is made in response to the reqAccountUpdates() method.Current maintenance margin NetLiquidation . Defines the currency of the value. The total market value of the instrument. ByVal marketPrice As Double. ByVal unrealizedPNL As Double. it means the position has just cleared. The exchange field in a contract is not set for portfolio update. Sub updatePortfolioEx(ByVal contract As TWSLib. ByVal accountName As String) Parameter contract Description This object contains a description of the contract which is being traded. ByVal averageCost As Double. if the value is a monetary amount.Short option value StockMarketValue . states the account the message applies to. ByVal marketValue As Double.

PUT. Valid values are: • • • • • • • expiry strike right curency localSymbol position marketPrice marketValue API Reference Guide STK OPT FUT IND FOP CASH BAG The expiration date. accountName updatePortfolio() This event updates a single holding in your portfolio. Use the format YYYYMM. Otherwise it is ignored. The unit price of the instrument. The local exchange symbol of the asset. ByVal realizedPNL As Double. ByVal marketPrice As Double. The strike price.ActiveX ActiveX Events Parameter unrealizedPNL realizedPNL Description The difference between the current market value of your open positions and the average cost. ByVal unrealizedPNL As Double. ByVal secType As String. Valid values are: P. ByVal averageCost As Double. Useful for Financial Advisor sub-account messages. ByVal marketValue As Double.Average Cost. or Value . Specifies a put or call. ByVal curency As String. ByVal position As Integer. 170 . If the value is 0. 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) The name of the account the message applies to. Sub updatePortfolio(ByVal symbol As String. ByVal localSymbol As String. it means the position has just cleared. CALL Specifies the currency. This field is only required when the secType = CASH. ByVal strike As Double. Note: This event has been deprecated as of API release 9. The security type. The total market value of the instrument. ByVal right As String. Indicates the position on the contract. Shows your profit on closed positions. ByVal accountName As String) Parameter symbol secType Description The symbol of the underlying asset. C.4 (December 2007) and will soon be removed. Please update your software to use the “Ex” counterparts to these deprecated events. ByVal expiry As String.

Sub nextValidId(ByVal id As Integer) Parameter id Description The next available order ID received from TWS upon connection. This id will remain the same from session to session permId API Reference Guide 171 . ByVal permId As Integer) Parameter id Description The next available order ID received from TWS upon connection. The permId will remain the same from session to session. Shows your profit on closed positions.ActiveX ActiveX Events Parameter averageCost Description The average cost per share is calculated by dividing your cost (execution price + commission) by the quantity of your position. Sub permId(ByVal id As Integer. Sub updateAccountTime(ByVal timeStamp As String) Parameter timeStamp Description This indicates the last update time of the account information. It gives the permId for the specified order id. States the account the message applies to. permId() This event is always received after an order Status event. or (Value . Increment all successive orders by one based on this ID. unrealizedPNL realizedPNL account updateAccountTime() This event sends the time at which the account values and portfolio market prices were calculated. which is the difference between your entry execution cost (execution price + commissions to open the position) and exit execution costs (execution price + commissions to close the position). Increment all successive orders by one based on this ID. nextValidId() This event is called after a successful connection to TWS.Average Cost). Useful for Financial Advisor sub-account messages. The difference between the current market value of your open positions and the average cost.

ActiveX ActiveX Events contractDetailsEx() This event is called only in response to the reqContractDetailsEx() method having been called. ByVal contractDetails As TWSLib.IContractDetails) Parameter reqId contractDetails Description The ID of the data request. Note: This event has been deprecated as of API release 9. Use the format YYYYMM. The strike price. Please update your software to use the “Ex” counterparts to these deprecated events. ByVal localSymbol As String. ByVal tradingClass As String. ByVal right As String. Sub contractDetails(ByVal symbol As String. PUT. Otherwise it is ignored. Valid values are: • • • • • • expiry strike right exchange curency localSymbol STK OPT FUT IND FOP CASH The expiration date. such as Smart. ByVal marketName As String. ByVal multiplier As String. This field is only required when the secType = CASH. Ensures that responses are matched to requests if several requests are in process. CALL The order destination. contractDetails() This event is fired when the reqContractDetails() or reqContractDetails2() methods are invoked. ByVal validExchanges As String) Parameter symbol secType Description The underlying symbol. ByVal strike As Double.4 (December 2007) and will soon be removed. The local exchange symbol of the asset. Specifies the currency. The security type. Valid values are: P. ByVal exchange As String. C. ByVal expiry As String. ByVal priceMagnifier As Integer. ByVal conId As Integer. ByVal minTick As Double. ByVal secType As String. This object contains a full description of the contract being looked up. Specifies a put or call. ByVal curency As String. API Reference Guide 172 . Sub contractDetailsEx(ByVal reqId As Integer. ByVal orderTypes As String.

The minimum price tick.ActiveX ActiveX Events Parameter marketName tradingClass conId minTick priceMagnifier Description The market name for this contract. The list of valid order types for this contract. The order size multiplier. This structure contains addition order execution details. This helps to define the end of an option chain. i. ByVal execution As TWSLib.IContract. This object contains a full description of the contract that was executed.e. The trading class name for this contract.IExecution) Parameter orderId contract execution Description The order Id that was specified previously in the call to placeOrderEx(). API Reference Guide 173 . or when an order is filled. Z on LIFFE is reported in index points and not GBP. execDetailsEx() This method is called when the reqExecutionsEx() method is invoked. historical data and the order price. Sub execDetailsEx(ByVal reqId As Integer. Sub contractDetailsEnd(ByVal reqId As Integer) Parameter reqID Description Id of the data request. Allows execution and strike prices to be reported consistently with market data. The unique contract identifier. ByVal contract As TWSLib. multiplier orderTypes validExchanges contractDetailsEnd() This method is called once all contract details for a given request are received. The list of exchanges on which this contract is traded.

-Specifies if the transaction was a purchase or a sale. which distinguishes them from API client orders. CALL The order destination. ByVal clientId As Integer. Valid values are: P. such as Smart. Sub execDetails(ByVal id As Integer. ByVal cExchange As String. Valid values are: • • • • • • expiry strike right cExchange curency localSymbol execId time acctNumber eExchange side STK OPT FUT IND FOP CASH symbol secType The expiration date.ActiveX ActiveX Events execDetails() This event is fired when the reqExecutions() methods is invoked. ByVal side As String. This field is only required when the secType = CASH. The security type. Note: TWS orders have a fixed orderId of 0. Valid values are: • • BOT SLD API Reference Guide 174 . Use the format YYYYMM. The strike price. C. The local exchange symbol for the underlying asset. ByVal isLiquidation As Integer) Parameter id Description The order id. This is the same value that was passed in openOrder1. ByVal price As Double. ByVal curency As String. The order execution id. ByVal expiry As String. ByVal time As String. ByVal symbol As String. ByVal secType As String. Please update your software to use the “Ex” counterparts to these deprecated events. ByVal acctNumber As String. Note: This event has been deprecated as of API release 9. PUT. The underlying symbol. The time of order execution. ByVal shares As Integer. ByVal strike As Double. or when an API order is filled or partially filled.4 (December 2007) and will soon be removed. The customer account number. Specifies a put or call. Specifies the currency. ByVal right As String. ByVal execId As String. Otherwise it is ignored. ByVal eExchange As String. ByVal localSymbol As String. ByVal permId As Integer.

Possible values are: • • 0 = execution is not the result of liquidation 1 = execution is the result of a liquidation 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 reqID Description Id of the data request. Note that TWS orders have a fixed ID of 0. Valid values are: • • 0 = ask 1 = bid API Reference Guide 175 . The TWS id used to identify orders. ByVal position As Integer.ActiveX ActiveX Events Parameter shares price permId permId isliquidation Description The number of shares filled. Specifies whether an execution is the result of a liquidation. updateMktDepth() This function is called when the market depth changes. ByVal price As Double. ByVal side As Integer. The ID of the client that placed the order. Identifies how this order should be applied to the market depth. The order execution price. ByVal size As Integer) Parameter id position operation Description The ticker ID that was specified previously in the call to reqMktDepth() Specifies the row ID of this market depth entry. remains the same over TWS sessions. Valid values are:· • • • side 0 = insert (insert this new order into the row identified by 'position')· 1 = update (update the existing order in the row identified by 'position')· 2 = delete (delete the existing order at the row identified by 'position') The side of the book to which this order belongs. Sub updateMktDepth(ByVal id As Integer. ByVal operation As Integer.

updateNewsBulletin() This event is triggered for each new bulletin if the client has subscribed (i. updateMktDepthL2() This function is called when the Level II market depth changes. Identifies the how this order should be applied to the market depth.ActiveX ActiveX Events Parameter price size Description The order price. Specifies the exchange hosting this order. by calling the reqNewsBulletins() method). increments for each new bulletin. The order size. ByVal price As Double. ByVal side As Integer. ByVal origExchange As String) Parameter msgId Description The bulletin ID. ByVal marketMaker As String. Sub updateMktDepthL2(ByVal id As Integer. ByVal message As String. Valid values are: • • • side 0 = insert (insert this new order into the row identified by 'position')· 1 = update (update the existing order in the row identified by 'position')· 2 = delete (delete the existing order at the row identified by 'position') Identifies the side of the book that this order belongs to.e. Sub updateNewsBulletin(ByVal msgId As Short. ByVal size As Integer) Parameter id position marketMaker operation Description The ticker ID that was specified previously in the call to reqMktDepth() Specifies the row id of this market depth entry. ByVal operation As Integer. Valid values are: • • 0 = ask 1 = bid price size The order price. API Reference Guide 176 . The order size. ByVal position As Integer. ByVal msgType As Short.

The date-time stamp of the start of the bar. Sub historicalData(ByVal reqId As Integer. ByVal open As Double. The exchange from which this message originated. ByVal low As Double. message origExchange The bulletins message text. receiveFA() This event receives previously requested FA configuration information from TWS. Valid values include: • • • cxml 1 = GROUPS 2 = PROFILE 3 =ACCOUNT ALIASES The XML string containing the previously requested FA configuration information. Valid values include: • • • 1 = Regular IB news bulletin 2 = Exchange no longer available for trading. ByVal cxml As String) Parameter faDataType Description Specifies the type of Financial Advisor configuration data being received from TWS. 3 = Exchange is available for trading. ByVal hasGaps As Integer) Parameter reqId date Description The ticker ID of the request to which this bar is responding. ByVal high As Double. historicalData() This event receives requested historical data from TWS.ActiveX ActiveX Events Parameter msgType Description Specifies the type of bulletin. Sub receiveFA(ByVal faDataType As Integer. ByVal WAP As Double. ByVal barCount As Integer. ByVal date As String. The format is determined by the reqHistoricalData() formatDate parameter. Sub managedAccounts(ByVal accountsList As String) Parameter accountsList Description The comma delimited list of FA-managed accounts. managedAccounts() This event id is fired when a successful connection is made to a Financial Advisor account. ByVal close As Double. It is also fired when the reqManagedAccts() method is invoked. API Reference Guide 177 . ByVal volume As Integer.

The weighted average price during the time covered by the bar. The volume during the time covered by the bar.ActiveX ActiveX Events Parameter open high low close volume WAP hasGaps Description The bar opening price. The bar closing price. The low price during the time covered by the bar. The high price during the time covered by the bar. API Reference Guide 178 . Identifies whether or not there are gaps in the data.

The trading class name for this contract. Values are: True or False. ByVal maturity As String. such as "FIXED. such as "Corp" for corporate. ByVal nextOptionType As String. ByVal issueDate As String. ByVal minTick As Double. ByVal tradingClass As String. ByVal conId As Integer. or 12 character SEDOL. Identifies the credit rating of the issuer. Description string containing further descriptive information about the bond. The currency in which the bond trades. ByVal marketName As String. ByVal ratings As String. The IB contract ID of the bond. ByVal nextOptionPartial As Integer. ByVal curency As String. A higher credit rating generally indicates a less risky investment. ByVal convertible As Integer. If true. BOND The nine-character bond CUSIP. The type of the bond. the bond can be sold back to the issuer under certain conditions. bondType couponType convertible callable putable descAppend exchange curency marketName tradingClass conId minTick orderTypes validExchanges API Reference Guide 179 . ByVal couponType As String. the bond can be called by the issuer under certain conditions. ByVal callable As Integer. ByVal orderTypes As String. ByVal notes As String) Parameter symbol secType cusip coupon maturity issueDate ratings Description The bond symbol." Values are: True or False. ByVal secType As String. The interest rate used to calculate the amount you will receive in interest payments over the course of the year. the bond can be converted to stock under certain conditions. ByVal coupon As Double.ActiveX ActiveX Events bondContractDetails() Sub bondContractDetails(ByVal symbol As String. ByVal descAppend As String. ByVal cusip As String. If true. he date on which the bond was issued. ByVal exchange As String. ByVal putable As Integer. ByVal nextOptionDate As String. ByVal validExchanges As String. The order types that apply to this bond. The type of the coupon. The market name for this contract. A comma-delimited string of exchanges on which this bond trades. The minimum price increment of the bond. If true. The exchange on which the BOND trades. The date on which the issuer must repay the face value of the bond. ByVal bondType As String. Values are: True or False. Bond ratings are from Moody's and S&P respectively.

Next option type. Sub scannerData(ByVal reqId As Integer. ByVal legsStr As String) Parameter reqId rank contractDetails distance benchmark projection legsStr Description The ID of the request to which this row is responding. if populated for the bond in IB’s database. Varies based on query. Applies only to bonds with embedded options (is the next option full or partial?). Please update your software to use the “Ex” counterparts to these deprecated events. ByVal secType As String. Describes combo legs when scan is returning EFP. Bond notes. ByVal rank As Integer. ByVal marketName As API Reference Guide 180 . ByVal curency As String. ByVal rank As Integer.IContractDetails. scannerParameters() Sub scannerParameters(ByVal xml As String) Parameter xml Description An XML document that describes the valid parameters that a scanner parameter can have. This object contains a full description of the contract. ByVal distance As String. ByVal exchange As String. scannerData() Note: This event has been deprecated as of API release 9. Sub scannerDataEx(ByVal reqId As Integer. scannerDataEx() This event receives the requested market scanner data results. ByVal benchmark As String. Applies only to bonds with embedded options. Varies based on query. Next option partial.4 (December 2007) and will soon be removed. ByVal projection As String. Varies based on query.ActiveX ActiveX Events Parameter nextOptionDate nextOptionType nextOptionPartial notes Description Next option date. The ranking within the response of this bar. ByVal expiry As String. ByVal symbol As String. ByVal localSymbol As String. ByVal strike As Double. ByVal right As String. ByVal contractDetails As TWSLib. Applies only to bonds with embedded options.

ByVal Count As Integer) Parameter reqId time open Description The ticker Id of the request to which this bar is responding. The exchange on which the symbol trades. Identifier assigned to derivatives that uniquely identifies them on an exchange. the expiration date. ByVal close As Double. Varies based on the query. The bar opening price. ByVal high As Double. The format is determined by the reqHistoricalData() formatDate parameter. Sub realtimeBar(ByVal tickerId As Integer. it's strike price. API Reference Guide 181 .ActiveX ActiveX Events String. ByVal low As Double. ByVal projection As String. scannerDataEnd() This function is called when the snapshot is received and marks the end of one scan. ByVal benchmark As String. The trading class name of the contract. Varies based on the query. The symbol to which this bar pertains. The date-time stamp of the start of the bar. If a derivative. ByVal WAP As Double. realtimeBar() This method receives the real-time bars data results. The market name of the contract. call or put. If an option. The currency the symbol trades in on the exchange. Varies based on the query. ByVal tradingClass As String. ByVal time As Integer. Sub scannerDataEnd(ByVal reqId As Integer) Parameter reqId Description The ID of the market data snapshot request being closed by this parameter. The security type of that symbol. ByVal legsStr As String) Parameter reqId rank symbol secType expiry strike right exchange currency localSymbol marketName tradingClass distance benchmark projection Description The ticker ID of the request to which this row is responding. If an option. ByVal distance As String. ByVal open As Double. The ranking within the response of this particular bar. ByVal volume As Integer.

The bar closing price. ByVal data As String) Parameter reqId data Description The ID of the data request. There must be a subscription to Reuters Fundamental set up in Account Management before you can receive this data. The low price during the time covered by the bar. When TRADES historical data is returned. represents the number of trades that occurred during the time period the bar covers. One of three XML reports: • • • Estimates (estimates) Financial statements (finstat) Summary (snapshot) API Reference Guide 182 . The weighted average price during the time covered by the bar. The volume during the time covered by the bar. Sub currentTime(ByVal time As Integer) Parameter time Description The current system time on the server side.ActiveX ActiveX Events Parameter high low close volume wap count Description The high price during the time covered by the bar. fundamentalData() This method is called to receive Reuters global fundamental market data. currentTime() This method receives the current system time on the server side.. Sub fundamentalData(ByVal reqId As Integer.

Do not try to pass a COM object to another instance of a TWS COM object. Once a COM object has been created by a factory method. API Reference Guide 183 . the COM object is tied to a corresponding TWS COM object (an instance of the COM object).ActiveX ActiveX COM Objects ActiveX COM Objects The tables below define properties for the following objects: • • • • • • • • • • • • IExecution IExecutionFilter IContract IContractDetails IComboLeg IComboLegList IOrder IOrderState IScannerSubscription ITagValueList ITagValue IUnderComp You must use the factory “create” methods to create the COM objects in this section.

Filter the results of the reqExecutionsEx() method based on execution reports received after the specified time. The customer account number. remains the same over TWS sessions.ActiveX ActiveX COM Objects IExecution Property orderId() As Integer clientId() As Integer execId() As String time() As String acctNumber() As String exchange() As String side() As String Description The order id. Exchange that executed the order. combo trades and legs of the combo. Filter the results of the reqExecutionsEx() method based on an account code." Unique order execution id. Cumulative quantity. Note: this is only relevant for Financial Advisor (FA) accounts. Used in regular trades. The order execution price. Note: TWS orders have a fixed order id of "0. The order execution time. Valid values are: • • BOT SLD shares() As Integer price() As Double permId() As Integer liquidation() As Integer cumQty() As Integer avgPrice() As Double The number of shares filled. IExecutionFilter Property clientId() As Integer acctCode() As String Description Filter the results of the reqExecutionsEx() method based on the clientId. The TWS id used to identify orders. Identifies the position as one to be liquidated last should the need arise. Note: TWS orders have a fixed client id of "0. The format for timeFilter is "yyyymmdd-hh:mm:ss" Filter the results of the reqExecutionsEx() method based on the order symbol. time() As String symbol() As String API Reference Guide 184 ." The id of the client that placed the order. Specifies if the transaction was a sale or a purchase. Average price. Used in regular trades. combo trades and legs of the combo.

Filter the results of the reqExecutionsEx() method based on the order exchange. Note: Refer to the Contract object for the list of valid security types. Note: Refer to the Order object for the list of valid order actions. Filter the results of the reqExecutionsEx() method based on the order action.ActiveX ActiveX COM Objects Property secType() String Description Filter the results of the reqExecutionsEx() method based on the order security type. exchange() As String side() As String API Reference Guide 185 .

The order destination. The unique contract identifier. Valid values are: P. Given the existence of this kind of ambiguity. such as Smart.ActiveX ActiveX COM Objects IContract Property symbol() As String secType() As String Description This is the symbol of the underlying asset. This is only necessary when multiple possibilities exist. contract details requests and historical data queries can be performed pertaining to expired contracts. Description for combo legs Dynamic memory structure used to store the leg definitions for this contract. Ambiguities may require that this field be specified. when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). PUT. CALL. Identifies the listing exchange for the contract (do not list SMART). This is the security type. Specifies a Put or Call. Note: Historical data queries on expired contracts are limited to the last year of the contracts life. This is the local exchange symbol of the underlying asset. If set to true. exchange() As String currency() As String localSymbol() As String primaryExch() As String includeExpired() As Integer comboLegsDescrip() As String comboLegs() As Object conId() As Integer API Reference Guide 186 . Use the format YYYYMM. for example. Allows you to specify a future or option contract multiplier. it is a good idea to always specify the currency. C. Valid values are: • • • • • • • STK OPT FUT IND FOP CASH BAG expiry() As String strike() As Double right() As String multiplier() As String The expiration date. The strike price. and are initially only supported for expired futures contracts. Specifies the currency.

API Reference Guide 187 .O for Apple on NASDAQ. Supported identifiers are: • • • • ISIN (Example: Apple: US0378331005) CUSIP (Example: Apple: 037833100) SEDOL (Consists of 6-AN + check digit.) secId as String Unique identifier for the secIdType. Example: BAE: 0263494) RIC (Consists of exchange-independent RIC Root and a suffix identifying the exchange.ActiveX ActiveX COM Objects Property secIdType As String Description Security identifier. Example: AAPL. when querying contract details or when placing orders.

Values are True or False. Values are True or False.e. For Bonds. the bond can be converted to stock under certain conditions. i. For Bonds. Identifies the credit rating of the issuer. A description string containing further descriptive information about the bond. applies to bonds with embedded options. For Bonds. The minimum price tick. The date on which the issuer must repay the face value of the bond. such as "CORP. For Bonds. The nine-character bond CUSIP or the 12-character SEDOL. For Bonds. if populated for the bond in IB's database orderTypes() As String validExchanges() As String underConId() As String longName() As String cusip() As String ratings() As String descAppend() As String bondType() As String couponType() As String callable() As Integer putable() As Integer coupon() As Double convertible() As Integer maturity() As String issueDate() As String nextOptionDate)_ As String nextOptionType() As String nextOptionPartial() As Integer notes() As String API Reference Guide 188 . For Bonds. Z on LIFFE is reported in index points and not GBP. If true. The descriptive name of the asset. For Bonds. Values are True or False. For Bonds. For Bonds. For Bonds. For Bonds. applies to bonds with embedded options. The list of exchanges this contract is traded on. The date the bond was issued. The market name for this contract." For Bonds. For Bonds. The type of bond. A higher credit rating generally indicates a less risky investment. the bond can be called by the issuer under certain conditions. For Bonds. applies to bonds with embedded options. Bond ratings are from Moody's and S&P respectively. If true. If true." For Bonds. The underlying contract ID. historical data and the order price. The interest rate used to calculate the amount you will receive in interest payments over the course of the year. Allows execution and strike prices to be reported consistently with market data.ActiveX ActiveX COM Objects IContractDetails Property summary() As Object marketName() String tradingClass() As String minTick() As Double priceMagnifier() Integer Description A contract summary. The trading class name for this contract. The list of valid order types for this contract. such as "FIXED. the bond can be sold back to the issuer under certain conditions.The type of bond coupon.

Unknown .clearing broker 2 . Financial. If this value is used. you must enter a designated location. 1 . This value is only valid for institutional customers.ActiveX ActiveX COM Objects Property contractMonth() As String industry() As String category() As String subcategory() As String timeZoneId() As String tradingHours() As String liquidHours() As String Description The contract month.Close.Same as the parent security. InvestmentSvc.20090508:CLOSED. 20090507:0700-1830.1830-2330. For example. The exchange to which the complete combination order will be routed. EST. This value is only valid for institutional customers. Specifies whether the order is an open or close order.(3) 0 . The trading hours of the product. To help determine the ratio for a specific combination order. For example. For example. Valid values are: • • • • 0 .20090508:CLOSED. refer to the Interactive Analytics section of the User's Guide. Brokerage. Select the relative number of contracts for the leg you are constructing. The liquid trading hours of the product. For example. For example.third party.Open.e. The industry category of the underlying. This is the only option for retail customers. 20090507:0930-1600. 2 . • • • API Reference Guide 189 . IComboLeg Property conId() As Integer action() As String ratio() As Integer Description The unique contract identifier specifying the security. For example. Typically the contract month of the underlying for a futures contract. The ID of the time zone for the trading hours of the product. retail customer or not short leg) 1 .inapplicable (i. The industry subcategory of the underlying. exchange() As String openClose() As Integer shortSaleSlot() Integer For institutional customers only. The side (buy or sell) for the leg you are constructing. The industry classification of the underlying/product.

remains the same over TWS sessions. Leg count. IComboLegList Property Add() As Object Count() As Integer Item(Integer) As Object Description Adds combo legs to a combo leg list. Otherwise leave blank or orders will be rejected. The id of the client that placed this order. Valid values are: • • • • • • • • • • • • MKT MKTCLS LMT LMTCLS PEGMKT SCALE STP STPLMT TRAIL REL VWAP TRAILLIMIT API Reference Guide 190 .ActiveX ActiveX COM Objects Property designatedLocation() As String Description If shortSaleSlot == 2. the designatedLocation must be specified. The TWS id used to identify orders. IOrder Property orderId() As Integer clientId() As Integer permid() As Integer action() As String totalQuantity() As Integer orderType() As String Description The id for this order. Identifies the side. SELL. Identifies the order type. SSHORT The order quantity. Valid values are: BUY. Get leg by index.

For relative orders with no limit price. 1 = firm The order reference. If set to true. Valid values are 0 = customer. also specify zero. In all other cases specify zero. IOC. used when placing Iceberg orders. The time in force. Specifies whether the order is an open or close order. specifies that the order is a Sweep-to-Fill order. The order origin. For institutional customers only. specify zero. For institutional customers only. C. origin() As Integer orderRef() String transmit() As Integer parentId() As Integer blockOrder() As Integer sweepToFill() As Integer displaySize() As Integer API Reference Guide 191 . This is the STOP price for stop-limit orders. Valid values are O. and the offset amount for relative orders. used for bracket and auto trailing stop orders. specifies that the order is an ISE Block order. If set to true. In all other cases. account() As String openClose() As String The account. GTD. Identifies an OCA (one cancels all) group. For institutional customers only. This means that only one order in the group will be routed at a time to remove the possibility of an overfill. The order ID of the parent order. The publicly disclosed order size.ActiveX ActiveX COM Objects Property lmtPrice() As Double Description This is the LIMIT price. Specifies whether the order will be transmitted by TWS. Valid values are: DAY. For institutional customers only. Valid values include: • • • 1 = Cancel all remaining orders with block 2 = Remaining orders are proportionately reduced in size with block auxPrice() As Double timeInForce() As String ocaGroup() As String ocaType() As Integer 3 = Remaining orders are proportionately reduced in size with no block If you use a value "with block" gives your order has overfill protection. If set to false. Tells how to handle remaining orders in an OCA group when one order or part of an order executes. GTC. the order will be created at TWS but will not be sent. used for limit. stop-limit and relative orders.

where stop orders are triggered based on two consecutive bid or ask prices. 7 last or bid/ask method. The Financial Advisor percentage concerning the trade's allocation -. The "double bid/ask" method will be used for orders for OTC stocks and US options.use an empty String if not applicable. You must enter a tif value of GTD. The trade's "Good Till Date.use an empty String if not applicable.use an empty String if not applicable. This option only applies to orders routed to the ISLAND exchange.use an empty String if not applicable. 8 mid-point method. 3 double last method.The default value. 2 . The trade's "Good After Time. discretionaryAmt() As Double goodAfterTime() As String goodTillDate() As String faGroup() As String faProfile() As String faMethod() As String faPercentage() As String shortSaleSlot() As Integer API Reference Guide 192 . If set to true. • • • • • • outsideRth() As Integer hidden() As Integer If set to true."last" method. The Financial Advisor allocation profile the trade will be allocated to -. All other orders will used the "last" method. allows orders to also trigger or fill outside of regular trading hours. Valid values are: • 0 .ActiveX ActiveX COM Objects Property triggerMethod() As Integer Description Specifies how Simulated Stop. where stop orders are triggered based on the last price." format "YYYYMMDD hh:mm:ss (optional time zone)" Use an empty String if not applicable. 4 bid/ask method. The amount off the limit price allowed for discretionary orders. The Financial Advisor group the trade will be allocated to -." format is: YYYYMMDD hh:mm:ss (optional time zone) Use an empty String if not applicable. 1 . Stop-Limit and Trailing Stop orders are triggered. The Financial Advisor allocation method the trade will be allocated with -. the order will not be visible when viewing the market depth.use "double bid/ask" method. Values are 1 or 2.

and PTA (post trade allocation). This value is required for FUT/FOP orders for reporting to the exchange. Valid values include: • • 0 = False 1 = True Individual = 'I' Agency = 'A'.ActiveX ActiveX COM Objects Property designatedLocation() As String ocaType() As Integer Description Use only when shortSaleSlot value = 2. The percent offset amount for relative orders. For IBExecution customers: Valid values are: IB. Cancel on Fill with Block = 1 Reduce on Fill with Block = 2 Reduce on Fill without Block = 3 Precautionary constraints are defined on the TWS Presets page. no=0 Identifies a minimum quantity order type. Orders sent from the API are also validated against these safety constraints. AgentOtherMember = 'W' IndividualPTIA = 'J' AgencyPTIA = 'U' AgentOtherMemberPTIA = 'M' IndividualPT = 'K' AgencyPT = 'Y' AgentOtherMemberPT = 'N' overridePercentageConstraints( ) As Integer rule80A() As String Valid values are: • • • • • • • • • settlingFirm() As String clearingAccount() As String Institutional only. set this parameter’s value to True. no = 0 Trade with firm quotes. yes=1. and may be rejected if any constraint is violated. Away. clearingIntent() As String allOrNone() As Integer minQty() As Integer percentOffset() As Double eTradeOnly() As Integer firmQuoteOnly() As Integer nbboPriceCap() As Double API Reference Guide 193 . yes = 1. no = 0 The maximum Smart order distance from the NBBO. Trade with electronic quotes. To override validation. and help ensure tha tyour price and size order values are reasonable. yes = 1. For IBExecution customers: Specifies the true beneficiary of the order.

VOL orders only. For price improvement option orders on BOX and VOL orders with dynamic management. How the volatility is calculated. Valid on BOX orders only. The lower value for the acceptable underlying stock price range. Volatility is expressed as a percentage. • • deltaNeutralOrderType() As String Daily = 1 Annual = 2 delta() As Double stockRangeLower() As Double stockRangeUpper() As Double volatility() Double volatilityType() Integer VOL orders only. the limit price sent to an exchange is not editable. as it is the output of a function. The stock delta. specify NONE. computed via TWS’s Options Analytics. and for price range monitoring. Enter an order type to instruct TWS to submit a delta neutral trade on full or partial execution of the VOL order. What the price is. Valid on BOX orders only. startingPrice() As Double stockRefPrice() As Double The starting price. For price improvement option orders on BOX and VOL orders with dynamic management. For VOL orders. The upper value for the acceptable underlying stock price range. For no hedge delta order to be sent. deltaNeutralAuxPrice() As Double API Reference Guide 194 . such as a REL order. The reference price is used for VOL orders to compute the limit price sent to an exchange (whether or not Continuous Update is selected). The stock reference price. Use this field to enter a value if the value in the deltaNeutralOrderType field is an order type that requires an Aux price.ActiveX ActiveX COM Objects Property auctionStrategy() As Integer Description Valid values are: • • match = 1 improvement = 2 • transparent = 3 For BOX exchange only.

and National Best Ask when selling a call or buying a put. margin and commissions data is received back via the IOrderState() object for the openOrder() callback. Determines whether TWS is supposed to update the order price as the underlying moves. the limit price sent to an exchange is modified by TWS if the computed price of the option changes enough to warrant doing so. This field is required. For EFP orders only For EFP orders only Use to request pre-trade commissions and margin information. ireferencePriceType() As Integer trailStopPrice() As Double scaleInitLevelSize() As Integer scaleSubsLevelSize() As Integer scalePriceIncrement() As Double basisPoints() As Integer basisPointsType() As Double whatIf() As Integer For TRAILLIMIT orders only For Scale orders: Defines the size of the first. For Scale orders: Defines the order size of the subsequent scale order components. Set to • • 1 = Average of National Best Bid or Ask. If set to true. If selected. order component. This is very helpful in keeping the limit price sent to the exchange up to date as the underlying price changes. or initial. Used in conjunction with scaleInitLevelSize(). API Reference Guide 195 . For Scale orders: Defines the price increment between scale components. Used for dynamic management of volatility orders.ActiveX ActiveX COM Objects Property continuousUpdate() As Integer Description Used for dynamic management of volatility orders. or set to 2 = National Best Bid when buying a call or selling a put.

ActiveX ActiveX COM Objects IOrderState Property status() As String initMargin() As String maintMargin() As String equityWithLoan() As String commission() As Double minCommission() As Double Description Displays the order status. maxCommission() As Double commissionCurrency() As String warningText() As String API Reference Guide 196 . Shows the impact the order would have on your initial margin. Used in conjunction with the minCommission field. this defines the highest end of the possible range into which the actual order commission will fall. Displays a warning message if warranted. Shows the currency of the commission value. Shows the commission amount on the order. Shows the impact the order would have on your equity with loan value. Used in conjunction with the maxCommission field. Shows the impact the order would have on your maintenance margin. this defines the lowest end of the possible range into which the actual order commission will fall.

Can be left blank. Can be left blank. averageOptionVolumeAbove () As Integer API Reference Guide 197 . Can leave empty. For example. Can be left blank. Filter out contracts with a volume lower than this value.ActiveX ActiveX COM Objects IScannerSubscription Property numberOfRows() As Integer instrument() As String locations() As String scanCode() As String priceAbove() As Double priceBelow() As Double volumeAbove() As Integer marketCapAbove() As Double marketCapBelow() As Double moodyRatingAbove() As String moodyRatingBelow() As String spRatingAbove() As String spRatingBelow() As String maturityDateAbove() As String maturityDateBelow() As String couponRateAbove() As String couponRateBelow() As String excludeConvertible() As Integer scannerSettingPairs() As String Description Defines the number of rows of data to return for a query. Filter out contracts with a maturity date earlier than this value. Can be left blank. Filter out contracts with a market cap above this value. a pairing "Annual. Filter out contracts with a Moody rating above this value. Filter out contracts with a coupon rate higher than this value. Filter out contracts with a Moody rating below this value. Can be left blank. Filter out contracts with a market cap lower than this value. Defines the instrument type for the scan. Can be left blank. Can leave empty. Can be left blank. Filter out contracts with a maturity date later than this value. Can be left blank. true" used on the "top Option Implied Vol % Gainers" scan would return annualized volatilities. Can be left blank. Filter out contracts with a price lower than this value. Filter out convertible bonds. Filter out contracts with a price higher than this value. Can be left blank. Can be left blank. Filter out contracts with a coupon rate lower than this value. Can be left blank. Can be left blank. Can be left blank. The location. Filter out contracts with an S&P rating below this value. Filter out contracts with an S&P rating above this value. Can be left blank.

see IBAlgo Parameters. For more information. Used for Delta-Neutral Combo contracts. The underlying stock or future delta. A tag-value pair (IBAlgo parameter). The price of the underlying. The value of the IBAlgo parameter. API Reference Guide 198 . For more information. ITagValue Property tag() As String value() As String Description An IBAlgo order parameter. IUnderComp Property conId() As Integer delta() As Double price() As Double Description The unique contract identifier specifying the security.ActiveX ActiveX COM Objects Property stockTypeFilter() As String Description Values are: • • • ALL (excludes nothing) STOCK (excludes ETFs) ETF (includes ETFs) ITagValueList Property Count() As Integer Item(Integer) As Object Description The number of tag-value pairs (IBAlgo parameters). Used for Delta-Neutral Combo contracts. see IBAlgo Parameters. Used for Delta-Neutral Combo contracts.

Please update your software to use the properties in the ActiveX IOrder COM object (except where otherwise noted) instead of these deprecated properties. Valid values are O. The publicly disclosed order size. If set to false. C. GTC. the order will be created but will not be sent. Identifies the account. except string TwsConnectionTime and long serverVersion) and will soon be removed. Note: All of these properties have been deprecated as of API release 9. Customer-defined order identification field. String tif boolean transmit The time in force.ActiveX ActiveX Properties ActiveX Properties The table below defines properties you can use when connecting to a server using ActiveX. Identifies an OCA (one cancels all) group. Valid values are: • • String openClose long parentId boolean blockOrder boolean sweepToFill long displaySize 0 = customer 1 = firm String oca String account String orderRef long origin Specifies whether the order is an open or close. Valid values are: DAY. For institutional customers only. Enter a reference string to help identify orders. Identifies the order origin. The order ID of the parent order. Description Connection time.4 (December 2007). specifies that the order is a Sweep-to-Fill order. Server Version. For institutional customers only. used for bracket and auto trailing stop orders. For institutional customers only. API Reference Guide 199 . Property String TwsConnectionTime long serverVersion The following properties have been deprecated. If set to true. IOC. used when placing Iceberg orders. If set to true. specifies that the order is an ISE Block order. GTD Specifies whether the order will be transmitted by the server. They have all been replaced by properties in the IOrder COM object except where otherwise noted.

Note: This property has been deprecated. Filter the results of the reqExecutions() method based on the order symbol. Filter the results of the reqExecutions() method based on the clientId. Filter the results of the reqExecutions() method based on execution reports received after the specified time.use "double bid/ask" method. allows triggering of orders outside of regular trading hours. This is only relevant for FA managed accounts."last" method. Filter the results of the reqExecutions() method based on the order exchange. Refer to the ActiveX methods section for the list of valid security types. Use the corresponding property in IExecutionFilter. If set to true. Note: This property has been deprecated. Filter the results of the reqExecutions() method based on an account code. Stop-Limit and Trailing Stop orders are triggered. Valid values are: • O .The default value. where stop orders are triggered based on two consecutive bid or ask prices.ActiveX ActiveX Properties Property long triggerMethod Description Specifies how Simulated Stop. • • boolean ignoreRth boolean hidden If set to true. this option only works with orders routed to the ISLAND exchange. Use the corresponding property in IExecutionFilter. Use the corresponding property in IExecutionFilter. The "double bid/ask" method will be used for orders for OTC stocks and US options. Note: This property has been deprecated. Note: This property has been deprecated. Note: This property has been deprecated. the order will not be visible when viewing the market depth. Filter the results of the reqExecutions() method based on the order security type. All other orders will used the "last" method. Use the corresponding property in IExecutionFilter. 2 . where stop orders are triggered based on the last price. long clientIdFilter String acctCodeFilter String timeFilter String symbolFilter String secTypeFilter String exchangeFilter API Reference Guide 200 . 1 . Note: This property has been deprecated. Use the corresponding property in IExecutionFilter. Use the corresponding property in IExecutionFilter.

String designatedLocation String goodAfterTime Only valid when shortSaleSlot value = 2. • • long minQty 0 = no 1 = yes String goodTillDate long ocaType boolean rthOnly String rule80A String settlingFirm boolean allOrNone Identifies a minimum quantity order type.clearing broker double discretionaryAmt long shortSaleSlot 2 . AgentOtherMember = 'W' IndividualPTIA = 'J' AgencyPTIA = 'U' AgentOtherMemberPTIA = 'M' IndividualPT = 'K' AgencyPT = 'Y' AgentOtherMemberPT = 'N' Institutional only." format "YYYYMMDD hh:mm:ss (optional time zone)" Use an empty String if not applicable. The trade's "Good After Time. You must enter a tif value of GTD.inapplicable (i. API Reference Guide 201 . you must enter a designated location. If this value is used. 0 = no 1 = yes. Individual = 'I' Agency = 'A'. For institutional customers only. Set an order's discretionary amount. Cancel on Fill with Block = 1 Reduce on Fill with Block = 2 Reduce on Fill without Block = 3 Regular trading hours only. The trade's "Good Till Date. Use the corresponding property in IExecutionFilter.third party. Otherwise leave blank or orders will be rejected. Note: This property has been deprecated.ActiveX ActiveX Properties Property String sideFilter Description Filter the results of the reqExecutions() method based on the order action. Note: This property has been deprecated. retail customer or not short leg) 1 . • • • 0 . Use the corresponding property in IExecutionFilter. Use the corresponding property in IComboLeg." format "YYYYMMDD hh:mm:ss (optional time zone)" Use an empty String if not applicable. Refer to the ActiveX methods sections for the list of valid order actions.e. This property has been deprecated.

202 int deltaNeutralAuxPrice API Reference Guide . For BOX orders only. as calculated by TWS' Option Analytics. For BOX orders only. Valid values are: • • match = 1 improvement = 2 • transparent = 3 For orders on BOX only. allows you to override TWS order price percentage constraints set to reject orders that deviate too far from the NBBO. For price improvement option orders on BOX and VOL orders with dynamic management. • • 0 = no 1 = yes 0 = no 1 = yes boolean firmquoteOnly Trade with firm quotes. If set. Enter an order type to instruct TWS to submit a delta neutral trade on full or partial execution of the VOL order. For price improvement option orders on BOX and VOL orders with dynamic management. Trade with electronic quotes. The option price in volatility. • • double nbboPriceCap long auctionStrategy Maximum Smart order distance from the NBBO. and for price range monitoring. VOL orders only. The lower value for the acceptable underlying stock price range. The upper value for the acceptable underlying stock price range. For no hedge delta order to be sent. Use this field to enter a value if the value in the deltaNeutralOrderType field is an order type that requires an Aux price. The stock delta. specify NONE. Select: • • string deltaNeutralOrderType 1 = Daily volatility 2 = Annual volatility double delta double stockRangeLower double stockRangeUpper bool overridePercentageConstrai nts double volatility long volatilityType VOL orders only. Used for VOL orders to compute the limit price sent to an exchange (whether or not Continuous Update is used). This was created to avoid transmitting orders with an incorrect price. Also used for price improvement option orders. double startingPrice double stockRefPrice Starting price. such as a REL order.ActiveX ActiveX Properties Property double percentOffset boolean eTradeOnly Description The percent offset for relative orders. This value is expressed as a percent and is used to calculate the limit price sent to the exchange.

VOL orders only. thereby backing into the number of units within each component.ActiveX ActiveX Properties Property bool continuousUpdate Description VOL orders only. and for stock range price monitoring. For EFP orders. Valid values include: • • 1 = Average of NBBO 2 = NBB or the NBO depending on the action and right. long referencePriceType int scaleNumComponents For Scale orders: Defines the number of component orders into which the parent order will be split. int scaleComponentSize double scalePriceIncrement double basisPoints int basisPointsType API Reference Guide 203 . For Scale orders: Defines the price increment per scale component. For EFP orders. For Scale orders: Defines the number of units per component. Specifies whether TWS will automatically update the limit price of the order as the underlying price moves. Specifies how you want TWS to calculate the limit price for options. backing into the number of components into which the parent order is split.

conversions and straddles using the BAG security type (defined in the Contract object).IContract con1 = Tws1.IContract con2 = Tws1.secType = "OPT" con1. To buy one calendar spread means: Leg 1: Sell 1 GOOG OPT SEP 18 '09 150. then it will be easier to place the same order using the API.multiplier = "100" con1. 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.strike = 150. Submit combo orders such as calendar spreads.0 CALL (100) Leg 2: Buy 1 GOOG OPT JAN 21 '11 150. Include each leg on the IComboLeg COM object by populating the related fields.createContract con1.expiry = "200909" con1.currency = "USD" Tws1.exchange = "SMART" con1. The key to implementing a successful API combination order using the API is to knowing how to place the same order using Trader Workstation. con1) 'Second Leg Dim con2 As TWSLib.symbol = "GOOG" con2. Example In this example.createContract con2.0 CALL (100) Here is a summary of the steps required to place a combo order using the API: • Obtain the contract id (conId) for each leg. because the API only imitates the behavior of TWS.secType = "OPT" API Reference Guide 204 .right = "C" con1.reqContractDetailsEx(1. a customer places a BUY order on a calendar spread for GOOG. Get this number by invoking the reqContractDetailsEx() method.symbol = "GOOG" con1.ActiveX Placing a Combination Order 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 transaction. If you are familiar with placing combination orders in TWS.0 con1.

reqContractDetailsEx(2. include it in the ComboLeg object: TWSLib.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.right = "C" con2._DTwsEvents_contractDetailsExEvent) Handles Tws1.openClose = 0 Leg1.exchange = "SMART" Leg1.strike = 150.expiry = "201101" con2.contractDetails Dim contract As TWSLib.conId 'to obtain conId for the first leg End If If e.IComboLeg Leg1 = addAllLegs.0 con2.IComboLegList addAllLegs = Tws1.ratio = 1 Leg1.reqId = 2 Then leg2 = contract.shortSaleSlot = 0 Leg1. ByVal e As AxTWSLib.IContractDetails contractDetails = e.action = "SELL" Leg1.multiplier = "100" con2.conId 'to obtain conId for the second leg End If End Sub 2 Once the program has acquired the conId value for each leg.contractDetailsEx Dim contractDetails As TWSLib.conId = leg1_conId Leg1.Add() Leg1.IComboLeg API Reference Guide 205 . con2) 'All conId numbers are delivered by the ContractDetail() Private Sub Tws1_contractDetailsEx(ByVal sender As Object.createComboLegList 'First Combo leg Dim Leg1 As TWSLib.designatedLocation = "" ' Second Combo leg Dim Leg2 As TWSLib.IContract contract = contractDetails.exchange = "SMART" con2.ActiveX Placing a Combination Order con2.currency = "USD" Tws1.

contract.createContract contract.action = "BUY" order.totalQuantity = 1 order. order) Note: For more information on combination orders.shortSaleSlot = 0 Leg1.symbol = "USD" contract.openClose = 0 Leg1.action = "BUY" Leg1.IOrder order = Tws1.conId = leg2_conId Leg1.ActiveX Placing a Combination Order Leg2 = addAllLegs.IContract contract = Tws1.createOrder order.placeOrderEx(OrderId.Add() Leg1.exchange = "SMART" Leg1.comboLegs = addAllLegs Dim order As TWSLib.designatedLocation = "" 3 Invoke the placeOrder() method with the appropriate contract and order objects: Dim contract As TWSLib.orderType = "MKT" Tws1. API Reference Guide 206 . see the TWS Users Guide topics About Combination Orders and Notes on Combination Orders.secType = "BAG" contract.exchange = "SMART" contract.ratio = 1 Leg1.currency = "USD" contract.

including the following topics: • • • • • • 4 Linking to TWS using the TwsSocketClient.C++ This chapter describes the C++ API.dll Using the C++ TestSocketClient Sample Program Class EClientSocket Functions Class EWrapper Functions SocketClient Properties Placing a Combination Order API Reference Guide 207 .

dll To link to TWS using the TwsSocketClient.C++ Linking to TWS using the TwsSocketClient.dll Linking to TWS using the TwsSocketClient.dll 1 2 Create a Windows application using MS Visual Studio (version 5. Receives execution report information. Description Handles market data. Override the following functions: Ewrapper Function tickPrice() tickSize() tickOptionComputation() tickGeneric() tickString() tickEFP() orderStatus() openOrder() error() connectionClosed() updateAccountValue() updateAccountTime() updatePortfolio() nextValidId() contractDetails() contractDetailsEnd() bondContractDetails() exectDetails() updateMktDepth() Receives order status. Receives market depth information. Add the full path to the \SocketClient\include directory in your API installation folder to your project's include path. Receives contract information. 3 4 5 6 API Reference Guide 208 .lib file in your API installation directory to your project's libraries path. Subclass the EWrapper class. Receives the next valid order ID upon connection. This should be done for any individual project that accesses the TwsSocketClient library. Receives the last time account information was updated.h and EClientSocket. Notifies when TWS terminates the connection. Receives current account values. This should be done for any individual project that accesses the TwsSocketClient library's header files. Include EWrapper.h in any Visual C++ source code that accesses their functionality and data structures.0 or higher). Add the full path to the \SocketClient\lib\TwsSocketclient. Receives current portfolio information. Receives bond contract information. Receives open orders. Identifies the end of a given contract details request. Receives error information.

Receives IB news bulletins. Receives an XML document that describes the valid parameters of a scanner subscription.C++ Linking to TWS using the TwsSocketClient.dll Ewrapper Function updateMktDepthL2() updateNewsBulletin() managedAccounts() receiveFA() historicalData() scannerParameters() Description Receives Level II market depth information. Receives Reuters global fundamental market data. Receives historical data results. This class will receive messages from the socket. Receives the current system time on the server.client. Receives real-time bars.* into your source code file.ib. Receives market scanner results. Call the following functions: a b Import com. API Reference Guide 209 . scannerData() realTimeBar() currentTime() fundamentalData() 7 8 Instantiate the EClientSocket class. Receives FA configuration information. Receives a list of Financial Advisor (FA) managed accounts. Implement the EWrapper interface.

Receives historical data results. Identifies the end of a given contract details request. Receives Level II market depth information. Receives current account values. 210 Description Handles market data. Receives FA configuration information. Receives the last time account information was updated. Receives bond contract information. Receives the next valid order ID upon connection. Receives contract information. Receives market depth information. Receives a list of Financial Advisor (FA) managed accounts. Receives real-time bars. Receives IB news bulletins.dll c Override the following functions: Ewrapper Functions tickPrice() tickSize() tickOptionComputation() tickGeneric() tickString() tickEFP() orderStatus() openOrder() error() connectionClosed() updateAccountValue() updateAccountTime() updatePortfolio() nextValidId() contractDetails() contractDetailsEnd() bondContractDetails() exectDetails() updateMktDepth() updateMktDepthL2() updateNewsBulletin() managedAccounts() receiveFA() historicalData() scannerParameters() Receives order status. Receives the current system time on the server. Receives open orders. Receives execution report information. Receives Reuters global fundamental market data. Receives current portfolio information. Receives error information.C++ Linking to TWS using the TwsSocketClient. Receives market scanner results. Notifies when TWS terminates the connection. scannerData() realTimeBar() currentTime() fundamentalData() API Reference Guide . Receives an XML document that describes the valid parameters of a scanner subscription.

Requests contract details. Cancels market depth. Requests FA configuration information from TWS. Requests a list of all open orders. Requests account values. This object will be used to send messages to TWS. The association only occurs if the requesting client has a Client ID of 0. Cancels a scanner subscription. portfolio. Cancels market data. Places an order.dll d e Instantiate the EClientSocket class. Requests a list of the day’s execution reports. Cancels IB news bulletins. Automatically associates a new TWS with the client. Requests an XML document that describes the valid parameters of a scanner subscription. Disconnects from TWS. Call the following functions: EClientSocket Functions eConnect() eDisconnect() reqMktData() cancelMktData() reqMktDepth() cancelMktDepth() reqContractDetails() placeOrder() cancelOrder() reqAccountUpdates() reqExecutions() reqOpenOrders() Description Connects to TWS. Modifies FA configuration information from the API. Requests market data. Requests IB news bulletins. Requests a list of current open orders for the requesting client and associates TWS open orders with the client. The association only occurs if the requesting client has a Client ID of 0. Requests a list of Financial Advisor (FA) managed account codes. reqAllOpenOrders() reqAutoOpenOrders() reqNewsBulletin() cancelNewsBulletins() setServerLogLevel() reqManagedAccts() requestFA() replaceFA() reqScannerParameters() reqScannerSubscription() cancelScannerSubscription() API Reference Guide 211 . Sets the level of API request and processing logging. Requests market scanner results. Cancels an order.C++ Linking to TWS using the TwsSocketClient. Requests market depth. and account update time information.

Cancels real-time bars.dll EClientSocket Functions reqHistoricalData() cancelHistoricalData() reqRealTimeBars() cancelRealTimeBars() exerciseOptions() reqCurrentTime() serverVersion() Description Requests historical data. Exercises options. Cancels Reuters global fundamental data. the TwsSocketClient. Returns the version of the TWS instance to which the API application is connected.C++ Linking to TWS using the TwsSocketClient. or in your path. Requests the current server time. TwsConnectionTime() reqFundamentalData() cancelFundamentalData() To run the program. There must be a subscription to Reuters Fundamental set up in Account Management before you can receive this data.dll file installs into your C:\Windows\system or C:\WINNT\system32 directory. Requests Reuters global fundamental data. API Reference Guide 212 . ensure that the TwsSocketClient. Returns the time the API application made a connection to TWS.dll is in the same directory as your executable. Requests real-time bars. Cancels historical data. By default.

(For example.0 or higher) installed on your PC. type SampleSocketClient. Select Visual C++ as the project type.exe. Run the file named client2. C:\SampleSocketClient. • The TestSocketClient program is a sample program that shows you how to use sockets to connect to TWS from a Microsoft Windows-based C++ application.C++ Using the C++ TestSocketClient Sample Program Using the C++ TestSocketClient Sample Program You can access the IB trading system via TWS or the IB Gateway through a Microsoft Windows-based C++ application using the TWSSocketClient.exe): 1 2 3 4 5 6 Download and install the latest version of the API software. In the Create New Project from Existing Code Files dialog: a b c For the Project File location. Before you can connect to TWS using the SocketClient component. Shared and SocketClient into the folder you created in Step 2. (For example. To run this sample application. API Reference Guide 213 . select New > Project From Existing Code from the File menu. To run the TestSocketClient program from Microsoft Visual Studio 2008 To create the project file and compile the TestSocketClient application (client2. Click Finish. select the folder you created in Step 2. configure it to support the API components Have Microsoft Visual Studio (Visual C++ 5. go to your TWS API installation folder. For example. C:\SampleSocketClient.) In Visual Studio. Create the folder where all project related files will be located. C:\SampleSocketClient.) For the Project Name. then open the \TestSocketClient\Release folder. Copy the folders TestSocketClient.dll component. To run the pre-built sample application We’ve included a complete C++ client with our API software. you must: • • Install the socket client component and sample programs If you are using TWS.

/Shared. Build the project./SocketClient/src b On left side of the dialog. select Configuration Parameters > C/C++ > Code Generation. In the Property Pages dialog: a On left side of the dialog. In the Runtime Library field on the right side of the dialog. In the Additional Include Directories field on the right side of the dialog.C++ Using the C++ TestSocketClient Sample Program 7 Right-click the project in the Solution Explorer and select Properties.. 8 9 Click OK to save your changes to the project properties. type: . select Configuration Parameters > C/C++ > General. select Multi-threaded (/MT). API Reference Guide 214 .

EClientSocket( EWrapper *ptr) Parameter ptr Description The pointer to an object that was derived from the EWrapper base class.C++ Class EClientSocket Functions Class EClientSocket Functions The list below define the class EClientSocket functions you can use when connecting to TWS. 215 API Reference Guide . 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() Orders placeOrder() cancelOrder() reqOpenOrders() reqAllOpenOrders() reqAutoOpenOrders() reqIDs() exerciseOptions() Account reqAccountUpdates() Executions reqExecutions() Contract Details reqContractDetails() Market Depth reqMktDepth() cancelMktDepth() News Bulletins reqNewsBulletins() cancelNewsBulletins() Financial Advisors reqManagedAccts() requestFA() replaceFA() Historical Data reqHistoricalData() cancelHistoricalData() Market Scanners reqScannerParameters() reqScannerSubscription() cancelScannerSubscription() Real Time Bars reqRealTimeBars() cancelRealTimeBars() Fundamental Data reqFundamentalData() cancelFundamentalData() EClientSocket() This is the constructor.

isConnected() Call this function to check if there is a connection with TWS void isConnected() API Reference Guide 216 . Calling this function does not cancel orders that have already been sent. Leave blank to connect to the local host. eDisconnect() Call this function to terminate the connections with TWS. A number used to identify this client connection. There is no feedback for a successful connection. Note: Each client MUST connect with a unique clientId. UINT port. but a subsequent attempt to connect will return the message "Already connected." bool eConnect( const char *host. void eDisconnect() Parameter ptr Description The pointer to an object that was derived from the EWrapper base class. Must match the port specified in TWS on the Configure>API>Socket Port field. int clientId=0) Parameter host port clientId Description The host name or IP address of the machine where TWS is running.C++ Class EClientSocket Functions eConnect() This function must be called before any other. All orders placed/modified from this client will be associated with this client identifier.

const Contract &contract. Tick types can be found in the Generic Tick Types page. The market data will be returned by the tickPrice and tickSize events. Must be a unique value. CString genericTicklist. contract genericTicklist snapshot cancelMktData() After calling this function. API Reference Guide 217 . calculateImpliedVolatility() Call this function to calculate volatility for a supplied option price and underlying price. The price of the option. Contract &contract. A comma delimited list of generic tick types. double optionPrice. Check to return a single snapshot of market data and have the market data subscription cancel. void calculateImpliedVolatility(TickerID reqId. market data for the specified id will stop flowing. Price of the underlying. This structure contains a description of the contract for which market data is being requested. bool snapshot) Parameter id Description The ticker id. This is also used when canceling the market data.C++ Class EClientSocket Functions reqMktData() Call this function to request market data. void cancelMktData(TickerID id) Parameter id Description The ID that was specified in the call to reqMktData(). double underPrice) Parameter reqId contract optionPrice underPrice Description The ticker id. Do not enter any genericTicklist values if you use snapshot. When the market data returns. void reqMktData(TickerID id. Describes the contract. it will be identified by this tag.

The order status will be returned by the orderStatus event. cancelCalculateOptionPrice(TickerId reqId) Parameter reqId Description The ticker id. const Contract &contract. You must specify a unique value. Describes the contract. calculateOptionPrice() Call this function to calculate option price and greek values for a supplied volatility and underlying price. double underPrice) Parameter reqId contract volatility underPrice Description The ticker ID. When the order status returns. cancelCalculateOptionPrice() Call this function to cancel a request to calculate the option price and greek values for a supplied volatility and underlying price. calculateImpliedVolatility(TickerId reqId) Parameter reqId Description The ticker id. contract order Call this function to place an order. Price of the underlying. void calculateOptionPrice(TickerId reqId. This structure contains the details of the order.C++ Class EClientSocket Functions cancelCalculateImpliedVolatility() Call this function to cancel a request to calculate volatility for a supplied option price and underlying price. it will be identified by this tag. This tag is also used when canceling the order. This structure contains a description of the contract which is being traded. double volatility. Note: Each client MUST connect with a unique clientId. API Reference Guide 218 . placeOrder() Parameter id Description The order id. The volatility.

Note: Each client MUST connect with a unique clientId. contract order cancelOrder() Call this function to cancel an order. This structure contains a description of the contract which is being traded. it will be identified by this tag. Each open order will be fed back through the openOrder() and orderStatus() functions on the EWrapper. const Order &order) Parameter id Description The order id. This tag is also used when canceling the order. and last update time information. acctCode API Reference Guide 219 . The account code for which to receive account and portfolio updates. void checkMessages() reqOpenOrders() Call this function to request the open orders that were placed from this client. If set to FALSE. These orders will be associated with the client and a new orderId will be generated.C++ Class EClientSocket Functions void placeOrder( OrderID id. void reqOpenOrders() reqAccountUpdates() Call this function to start getting account values. When the order status returns. the client will start receiving account and portfolio updates. void reqAccountUpdates(bool subscribe. const CString& acctCode) Parameter subscribe Description If set to TRUE. You must specify a unique value. portfolio. This structure contains the details of the order. This association will persist over multiple API and TWS sessions. Note: The client with a clientId of 0 will also receive the TWS-owned open orders. const Contract &contract. void cancelOrder(OrderID id) Parameter id Description The order ID that was specified previously in the call to placeOrder() checkMessages() This function should be called frequently (every 1 second) to check for messages received from TWS. the client will stop receiving this information.

it will be identified by this tag. contract numRows API Reference Guide 220 . The market depth will be returned by the updateMktDepth() and updateMktDepthL2() events. This object contains attributes that describe the filter criteria used to determine which execution reports are returned. When the market depth data returns. reqIDs() Call this function to request from TWS the next valid ID that can be used when placing an order. reqMktDepth() Call this function to request market depth for a specific contract. and the id returned is that next valid ID. long numRows) Parameter id Description The ticker id.specified the number of market depth rows to display. void reqMktDepth (TickerID id. void reqIds(int numIds) Parameter numIds Description The number of ids you want to reserve. The summary description of the contract being looked up. This is also used when canceling the market depth This structure contains a description of the contract for which market depth data is being requested. const ExecutionFilter& filter) Parameter reqId filter Description The ID of the data request. void reqExecutions(int reqID. the nextValidId() event will be triggered. reqContractDetails() Call this function to download all details for a particular underlying. Ensures that responses are matched to requests if several requests are in process. const Contract &contract. the execution reports that meet the filter criteria are downloaded to the client via the execDetails() function. Ensures that responses are matched to requests if several requests are in process.C++ Class EClientSocket Functions reqExecutions() When this function is called. . After calling this function. void reqContractDetails (const Contract &contract) Parameter reqId Contract Description The ID of the data request. That ID will reflect any autobinding that has occurred (which generates new IDs and increments the next valid ID therein). The contract details will be received via the contractDetails() function on the EWrapper. Must be a unique value.

void reqAllOpenOrders() API Reference Guide 221 . Note: No association is made between the returned orders and the requesting client. will only return new bulletins. Each bulletin will be returned by the updatedNewsBulletin() event. void reqNewsBulletins(bool allMsgs) Parameter allMsgs Description If set to TRUE. If set to FALSE. returns all the existing bulletins for the current day and any new ones. void cancelMktDepth (TickerID id) Parameter id Description The ID that was specified in the call to reqMktDepth(). market depth data for the specified id will stop flowing. see “API Logging” on page -19. Valid values include: • • • • • 1 = SYSTEM 2 = ERROR 3 = WARNING 4 = INFORMATION 5 = DETAIL reqAllOpenOrders() Call this function to request the open orders placed from all clients and also from TWS. For more details. reqNewsBulletins() Call this function to start receiving news bulletins.C++ Class EClientSocket Functions cancelMktDepth() After calling this function. Each open order will be fed back through the openOrder() and orderStatus() functions on the EWrapper. cancelNewsBulletins() Call this function to stop receiving news bulletins. void setLogLevel(int logLevel) Parameter logLevel Description Specifies the level of log entry detail used by the server (TWS) when processing API requests. void cancelNewsBulletins() setLogLevel() The default detail level is ERROR.

C++ Class EClientSocket Functions reqAutoOpenOrders() Call this function to request that newly created TWS orders be implicitly associated with the client. Note: This request can only be made when connected to a FA managed account. the order will be associated with the client. The data returns in an XML string via a "receiveFA" ActiveX event. When a new TWS order is created. Note: This request can only be made from a client with clientId of 0. and fed back through the openOrder() and orderStatus() functions on the EWrapper. requestFA(long faDataType) Parameter faDataType Description Specifies the type of Financial Advisor configuration data being requested. The list will be returned by the managedAccounts() function on the EWrapper. If set to FALSE. reqAutoOpenOrders (bool bAutoBind) Parameter bAutoBind Description If set to TRUE. void reqManagedAccts() requestFA() Call this function to request FA configuration information from TWS. Valid values include: • • • 1 = GROUPS 2 = PROFILE 3 = ACCOUNT ALIASES API Reference Guide 222 . no association will be made. newly created TWS orders will be implicitly associated with the client. reqManagedAccts() Call this function to request the list of managed accounts.

String durationStr. This is also used when canceling the market data. seconds is used. replaceFA(long faDataType.C++ Class EClientSocket Functions replaceFA() Call this function to modify FA configuration information from the API. using a time unit of seconds. Valid values include any integer followed by a space and then S (seconds). When the market data returns. This object contains a description of the contract for which market data is being requested. Must be a unique value. Set the query duration up to one week. it will be identified by this tag. Valid values include: • • • XML 1 = GROUPS 2 = PROFILE 3 =ACCOUNT ALIASES The XML string containing the new FA configuration information. reqHistoricalData() void reqHistoricalData (TickerID id. int formatDate) Parameter id Description The id of the request. days or weeks. 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. string XML) Parameter faDataType Description Specifies the type of Financial Advisor configuration data being modified via the API. String endDateTime. Note that this can also be done manually in TWS itself. contract endDateTime durationStr API Reference Guide 223 . Defines a query end date and time at any point during the past 6 mos. D (days) or W (week). const Contract &contract. int useRTH. long barSizeSetting String whatToShow. If no unit is specified.

1 . even if the requested time span falls partially or completely outside of the RTH. Valid values include: • • 0 . Valid values include: • • • • • • • • TRADES MIDPOINT BID ASK BID_ASK HISTORICAL_VOLATILITY OPTION_IMPLIED_VOLATILITY OPTION_VOLUME whatToShow useRTH Determines whether to return all data available during the requested time span.all data is returned even where the market in question was outside of its regular trading hours.only data within the regular trading hours is returned. or only data that falls within regular trading hours. API Reference Guide 224 . Valid values include: Bar Size 1 sec 5 secs 15 secs 30 secs 1 min 2 mins 3 mins 5 mins 15 mins 30 mins 1 hour 1 day 1 week 1 month 3 months 1 year Determines the nature of data being extracted.C++ Class EClientSocket Functions Parameter barSizeSetting Description Specifies the size of the bars that will be returned (within IB/TWS limits).

This structure contains possible parameters used to filter results. Specifies whether your setting will override the system's natural action.dates applying to bars returned in the format: yyyymmdd{space}{space}hh:mm:dd 2 . Must be a unique value. Values are: 0 = no. if your action is "exercise" and the option is not in-the-money. exerciseOptions() void exerciseOptions(long id. 2 = lapse. by natural action the option would not exercise.dates are returned as a long integer specifying the number of seconds since 1/1/1970 GMT. If you have override set to "yes" the natural action would be overridden and the out-of-the money option would be exercised. see Historical Data Limitations. int override) Parameter id contract exerciseAction exerciseQuantity override Description The ticker id. Valid values include: • • 1 . 1 = yes. Values are 1 = exercise. Note: For a information about historical data request limitations. reqScannerParameters() Requests an XML string that describes all possible scanner queries. The quantity you want to exercise. int exerciseQuantity. const CString &account. API Reference Guide 225 . This structure contains a description of the contract for which market depth data is being requested. const ScannerSubscription&subscription) Parameter tickerId ScannerSubscription Description The ticker ID. For example. Must be a unique value. const Contract &contract.C++ Class EClientSocket Functions Parameter formatDate Description Determines the date format applied to returned bars. int exerciseAction. Specifies whether you want the option to lapse or be exercised. void reqScannerParameters() reqScannerSubscription() void reqScannerSubscription(int tickerId.

Must be a unique value. This object contains a description of the contract for which real time bars are being requested Currently only 5 second bars are supported. even if the time time span falls partially or completely outside. reqRealTimeBars() Call the reqRealTimeBars() function to start receiving real time bar results through the realtimeBar() EWrapper function. including time intervals when the market in question was outside of regular trading hours. Must be a unique value. boolean useRTH) Parameter tickerId Description The Id for the request. if any other value is used. void reqRealTimeBars(int tickerId. Must be a unique value. String whatToShow. When the data is received. contract barSize whatToShow Regular Trading Hours only. an exception will be thrown. Valid values include: • • • • useRTH • TRADES BID ASK MIDPOINT 0 = all data available during the time span requested is returned. Contract contract. 1 = only data within the regular trading hours for the product requested is returned. cancelScannerSubscription() void cancelScannerSubscription(int tickerId) Parameter tickerId Description The ticker ID. Determines the nature of the data extracted. void cancelHistoricalData (int tickerId) Parameter tickerId Description The ticker ID. int barSize. Valid values include: • API Reference Guide 226 .C++ Class EClientSocket Functions 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. This is also used when canceling the request. it will be identified by this Id.

Ensures that responses are matched to requests if several requests are in process. void reqCurrentTime() serverVersion() Returns the version of the TWS instance to which the API application is connected. void reqFundamentalData(int reqId.C++ Class EClientSocket Functions cancelRealTimeBars() Call the cancelRealTimeBars() function to stop receiving real time bar results. reqCurrentTime() Returns the current system time on the server side. Identifies the report type. serverVersion() TwsConnectionTime() Returns the time the API application made a connection to TWS. String reportType) Parameter reqId contract reportType Description The ID of the data request. void cancelRealTimeBars (int tickerId) Parameter tickerId Description The Id that was specified in the call to reqRealTimeBars(). This structure contains a description of the contract for which Reuters Fundamental data is being requested. which is one of the following: • • • Estimates Financial Statements Summary API Reference Guide 227 . There must be a subscription to Reuters Fundamental set up in Account Management before you can receive this data. const Contract &contract. TwsConnectionTime() reqFundamentalData() Call this function to receive Reuters global fundamental data.

void cancelFundamentalData(int reqId) Parameter reqId Description The ID of the data request. API Reference Guide 228 .C++ Class EClientSocket Functions cancelFundamentalData() Call this function to stop receiving Reuters global fundamental data.

C++ Class EWrapper Functions

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() Orders orderStatus() openOrder() nextValidId() Account and Portfolio updateAccountValue() updatePortfolio() updateAccountTime() News Bulletins updateNewsBulletin() Contract Details contractDetails() contractDetailsEnd() bondContractDetails() Executions execDetails() execDetailsEnd() Market Depth updateMktDepth() updateMktDepthL2() Financial Advisors managedAccounts() receiveFA() Historical Data historicalData() Market Scanners scannerParameters() scannerData() scannerDataEnd() Real Time Bars realtimeBar() Fundamental Data fundamentalData()

API Reference Guide

229

C++ Class EWrapper Functions

tickPrice()
This function is called when the market data changes. Prices are updated immediately with no delay. virtual void tickPrice(TickerID id, TickType field, double price, int canAutoExecute) Parameter id tickType Description The ticker ID that was specified previously in the call to reqMktData() Specifies the type of price. Possible values are: • • • • • • price canAutoExecute 1 = bid 2 = ask 4 = last 6 = high 7 = low 9 = close

- could be the bid, ask, last price, daily high, daily low or last day close, depending on tickType value. Specifies whether the price tick is available for automatic execution. Possible values are: • • 0 = not eligible for automatic execution 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 id, TickType field, int size) Parameter id tickType Description The ticker ID that was specified previously in the call to reqMktData() Specifies the type of size. Possible values are: • • • • size 0 = bid size 3 = ask size 5 = last size 8 = volume

Could be the bid size, ask size, last size or trading volume, depending on the tickType value.

API Reference Guide

230

C++ Class EWrapper Functions

tickOptionComputation()
This function is called when the market in an option or its underlier moves. TWS’s option model volatilities, prices, and deltas, along with the present value of dividends expected on that options underlier are received. virtual void tickOptionComputation(TickerID tickerId, TickType tickType, double impliedVol, double delta, double modelPrice, double pvDividend, double gamma, double vega, double theta, double undPrice) Parameter id tickType Description The ticker ID that was specified previously in the call to reqMktData() Specifies the type of tick. Possible values are: • • • impliedVol delta optPrice pvDividend gamma vega theta undPrice 10 = Bid 11 = Ask 12 = Last

The implied volatility calculated by the TWS option modeler, using the specified ticktype value. The option delta value. The option price. The present value of dividends expected on the options underlying instrument. The option gamma value. The option vega value. The option theta value. 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 tickerId tickType Description The ticker Id that was specified previously in the call to reqMktData(). 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. The value of the specified field.

value

API Reference Guide

231

C++ Class EWrapper Functions

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 CString& value) Parameter tickerId field Description The ticker Id that was specified previously in the call to reqMktData(). 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 lastTimestamp, etc. The value of the specified field.

value

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 CString& formattedBasisPoints, double totalDividends, int holdDays, const CString& futureExpiry, double dividendImpact, double dividendsToExpiry) Parameter tickerId field Description The ticker Id that was specified previously in the call to reqMktData() 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. Annualized basis points, which is representative of the financing rate that can be directly compared to broker rates. Annualized basis points as a formatted string that depicts them in percentage form. Implied futures price. Number of hold days until the expiry of the EFP. Expiration date of the single stock future. The dividend impact upon the annualized basis points interest rate. The dividends expected until the expiration of the single stock future.

basisPoints formattedBasisPoint s impliedFuture holdDays futureExpiry dividendImpact dividendsToExpiry

API Reference Guide

232

C++ Class EWrapper Functions

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 reqID Description Id of the data request.

API Reference Guide

233

C++ Class EWrapper Functions

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 id, const CString &status, int filled, int remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId, const CString& whyHeld) Parameter id status Description The order ID that was specified previously in the call to placeOrder() The order status. Possible values include: • 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. 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 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. 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. Submitted - indicates that your order has been accepted at the order destination and is working. 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. Filled - indicates that the order has been completely filled. 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 remaining

Specifies the number of shares that have been executed. Specifies the number of shares still outstanding.

API Reference Guide

234

C++ Class EWrapper Functions

Parameter avgFillPrice

Description The average price of the shares that have been executed. This parameter is valid only if the filled parameter value is greater than zero. Otherwise, the price parameter will be zero. The TWS id used to identify orders. Remains the same over TWS sessions. The order ID of the parent order, used for bracket and auto trailing stop orders. The last price of the shares that have been executed. This parameter is valid only if the filled parameter value is greater than zero. Otherwise, the price parameter will be zero. 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. 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'.

permId parentId lastFilledPrice

clientId

whyHeld

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 CString errorString) Parameter id errorCode errorString Description This is the orderId or tickerId of the request that generated the error. Error codes are documented in the API Message Codes topic. This is the textual description of the error, also documented in the Error Codes topic.

winError()
This event is called when there is an error on the client side.

virtual void winError(const CString &str, int lastError) Parameter str lastError Description This is the error message text. The error code returned by GetLastError().

API Reference Guide

235

C++ Class EWrapper Functions

connectionClosed()
This function is called when TWS closes the sockets connection with the ActiveX control, or when TWS is shut down.

virtual void connectionClosed()

managedAccounts()
This function is called when a successful connection is made to a Financial Advisor account. It is also called when the reqManagedAccts() function is invoked.

virtual void managedAccounts(const CString& accountsList) Parameter accountsList Description The comma delimited list of FA managed accounts.

openOrder()
This function is called to feed in open orders. virtual void openOrder(OrderId orderId, const Contract &contract, const Order &order, const OrderState &orderState) For more information, see Extended Order Attributes. Parameter orderID contract order orderState Description The order ID assigned by TWS. Use to cancel or update the order. The Contract class attributes describe the contract. The Order class gives the details of the open order. The orderState class includes attributes used for both pre and post trade margin and commission data.

API Reference Guide

236

const CString& currency.A string that indicates one type of account value.Current initial margin requirement LongOptionValue . API Reference Guide 237 .Account cash balance Currency . States the account to which the message applies. const CString& accountName) Parameter key Description .Current maintenance margin NetLiquidation . virtual void updateAccountValue(const CString& key.Currency string DayTradesRemaining .C++ Class EWrapper Functions updateAccountValue() This function is called only when ReqAccountUpdates on EClientSocket object has been called.Overnight maintenance margin requirement The value associated with the key. Useful for Financial Advisor sub-account messages.Equity with Loan Value InitMarginReq . in case the value is a currency type.Short option value StockMarketValue .Option market value ShortOptionValue . • • • • • • • • • • • • • value currency account CashBalance .Net liquidation value OptionMarketValue . Defines the currency type. const CString& value.Number of day trades left EquityWithLoanValue .Stock market value UnalteredInitMarginReq . Below is a set of keys sent by TWS.Overnight initial margin requirement UnalteredMaintMarginReq .Long option value MaintMarginReq .

position marketPrice marketValue averageCost unrealizedPNL realizedPNL accountName updateAccountTime() This function is called only when reqAccountUpdates on EClientSocket object has been called. double unrealizedPNL. int position. The exchange field in a contract is not set for portfolio update. The total market value of the instrument. double averageCost. virtual void updateAccountTime(const CString& timeStamp) Parameter timeStamp Description This indicates the last update time of the account information. virtual void updatePortfolio(const Contract& contract.Average Cost.C++ Class EWrapper Functions updatePortfolio() This function is called only when reqAccountUpdates on EClientSocket object has been called. If the position is 0. API Reference Guide 238 . double marketValue. const CString& accountName) Parameter contract Description This structure contains a description of the contract which is being traded. The average cost per share is calculated by dividing your cost (execution price + commission) by the quantity of your position. This integer indicates the position on the contract. The difference between the current market value of your open positions and the average cost. or Value . it means the position has just cleared. Unit price of the instrument. Useful for Financial Advisor sub-account messages. double realizedPNL. double marketPrice. 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) States the account to which the message applies.

Ensures that responses are matched to requests if several requests are in process. This helps to define the end of an option chain.C++ Class EWrapper Functions nextValidId() This function is called after a successful connection to TWS. Increment all successive orders by one based on this ID. virtual void contractDetails(const ContractDetails &contractDetails) Parameter reqId contractDetails Description The ID of the data request. or when an order is filled. virtual void nextValidId(OrderID orderId) Parameter orderId Description The next available order ID received from TWS upon connection. void contractDetailsEnd(int reqId) Parameter reqID Description The ID of the data request. const Contract& contract. This structure contains a full description of the contract that was executed. This structure contains addition order execution details. contractDetailsEnd() This function is called once all contract details for a given request are received. API Reference Guide 239 . const Execution& execution. virtual void execDetails( OrderId orderId. execDetails() This event is fired when the reqExecutions() functions is invoked. This structure contains a full description of the contract being looked up. contractDetails() This function is called only when reqContractDetails function on the EClientSocket object has been called. long liquidation) Parameter id contract execution Description The order ID that was specified previously in the call to placeOrder().

int size) Parameter id position operation Description The ticker ID that was specified previously in the call to reqMktDepth() Specifies the row id of this market depth entry. int size) Parameter id position marketMaker Description The ticker ID that was specified previously in the call to reqMktDepth() Specifies the row id of this market depth entry. Specifies the exchange hosting this order. updateMktDepthL2() This function is called when the Level II market depth changes. virtual void execDetailsEnd(int reqId) Parameter reqID Description The Id of the data request. Identifies the how this order should be applied to the market depth. API Reference Guide 240 . int side. double price.C++ Class EWrapper Functions execDetailsEnd() This function is called once all executions have been sent to a client in response to reqExecutions(). double price. int position. virtual void updateMktDepthL2(TickerId id. Valid values are:· • • • side 0 = insert (insert this new order into the row identified by 'position')· 1 = update (update the existing order in the row identified by 'position')· 2 = delete (delete the existing order at the row identified by 'position') Identifies the side of the book that this order belongs to. updateMktDepth() This function is called when the market depth changes. Valid values are: • • 0 = ask 1 = bid price size The order price. The order size. virtual void updateMktDepth(TickerId id. int operation. int position. CString marketMaker. int side. int operation.

virtual void updateNewsBulletin(int msgId. by calling the reqNewsBulletins() function. Specifies the type of bulletin. Valid values are: • • 0 = ask 1 = bid price size The order price. The exchange from which this message originated. Valid values are:· • • • 0 = insert (insert this new order into the row identified by 'position')· 1 = update (update the existing order in the row identified by 'position')· 2 = delete (delete the existing order at the row identified by 'position') side Identifies the side of the book that this order belongs to. int msgType.e. API Reference Guide 241 .C++ Class EWrapper Functions Parameter operation Description Identifies the how this order should be applied to the market depth. const CString& message. incrementing for each new bulletin. The order size. const CString& origExchange Parameter msgId msgType Description The bulletin ID. Valid values include: • • • message origExchange 1 = Regular news bulletin 2 = Exchange no longer available for trading 3 = Exchange is available for trading The bulletin's message text. updateNewsBulletin() This event is triggered for each new bulletin if the client has subscribed (i.

Valid values include: • • • XML 1 = GROUPS 2 = PROFILE 3 =ACCOUNT ALIASES The XML string containing the previously requested FA configuration information. double open. double high. The volume during the time covered by the bar. string XML) Parameter faDataType Description Specifies the type of Financial Advisor configuration data being received from TWS. int volume. virtual void bondContractDetails(const contractDetails&contractDetails) Parameter reqId contractDetails Description The ID of the data request. The weighted average price during the time covered by the bar. const CString& date. This structure contains a description of the contract which is being traded. The high price during the time covered by the bar. bondContractDetails() This function is called only when reqContractDetails function on the EClientSocket object has been called for bonds. The format is determined by the reqHistoricalData() formatDate parameter. The date-time stamp of the start of the bar. API Reference Guide 242 . int hasGaps) Parameter reqId date open high low close volume WAP Description The ticker ID of the request to which this bar is responding. virtual receiveFA(long faDataType. The exchange field in a contract is not set for portfolio update. double WAP. virtual void historicalData(TickerId reqId.C++ Class EWrapper Functions receiveFA() This event receives previously requested FA configuration information from TWS. The bar opening price. double low. double close. The bar closing price. historicalData() This function receives the requested historical data results. The low price during the time covered by the bar.

API Reference Guide 243 . virtual void scannerParameters(String xml) Parameter xml Description An XML document that describes the valid parameters for queries. const ContractDetails &contractDetails. The ranking within the response of this bar. Reports whether or not there are gaps in the data. Varies based on query. String projection) Parameter reqId rank contractDetails distance benchmark projection legsStr Description The ticker ID of the request to which this row is responding. scannerDataEnd() This function is called when the snapshot is received and marks the end of one scan. hasGaps scannerParameters() This function receives an XML document that describes the valid parameters that a scanner subscription can have. int rank.C++ Class EWrapper Functions Parameter count Description When TRADES historical data is returned. String benchmark. scannerData() This function receives the requested market scanner data results. virtual void scannerData(int reqId. represents the number of trades that occurred during the time period the bar covers. Describes combo legs when scan is returning EFP. Varies based on query. Varies based on query. virtual void scannerDataEnd(int reqId) Parameter reqId Description The ID of the market scanner request being closed by this parameter. This object contains a full description of the contract. String distance.

One of three XML reports: • • • Estimates (estimates) Financial statements (finstat) Summary (snapshot) API Reference Guide 244 . fundamentalData() This function is called to receive Reuters global fundamental market data. int count) Parameter reqId time open high low close volume wap count Description The ticker Id of the request to which this bar is responding. currentTime() This function receives the current system time on the server side. double high. double close. double open. The bar closing price. represents the number of trades that occurred during the time period the bar covers. The weighted average price during the time covered by the bar.C++ Class EWrapper Functions realtimeBar() This function receives the real-time bars data results. string data) Parameter reqId data Description The ID of the data request. virtual void realtimeBar(TickerId reqId. long time. There must be a subscription to Reuters Fundamental set up in Account Management before you can receive this data. The high price during the time covered by the bar. The bar opening price. The low price during the time covered by the bar. virtual void fundamentalData(int reqId. The volume during the time covered by the bar. The date-time stamp of the start of the bar. double wap. long volume. The format is determined by the reqHistoricalData() formatDate parameter. When TRADES historical data is returned. double low. virtual void currentTime(long time) Parameter time Description The current system time on the server side.

and classes that are closely related to them.C++ SocketClient Properties SocketClient Properties The tables below define properties for the Execution. • • • • • • • • • Execution ExecutionFilter Contract ContractDetails ComboLeg Order OrderState ScannerSubscription UnderComp API Reference Guide 245 . Contract and Order classes.

combo trades and legs of the combo. Specifies if the transaction was a sale or a purchase. remains the same over TWS sessions. The format for timeFilter is "yyyymmdd-hh:mm:ss" Filter the results of the reqExecutions() function based on the order symbol. Note: this is only relevant for FA managed accounts. The TWS id used to identify orders.C++ SocketClient Properties Execution Property CString execId CString time CString acctNumber CString exchange CString side Description Unique order execution id. Note: TWS orders have a fixed client id of 0. ExecutionFilter Property long clientId CString acctCode Description Filter the results of the reqExecutions() function based on the clientId. Valid values are: • • BOT SLD int shares double price int permId long clientId long orderId int liquidation int cumQty double avgPrice The number of shares filled. Note: TWS orders have a fixed order id of 0. Used in regular trades. The order id. Cumulative quantity. combo trades and legs of the combo. Filter the results of the reqExecutions() function based on an account code. The order execution time. The customer account number. Filter the results of the reqExecutions() function based on execution reports received after the specified time. Identifies the position as one to be liquidated last should the need arise. Average price. The order execution price. The id of the client that placed the order. Used in regular trades. CString time CString symbol API Reference Guide 246 . Exchange that executed the order.

Note: Refer to the Order struct for the list of valid order actions. Filter the results of the reqExecutions() function based on the order action. CString exchange CString side API Reference Guide 247 . Filter the results of the reqExecutions() function based on the order exchange. Note: Refer to the Contract struct for the list of valid security types.C++ SocketClient Properties Property CString secType Description Filter the results of the reqExecutions() function based on the order security type.

Use the format YYYYMM. Given the existence of this kind of ambiguity. API Reference Guide 248 . Dynamic memory structure used to store the leg definitions for this contract. Note: Historical data queries on expired contracts are limited to the last year of the contracts life. Specifies a Put or Call. contract details requests and historical data queries can be performed pertaining to expired contracts. include the primary exchange. along with the Smart designation. when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). and are initially only supported for expired futures contracts. it is a good idea to always specify the currency.C++ SocketClient Properties Contract Property CString symbol CString secType Description This is the symbol of the underlying asset. This is the security type. Description for combo legs. Specifies the currency. To clarify any ambiguity for Smart-routed contracts. If set to true. CALL. This is the local exchange symbol of the underlying asset. CString comboLegsDescrip CString primaryExchange bool includeExpired int conId The unique contract identifier. Valid values are: P. for example. such as Smart. This is only necessary when multiple possibilities exist. CString localSymbol vector<ComboLeg*>* comboLegs. C.. Ambiguities may require that this field be specified. The order destination. Valid values are • • • • • • • STK OPT FUT IND FOP CASH BAG CString expiry double strike CString right CString multiplier CString exchange CString currency The expiration date. The strike price. for the destination. PUT. Allows you to specify a futures or options multiplier.

API Reference Guide 249 . Supported identifiers are: • • • • ISIN (Example: Apple: US0378331005) CUSIP (Example: Apple: 037833100) SEDOL (Consists of 6-AN + check digit.) CString secId Unique identifier for the secIdType. Example: BAE: 0263494) RIC (Consists of exchange-independent RIC Root and a suffix identifying the exchange.C++ SocketClient Properties Property CString secIdType Description Security identifier. Example: AAPL.O for Apple on NASDAQ. when querying contract details or when placing orders.

A higher credit rating generally indicates a less risky investment. relevant if the bond has embedded options. i. Typically the contract month of the underlying for a futures contract. For Bonds. The descriptive name of the asset. The underlying contract ID. Z on LIFFE is reported in index points and not GBP. the bond can be called by the issuer under certain conditions. the bond can be sold back to the issuer under certain conditions. The contract month. The minimum price tick. A description string containing further descriptive information about the bond. The date the bond was issued. For Bonds." For Bonds. historical data and the order price.e. Values are True or False. The type of bond coupon. For Bonds. The date on which the issuer must repay the face value of the bond. relevant if the bond has embedded options. For Bonds. For Bonds. The trading class name for this contract. i. The interest rate used to calculate the amount you will receive in interest payments over the course of the year. The market name for this contract.. If true. For Bonds. If true. Values are True or False. Identifies the credit rating of the issuer. The nine-character bond CUSIP or the 12-character SEDOL. Bond ratings are from Moody's and S&P respectively. For Bonds. For Bonds.C++ SocketClient Properties ContractDetails Property Contract summary CString marketName CString tradingClass double minTick CString orderTypes CString validExchanges CString underConId CString longName CString cusip CString ratings Description A contract structure. For Bonds. If true. The type of bond. For Bonds. The list of valid order type for this contract The list of exchanges on which this contract is traded." For Bonds. if populated for the bond in IB's database Allows execution and strike prices to be reported consistently with market data. relevant if the bond has embedded options. is the next option full or partial? For Bonds.e. Values are True or False. such as "CORP. For Bonds. CString descAppend CString bondType CString couponType bool callable bool putable double coupon bool convertible CString maturity CString issueDate CString nextOptionDate CString nextOptionType Bool nextOptionPartial CString notes long priceMagnifier CString contractMonth API Reference Guide 250 . For Bonds. such as "FIXED. the bond can be converted to stock under certain conditions.

The exchange to which the complete combination order will be routed. To help determine the ratio for a specific combination order. 20090507:0700-1830. The liquid trading hours of the product. The industry category of the underlying.e. Select the relative number of contracts for the leg you are constructing.(2) only valid for institutional customers. For example. Open .20090508:CLOSED. ComboLeg Property long conId long ratio Description The unique contract identifier specifying the security. The industry subcategory of the underlying. Unknown 0 .inapplicable (i. Otherwise leave blank or orders will be rejected. the designatedLocation must be specified. This is the only option for retail customers. For example. retail customer or not short leg) 1 . Financial. The trading hours of the product. Valid values are: • • • • Same .clearing broker 2 .1830-2330. API Reference Guide 251 . CString action CString exchange long openClose int shortSaleSlot For institutional customers only.(0) same as the parent security. • • • CString designatedLocation If shortSaleSlot == 2. you must enter a designated location. For example.(1) only valid for institutional customers.20090508:CLOSED. Close . For example. Specifies whether the order is an open or close order. For example. The ID of the time zone for the trading hours of the product. Brokerage. InvestmentSvc. For example.third party. EST. 20090507:0930-1600. If this value is used.C++ SocketClient Properties Property CString industry CString category CString subcategory CString timeZoneId CString tradingHours CString liquidHours Description The industry classification of the underlying/product. refer to the Interactive Analytics section of the User's Guide. The side (buy or sell) for the leg you are constructing.

API Reference Guide 252 . Valid values are: DAY. The TWS id used to identify orders. This means that only one order in the group will be routed at a time to remove the possibility of an overfill. In all other cases specify zero. also specify zero. The id of the client that placed this order. Identifies the order type. Valid values include: • • • 1 = Cancel all remaining orders with block 2 = Remaining orders are proportionately reduced in size with block double auxPrice CString tif CString ocaGroup int ocaType 3 = Remaining orders are proportionately reduced in size with no block If you use a value "with block" gives your order has overfill protection. The time in force. SELL. Identifies the side. Valid values are: • • • • • • • • • • • • MKT MKTCLS LMT LMTCLS PEGMKT SCALE STP STPLMT TRAIL REL VWAP TRAILLIMIT double lmtPrice This is the LIMIT price. This is the STOP price for stop-limit orders. Tells how to handle remaining orders in an OCA group when one order or part of an order executes. SSHORT The order quantity. remains the same over TWS sessions. Identifies an OCA (one cancels all) group. GTD. For relative orders with no limit price. GTC.C++ SocketClient Properties Order Property long orderId long clientId long permId CString action long totalQuantity CString orderType Description The id for this order. Valid values are: BUY. In all other cases. specify zero. used for limit. IOC. and the offset amount for relative orders. stop-limit and relative orders.

Valid values are 0 = customer. specifies that the order is a Sweep-to-Fill order.C++ SocketClient Properties Property CString account CString openClose int origin CString orderRef bool transmit long parentId bool blockOrder bool sweepToFill int displaySize int triggerfunction Description The account. 1 = firm The order reference. • • • • • • boolean outsideRth() boolean hidden If set to true. If set to true. specifies that the order is an ISE Block order. For institutional customers only. Specifies whether the order will be transmitted by TWS. Stop-Limit and Trailing Stop orders are triggered. If set to false. 3 double last function. the order will be created at TWS but will not be sent. C. For institutional customers only. used for bracket and auto trailing stop orders. This option only applies to orders routed to the ISLAND exchange. 1 . The trade's "Good After Time. 7 last or bid/ask function.The default value.use "double bid/ask" function. Used only when shortSaleSlot = 2. All other orders will used the "last" function. the order will not be visible when viewing the market depth. For institutional customers only."last" function. 8 mid-point function. Specifies how Simulated Stop. 2 . Valid values are O. where stop orders are triggered based on two consecutive bid or ask prices. where stop orders are triggered based on the last price. The order ID of the parent order. The publicly disclosed order size. Valid values are 1 or 2. double discretionaryAmt int shortSaleSlot CString designatedLocation CString goodAfterTime API Reference Guide 253 . If set to true. The "double bid/ask" function will be used for orders for OTC stocks and US options. The amount off the limit price allowed for discretionary orders. For institutional customers only. 4 bid/ask function. used when placing Iceberg orders. Valid values are: • 0 ." format "YYYYMMDD hh:mm:ss (optional time zone)" Use an empty String if not applicable. If set to true. The order origin. allows orders to also trigger or fill outside of regular trading hours.

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. 1 = yes Maximum smart order distance from the NBBO. 1 = yes Trade with firm quotes. Away. This value is required for FUT/FOP orders for reporting to the exchange." format "YYYYMMDD hh:mm:ss (optional time zone)" Use an empty String if not applicable. 1 = yes Identifies a minimum quantity order type. The percent offset amount for relative orders. For IBExecution customers: Specifies the true beneficiary of the order. 0 = no. double startingPrice double stockRefPrice The auction starting price. 0 = no. For orders on BOX only. The stock delta. The trade's "Good Till Date. Values include: • • match = 1 improvement = 2 bool allOrNone int minQty double percentOffset bool eTradeOnly bool firmQuoteOnly double nbboPriceCap int auctionStrategy • transparent = 3 For orders on BOX only. For orders on BOX only. 0 = no. AgentOtherMember = 'W' IndividualPTIA = 'J' AgencyPTIA = 'U' AgentOtherMemberPTIA = 'M' IndividualPT = 'K' AgencyPT = 'Y' AgentOtherMemberPT = 'N' CString rule80A CString settlingFirm CString clearingIntent CString clearingAccount Institutional only. Trade with electronic quotes. Values include: • • • • • • • • • Individual = 'I' Agency = 'A'.C++ SocketClient Properties Property CString goodTillDate Description You must enter GTD as the time in force to use this string. For IBExecution customers: Valid values are: IB. double delta API Reference Guide 254 . and PTA (post trade allocation).

VOL orders only. For no hedge delta order to be sent. For price improvement option orders on BOX and VOL orders with dynamic management.use an empty String if not applicable. VOL orders only. The Financial Advisor allocation function the trade will be allocated with -.use an empty String if not applicable. VOL orders only. Specifies how you want TWS to calculate the limit price for options.use an empty String if not applicable. as calculated by TWS' Option Analytics. Valid values include: • • 0 = False 1 = True double volatility The option price in volatility. Precautionary constraints are defined on the TWS Presets page. Orders sent from the API are also validated against these safety constraints. such as a REL order. The upper value for the acceptable underlying stock price range.use an empty String if not applicable. Enter an order type to instruct TWS to submit a delta neutral trade on full or partial execution of the VOL order.C++ SocketClient Properties Property double stockRangeLower double stockRangeUpper CString faGroup CString faProfile CString fafunction CString faPercentage bool overridePercentageCon straints Description The lower value for the acceptable underlying stock price range. Values include: • • 1 = Daily volatility 2 = Annual volatility int volatilityType CString deltaNeutralOrderType int deltaNeutralAuxPrice bool continuousUpdate VOL orders only. 255 int referencePriceType API Reference Guide . and help ensure tha tyour price and size order values are reasonable. For price improvement option orders on BOX and VOL orders with dynamic management. The Financial Advisor group the trade will be allocated to -. Use this field to enter a value if the value in the deltaNeutralOrderType field is an order type that requires an Aux price. This value is expressed as a percent and is used to calculate the limit price sent to the exchange. and for stock range price monitoring. Valid values include: • • 1 = Average of NBBO 2 = NBB or the NBO depending on the action and right. Specifies whether TWS will automatically update the limit price of the order as the underlying price moves. To override validation. specify NONE. The Financial Advisor allocation profile the trade will be allocated to -. The Financial Advisor percentage concerning the trade's allocation -. set this parameter’s value to True. and may be rejected if any constraint is violated.

Used in conjunction with scaleInitLevelSize(). This field is required. this defines the highest end of the possible range into which the actual order commission will fall. double scalePriceIncrement double basisPoints int basisPointsType bool whatIf OrderState Property CString status CString initMargin CString maintMargin CString equityWithLoan double commission double minCommission Description Displays the order status. Used in conjunction with the minCommission field. this defines the lowest end of the possible range into which the actual order commission will fall. Displays a warning message if warranted. For Scale orders: Defines the price increment between scale components. Shows the impact the order would have on your initial margin. double maxCommission CString commissionCurrency CString warningText API Reference Guide 256 . Shows the commission amount on the order. margin and commissions data is received back via the OrderState() object for the openOrder() callback. For Scale orders: Defines the order size of the subsequent scale order components. Shows the impact the order would have on your equity with loan value. or initial. If set to true. order component. Shows the currency of the commission value. Shows the impact the order would have on your maintenance margin. For EFP orders only For EFP orders only Use to request pre-trade commissions and margin information. Used in conjunction with the maxCommission field.C++ SocketClient Properties Property double trailStopPrice int scaleInitLevelSize int scaleSubsLevelSize Description For TRAILLIMIT orders only For Scale orders: Defines the size of the first.

Can be left blank. Can be left blank. The location. Can be left blank. Filter out contracts with a maturity date later than this value. Can be left blank. Filter out convertible bonds. Can be left blank. Can be left blank. Can be left blank. Filter out contracts with a Moody rating below this value. Filter out contracts with a Moody rating above this value.C++ SocketClient Properties ScannerSubscription Property int numberOfRows CString instrument CString locationCode CString scanCode double abovePrice double belowPrice int aboveVolume double marketCapAbove double marketCapBelow CString moodyRatingAbove CString moodyRatingBelow CString spRatingAbove CString spRatingBelow CString maturityDateAbove CString maturityDateBelow double couponRateAbove double couponRateBelow CString excludeConvertible CString scannerSettingPairs int averageOptionVolumeA bove Description Defines the number of rows of data to return for a query. Filter out contracts with a price lower than this value. Can be left blank. Can be left blank. Filter out contracts with a price higher than this value. Can be left blank. a pairing "Annual. For example. Filter out contracts with a maturity date earlier than this value. Filter out contracts with a market cap lower than this value. Filter out contracts with a coupon rate higher than this value. Can be left blank. Filter out contracts with a volume lower than this value. Can be left blank. Can be left blank. Filter out contracts with a coupon rate lower than this value. Defines the instrument type for the scan. API Reference Guide 257 . Can leave empty. Filter out contracts with an S&P rating below this value. Can be left blank. Filter out contracts with an S&P rating above this value. Can be left blank. Can leave empty. Filter out contracts with a market cap above this value. true" used on the "top Option Implied Vol % Gainers" scan would return annualized volatilities.

Used for Delta-Neutral Combo contracts. Used for Delta-Neutral Combo contracts. The price of the underlying.C++ SocketClient Properties Property CString stockTypeFilter Description Values include: • • • ALL (excludes nothing) STOCK (excludes ETFs) ETF (includes ETFs) UnderComp Attribute int conId double delta double price Description The unique contract identifier specifying the security. The underlying stock or future delta. Used for Delta-Neutral Combo contracts. API Reference Guide 258 .

con1. Request 1 is assigned to CLK9 and Request 2 is assigned to CLM9. m_client->reqContractDetails(2. con1.m_secType = "FUT". // request 2 The conId values are delivered by the following event. because the API only imitates the behavior of TWS.exchange = "NYMEX". then the conid is for the CLK9 contract. then it will be easier to place the same order using the API.localSymbol = "CLK9". con2. Implement the placeOrder() method with the Contract and Order socket client properties. con2->getContract()). con1->getContract()). Get this number by invoking the reqContractDetails() method. If reqId is equal to 2. The key to implementing a successful API combination order using the API is to knowing how to place the same order using Trader Workstation.C++ Placing a Combination Order 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 transaction. con1. con2. // request 1 con2. Example In this example. If reqId is equal to 1.currency = "USD". con1. a customer places a BUY order for a CLK9 futures contract and a SELL order for a CLM9 futures contract. m_client->reqContractDetails(1. Include each leg on the ComboLeg object by populating the related fields.m_currency = "USD".m_exchange = "NYMEX".m_localSymbol = "CLM9". If you are familiar with placing combination orders in TWS. conversions and straddles using the BAG security type (defined in the Contract object). In this procedure. API Reference Guide 259 .secType = "FUT". the customer must invoke reqContractDetails() to obtain the conId for both CLK9 and CLM9 contracts. Submit combo orders such as calendar spreads. then the conId is for CLM9. con2. • • To place this combo order 1 Get the Contract IDs for both leg definitions. 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: • Obtain the contract id (conId) for each leg.

// abitrary value only combo orders contract.. leg2. leg1. leg1. // BAG is the security type for COMBO order contract.symbol = "USD". 3 Invoke the placeOrder() method with the appropriate contract and order objects.secType = "BAG".action = "SELL". leg2.designatedLocation = "". order->getOrder()).shortSaleSlot = 0. contract.exchange = "NYMEX". } 2 Assign all the related values for combo orders and combine them: leg1. const ContractDetails &contractDetails) { // to obtain conId for CLK9 if (reqId == 1) … // to obtain conid for CLM9 if (reqId == 2) . m_client->placeOrder(Orderid. contract->getContract().openClose = 0. contract..comboLegs = addAllLegs. API Reference Guide 260 . Note: For more information on combination orders.m_action = "BUY". order.shortSaleSlot = 0. leg2.m_totalQuantity = 1. it includes the addAllLegs declaration in the contract object.openClose = 0.C++ Placing a Combination Order ::contractDetails( int reqId. leg1. see the TWS Users Guide topics About Combination Orders and Notes on Combination Orders.m_orderType = "MKT". //including combo order in contract object order.action = "BUY".currency = "USD".conId = Leg2_conId.exchange = "NYMEX". leg2. order. leg2. contract.designatedLocation = "".exchange = "NYMEX". leg2.conId = Leg1_conId.ratio = 1.ratio = 1. leg1. leg1. leg1. leg2. As shown below.

Java This chapter describes the Java API. including the following topics: • • • • • • • • 5 Linking to TWS using the Java API Running the Java Test Client Sample Program Java Test Client Overview Java API Overview Java EClientSocket Methods Java EWrapper Methods Java SocketClient Properties Placing a Combination Order API Reference Guide 261 .

ib. Receives bond contract information. Override the following methods: Ewrapper Method tickPrice() tickSize() tickOptionComputation() tickGeneric() tickString() tickEFP() orderStatus() openOrder() error() connectionClosed() updateAccountValue() updateAccountTime() updatePortfolio() nextValidId() contractDetails() contractDetailsEnd() bondContractDetails() exectDetails() updateMktDepth() updateMktDepthL2() updateNewsBulletin() managedAccounts() receiveFA() historicalData() Receives order status. Receives historical data results. This class will receive messages from the socket. Notifies when TWS terminates the connection. Receives current account values. Receives current portfolio information. Receives IB news bulletins. API Reference Guide 262 . Receives Level II market depth information.* into your source code file. Receives the last time account information was updated. Receives execution report information. Receives the next valid order ID upon connection. Implement the EWrapper interface. Receives contract information. Identifies the end of a given contract details request. Receives a list of Financial Advisor (FA) managed accounts. Description Handles market data.client.Java Linking to TWS using the Java API Linking to TWS using the Java API To link to TWS using the Java API 1 2 3 Import com. Receives market depth information. Receives FA configuration information. Receives error information. Receives open orders.

Automatically associates a new TWS with the client. Requests account values. Requests market data.Java Linking to TWS using the Java API Ewrapper Method scannerParameters() Description Receives an XML document that describes the valid parameters of a scanner subscription. Requests a list of all open orders. 263 reqAllOpenOrders() reqAutoOpenOrders() reqNewsBulletin() cancelNewsBulletins() setServerLogLevel() reqManagedAccts() API Reference Guide . scannerData() realTimeBar() currentTime() fundamentalData() 4 5 Instantiate the EClientSocket class. Cancels market data. Requests a list of the day’s execution reports. Requests market depth. Receives Reuters global fundamental market data. Places an order. Requests contract details. Receives market scanner results. and account update time information. Cancels IB news bulletins. Requests IB news bulletins. Sets the level of API request and processing logging. Cancels an order. Receives real-time bars. portfolio. The association only occurs if the requesting client has a Client ID of 0. Disconnects from TWS. Call the following methods: EClientSocket Method eConnect() eDisconnect() reqMktData() cancelMktData() reqMktDepth() cancelMktDepth() reqContractDetails() placeOrder() cancelOrder() reqAccountUpdates() reqExecutions() reqOpenOrders() Description Connects to TWS. Receives the current system time on the server. Requests a list of current open orders for the requesting client and associates TWS open orders with the client. This object will be used to send messages to TWS. Cancels market depth. The association only occurs if the requesting client has a Client ID of 0. Requests a list of Financial Advisor (FA) managed account codes.

Requests an XML document that describes the valid parameters of a scanner subscription.Java Linking to TWS using the Java API EClientSocket Method requestFA() replaceFA() reqScannerParameters() Description Requests FA configuration information from TWS. Requests Reuters global fundamental data. Exercises options. Cancels historical data. reqScannerSubscription() cancelScannerSubscription() reqHistoricalData() cancelHistoricalData() reqRealTimeBars() cancelRealTimeBars() exerciseOptions() reqCurrentTime() serverVersion() TwsConnectionTime() reqFundamentalData() cancelFundamentalData() API Reference Guide 264 . Cancels real-time bars. Modifies FA configuration information from the API. Requests market scanner results. Cancels a scanner subscription. Requests real-time bars. Cancels Reuters global fundamental data. Requests historical data. Returns the version of the TWS instance to which the API application is connected. Requests the current server time. Returns the time the API application made a connection to TWS. There must be a subscription to Reuters Fundamental set up in Account Management before you can receive this data.

or NetBeans at netbeans. If you are using TWS. navigate to the Jts:\Java folder. select Java Application and click Next. API Reference Guide 265 . and uncheck the check box for Create Main Class.org. To run the Java Test Client sample program from a new project in NetBeans 1 2 3 4 Open NetBeans and click New Project to start the wizard.Java Running the Java Test Client Sample Program Running the Java Test Client Sample Program You can access the IB trading system via TWS or the IB Gateway through a Java application using the socket client component. Run the file run. configure it to support the API components. You can download the bundle at the Sun Website. In the Projects area. Click Finish.bat. choose a location. Before you can connect to TWS. you must: • • • Install the socket client component and sample programs. Have NetBeans with the J2SE development kit installed on your PC. name your project. To run the Java Test Client sample program on Windows 1 2 From Windows Explorer. In the New Java Application window.

Java Running the Java Test Client Sample Program 5 To set up Java to use the API. API Reference Guide 266 . right-click SampleJavacode and select Properties. 6 7 From the source category click Add Folder. Click OK. The folders you want to add are called Java\com and Java\TestJavaClient. Navigate to the folder where the TWS API is installed.

Main and click OK.Java Running the Java Test Client Sample Program 8 Press F6 to run the sample java project. When the message says "Project Samplejavacode does not have main class set" select TestJavaclient. API Reference Guide 267 .

Java Running the Java Test Client Sample Program The Java Test Client’s sample application window is pictured below. API Reference Guide 268 .

which the Java Test Client sample program uses to let FA customers subscribe to account updates. Defines the Account Updates dialog. which the Java Test Client sample program uses to let customers enter filter criteria for execution reports. TestJavaClient Classes TestJavaClient includes the following classes: Class AccountDlg Description Defines the Account/Portfolio dialog. Defines the Log Configuration dialog. Defines the Financial Advisor dialog. Package The Java Test Client includes the package TestJavaClient. which the Java Test Client sample program uses to let customers specify the level of log entries in the log file. which Financial Advisor customers use in the Java Test Client sample program. which the Java Test Client sample program uses to let customers enter values for extended order attributes. which the Java Test Client sample program uses to display a customer’s account and portfolio information.Java Java Test Client Overview Java Test Client Overview This section describes the package. the sample Java program included in the TWS API. which the Java Test Client sample program uses to let customers connect to TWS Defines the Execution Report Filter dialog. This package includes all the classes and methods required by the Java Test Client sample program. which the Java Test Client sample program uses to let customers add and remove combo legs. AcctUpdatesDlg ComboLegDlg ConnectDlg ExecFilterDlg ExtOrdDlg FAAllocationInfoDlg FinancialAdvisorDlg LogConfigDlg API Reference Guide 269 . which the Java Test Client sample program uses to let Financial Advisor customers enter information about allocation profiles and account groups. Note: The classes and methods used in the Java Test Client were developed for the sample program and are not part of the TWS Java API. Defines the Combination Legs dialog. Defines the Connect dialog. Defines the FA Allocation Info dialog. classes and methods used in the Java Test Client. Defines the Extended Order Info dialog.

All of the text panels and buttons on the main window are defined in this class. Defines the Market Scanner dialog (also called the Sample dialog in the test client). which the Java Test Client sample program uses to let customers view market depth for a specified contracts. as well as request market scan parameters. options exercise. which the Java Test Client sample program uses to let customers enter contract and order information for orders and requests for contract data. API Reference Guide 270 . see the Getting Started with the TWS Java API guide. NewsBulletinDlg OrderDlg SampleFrame ScannerDlg Note: For more information about the Java code in the Java Test Client sample program. which the Java Test Client sample program uses to let customers subscribe and unsubscribe to news bulletins. Defines the IB News Bulletin Subscription dialog. and historical data queries. market depth. which the Java Test Client sample program uses to let customers subscribe and unsubscribe to markets scans. Defines the Sample dialog.Java Java Test Client Overview Class MktDepthDlg Description Defines the Market Depth dialog. Defines the Java Test Client sample program main window. market data.

including bond information.client. This class contains attributes used to describe a contract.ib. This class contains attributes used to describe a trade. which contains the following classes: Class EWrapper ComboLeg Contract ContractDetails EClientSocket Execution ExecutionFilter Order OrderState ScannerSubscription TickType Description This interface is responsible for receiving messages from TWS. API Reference Guide 271 . This class contains attributes used to describe combo legs. This class contains attributes used to describe contract details. This class contains attributes used to describe the elements of a market scan. This class contains attributes used to describe the status of an order. This class is responsible for sending messages to TWS. This class contains attributes used to describe execution filter criteria. This class defines the generic tick types and their tick values.Java Java API Overview Java API Overview The TWS Java API contains the package com. The methods and attributes of these classes are described in the rest of this chapter. This class contains attributes used to describe an order.

Java Java EClientSocket Methods Java EClientSocket Methods This section describes the class EClientSocket methods you can use when connecting to TWS. The list of methods includes: Connection and Server EClientSocket() eConnect() eDisconnect() isConnected() setServerLogLevel() reqCurrentTime() serverVersion() TwsConnectionTime() Market Data reqMktData() cancelMktData() calculateImpliedVolatility() cancelCalculateImpliedVolatility() calculateOptionPrice() cancelCalculateOptionPrice() Orders placeOrder() cancelOrder() reqOpenOrders() reqAllOpenOrders() reqAutoOpenOrders() exerciseOptions() Account reqAccountUpdates() Executions reqExecutions() Contract Details reqContractDetails() Market Depth reqMktDepth() cancelMktDepth() News Bulletins reqNewsBulletins() cancelNewsBulletins() Financial Advisors reqManagedAccts() requestFA() replaceFa() Market Scanners reqScannerParameters() reqScannerSubscription() cancelScannerSubscription() Historical Data reqHistoricalData() cancelHistoricalData() Real Time Bars reqRealTimeBars() cancelRealTimeBars() Fundamental Data reqFundamentalData() cancelFundamentalData() API Reference Guide 272 .

EClientSocket(AnyWrapper anyWrapper) Parameter anyWrapper Description The reference to an object that was derived from the AnyWrapper base interface. A number used to identify this client connection. Leave blank to connect to the local host. void isConnected() API Reference Guide 273 . int port. but a subsequent attempt to connect will return the message "Already connected. int clientId) Parameter host port clientId Description The host name or IP address of the machine where TWS is running.Java Java EClientSocket Methods EClientSocket() This is the constructor. eConnect() This function must be called before any other. Calling this method does not cancel orders that have already been sent. Note: Each client MUST connect with a unique clientId. eDisconnect() Call this method to terminate the connections with TWS. Note EWrapper extends AnyWrapper." void eConnect( String host. There is no feedback for a successful connection. void eDisconnect() isConnected() Call this method to check if there is a connection with TWS. All orders placed/modified from this client will be associated with this client identifier. Must match the port specified in TWS on the Configure>API>Socket Port field.

Must be a unique value. This is also used when canceling the market data. Contract optionContract. When the market data returns. Describes the contract. tickOptionComputation(). tickGeneric(). tickString() and tickEFP() methods. A comma delimited list of generic tick types. contract genericTicklist snapshot cancelMktData() After calling this method. This class contains attributes used to describe the contract. tickSize(). boolean snapshot) Parameter tickerId Description The ticker id. double optionPrice. calculateImpliedVolatility() Call this function to calculate volatility for a supplied option price and underlying price. it will be identified by this tag. Do not enter any genericTicklist values if you use snapshot. Check to return a single snapshot of market data and have the market data subscription cancel. Price of the underlying. calculateImpliedVolatility(int reqId. void reqMktData(int tickerId. API Reference Guide 274 . void cancelMktData(int tickerId) Parameter tickerId Description The Id that was specified in the call to reqMktData().Java Java EClientSocket Methods reqMktData() Call this method to request market data. market data for the specified Id will stop flowing. double underPrice) Parameter reqId optionContract optionPrice underPrice Description The ticker id. Contract contract. The market data will be returned by the tickPrice(). The price of the option. String genericTicklist. Tick types can be found in the Generic Tick Types page.

Price of the underlying. contract order cancelOrder() Call this method to cancel an order. placeOrder() void placeOrder( int id. Order order) Parameter id Description The order Id. This tag is also used when canceling the order. This structure contains the details of the order. Describes the contract. double underPrice) Parameter conid contract volatility underPrice Description The ticker ID. This class contains attributes used to describe the contract. Contract contract. The volatility. Note: Each client MUST connect with a unique clientId. it will be identified by this tag. double volatility. API Reference Guide 275 . calculateImpliedVolatility(int reqId) Parameter reqId Description The ticker id. void calculateOptionPrice(int reqId. cancelCalculateOptionPrice(int reqId) Parameter reqId Description The ticker id. calculateOptionPrice() Call this function to calculate option price and greek values for a supplied volatility and underlying price. When the order status returns. You must specify a unique value.Java Java EClientSocket Methods cancelCalculateImpliedVolatility() Call this function to cancel a request to calculate volatility for a supplied option price and underlying price. cancelCalculateOptionPrice() Call this function to cancel a request to calculate the option price and greek values for a supplied volatility and underlying price. Contract contract.

acctCode reqExecutions() When this method is called. and last update time information. This association will persist over multiple API and TWS sessions. updateAccountValue() and updatePortfolio() EWrapper methods. If set to FALSE. String acctCode) Parameter subscribe Description If set to TRUE. Each open order will be fed back through the openOrder() and orderStatus() methods on the EWrapper. API Reference Guide 276 . void reqOpenOrders() reqAccountUpdates() Call this function to start getting account values. void reqAccountUpdates (boolean subscribe. These orders will be associated with the client and a new orderId will be generated. the client will start receiving account and portfolio updates. the client will stop receiving this information. The account code for which to receive account and portfolio updates. portfolio. The account data will be fed back through the updateAccountTime().Java Java EClientSocket Methods void cancelOrder(int id) Parameter id Description The order Id that was specified previously in the call to placeOrder() reqOpenOrders() Call this method to request any open orders that were placed from this API client. the execution reports that meet the filter criteria are downloaded to the client via the execDetails() method. Note: The client with a clientId of "0" will also receive the TWS-owned open orders. void reqExecutions(ExecutionFilter filter) Parameter filter Description The filter criteria used to determine which execution reports are returned.

Java Java EClientSocket Methods

reqContractDetails()
Call this method to download all details for a particular contract. The contract details will be received via the contractDetails() method on the EWrapper. void reqContractDetails (int reqId, Contract contract) Parameter reqId contract Description The ID of the data request. Ensures that responses are matched to requests if several requests are in process. This class contains attributes used to describe the contract.

reqMktDepth()
Call this method to request market depth for a specific contract. The market depth will be returned by the updateMktDepth() and updateMktDepthL2() methods. void reqMktDepth(int tickerId, Contract contract, int numRows) Parameter tickerId Description 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 canceling the market depth. This class contains attributes used to describe the contract. Specifies the number of market depth rows to return.

contract numRows

cancelMktDepth()
After calling this method, market depth data for the specified Id will stop flowing. void cancelMktDepth(int id) Parameter tickerId Description The Id that was specified in the call to reqMktDepth().

reqNewsBulletins()
Call this method to start receiving news bulletins. Each bulletin will be returned by the updateNewsBulletin() method. void reqNewsBulletins(boolean allMsgs) Parameter allMsgs Description 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.

API Reference Guide

277

Java Java EClientSocket Methods

cancelNewsBulletins()
Call this method to stop receiving news bulletins. void cancelNewsBulletins()

setServerLogLevel()
The default level is ERROR. Refer to the API logging page for more details. void setServerLogLevel(int logLevel) Parameter logLevel Description Specifies the level of log entry detail used by the server (TWS) when processing API requests. Valid values include: • • • • • 1 = SYSTEM 2 = ERROR 3 = WARNING 4 = INFORMATION 5 = DETAIL

reqAllOpenOrders
Call this method to request all open orders that were placed from all API clients linked to one TWS, and also from the TWS. Note that you can run up to 8 API clients from a single TWS. Each open order will be fed back through the openOrder() and orderStatus() methods on the EWrapper. Note: No association is made between the returned orders and the requesting client.

void reqAllOpenOrders()

reqAutoOpenOrders()
Call this method to request that newly created TWS orders be implicitly associated with the client. When a new TWS order is created, the order will be associated with the client and automatically fed back through the openOrder() and orderStatus() methods on the EWrapper. Note: TWS orders can only be bound to clients with a clientId of 0.

void reqAutoOpenOrders(boolean bAutoBind) Parameter bAutoBind Description If set to TRUE, newly created TWS orders will be implicitly associated with the client. If set to FALSE, no association will be made.

API Reference Guide

278

Java Java EClientSocket Methods

reqManagedAccts()
Call this method to request the list of managed accounts. The list will be returned by the managedAccounts() method on the EWrapper. Note: This request can only be made when connected to a Financial Advisor (FA) account

void reqManagedAccts()

requestFA()
Call this method to request FA configuration information from TWS. The data returns in an XML string via the receiveFA() method. void requestFA(long faDataType) Parameter faDataType Description Specifies the type of Financial Advisor configuration data being requested. Valid values include: • • • 1 = GROUPS 2 = PROFILE 3 = ACCOUNT ALIASES

replaceFA()
Call this method to request new FA configuration information from TWS. The data returns in an XML string via a "receiveFA" method. void replaceFA(long faDataType, string xml) Parameter faDataType Description Specifies the type of Financial Advisor configuration data being requested. Valid values include: 1 = GROUPS 2 = PROFILE 3 = ACCOUNT ALIASES The XML string containing the new FA configuration information.

xml

API Reference Guide

279

Java Java EClientSocket Methods

reqScannerParameters()
Call the reqScannerParameters() method to receive an XML document that describes the valid parameters that a scanner subscription can have. void reqScannerParameters()

reqScannerSubscription()
Call the reqScannerSubscription() method to start receiving market scanner results through the scannerData() EWrapper method. void reqScannerSubscription(int tickerId, ScannerSubscription subscription) Parameter tickerId Description 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. Summary of the scanner subscription parameters including filters.

subscription

cancelScannerSubscription()
Call the cancelScannerSubscription() method to stop receiving market scanner results. void cancelScannerSubscription(int tickerId) Parameter tickerId Description The Id that was specified in the call to reqScannerSubscription().

API Reference Guide

280

Java Java EClientSocket Methods

reqHistoricalData()
Call the reqHistoricalData() method to start receiving historical data results through the historicalData() EWrapper method. void reqHistoricalData (int id, Contract contract, String endDateTime, String durationStr, String barSizeSetting, String whatToShow, int useRTH, int formatDate) Parameter tickerId Description 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 historical data request. This class contains attributes used to describe the contract. Use the format yyyymmdd hh:mm:ss tmz, where the time zone is allowed (optionally) after a space at the end. 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: • • • • " S (seconds) " D (days) " W (weeks) " M (months)

contract endDateTime durationStr

• " Y (years) If no unit is specified, seconds are used. Also, note "years" is currently limited to one. barSizeSetting Specifies the size of the bars that will be returned (within IB/TWS limits). Valid values include: Bar Size 1 sec 5 secs 15 secs 30 secs 1 min 2 mins 3 mins 5 mins 15 mins 30 mins 1 hour 1 day 1 week 1 month 3 months 1 year

API Reference Guide

281

Java Java EClientSocket Methods

Parameter whatToShow

Description Determines the nature of data being extracted. Valid values include: • • • • • • • • TRADES MIDPOINT BID ASK BID_ASK HISTORICAL_VOLATILITY OPTION_IMPLIED_VOLATILITY OPTION_VOLUME

useRTH

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

formatDate

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

Note:

For a information about historical data request limitations, see Historical Data Limitations.

cancelHistoricalData()
Call the cancelHistoricalData() method to stop receiving historical data results. void cancelHistoricalData (int tickerId) Parameter tickerId Description The Id that was specified in the call to reqHistoricalData().

API Reference Guide

282

Java Java EClientSocket Methods

reqRealTimeBars()
Call the reqRealTimeBars() method to start receiving real time bar results through the realtimeBar() EWrapper method. void reqRealTimeBars(int tickerId, Contract contract, int barSize, String whatToShow, boolean useRTH) Parameter tickerId Description 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 historical data request. This class contains attributes used to describe the contract. Currently only 5 second bars are supported, if any other value is used, an exception will be thrown. Determines the nature of the data extracted. Valid values include: • • • • useRTH • - TRADES - BID - ASK - MIDPOINT 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. 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.

contract barSize whatToShow

Regular Trading Hours only. Valid values include:

cancelRealTimeBars()
Call this method to stop receiving real time bar results. void cancelRealTimeBars (int tickerId) Parameter tickerId Description The Id that was specified in the call to reqRealTimeBars().

API Reference Guide

283

Java Java EClientSocket Methods

exerciseOptions()
Call the exerciseOptions() method to exercise options. Note: SMART is not an allowed exchange in exerciseOptions() calls, and TWS does a request for the position in question whenever any API initiated exercise or lapse is attempted.

void exerciseOptions(int tickerId, Contract contract, int exerciseAction, int exerciseQuantity, String account, int override) Parameter tickerId contract exerciseAction Description The Id for the exercise request This class contains attributes used to describe the contract. this can have two values: • • exerciseQuantity account override 1 = exercise 2 = lapse

The number of contracts to be exercised For institutional orders. Specifies the IB account. 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 = do not override 1 = override

reqCurrentTime()
Returns the current system time on the server side via the currentTime() EWrapper method.

void reqCurrentTime()

serverVersion()
Returns the version of the TWS instance to which the API application is connected. void serverVersion()

TwsConnectionTime()
Returns the time the API application made a connection to TWS. void TwsConnectionTime ()

API Reference Guide

284

API Reference Guide 285 . Ensures that responses are matched to requests if several requests are in process. Identifies the report type. string reportType) Parameter reqId contract reportType Description The ID of the data request. Contract contract. void cancelFundamentalData(int reqId) Parameter reqId Description The ID of the data request. There must be a subscription to Reuters Fundamental set up in Account Management before you can receive this data. which is one of the following: • • • Estimates Financial Statements Summary cancelFundamentalData() Call this method to stop receiving Reuters global fundamental data.Java Java EClientSocket Methods reqFundamentalData() Call this method to receive Reuters global fundamental data. This structure contains a description of the contract for which Reuters Fundamental data is being requested. void reqFundamentalData(int reqId.

The list of methods includes: Connection and Server currentTime() error() connectionClosed() Market Data tickPrice() tickSize() tickOptionComputation() tickGeneric() tickString() tickEFP() tickSnapshotEnd() Orders orderStatus() openOrder() nextValidId() Account and Portfolio updateAccountValue() updatePortfolio() updateAccountTime() Contract Details contractDetails() contractDetailsEnd() bondContractDetails() Executions execDetails() execDetailsEnd() Market Depth updateMktDepth() updateMktDepthL2() News Bulletins updateNewsBulletin() Financial Advisors managedAccounts() receiveFA() Historical Data historicalData() Market Scanners scannerParameters() scannerData() scannerDataEnd() Real Time Bars realtimeBar() Fundamental Data fundamentalData() API Reference Guide 286 .Java Java EWrapper Methods Java EWrapper Methods This section describes the class EWrapper methods you can use when connecting to TWS.

int canAutoExecute) Parameter tickerId field Description The ticker Id that was specified previously in the call to reqMktData() Specifies the type of price. void tickPrice(int tickerId.Java Java EWrapper Methods tickPrice() This method is called when the market data changes. etc. For example. Possible values are: • • 0 = not eligible for automatic execution 1 = eligible for automatic execution API Reference Guide 287 . int field. a field value of 2 will map to askPrice. • • • • • • price canAutoExecute 1 = bid 2 = ask 4 = last 6 = high 7 = low 9 = close Specifies the price for the specified field Specifies whether the price tick is available for automatic execution. double price. Pass the field value into TickType. a field value of 1 will map to bidPrice. Prices are updated immediately with no delay.getField(int tickType) to retrieve the field description.

• • • impliedVol delta optPrice pvDividend gamma API Reference Guide 10 = Bid 11 = Ask 12 = Last The implied volatility calculated by the TWS option modeler.Java Java EWrapper Methods tickSize() This method is called when the market data changes. For example. int size) Parameter tickerId field Description The ticker Id that was specified previously in the call to reqMktData() Specifies the type of price. The option delta value. prices. double vega. using the specified ticktype value. double optPrice. double theta. and deltas. double impliedVol. void tickOptionComputation(int tickerId. double pvDividend. • • • • size 0 = bid size 3 = ask size 5 = last size 8 = volume Specifies the size for the specified field tickOptionComputation() This method is called when the market in an option or its underlier moves. along with the present value of dividends expected on that options underlier are received. void tickSize(int tickerId. For example. The option price. The present value of dividends expected on the options underlier The option gamma value. Pass the field value into TickType. double undPrice) Parameter tickerId field Description The ticker Id that was specified previously in the call to reqMktData() Specifies the type of option computation. a field value of 13 will map to modelOptComp. Pass the field value into TickType.getField(int tickType) to retrieve the field description. int field. 288 . Sizes are updated immediately with no delay. double delta. etc. double gamma. TWS’s option model volatilities. etc.getField(int tickType) to retrieve the field description. a field value of 0 will map to bidSize. a field value of 3 will map to askSize. int field.

etc. int tickType. Values are updated immediately with no delay. The value of the specified field value tickEFP() This method is called when the market data changes.getField(int tickType) to retrieve the field description. String value) Parameter tickerId field Description The ticker Id that was specified previously in the call to reqMktData() Specifies the type of price. The price of the underlying. void tickGeneric(int tickerId. For example. For example. Pass the field value into TickType. void tickString(int tickerId. a field value of 45 will map to lastTimestamp. etc. int tickType.getField(int tickType) to retrieve the field description. Pass the field value into TickType. The option theta value. Values are updated immediately with no delay.Java Java EWrapper Methods Parameter vega theta undPrice Description The option vega value. tickGeneric() This method is called when the market data changes. double value) Parameter tickerId tickType Description The ticker Id that was specified previously in the call to reqMktData() Specifies the type of price. a field value of 46 will map to shortable. The value of the specified field value tickString() This method is called when the market data changes. Values are updated immediately with no delay. API Reference Guide 289 .

void tickSnapshotEnd(int reqId) Parameter reqID Description Id of the data request. This also covers the timeout case. API Reference Guide 290 . Pass the field value into TickType. int tickType. String futureExpiry. etc. which is representative of the financing rate that can be directly compared to broker rates Annualized basis points as a formatted string that depicts them in percentage form Implied futures price The number of hold days until the expiry of the EFP The expiration date of the single stock future The dividend impact upon the annualized basis points interest rate The dividends expected until the expiration of the single stock future basisPoints formattedBasisPoint s impliedFuture holdDays futureExpiry dividendImpact dividendsToExpiry tickSnapshotEnd() This is called when a snapshot market data subscription has been fully handled and there is nothing more to wait for. Annualized basis points. For example. a field value of 38 will map to bidEFP.getField(int tickType) to retrieve the field description. double impliedFuture. double dividendImpact. String formattedBasisPoints.Java Java EWrapper Methods void tickEFP(int tickerId. double dividendsToExpiry) Parameter tickerId field Description The ticker Id that was specified previously in the call to reqMktData() Specifies the type of price. double basisPoints. int holdDays.

• • • • • • filled remaining Specifies the number of shares that have been executed. You may still receive an execution while your cancellation request is pending. your order is not confirmed canceled.indicates that you have transmitted the order. int clientId. Specifies the number of shares still outstanding. NOTE: This order status is not sent by TWS and should be explicitly set by the API developer when an order is canceled. int remaining. Inactive . At that time the order is transmitted to the order destination as specified . NOTE: This order status is not sent by TWS and should be explicitly set by the API developer when an order is submitted.indicates that the order has been completely filled. Cancelled . API Reference Guide 291 .Java Java EWrapper Methods orderStatus() This method is called whenever the status of an order changes.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.indicates that your order has been accepted at the order destination and is working.indicates that you have sent a request to cancel the order but have not yet received cancel confirmation from the order destination.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. Possible values include: • PendingSubmit . double avgFillPrice. double lastFillPrice. but have not yet received confirmation that it has been accepted by the order destination. void orderStatus(int orderId. int permId. Submitted . String whyHeld) Parameter id status Description The order Id that was specified previously in the call to placeOrder() The order status. This could occur unexpectedly when IB or the destination has rejected your order. PendingCancel . exchange or other issues. int filled. PreSubmitted . int parentId. Filled . At this point. String status.indicates that the balance of your order has been confirmed canceled by the IB system. It is also fired after reconnecting to TWS if the client has any open orders.

Java Java EWrapper Methods Parameter avgFillPrice Description The average price of the shares that have been executed. The order ID of the parent order. This field is used to identify an order held when TWS is trying to locate shares for a short sell. This method is called when exception occurs while handling a request. see Error Codes. the price parameter will be zero. void error(Exception e) Parameter e Description The exception that occurred This method is called when TWS wants to send an error message to the client. (V1). This parameter is valid only if the filled parameter value is greater than zero. Remains the same over TWS sessions. The ID of the client (or TWS) that placed the order. String errorString) Parameter id errorCode errorString Description This is the orderId or tickerId of the request that generated the error. int errorCode. Note that TWS orders have a fixed clientId and orderId of 0 that distinguishes them from API orders. used for bracket and auto trailing stop orders. The value used to indicate this is 'locate'. For information on error codes. void error(String str) Parameter str Description This is the textual description of the error API Reference Guide 292 . Otherwise. the price parameter will be zero. The last price of the shares that have been executed. The textual description of the error. void error(int id. The TWS id used to identify orders. permId parentId lastFilledPrice clientId whyHeld error() This method is called when there is an error with the communication or when TWS wants to send a message to the client. Otherwise. This parameter is valid only if the filled parameter value is greater than zero.

void managedAccounts(String accountsList) Parameter accountsList Description The comma delimited list of FA managed accounts. void openOrder(int orderId. It is also called when the reqManagedAccts() method is invoked. Order order. The Order class attributes define the details of the order. void connectionClosed() managedAccounts() This method is called when a successful connection is made to a Financial Advisor account.Java Java EWrapper Methods connectionClosed() This method is called when TWS closes the sockets connection. Contract contract. The Contract class attributes describe the contract. Used to cancel or update the order. The orderState attributes include margin and commissions fields for both pre and post trade data. OrderState orderState ) Parameter orderId contract order orderState Description The order Id assigned by TWS. or when TWS is shut down. API Reference Guide 293 . openOrder() This method is called to feed in open orders.

equity with Loan Value InitMarginReq .Java Java EWrapper Methods updateAccountValue() This method is called only when reqAccountUpdates() method on the EClientSocket object has been called. API Reference Guide 294 . States the account the message applies to.current maintenance margin NetLiquidation . void updateAccountValue(String key.net liquidation value The value associated with the key.number of day trades left EquityWithLoanValue .current initial margin requirement MaintMarginReq . in case the value is a currency type.account cash balance DayTradesRemaining . here are just a few examples: • • • • • • value currency account CashBalance . Defines the currency type. String currency. String value. String accountName) Parameter key Description A string that indicates one type of account value. Useful for Financial Advisor sub-account messages. There is a long list of possible keys that can be sent.

Shows your profit on closed positions. The unit price of the instrument. void nextValidId(int orderId) Parameter orderId Description The next available order Id received from TWS upon connection. String accountName) Parameter contract Description This structure contains a description of the contract which is being traded. int position. The total market value of the instrument. or Value . 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) The name of the account the message applies to. Increment all successive orders by one based on this Id. void updateAccountTime(String timeStamp) Parameter timeStamp Description This indicates the last update time of the account information nextValidId() This method is called after a successful connection to TWS. The exchange field in a contract is not set for portfolio update. If the position is 0.Average Cost. double marketPrice. double averageCost. Useful for Financial Advisor sub-account messages. position marketPrice marketValue averageCost unrealizedPNL realizedPNL accountName updateAccountTime() This method is called only when reqAccountUpdates() method on the EClientSocket object has been called. void updatePortfolio(Contract contract. double realizedPNL. double unrealizedPNL. it means the position has just cleared. The average cost per share is calculated by dividing your cost (execution price + commission) by the quantity of your position.Java Java EWrapper Methods updatePortfolio() This method is called only when reqAccountUpdates() method on the EClientSocket object has been called. double marketValue. API Reference Guide 295 . This integer indicates the position on the contract. The difference between the current market value of your open positions and the average cost.

Java Java EWrapper Methods contractDetails() This method is called only when reqContractDetails method on the EClientSocket object has been called. This structure contains a full description of the contract that was executed. or when an order is filled. execDetails() This method is called when the reqExecutions() method is invoked. void contractDetails(int ReqId. Contract contract. contractDetailsEnd() This method is called once all contract details for a given request are received. This structure contains a full description of the contract being looked up. void bondContractDetails(int reqId. Note: Refer to the Java SocketClient Properties page for more information. bondContractDetails() This method is called only when reqContractDetails method on the EClientSocket object has been called for bonds. void execDetails(int reqId. This helps to define the end of an option chain. ContractDetails contractDetails) Parameter reqId contractDetails Description The ID of the data request. ContractDetails contractDetails) Parameter reqID contractDetails Description The ID of the data request. Execution execution) Parameter reqId contract Description The reqID that was specified previously in the call to reqExecution(). This structure contains a full description of the bond contract being looked up. void contractDetailsEnd(int reqId) Parameter reqID Description The Id of the data request. API Reference Guide 296 . Ensures that responses are matched to requests if several requests are in process.

void updateMktDepth(int tickerId. double price. Note: Refer to the Java SocketClient Properties page for more information. int size) Parameter tickerId position operation Description The ticker Id that was specified previously in the call to reqMktDepth() Specifies the row Id of this market depth entry. execDetailsEnd() This method is called once all executions have been sent to a client in response to reqExecutions(). The order size. int side. int position. int operation. void execDetailsEnd(int reqId) Parameter reqID Description The Id of the data request. Valid values are:· • • • side 0 = insert (insert this new order into the row identified by 'position')· 1 = update (update the existing order in the row identified by 'position')· 2 = delete (delete the existing order at the row identified by 'position') identifies the side of the book that this order belongs to. Identifies how this order should be applied to the market depth. API Reference Guide 297 .Java Java EWrapper Methods Parameter execution Description This structure contains addition order execution details. Valid values are: • • 0 = ask 1 = bid price size The order price. updateMktDepth() This method is called when the market depth changes.

void updateNewsBulletin(int msgId. String marketMaker. void updateMktDepthL2(int tickerId. Valid values are: • • 0 = ask 1 = bid price size The order price. The order size. int position. double price. The exchange from which this message originated. int side. Specifies the type of bulletin.e. by calling the reqNewsBulletins() method. String origExchange) Parameter msgId msgType Description The bulletin ID. int operation. incrementing for each new bulletin. updateNewsBulletin() This method is triggered for each new bulletin if the client has subscribed (i. Valid values are:· • • • side 0 = insert (insert this new order into the row identified by 'position')· 1 = update (update the existing order in the row identified by 'position')· 2 = delete (delete the existing order at the row identified by 'position') Identifies the side of the book that this order belongs to. identifies the how this order should be applied to the market depth. Valid values include: • • • message origExchange 1 = Reqular news bulletin 2 = Exchange no longer available for trading 3 = Exchange is available for trading The bulletin's message text.Java Java EWrapper Methods updateMktDepthL2() This method is called when the Level II market depth changes. int size) Parameter tickerId position marketMaker operation Description The ticker Id that was specified previously in the call to reqMktDepth() Specifies the row id of this market depth entry. String message. API Reference Guide 298 . int msgType. Specifies the exchange hosting this order.

double high. historicalData() This method receives the requested historical data results. double close. represents the number of trades that occurred during the time period the bar covers The weighted average price during the time covered by the bar. The date-time stamp of the start of the bar. WAP hasGaps API Reference Guide 299 . int volume. The volume during the time covered by the bar. The low price during the time covered by the bar. The bar opening price. double WAP. String date. The high price during the time covered by the bar. double open. receiveFA(long faDataType. Valid values include: • • • xml 1 = GROUPS 2 = PROFILE 3 =ACCOUNT ALIASES The XML string containing the previously requested FA configuration information. The bar closing price. boolean hasGaps) Parameter reqId date open high low close volume count Description The ticker Id of the request to which this bar is responding. double low. Whether or not there are gaps in the data. When TRADES historical data is returned. void historicalData (int reqId.Java Java EWrapper Methods receiveFA() This method receives previously requested FA configuration information from TWS. string xml) Parameter faDataType Description Specifies the type of Financial Advisor configuration data being received from TWS. The format is determined by the reqHistoricalData() formatDate parameter. int count.

void scannerDataEnd(int reqId) Parameter reqId Description The ID of the market data snapshot request being closed by this parameter.Java Java EWrapper Methods scannerParameters() This method receives an XML document that describes the valid parameters that a scanner subscription can have. String projection. int rank. scannerDataEnd() This method is called when the snapshot is received and marks the end of one scan. void scannerData(int reqId. String legsStr) Parameter reqId rank contractDetails distance benchmark projection legsStr Description The ID of the request to which this row is responding. String benchmark. Describes combo legs when scan is returning EFP. void scannerParameters(String xml) Parameter xml Description A document describing available scanner subscription parameters. This structure contains a full description of the contract that was executed. The ranking within the response of this bar. Varies based on query. Varies based on query. API Reference Guide 300 . scannerData() This method receives the requested market scanner data results. Varies based on query. ContractDetails contractDetails. String distance.

double low. double high. int count) Parameter reqId time open high low close volume wap count Description The ticker ID of the request to which this bar is responding. double close. double wap. The weighted average price during the time covered by the bar. The low price during the time covered by the bar. The bar closing price. String data) Parameter reqId data Description The ID of the data request. represents the number of trades that occurred during the time period the bar covers. void currentTime(long time) Parameter time Description The current system time on the server side fundamentalData() This method is called to receive Reuters global fundamental market data. The bar opening price. The date-time stamp of the start of the bar. long volume. void fundamentalData(int reqId.Java Java EWrapper Methods realtimeBar() This method receives the real-time bars data results. One of three XML reports: • • • Estimates (estimates) Financial statements (finstat) Summary (snapshot) API Reference Guide 301 . There must be a subscription to Reuters Fundamental set up in Account Management before you can receive this data. When TRADES historical data is returned. double open. currentTime() This method receives the current system time on the server side. The volume during the time covered by the bar. The format is determined by the reqHistoricalData() formatDate parameter. The high price during the time covered by the bar. void realtimeBar(int reqId. long time.

Java Java SocketClient Properties Java SocketClient Properties The tables below define attributes for the following classes: • • • • • • • • • Execution ExecutionFilter Contract ContractDetails ComboLeg Order OrderState ScannerSubscription UnderComp API Reference Guide 302 .

Used in regular trades. Used in regular trades." The id of the client that placed the order. Note: TWS orders have a fixed client id of "0. Identifies the position as one to be liquidated last should the need arise. combo trades and legs of the combo.Java Java SocketClient Properties Execution Attribute int m_orderId int m_clientId String m_execId String m_time String m_acctNumber String m_exchange String m_side Description The order id. Valid values are: • • BOT SLD int m_shares double m_price int m_permId int m_liquidation int m_cumQty double m_avgPrice The number of shares filled. The order execution price. Exchange that executed the order. The order execution time. remains the same over TWS sessions." Unique order execution id. Note: this is only relevant for Financial Advisor (FA) accounts. combo trades and legs of the combo. String m_time String m_symbol API Reference Guide 303 . ExecutionFilter Attribute int m_clientId String m_acctCode Description Filter the results of the reqExecutions() method based on the clientId. The customer account number. Average price. Cumulative quantity. Specifies if the transaction was a sale or a purchase. The TWS id used to identify orders. Filter the results of the reqExecutions() method based on an account code. Filter the results of the reqExecutions() method based on execution reports received after the specified time. Note: TWS orders have a fixed order id of "0. The format for timeFilter is "yyyymmdd-hh:mm:ss" Filter the results of the reqExecutions() method based on the order symbol.

Filter the results of the reqExecutions() method based on theorder exchange. Note: Refer to the Contract struct for the list of valid security types. String m_exchange String m_side API Reference Guide 304 .Java Java SocketClient Properties Attribute String m_secType Description Filter the results of the reqExecutions() method based on the order security type. Note: Refer to the Order class for the list of valid order actions. Filter the results of the reqExecutions() method based on the order action.

contract details requests and historical data queries can be performed pertaining to expired contracts. Use the format YYYYMM. This is only necessary when multiple possibilities exist.Java Java SocketClient Properties Contract Attribute String m_symbol String m_secType Description This is the symbol of the underlying asset. PUT. it is a good idea to always specify the currency. Specifies a Put or Call. Note: Historical data queries on expired contracts are limited to the last year of the contracts life. for example. Given the existence of this kind of ambiguity. If set to true. Ambiguities may require that this field be specified. when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). Allows you to specify a future or option contract multiplier. This is the security type. Description for combo legs Dynamic memory structure used to store the leg definitions for this contract. and are initially only supported for expired futures contracts. C. Specifies the currency. such as Smart. The strike price. This is the local exchange symbol of the underlying asset. CALL. Valid values are: • • • • • • • STK OPT FUT IND FOP CASH BAG String m_expiry double m_strike String m_right String m_multiplier The expiration date. Identifies the listing exchange for the contract (do not list SMART). The unique contract identifier. The order destination. Valid values are: P. String m_exchange String m_currency String m_localSymbol String m_primaryExch boolean m_includeExpired String m_comboLegsDescrip Vector m_comboLegs int m_conId API Reference Guide 305 .

the bond can be called by the issuer under certain conditions. Bond ratings are from Moody's and S&P respectively. For Bonds. If true. The underlying contract ID. the bond can be sold back to the issuer under certain conditions.) String m_secId Unique identifier for the secIdType. For Bonds. For Bonds. Z on LIFFE is reported in index points and not GBP. For Bonds. For Bonds. Example: BAE: 0263494) RIC (Consists of exchange-independent RIC Root and a suffix identifying the exchange. such as "CORP.e.Java Java SocketClient Properties Attribute String m_secIdType Description Security identifier. For Bonds.O for Apple on NASDAQ. Supported identifiers are: • • • • ISIN (Example: Apple: US0378331005) CUSIP (Example: Apple: 037833100) SEDOL (Consists of 6-AN + check digit. The type of bond coupon. A higher credit rating generally indicates a less risky investment. The list of exchanges this contract is traded on. If true. A description string containing further descriptive information about the bond. Descriptive name of the asset. Values are True or False. Identifies the credit rating of the issuer. String m_orderTypes String m_validExchanges String m_underConId String m_longName String m_cusip String m_ratings String m_descAppend String m_bondType String m_couponType boolean m_callable boolean m_putable API Reference Guide 306 . The list of valid order types for this contract. Allows execution and strike prices to be reported consistently with market data. The market name for this contract. The minimum price tick. The type of bond. Example: AAPL." For Bonds. The nine-character bond CUSIP or the 12-character SEDOL. ContractDetails Attribute Contract m_summary String m_marketName String m_tradingClass double m_minTick String m_priceMagnifier Description A contract summary. when querying contract details or when placing orders. historical data and the order price. The trading class name for this contract. i. Values are True or False.

The side (buy or sell) for the leg you are constructing.20090508:CLOSED.20090508:CLOSED. The industry subcategory of the underlying. Values are True or False. 20090507:0930-1600. if populated for the bond in IB's database The contract month. For Bonds. Select the relative number of contracts for the leg you are constructing. The liquid trading hours of the product. For Bonds. the bond can be converted to stock under certain conditions.1830-2330. InvestmentSvc. For example. For example. For example. The date the bond was issued. For example. For Bonds. The date on which the issuer must repay the face value of the bond. String m_exchange API Reference Guide 307 . For example. EST. For Bonds. For Bonds. Typically the contract month of the underlying for a futures contract. Financial. For example. only if bond has embedded options. only if bond has embedded options. 20090507:0700-1830. If true. For Bonds. For Bonds. Brokerage. The industry classification of the underlying/product. The industry category of the underlying. only if bond has embedded options. refer to the Interactive Analytics section of the User's Guide. To help determine the ratio for a specific combination order.Java Java SocketClient Properties Attribute double m_coupon Description For Bonds. The ID of the time zone for the trading hours of the product. The interest rate used to calculate the amount you will receive in interest payments over the course of the year. boolean m_convertible String m_maturity String m_issueDate String m_nextOptionDate String m_nextOptionType boolean m_nextOptionPartial String m_notes String m_contractMonth String m_industry String m_category String m_subcategory String m_timeZoneId String m_tradingHours String m_liquidHours ComboLeg Attribute int m_conId String m_action int m_ratio Description The unique contract identifier specifying the security. The exchange to which the complete combination order will be routed. The trading hours of the product.

This value is only valid for institutional customers. This is the only option for retail customers.Java Java SocketClient Properties Attribute int m_openClose Description Specifies whether the order is an open or close order. 1 .e. int m_shortSaleSlot For institutional customers only.Same as the parent security.clearing broker 2 . Otherwise leave blank or orders will be rejected. If this value is used.Open. This value is only valid for institutional customers. 2 .Close. you must enter a designated location. • • • String m_designatedLocation If shortSaleSlot == 2. Valid values are: • • • • 0 .inapplicable (i. API Reference Guide 308 . Unknown .(3) 0 . the designatedLocation must be specified.third party. retail customer or not short leg) 1 .

also specify zero. In all other cases specify zero. For relative orders with no limit price. The order quantity. In all other cases. Valid values are: • • • • • • • • • • • • MKT MKTCLS LMT LMTCLS PEGMKT SCALE STP STPLMT TRAIL REL VWAP TRAILLIMIT double m_lmtPrice This is the LIMIT price. SSHORT. and the offset amount for relative orders. Valid values are: DAY. used for limit. specify zero. This is the STOP price for stop-limit orders. Valid values are: BUY. IOC. The TWS id used to identify orders. Identifies an OCA (one cancels all) group. GTC. The time in force. Identifies the side. double m_auxPrice String m_tif String m_ocaGroup API Reference Guide 309 . stop-limit and relative orders. The id of the client that placed this order. remains the same over TWS sessions.Java Java SocketClient Properties Order Attribute int m_orderId int m_clientId int m_permid String m_action long m_totalQuantity String m_orderType Description The id for this order. SELL. GTD. Identifies the order type.

The publicly disclosed order size. The order ID of the parent order. int m_parentId boolean m_blockOrder boolean m_sweepToFill int m_displaySize API Reference Guide 310 . String m_account String m_openClose int m_origin String m_orderRef bool m_transmit The account. Specifies whether the order is an open or close order. This means that only one order in the group will be routed at a time to remove the possibility of an overfill. specifies that the order is an ISE Block order. For institutional customers only. used when placing Iceberg orders. If set to true. If set to true. For institutional customers only. Specifies whether the order will be transmitted by TWS.Java Java SocketClient Properties Attribute int m_ocaType Description Tells how to handle remaining orders in an OCA group when one order or part of an order executes. 1 = firm The order reference. Valid values include: • • • 1 = Cancel all remaining orders with block 2 = Remaining orders are proportionately reduced in size with block 3 = Remaining orders are proportionately reduced in size with no block If you use a value "with block" gives your order has overfill protection. C. used for bracket and auto trailing stop orders. For institutional customers only. For institutional customers only. Valid values are 0 = customer. If set to false. The order origin. Valid values are O. specifies that the order is a Sweep-to-Fill order. the order will be created at TWS but will not be sent.

mid-point method. 3 . If set to true.double last method. The Financial Advisor allocation profile the trade will be allocated to -. allows orders to also trigger or fill outside of regular trading hours. 1 . the order will not be visible when viewing the market depth. All other orders will used the "last" method. where stop orders are triggered based on two consecutive bid or ask prices.bid/ask method.use an empty String if not applicable."last" method." format is: YYYYMMDD hh:mm:ss (optional time zone) Use an empty String if not applicable. • • • • • • boolean m_outsideRth boolean m_hidden If set to true. The Financial Advisor group the trade will be allocated to -.The default value. Valid values are: • 0 . Use only when shortSaleSlot value = 2. This option only applies to orders routed to the ISLAND exchange.use an empty String if not applicable. The trade's "Good Till Date.last or bid/ask method. The Financial Advisor percentage concerning the trade's allocation -. The trade's "Good After Time.use an empty String if not applicable. The Financial Advisor allocation method the trade will be allocated with -. Cancel on Fill with Block = 1 Reduce on Fill with Block = 2 Reduce on Fill without Block = 3 double m_discretionaryAmt String m_goodAfterTime String m_goodTillDate String m_faGroup String m_faProfile String m_faMethod String m_faPercentage int m_shortSaleSlot String m_designatedLocation int m_ocaType API Reference Guide 311 . 8 . 2 . The "double bid/ask" method will be used for orders for OTC stocks and US options.use an empty String if not applicable." format "YYYYMMDD hh:mm:ss (optional time zone)" Use an empty String if not applicable. Values are 1 or 2. 4 . The amount off the limit price allowed for discretionary orders. Stop-Limit and Trailing Stop orders are triggered.use "double bid/ask" method. where stop orders are triggered based on the last price.Java Java SocketClient Properties Attribute int m_triggerMethod Description Specifies how Simulated Stop. You must enter a tif value of GTD. 7 .

For IBExecution customers: Valid values are: IB. double m_startingPrice The starting price. and may be rejected if any constraint is violated. Valid on BOX orders only. Orders sent from the API are also validated against these safety constraints. API Reference Guide 312 . Trade with electronic quotes. This value is required for FUT/FOP orders for reporting to the exchange. set this parameter’s value to True. The percent offset amount for relative orders.Java Java SocketClient Properties Attribute int m_overridePercentageConstrai nts Description Precautionary constraints are defined on the TWS Presets page. yes=1. no = 0 Trade with firm quotes. To override validation. Valid values are: • • match = 1 improvement = 2 string m_clearingIntent boolean m_allOrNone int m_minQty double m_percentOffset boolean m_eTradeOnly boolean m_firmQuoteOnly double m_nbboPriceCap int m_auctionStrategy • transparent = 3 For BOX exchange only. no=0 Identifies a minimum quantity order type. yes = 1. yes = 1. Away. For IBExecution customers: Specifies the true beneficiary of the order. no = 0 The maximum Smart order distance from the NBBO. AgentOtherMember = 'W' IndividualPTIA = 'J' AgencyPTIA = 'U' AgentOtherMemberPTIA = 'M' IndividualPT = 'K' AgencyPT = 'Y' AgentOtherMemberPT = 'N' string m_rule80A Valid values are: • • • • • • • • • string m_settlingFirm string m_clearingAccount Institutional only. Valid values include: • • 0 = False 1 = True Individual = 'I' Agency = 'A'. and PTA (post trade allocation). and help ensure tha tyour price and size order values are reasonable.

Enter an order type to instruct TWS to submit a delta neutral trade on full or partial execution of the VOL order.Java Java SocketClient Properties Attribute double m_stockRefPrice Description The stock reference price. Used for dynamic management of volatility orders. int m_deltaNeutralAuxPrice int m_continuousUpdate int m_referencePriceType double m_trailStopPrice int m_scaleInitLevelSize For TRAILLIMIT orders only For Scale orders: Defines the size of the first. Valid on BOX orders only. The lower value for the acceptable underlying stock price range. Used for dynamic management of volatility orders. such as a REL order. the limit price sent to an exchange is modified by TWS if the computed price of the option changes enough to warrant doing so. For VOL orders. computed via TWSs Options Analytics. Determines whether TWS is supposed to update the order price as the underlying moves. How the volatility is calculated. What the price is. 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 National Best Ask when selling a call or buying a put. Volatility is expressed as a percentage. For no hedge delta order to be sent. or initial. and for price range monitoring. as it is the output of a function. For price improvement option orders on BOX and VOL orders with dynamic management. Use this field to enter a value if the value in the deltaNeutralOrderType field is an order type that requires an Aux price. order component. the limit price sent to an exchange is not editable. Set to • • 1 = Average of National Best Bid or Ask. The stock delta. This is very helpful in keeping the limit price sent to the exchange up to date as the underlying price changes. The upper value for the acceptable underlying stock price range. specify NONE. • • Daily = 1 Annual = 2 double m_delta double m_stockRangeLower double m_stockRangeUpper double m_volatility int m_volatilityType string m_ deltaNeutralOrderType VOL orders only. For price improvement option orders on BOX and VOL orders with dynamic management. If selected. API Reference Guide 313 . or set to 2 = National Best Bid when buying a call or selling a put. VOL orders only.

Displays a warning message if warranted. double m_maxCommission String m_commissionCurrency String m_warningText API Reference Guide 314 . Shows the impact the order would have on your initial margin. this defines the highest end of the possible range into which the actual order commission will fall. Shows the impact the order would have on your equity with loan value. For EFP orders only For EFP orders only Use to request pre-trade commissions and margin information. Used in conjunction with scaleInitLevelSize(). Used in conjunction with the maxCommission field. margin and commissions data is received back via the OrderState() object for the openOrder() callback. This field is required. Shows the impact the order would have on your maintenance margin. double m_scalePriceIncrement double m_basisPoints int m_basisPointsType boolean m_whatIf OrderState Attribute string m_status String m_initMargin String m_maintMargin String m_equityWithLoan double m_commission double m_minCommission Description Displays the order status. For Scale orders: Defines the price increment between scale components. If set to true. Shows the currency of the commission value. Used in conjunction with the minCommission field.Java Java SocketClient Properties Attribute int m_scaleSubsLevelSize Description For Scale orders: Defines the order size of the subsequent scale order components. Shows the commission amount on the order. this defines the lowest end of the possible range into which the actual order commission will fall.

Can be left blank. Can be left blank. Filter out contracts with a Moody rating below this value. Can be left blank. Filter out contracts with an S&P rating below this value. Can be left blank. For example. Filter out contracts with a volume lower than this value. Filter out contracts with a maturity date earlier than this value. Can be left blank. Can be left blank. Filter out contracts with a market cap above this value. Can be left blank.Java Java SocketClient Properties ScannerSubscription Attribute int m_numberOfRows String m_instrument String m_locationCode String m_scanCode double m_abovePrice double m_belowPrice int m_aboveVolume double m_marketCapAbove double m_marketCapBelow String m_moodyRatingAbove String m_moodyRatingBelow String m_spRatingAbove String m_spRatingBelow String m_maturityDateAbove String m_maturityDateBelow double m_couponRateAbove double m_couponRateBelow String m_excludeConvertible String m_scannerSettingPairs Description Defines the number of rows of data to return for a query. Filter out contracts with a coupon rate higher than this value. Filter out contracts with a maturity date later than this value. Can be left blank. Can leave empty. Filter out convertible bonds. a pairing "Annual. Can be left blank. Defines the instrument type for the scan. Filter out contracts with an S&P rating above this value. true" used on the "top Option Implied Vol % Gainers" scan would return annualized volatilities. Filter out contracts with a market cap lower than this value. Filter out contracts with a price higher than this value. Can be left blank. int m_averageOptionVolumeAbove API Reference Guide 315 . Filter out contracts with a coupon rate lower than this value. Can be left blank. Filter out contracts with a price lower than this value. Can leave empty. Filter out contracts with a Moody rating above this value. Can be left blank. Can be left blank. Can be left blank. Can be left blank. The location.

Used for Delta-Neutral Combo contracts. API Reference Guide 316 . Used for Delta-Neutral Combo contracts. Used for Delta-Neutral Combo contracts.Java Java SocketClient Properties Attribute String m_stockTypeFilter Description Valid values are: • • • ALL (excludes nothing) STOCK (excludes ETFs) ETF (includes ETFs) UnderComp Attribute int m_conId double m_delta double m_price Description The unique contract identifier specifying the security. The price of the underlying. The underlying stock or future delta.

m_currency = "USD". con1. con1.0 con1.reqContractDetails(1. The key to implementing a successful API combination order using the API is to knowing how to place the same order using Trader Workstation.m_expiry = “200909”. Get this number by invoking the reqContractDetails() method.m_symbol = "GOOG". API Reference Guide 317 .m_multiplier = “100” con1.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: • Obtain the contract id (conId) for each leg. because the API only imitates the behavior of TWS.m_right = “C” con1. To buy one calendar spread means: Leg 1: Sell 1 GOOG OPT SEP 18 '09 150. con1). Implement the placeOrder() method with the Contract and Order socket client properties. Include each leg on the ComboLeg object by populating the related fields. • • To place this combo order 1 Get the Contract IDs for both leg definitions: //First leg Contract con1 = new Contract().m_strike = 150. con1. Submit combo orders such as calendar spreads.m_secType = "OPT". conversions and straddles using the BAG security type (defined in the Contract object). a customer places a BUY order on a calendar spread for GOOG. then it will be easier to place the same order using the API.m_exchange = "SMART”.Java Placing a Combination Order 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 transaction. con1. con1. If you are familiar with placing combination orders in TWS. Example In this example. .

m_openClose = 0.m_exchange = "SMART”.m_symbol = "GOOG". include it in the ComboLeg object: ComboLeg leg1 = new ComboLeg(). leg1. con2.} // to obtain conId for first leg if (reqId == 2) { Leg2_conId = contract. . con2. /*Base on the request above.reqContractDetails(2. reqId = 1 is corresponding to the first request or first leg reqId = 2 is corresponding to the second request or second leg*/ if (reqId == 1) { Leg1_conId = contract. leg1.Java Placing a Combination Order //Second leg Contract con2 = new Contract(). leg1. ContractDetails contractDetails) { Contract contract = contractDetails. con2. con2. //All conId numbers are delivered by the ContractDetail() static public String contractDetails(int reqId.m_conId. // for the second leg Vector addAllLegs = new Vector(). leg1.m_expiry = “201101”.m_currency = "USD".} // to obtain conId for second leg } 2 Once the program has acquired the conId value for each leg.m_strike = 150.m_shortSaleSlot = 0.m_designatedLocation = "". con2). leg1.m_conId. // for the first leg ComboLeg leg2 = new ComboLeg().m_summary.0 con2. con2. API Reference Guide 318 .m_multiplier = “100” con2.m_conId = Leg1_conId.m_ratio = 1. leg1.m_secType = "OPT".m_exchange = "SMART".m_right = “C” con2. leg1.m_action = "SELL".

addAllLegs.m_conId = Leg2_conId.m_comboLegs = addAllLegs. leg2. contract.m_orderType = “MKT” . order. leg2. contract.m_shortSaleSlot = 0. addAllLegs.add(leg2). Note: For more information on combination orders.m_totalQuantity = 1.m_openClose = 0.Java Placing a Combination Order leg2.m_symbol = "USD". Order order = new Order(). contract.m_currency = "USD". see the TWS Users Guide topics About Combination Orders and Notes on Combination Orders. 3 Invoke the placeOrder() method with the appropriate contract and order objects: Contract contract = new Contract(). API Reference Guide 319 .m_designatedLocation = "". order. order).m_ratio = 1. //including combo order in contract object order. leg2.m_exchange = "SMART". leg2. // For combo order use “USD” as the symbol value all the time contract.m_action = “BUY”.placeOrder(OrderId.add(leg1). leg2.m_action = "BUY".m_exchange = "SMART".m_secType = "BAG". contract. // BAG is the security type for COMBO order contract. leg2.

Java Placing a Combination Order API Reference Guide 320 .

including the following topics: • • • • • API Reference Guide 321 .Advisors 6 Financial Advisor Orders and Account Configuration Excel DDE Support Support by Other API Technologies Improved Financial Advisor Execution Reporting Allocation Methods for Account Groups This chapter describes API functionality for users with Financial Advisor accounts.

and account aliases. These methods and that event pertain to the following three parts of TWS FA account configuration: creating groups. replaceFA(int faDataType. Java. These can be left empty if they do not apply to an order. or C++ based API technologies. and account aliases. profiles. via an event that TWS sends that contains the data requested. TWS Financial Advisor account configuration is done via two new methods and one new event. or via both. The event is called receiveFA. When one or more of these new values is not relevant to an order. FA Group. DDE orders now have six Extended Order Attributes: Good After Time.xls DDE for Excel API spreadsheet. Java. or C++ based. For more information. string XML) receives the requested data from TWS. You can place FA orders on the Advisors page in the most recent release of the TwsDde. profiles. The methods are called replaceFA. Prior to those new methods being used. API FA functionality became significantly more powerful in TWS release 821 and higher. simply pass in an empty string. Good Till Date.Advisors Financial Advisor Orders and Account Configuration Financial Advisor Orders and Account Configuration This section assumes familiarity on the part of the reader with TWS Financial Advisor account configuration and order placement. • • In accordance with the existence of this new functionality. or via the API. in that the now deprecated "allocation string" method was replaced by the much more powerful Financial Advisor order allocation methods. faPercentage. receiveFA(int faDataType. TWS Financial Advisor account configuration should be done manually for DDE access. The event includes an XML string containing the requested information. API Reference Guide 322 . • requestFA(int faDataType) is a method that is called by an API application to request one of those types of FA configuration data. Excel DDE Support Starting with TWS release 824. and requestFA. whether ActiveX. FA Percentage. TWS had to be configured to understand the desired FA order groups. faMethod. FA Method. Support by Other API Technologies For all ActiveX. have four new parameters pertaining to Financial Advisor order placement: faGroup. all placeOrder methods. string XML) can be called from the API if the API application wishes to replace the previous FA configuration information with a new XML string. and FA Profile. see the Advisors Page topic. This can be done manually in TWS. and faProfile.

" SUB2 Account: BUY 33 IBM. and who wants them allocated with Equal Quantity to each." SUB3 Account: BUY 33 IBM." • • • • • API Reference Guide 323 . as well as its being allocated to its various subaccounts. the execution messages resulting from a new FA order will report both the initial execution of the order. Message says "BUY -33 IBM. FA Account: allocation of 33 shares out of FA account and into sub account 3." The negative quantity reflects the fact that the execution being reported is reducing the purchase. The following example will serve to explain the new reporting scheme: Assume that 100 shares of IBM is being bought on the NYSE by a Financial Advisor who has three sub-accounts. The following seven execution messages will occur: • • FA Account: Order filled on NYSE to BUY 100 IBM FA Account: allocation of 34 shares out of FA account and into sub account 1. FA Account: allocation of 33 shares out of FA account and into sub account 2. Message says "BUY -34 IBM. Message says "BUY -33 IBM. SUB1 Account: BUY 34 IBM.Advisors Improved Financial Advisor Execution Reporting Improved Financial Advisor Execution Reporting When using TWS version 823 or higher.

and 400 shares to Client C. Example 2: You want to close out all long positions for three of the five accounts in a group. so you enter "50" in the percentage field. The account group includes three accounts. The system calculates ratios based on the Net Liquidation value in each account and allocates shares based on these ratios. This method distributes shares based on the net liquidation value of each account. The system calculates a ratio of 1:2:4 and allocates 100 shares to Client A. The system calculates a ratio of 1:2:4 and allocates 100 shares to Client A. each account receives 66 shares. It then allocates 50 shares to Client A. A. The system calculates ratios based on the Equity with Loan value in each account and allocates shares based on these ratios.000 and $100.Advisors Allocation Methods for Account Groups Allocation Methods for Account Groups Note that you must type the method name in exactly as appears here. NetLiq Method Requires you to specify an order size.000 respectively. and Client C has 200 shares. You want to increase their holdings by 50%. B and C with available equity in the amounts of $25. each account receives 100 shares. AvailableEquity Method Requires you to specify an order size.000. Example: You transmit an order for 700 shares of stock XYZ. negative percents will decrease a position. You create a sell order and enter "-100" in the Percentage field. The account group includes three accounts. Client B has 400 shares. This method distributes shares equally between all accounts in the group. A. Client A has 100 shares. and 100 shares to Client C. 200 shares to Client B. If your Account Group includes four accounts. Example: You transmit an order for 400 shares of stock ABC. or your order won't work. If your Account Group includes six accounts. The system calculates that your order size needs to be equal to 350 shares. $50. and 400 shares to Client C. Example: You transmit an order for 700 shares of stock XYZ. Since the quantity is calculated by the system.000. EqualQuantity Method Requires you to specify an order size.000 respectively. This method increases or decreases an already existing position. the order size is displayed in the Quantity field after the order is acknowledged. The system calculates 100% of API Reference Guide 324 . Example 1: Assume that three of the six accounts in this group hold long positions in stock XYZ.000 and $100. PctChange Method This method only works when you already hold a position in the selected instrument. 200 shares to Client B. Do not specify an order size. and then 1 share is allocated to each account until all are distributed. $50. Positive percents will increase a position. B and C with Net Liquidation values of $25. This method distributes shares based on the amount of equity with loan value currently available in each account. 200 shares to Client B.

These handy charts make it easy to see how negative and positive percent values will affect long and short positions for both buy and sell orders. Phew. that was a mouthful! BUY ORDER Long Position Short Position Positive Percent Increases position No effect Negative Percent No effect Decreases position SELL ORDER Long Position Short Position Positive Percent No effect Increases position Negative Percent Decreases position No effect API Reference Guide 325 .Advisors Allocation Methods for Account Groups each position for every account in the group that holds a position. and sells all shares to close the positions.

Advisors Allocation Methods for Account Groups API Reference Guide 326 .

xls. including the following topics: Getting Started with the ActiveX for Excel API Using the ActiveX for Excel Sample Spreadsheet The ActiveX for Excel sample spreadsheet.ActiveX for Excel • • 7 This chapter describes the ActiveX for Excel sample spreadsheet. events and COM objects used in the code for the ActiveX for Excel sample spreadsheet are the same as those used in the ActiveX API. One of the benefits of using this spreadsheet is that it can connect to a TWS or IB Gateway session that is running on a remote PC. duplicates the functionality of the ActiveX for Excel API spreadsheet but internally uses an ActiveX component.ocx. API Reference Guide 327 . The methods. The DDE for Excel API spreadsheet cannot do this. TwsActiveX. See the ActiveX chapter for complete details about the ActiveX API. Tws. The following figure shows the Tickers page in the ActiveX for Excel API sample spreadsheet.

Ensure that either: • • the application server is running and that it is configured to support ActiveX or the IB Gateway is running. send orders and view your activity. that uses an ActiveX control.ActiveX for Excel Getting Started with the ActiveX for Excel API Getting Started with the ActiveX for Excel API We have created a sample Excel spreadsheet. API Reference Guide 328 . click Download latest version. The sample spreadsheet currently comprises several pages complete with sample data and action buttons that make it easy for you to get market data. TwsActiveX. then double-click the file to begin the API installation.xls. • • Open the spreadsheet and start using the ActiveX for Excel API. select API Solutions from the Software menu. select a different directory. which includes the ActiveX for Excel sample spreadsheet. Click the IB API icon. Click Save. Close any versions of TWS and Excel that you have running. TwsActiveX. and on the API Software page. Note: Windows users can download the beta test version of the API by using the Windows Beta column. find the column appropriate to your operating system. or revert to the previous production version by selecting Downgrade to Previous Version. Follow the steps below to download the sample spreadsheet. It's easy to get started: • Download the API components. Locate the installation program you just saved to your computer. and if desired. Download the API Components and Spreadsheet We recommending using the sample Excel spreadsheet that we provide as a starting point toward creating your own ActiveX for Excel API. To install the ActiveX for Excel sample spreadsheet 1 2 From the IB homepage. or use it create your own custom TWS API Excel application. You can use this spreadsheet with TWS as is. Before you can use the spreadsheet.xls. Follow the instructions in the installation wizard.ocx. you must have TWS running and configured to support the ActiveX API. See Run the API through TWS for detailed instructions. Tws. 3 4 5 6 Save the installation program to your computer.

0 Redistributable Package. do the following: 1 2 3 Install Microsoft Visual C++ 2005 SP1 Redistributable Package (x86). Note: Note that not more than one API application can simultaneously access a single instance. Modify the default values in the Host. you must click OK to dismiss any messages that appear. and ClientID cells. Port. Download and install the API software. To open the sample spreadsheet 1 2 3 4 Go to the API installation folder in which the Excel API sample spreadsheet was installed (typically C:\Jts\Excel) and double-click TwsActiveX. Install Microsoft Visual J# 2.ActiveX for Excel Getting Started with the ActiveX for Excel API Running the ActiveX for Excel API on 64-bit Windows XP Systems To run the ActiveX for Excel API on 64-bit Windows XP systems. • If you select the Show Errors Message Box check box. then click Connect to TWS on the Toolbar.xls. error messages display when you connect to TWS. This lets you customize the spreadsheet without changing the original. In this case. Save the spreadsheet with a different file name. Click the General tab. The API application does not need to be running on the same computer on which the application is running. open the spreadsheet and save it as your personal file. Open the Sample Spreadsheet After you have downloaded the sample spreadsheet and configured the application to allow the ActiveX for Excel API to link to it. API Reference Guide 329 .

Lets you set up your ticker lines and request market data. Conditional Orders and Advisors pages. includes the following pages (tabs): Page General Tickers Description Lets you connect to and disconnect from TWS. set up combination orders and EFPs. and includes a filtering box so you can limit your results. TwsDde. Lets you subscribe to and view IB News Bulletins. including the conid and supported order types for a contract Lets you collect bond contract-specific information you will need for other actions. Lets you collect contract-specific information you will need for other actions.xls. Lets Financial Advisors send and modify FA orders. such as Bracket. this page lets you change the time in force. including those that have been accepted by the IB system. and those that are working at an exchange. Advanced Orders. Lets you view market depth for selected quotes. Used in conjunction with the Basic Orders. You can view market data for all asset types including EFPs and combination orders. Lets you send and modify advanced orders types that require the use of extended order attributes. Request historical data for an instrument based on data you enter in a query. Lets you request and view Fundamentals data from TWS. Shows you all transmitted orders. Lets you request and view real time bars from TWS. 330 Bulletins Market Depth Basic Orders Conditional Orders Advanced Orders Extended Order Attributes Open Orders Account Portfolio Executions Historical Data Contract Details Bond Contract Details Real Time Bars Market Scanner Fundamentals Advisors Log API Reference Guide . Lets you view all execution reports. including bond coupon and maturity date. set the server log level and request the current time. Provides up to date account information and displays your portfolio.ActiveX for Excel Using the ActiveX for Excel Sample Spreadsheet Using the ActiveX for Excel Sample Spreadsheet The ActiveX for Excel API sample spreadsheet. and request open orders. Lets you create an order whose submission is contingent on other conditions being met. Displays all your current positions. Lets you send and modify orders. Lets you view market scanner parameters and subscribe to TWS market scanners. Scale and Trailing Stop Limit orders. Lets you view all error messages. create Hidden or Iceberg orders and apply many other order attributes. for example an order based on a prior fill.

ActiveX for Excel General Page General Page Use the General page to: • • • • Connect to TWS. API Reference Guide 331 . Set the level of log entry detail used by the server when processing API requests. Request the current server time. Disconnect from TWS.

Port and ClientID cells. 2 Click Set Server Log Level in the toolbar. To set the server log level 1 Type one of the following values in the Log Level cell: • • • • • 1 = SYSTEM 2 = ERROR 3 = WARNING 4 = INFORMATION 5 = DETAIL The higher the number.ActiveX for Excel General Page To connect to TWS 1 Click Connect to TWS in the toolbar. Select the Show Errors Message Box to display errors when connecting to TWS. To disconnect from TWS 1 Click Disconnect from TWS in the toolbar. • • If required. change the values in the Host. API Reference Guide 332 . the greater the level of detail and performance overhead.

which when selected. Disconnects from TWS.txt log file. Requests the current server time.ActiveX for Excel General Page To request the current time 1 Click Request Current Time in the toolbar. API Reference Guide 333 . The toolbar also includes the Show Errors Message Box check box. General Page Toolbar Buttons The toolbar on the General page includes the buttons described below. displays error when connecting to TWS. Sets the level of detail of entries in the log. Button Connect to TWS Disconnect from TWS Set Server Log Level Request Current Time Description Connects to TWS.

Click the line number to the left of a blank row to select the row. Request market data. Create market data line for Exchange for Physical (EFP) combination orders. API Reference Guide 334 . You must have a blank row selected to create a ticker line. and that you have entered your user name in the User Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet to properly connect to TWS.ActiveX for Excel Tickers Page Tickers Page Use the Tickers page to: • • • • Create market data (ticker) lines. Using the Tickers Page Note: Ensure that TWS is running. To create a ticker using the Create Ticker button 1 2 Click the Tickers tab at the bottom of the spreadsheet. Create a combination order for options.

ActiveX for Excel Tickers Page 3 4 Click the Create Ticker button on the toolbar and enter information in the Create Tickers dialog. Note: The Exchange field accepts the following values: SMART (for smart order routing). then click Request Market Data multiple times until all rows are showing data. select multiple ticker rows while holding down the Shift key. P/C and Multiplier fields. Enter a comma-separated list of generic tick values in the Generic Tick List cell. for example if you are entering a stock ticker. Optionally. Click Request Market Data on the toolbar. Exchange (usually SMART). you only need to specify the Symbol. To request market data for a ticker 1 2 3 4 Select the ticker row for which you want to request market data by clicking the row number. Type. see Generic Tick Types. Strike. and any valid exchange acronym. For stocks. Click OK. click the Snapshot check box to request a single snapshot of market data. To create a ticker on the spreadsheet 1 2 Select a blank cell in the Symbol column and enter a symbol. and Currency. For details about generic tick values. Tab through the all contract description fields and enter data where necessary. API Reference Guide 335 . To get market data for a group of tickers. you don't need values in the Expiry.

API Reference Guide 336 . in seconds) in the Market Data Refresh Rate cell. TWS market data updates every 3 seconds by default. The toolbar also includes the Snapshot check box. which when selected. Clears all market data from the page. Enter contract details to create legs of a combination order one by one.ActiveX for Excel Tickers Page To set the refresh rate The market data refresh rate determines how often the link to TWS is refreshed. • Enter the refresh rate value (in whole numbers. Select a line and click to get market data for the selected contract. requests only a single snapshot of market data. Cancel market data for the selected ticker. Tickers Page Toolbar Buttons The toolbar on the Tickers page includes the buttons described below. Button Create Ticker Combo Legs Request Market Data Cancel Market Data Clear Market Data Description Opens the Ticker box. Enter information to create a market data line. Opens the Combination Legs box.

which when selected. Button Request News Bulletins Cancel News Bulletins Clear News Bulletins Description Requests all the new news bulletins. you will receive only new bulletins. select the All Day News check box on the toolbar. API Reference Guide 337 . If this check box is not selected. Bulletins Page Toolbar Buttons The toolbar on the Tickers page includes the buttons described below. Clears all news bulletins from the page.ActiveX for Excel Bulletins Page Bulletins Page Use the Bulletins page to request and view IB news bulletins. requests all the existing bulletins for the current day and any new ones. Simply click Request News Bulletins in the toolbar. Cancels receipt of all news bulletins. To request all the existing bulletins for the current day and any new ones. The toolbar also includes the All Day News check box. News bulletins display in the table on the page.

if you have signed up for those subscriptions. API Reference Guide 338 .ActiveX for Excel Market Depth Page Market Depth Page Use the Market Depth page to view market depth for selected contracts. and NASDAQ-listed products through the TotalView Market Data Subscriptions. You can also view market depth for NYSE-listed products through the Open Book Market Data Subscription.

Select the ticker symbol for which you want to request the market depth.9. The page also includes a Market Depth Refresh Rate cell. Cancel market depth for the selected contract. or enter a new ticker on a blank line. To request market depth for a contract 1 2 3 Click the Market Depth tab at the bottom of the spreadsheet to open the Market Depth page. API Reference Guide 339 . which lets you rest the market depth refresh rate in seconds. To reset the market data refresh rate for market depth 1 Type the desired market data refresh rate in seconds in the Market Depth Refresh Rate cell.ActiveX for Excel Market Depth Page Using the Market Depth Page Note: Ensure that TWS is running. Click the Request Market Depth button on the toolbar. Market Depth Page Toolbar Buttons The toolbar on the Market Depth page includes the following buttons: Button Request Market Depth Cancel Market Depth Clear Market Depth Description View bid/ask depth prices for the selected contract. Clears all market depth data from the page. The default refresh rate is 3 seconds. and that you have connected the spreadsheet to TWS. in whole numbers from 1 . The value must be in whole numbers from 1 to 9.

Modify and cancel orders.ActiveX for Excel Basic Orders Page Basic Orders Page Use the Basic Orders page to: • • Create an order. which shows you the margin and commission information before you place an order. • • • API Reference Guide 340 . Create combination orders. Create a "basket" of orders. Place a “what if” order.

and that you have connected the spreadsheet to TWS. then entering information in the relevant contract description fields. the Aux. Order Type. Select a contract and set up the order using the Order Description fields. 5 To place a "basket" of orders 1 2 3 4 5 Click the Basic Orders tab at the bottom of the spreadsheet. Note: To place an order 1 2 3 Click the Basic Orders tab at the bottom of the spreadsheet. then entering information in the relevant contract description fields. hold down the Shift key. select the contract (the ticker row) and apply extended order attributes by clicking the Apply Extended Template button on the toolbar. Price for order types that require it. Sell or Short Sell). hold the Ctrl key down as you select each order. then highlight the last order of the group. • To select a group of contiguous orders. Repeat Steps 1 and 2 for additional orders. Quantity. highlight the first order. Define a contract by typing a symbol in a blank Symbol field. To select a group of non-contiguous orders.ActiveX for Excel Basic Orders Page Placing Orders This topic describes how to place the following types of orders on the Orders page: • • • Simple orders Basket orders Modified orders Ensure that TWS is running. 4 If desired. This applies all attributes you have defined on the Extended Order Attributes page to the selected contract. Select a group of orders. API Reference Guide 341 . Limit Price (unless it's a market order) and if necessary. Click the Place/Modify Order button on the toolbar. • 6 Click the Place/Modify Order button. You must define the Action (Buy. Select a contract and set up the order using fields in the Order Description section. Define a contract by typing a symbol in a blank Symbol field.

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 transaction. • To select a group of contiguous orders. hold down the Shift key. • 3 Click the Place/Modify Order button. Select the order or a group of orders. then highlight the last order of the group. To select a group of non-contiguous orders.5 CALL (100) To create a calendar spread order The following example walks you through the process of placing a hypothetical calendar spread order for XYZ on ISE. API Reference Guide 342 . To buy a calendar spread. you would: • • Buy 1 OPT JUL03 17. highlight the first order. hold the Ctrl key down as you select each order.5 CALL (100) Sell 1 OPT AUG03 17.ActiveX for Excel Basic Orders Page To modify an order (or group of orders) 1 2 On the Basic Orders page. change any necessary parameters in an order or group of orders.

so the resulting combo substring looks as follows: CMBLGS_2_17496957_1_BUY_EMPTY_0_15910089_1_SELL_EMPTY_0_CMBL GS • • 3 The combination leg definitions must occur before the extended order attributes.5 CALL on ISE is "12345678". The exception is for a STK leg definition. 315 = Stock combo legs are restricted to SMART exchange. API Reference Guide 343 . 314 = Security type 'BAG' requires combo leg details.ActiveX for Excel Basic Orders Page 1 Use the Contract Details page to get the contract id for both of the leg definitions. which must specify the SMART exchange. and each leg definition consists of [conid]_[ratio]_[action]_[exchange]_[openClose]. • • The conid for XYZ option JUL08 17. The full place order DDE request string will look like this: =acctName|ord!id12345?place?BUY_1_XYZ_BAG_ISE_LMT_1_CMBLGS_2_1234 5678_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. CLOSE). Click the Combo Legs button on the Basic Orders page toolbar and enter leg information.5 CALL on ISE is "12345679". one of the following errors will be returned: • • • • 312 = The combo details are invalid. 313 = The combo details for '<leg number>' are invalid. 2. OPEN.0) for retail accounts. The exchange for the leg definition must match that of the combination order. Your leg information is translated into the format: [CMBLGS]_[NumOfLegs]_[Combo Leg Definitions]_[CMBLGS] where: • [CMBLGS] is the delimiter used to identify the start and end of the leg definitions [NumOfLegs] is the number of leg definitions [Combo Leg Definitions] defines N leg definitions. The conid for XYZ option AUG08 17. The openClose leg definition value is always 'SAME' (i. 2 Click the Basic Orders tab to build the combo leg definitions. For institutional accounts. the value may be any of the following: (SAME.e. Notes: 1.

you will receive margin and commission data as if the order were placed. This button cancels the selected order(s). Clears all order status information from the page. and defined any extended attributes. Apply Extended Template Place/Modify Orders Cancel Order Clear Order Statuses There is also a WhatIf check box on the toolbar. Enter information to create a market data line. You can also enter Delta Neutral information. When checked. Applies the current values on the Extended Order Attributes page to the highlighted order row. API Reference Guide 344 .ActiveX for Excel Basic Orders Page Supported Order Types The order types currently supported through the ActiveX for Excel API are: • • • • • • • • • • • • • • Limit (LMT) Market (MKT) Limit if Touched (LIT) Market if Touched (MIT) Market on Close (MOC) Limit on Close (LOC) Pegged to Market (PEGMKT) Relative (REL) Stop (STP) Stop Limit (STPLMT) Trailing Stop (TRAIL) Trailing Stop Limit (TRAILLIMIT) Volume-Weighted Average Price (VWAP) Volatility orders (VOL) Basic Orders Page Toolbar Buttons The toolbar on the Basic Orders page includes the following buttons: Button Create Ticker Combo Legs Description Opens the Ticker box. click to create an order for the selected contract. After you have completed the Order Description fields. Enter contract details to create legs of a combination order one by one. but the order will NOT be placed. Opens the Combination Legs box.

use the Statement field to set the criteria which must be met to trigger the order. Setting Up Conditional Orders Note: Ensure that TWS is running. and that you have entered your user name in the User Name field in the Which Trader Workstation? section of all pages in the Excel spreadsheet to properly connect to TWS. an order based on a prior fill or a change in the bid or ask price. In this case. When the Statement = TRUE. for example. use the scroll bar on the bottom of the page to scroll to the right. To see the Conditional Statement fields (in blue). The sample spreadsheet includes a pair of orders. first create the order you want transmitted when a condition is met by defining the contract in the Contract Description fields. with the second orders transmission depending on the first order being completely filled. the Statement field 2 API Reference Guide 345 . In the blue Condition Statements area. and then using the Order Description area to set up the order parameters.ActiveX for Excel Conditional Orders Page Conditional Orders Page Use the Conditional Orders page to create an order whose submission is contingent on other conditions being met. To set up a conditional order 1 On the Conditional Orders page. your order will be submitted.

or the offset for relative orders. Use MOD to continue checking and modifying the order until it is completely filled. The limit price for Limit and Stop Limit order types. 3 4 Type ADD in the ADD/MOD field because you are creating a one-time order. and orders will be activated only with the "ADD" or "MOD" tags. Price All of the fields described above may be variables that depend on other cells.ActiveX for Excel Conditional Orders Page trigger is that the value in cell T10 (the Filled field) must be equal to the value in M10 (the order Quantity field). Conditional Order Examples If-Filled order An if-filled order is an order that executes if a prior order executes.00": Field Statement ADD/MOD Action Quantity Value Filled cell = 100 ADD SELL 100 API Reference Guide 346 . when false. nothing happens. 5 Complete the necessary fields on the Conditional Orders page according to the syntax in the following table. Use ADD for a one-time order. This is the field that activates a conditional order. Field Statement ADD/MOD Action Quantity Order Type Lmt Price Aux. BUY SELL Enter the quantity of the order. so any type of conditional order may be created. the order will be submitted. Define the remaining order parameters just as you did in the Order Description area. Description An Excel function which returns a true or false. 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. The stop-election price for Stop and Stop Limit order types. Refer to list of supported order types. When true.

This value looks something like this: =username|tik!id4?bid where "4" identifies the bid price for a specific contract. • 2 3 Click the Place/Modify Order button. Price Price-change order Value LMT 50 empty A price-change order will be triggered if a specific bid or ask price is greater than. put your cursor in the bid price field you want to use.ActiveX for Excel Conditional Orders Page Field Order Type Lmt Price Aux. To select a group of non-contiguous orders. To create a price change order with the condition "If the bid price drops below 81. less than or equal to a specific price.20 ADD BUY 200 LMT 81.10: Field Statement Value On the Tickers page.10 Not used in this example. "=" ">" or "<" followed by the price. hold the Ctrl key down as you select each order. Paste this in the formula bar ("=" entry field) for the Statement. then copy the value that appears in the formula bar (“=” entry field) at the top of the spreadsheet. submit a buy limit order for 200 shares with a limit price of $81.20. then highlight the last order of the group. • To select a group of contiguous orders. highlight the first order. In this example. and add your qualifier. Price To modify an order (or basket of orders) 1 Select the order or a group of orders. the formula would be: =username|tik!id4?bid<81. then click the Place/Modify Order button. Change any necessary parameters. hold down the Shift key. ADD/MOD Action Quantity Order Type Lmt Price Aux. API Reference Guide 347 .

This button cancels the order(s) you have highlighted. Enter contract details to create legs of a combination order one by one. Applies all attributes on the Extended Order Attributes page to the selected order(s). Jumps to the Error Code field and shows the error code. and defined any extended attributes. click to create an order for the selected contract. Place/Modify Order Apply Extended Template Cancel Order Show Errors API Reference Guide 348 .ActiveX for Excel Conditional Orders Page Conditional Orders Page Toolbar Buttons The toolbar on the Conditional Orders page includes the following buttons: Button Combo Legs Description Opens the Combination Legs box. After you have completed the Order Description fields.

including: • • • • • Bracket orders VOL orders Trailing Stop Limit Orders Scale Orders Relative Orders API Reference Guide 349 .ActiveX for Excel Advanced Orders Page Advanced Orders Page Use the Advanced Orders page to: • Create complex orders that require the use of extended order attributes.

ActiveX for Excel Advanced Orders Page This page includes several example orders with mouseover help to assist you in learning how to place these orders. Simply move your mouse over the red triangle of the corner of cells on the page to display pop-up help. see Apply Extended Order Attributes to Individual Orders and Groups of Orders API Reference Guide 350 . For more information about using extended order attributes for individual orders or groups of orders.

The first order of the bracket order is now the primary order. go to the Extended Order Attributes page and delete the Parent Order Id value you entered. and you must identify the first order in the bracket as the Parent Order. To place a Buy-Limit bracket order 1 2 Click the Advanced Orders tab at the bottom of the spreadsheet. The third order should be a SELL LMT order. 7 8 9 Click the Extended Order Attributes tab and change the value for Transmit back to 1 (row 13). highlight the first order in the bracket order. API Reference Guide 351 . then click the Place/Modify Order button. then click the Place/Modify Order button. This ensures that your orders are not transmitted until you have completed the order setup. The order is not executed. Click the Advanced Orders tab. Change the value for Transmit to 0 (row 13 on the Extended Order Attributes page). this value will be applied to all subsequent orders that you place in the spreadsheet. 4 Click the Advanced Orders tab. Enter the contract descriptions and order descriptions for all three orders on three contiguous rows: • • • The first order should be a BUY LMT order. but the system generates an Order ID. The second order should be a SELL STP order. The entire bracket order is transmitted. highlight the second order. highlight the third order in the bracket order.ActiveX for Excel Advanced Orders Page Placing a Bracket Order Bracket orders in the ActiveX for Excel sample spreadsheet require the use of the extended order attributes Transmit and Parent Order Id. then click the Place/Modify Order button. 5 Copy the Order ID for the first order. then click the Extended Order Attributes tab and paste the Order ID into the Value field for Parent Order Id (row 14). omitting the “id” prefix. 3 Click the Extended Order Attributes tab. When you are done placing your bracket order. 6 Click the Advanced Orders tab. If you do not. This value will be applied to all subsequent orders until you remove it from the Extended Order Attributes page. The order is not executed but is now associated with the primary order by means of the Parent Order Id extended order attribute. You must turn Transmit off until the order is completely set up.

ActiveX for Excel Advanced Orders Page Placing a Volatility Order In the ActiveX for Excel sample spreadsheet. Select a contract and set up the order using the Order Description fields. 4 Click the Extended Order Attributes tab. If the price of the underlying instrument rises above the higher stock range price. Enter 1 to use the average of the best bid and ask.Enter a low-end acceptable stock price relative to the selected option order.This value is used to compute the limit price sent to an exchange and for stock range price monitoring.Enter a high-end acceptable stock price relative to the selected option order. enter values in the Value field for the following optional extended order attributes: • Underlying Range (Low) . Enter this value as a percentage.optional To place a VOL order 1 2 3 Click the Advanced Orders tab at the bottom of the spreadsheet.Enter 1 for daily volatility or 2 for annual volatility.optional Underlying Range (High) . If the price of the underlying instrument falls below the lower stock range price.optional Hedge Delta Order Type .Enter 1 to automatically update the option price as the underlying stock price (or futures price.1712. or 2 to use NBB (bid) when buying a call or selling a put. • Enter VOL in the Order Type field. the option order will be canceled. for index options) moves. • • • 5 On the Extended Order Attributes page. or the NBO (ask) when selling a call or buying a put. Continuous Update . enter 17.optional Hedge Delta Aux Price .12 instead of . not as the market data is displayed. Define a contract by typing a symbol in a blank Symbol field. • API Reference Guide 352 . Underlying Range (High) . For example. you place VOL orders by entering values for the following extended order attributes: • • • • • • • • Volatility Volatility Type Reference Price Type Continuous Update Underlying Range (Low) . Enter 0 if you do not want to use this feature. Enter values in the Value field for the following extended order attributes: • Volatility .This value represents the volatility to use in calculating a limit price for the option. Volatility Type . the option order will be canceled. then entering information in the relevant contract description fields. Reference Price Type .

4 Click the Extended Order Attributes tab. 8 9 Placing a Trailing Stop Limit Order In TWS. enter the price as the value for this attribute.Enter LMT. these values will be applied to all subsequent orders that you place in the spreadsheet. you enter the trailing amount.ActiveX for Excel Advanced Orders Page • Hedge Delta Order Type . To create a Trailing Stop Limit Order 1 2 3 Click the Advanced Orders tab at the bottom of the spreadsheet. Click the Apply Extended Template button. When you are done placing VOL orders. Specify the trailing stop price as an extended order attribute. You must include the limit offset in the stop price (the Trail Stop Price extended order attribute).Limit Offset API Reference Guide 353 . then highlight the order row. Define a contract by typing a symbol in a blank Symbol field. Hedge Delta Aux Price . there are four values that make up a trailing stop limit order: • • • • trailing amount stop price limit price limit offset In the ActiveX for Excel API spreadsheet. Enter NONE if you do not want to use delta hedging. stop price and limit price. For a sell order: Trail Stop Price = Limit Price . With the order row highlighted. Enter TRAILLIMIT in the Order Type field. click the Place/Modify Order 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. Enter the limit price in the Lmt Price field. There is no field or extended order attribute for the limit offset value.Trailing Amount .If you have entered LMT or REL as the Hedge Delta Order Type. then entering information in the relevant contract description fields. • • • • Enter BUY or SELL in the Action field. Enter the trailing amount in the Aux Price field. • 6 7 Click the Advanced Orders tab. • The Trail Stop Price value must include the limit offset. MKT or REL. Select a contract and set up the order using the Order Description fields. go to the Extended Order Attributes page and delete the VOL order values you entered. Type this value in the Trail Stop Price Value field. If you do not.

order component. Click the Place/Modify Order button. • Note: 5 On the Advanced Orders page. Enter values in the Value field for the following extended order attributes: • Scale Component Size .Enter the amount used to calculate the per-unit price of each component in the scale ladder. Scale Price Increment . this value will be applied to all subsequent orders that you place in the spreadsheet. The Trail Stop Price value is applied to the selected order and displayed in the Trail Stop Price field in the Extended Order Attributes section of the page. these values will be applied to all subsequent orders that you place in the spreadsheet. As of API Release 9. go to the Extended Order Attributes page and delete the scale order values you entered. Click the Place/Modify Order button. Select a contract and set up the order using the Order Description fields. If you do not.Enter the size of the first. select the order row and click the Apply Extended Template button. or initial. then entering information in the relevant contract description fields. The scale order values are applied to the selected order and displayed in the Extended Order Attributes section of the page. This cannot be a negative number. go to the Extended Order Attributes page and delete the Trail Stop Price value you entered. 6 7 Placing a Scale Order In the ActiveX for Excel sample spreadsheet. if you submit a 10. The order type should be LMT or REL.41.ActiveX for Excel Advanced Orders Page For a buy order: Trail Stop Price = Limit Price + Trailing Amount + Limit Offset 5 On the Advanced Orders page. When you are done placing your order. the Scale Num Components not supported. 6 7 API Reference Guide 354 . select the order row and click the Apply Extended Template button.000-share order with a Scale Component Size value of 1000. If you do not. you place scale orders by entering values for the following extended order attributes: • • Scale Component Size Scale Price Increment To place a scale order 1 2 3 4 Click the Advanced Orders tab at the bottom of the spreadsheet. the first component will be fore 1000 shares. For example. Click the Extended Order Attributes tab. When you are done placing your order. Define a contract by typing a symbol in a blank Symbol field.

Clears all order status information from the page. Applies the current values on the Extended Order Attributes page to the highlighted order row. 6 7 Advanced Orders Page Toolbar Buttons The toolbar on the Advanced Orders page includes the following buttons: Button Create Ticker Combo Legs Apply Extended Template Place/Modify Orders Description Opens the Ticker box. Click the Place/Modify Order button. Opens the Combination Legs box. Enter information to create a market data line. Enter contract details to create legs of a combination order one by one. After you have completed the Order Description fields. and defined any extended attributes. To place a relative order 1 2 3 Click the Advanced Orders tab at the bottom of the spreadsheet. Enter a percentage in decimal form in the Value field for the Percent Offset extended order attribute. When you are done placing your order.ActiveX for Excel Advanced Orders Page Placing a Relative Order In the ActiveX for Excel sample spreadsheet. you place relative orders by entering a value for the Percent Offset extended order attribute. 4 5 Click the Extended Order Attributes tab. API Reference Guide 355 . • • Enter REL as the order type. but the order will NOT be placed. Enter the price cap in the Lmt Price cell. you will receive margin and commission data as if the order were placed. select the order row and click the Apply Extended Template button. Select a contract and set up the order using the Order Description fields. Cancel Order Clear Order Statuses There is also a WhatIf check box on the toolbar. When checked. Define a contract by typing a symbol in a blank Symbol field. The percent offset value is applied to the selected order and displayed in the Extended Order Attributes section of the page. this value will be applied to all subsequent orders that you place in the spreadsheet. If you do not. go to the Extended Order Attributes page and delete the Percent Offset value you entered. click to create an order for the selected contract. then entering information in the relevant contract description fields. On the Advanced Orders page. This button cancels the selected order(s).

Once you define the attributes on this page. which occurs on both the Orders page and the Conditional Orders page. see Extended Order Attributes. such as setting a display size to create an iceberg order. API Reference Guide 356 .ActiveX for Excel Extended Order Attributes Page Extended Order Attributes Page The Extended Order Attributes page includes all of the optional attributes you can use when you send an order. adding orders to an OCA group. and setting the transmit date for a Good After Time order. For a complete list of extended order attributes supported by the API. The attributes populate the extended order attributes fields that follow the Order Status fields to the far right of the page. you can apply them to a single order or selected group of orders using the Apply Extended Template button.

values that you enter on the Extended Order Attributes page apply to all subsequent orders. the extended order attribute values you entered are applied to the order. For any attribute that is not defined. To apply extended order attributes to individual orders or a group of orders 1 2 3 Enter the value or values on the Extended Order Attributes page that you want to apply to an individual order or group of orders. On the Orders page. Note: You can also use this procedure to apply extended order attributes to orders on the Conditional Orders page. with the primary exchange "ISLAND" separating the extended attributes: =psmith12|ord!'id1814454745?place?BUY_1_MSFT_STK_SMART_USD_LMT_26 _{}_DAY_{}_{}_O_0_{}_1_{}_0_0_0_0_0_0_{}_{}_{}_{}_{}_{}_{}_{}_ISL AND_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_1_2_3_4_5' • • Apply Extended Order Attributes to Individual Orders and Groups of Orders Normally. you would enter the number for the Order Ref attribute on the Extended Order Attributes page. These values will still apply to all subsequent orders that you place from the ActiveX for Excel API spreadsheet unless you remove the value. When you place the order or group of orders. For example. To do this. we recommend using the open/close curly braces {}. select the order or group of orders. you might want to assign a unique Order Ref number to a group or basket of orders. 4 Delete the value of the extended order attributes you used for the order from the Extended Order Attributes page.ActiveX for Excel Extended Order Attributes Page Manually Program Extended Order Attributes Observe the following guidelines when you manually assign an attribute: • When appended to orderDescription. 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 Attributes page are added to the corresponding fields in the Extended Order Attributes section of the Orders page. However. the number and order of attributes cannot be changed. you also can apply selected attributes to an individual order or a group of orders on the Orders page. use the value 'EMPTY' or {}. A place order message for a simple stock limit day order looks as follows. Since a string length is limited to 255 characters. API Reference Guide 357 . then select all the orders in the group on the Orders page and click Apply Extended Template.

with the Status value changed to FILLED. Once an order executes. and those that are working at an exchange.ActiveX for Excel Open Orders Page Open Orders Page The Open Orders page shows you all transmitted orders. the page is updated each time you submit a new order. API Reference Guide 358 . either through the API or in TWS. it remains on the Open Orders page for 30 seconds. Once you have subscribed. Then the filled order is cleared and you can see it on the Executions page if you subscribed to real-time executions. including those that have been accepted by the IB system.

including orders you enter in the spreadsheet and in TWS. and that you have connected the spreadsheet to TWS. click Subscribe to Open Orders on the toolbar. Queries TWS and associate all newly created TWS orders with the current client.ActiveX for Excel Open Orders Page Viewing Open Orders Note: Ensure that TWS is running. click Request All Open Orders on the toolbar. Orders that fill remain on the page for 30 seconds with a value of Fill in the Status field. Do one of the following: • To request open orders from the current ActiveX for Excel spreadsheet. Click the Clear Open Orders button. To view open orders: 1 2 Click the Open Orders tab at the bottom of the spreadsheet. To remove open orders 1 2 Click the Cancel Open Orders Subscription button on the toolbar. Once you subscribe to open orders. this page updates each time there is a new open order. this page updates each time there is a new open order. Queries TWS and returns all open orders from the current account. Note that the Client ID must be 0. click Request Auto Open Orders on the toolbar. To associate all newly created TWS orders with the current client. which must be Client ID 0. Open Orders Tab Toolbar The toolbar on the Open Orders page includes the following buttons: Button Request Open Orders Description Queries TWS and returns all open orders. Once you subscribe to open orders. Request All Open Orders Request Auto Open Orders Cancel Auto Open Orders Clear Open Orders API Reference Guide 359 . To request all open orders for the current account. • • All of the requested open orders are displayed on the page. Cancels association of newly created TWS orders with the client Removes all open orders from the page.

To remove account information 1 2 API Reference Guide Click the Account tab at the bottom of the spreadsheet. View your current portfolio. View list of advisor-managed account codes. Click Cancel Account Updates on the toolbar to stop receiving account updates. To view account information 1 2 Click the Account tab at the bottom of the spreadsheet. Using the Account Page Note: Ensure that TWS is running.ActiveX for Excel Account Page Account Page Use the Account page to: • • • • View account details including your current Equity with Loan Value and Available funds. and that you have connected the spreadsheet to TWS. Financial Advisors can view FA information. Click Request Account Updates on the toolbar. 360 .

In the FA Data Type cell. API Reference Guide 361 . 4 Click Request Managed Accounts on the toolbar. In the Account Code cell. Type 3 for account aliases. Click Request Managed Accounts on the toolbar. type the account code for which you want details. To request Financial Advisor (FA) information 1 2 3 Click the Account tab at the bottom of the spreadsheet.ActiveX for Excel Account Page 3 Click Clear Account Data on the toolbar to clear all data from the page. A comma-separated list of all managed account numbers displays in the Managed Accounts cell. To request the list of Financial Advisor (FA) managed account codes 1 2 Click the Account tab at the bottom of the spreadsheet. Type 2 for profiles. enter a numeric value representing the type of data you wish you receive: • • • Type 1 for groups.

For advisor accounts. When you get a line of "0's" you know you have downloaded all current positions. Button Request Account Updates Description Each click gives you data for a specific account value. For advisor accounts. You must first cancel your subscription before you can clear the data.ActiveX for Excel Account Page Account Page Toolbar Buttons The toolbar on the Account page includes the following buttons. All blank lines that precede the Account Portfolio section will hold data. Cancel Account Updates Request Managed Accounts Request FA Clear Account Data API Reference Guide 362 . Continue to click until all lines are populated. Clears all information from the page. receives a list of managed accounts and displays them as a comma-separated list in the Management Accounts cell. displays FA data of the type specified in the FA Data Type cell. Click this button one time for each position you hold. These values continue to update in real-time.

• • 3 API Reference Guide Click Exercise Options in the toolbar. Exercising Options You can exercise options or let options lapse on the Portfolio page.Enter 1 to override the system’s natural action. Exercise Quantity . 363 . Note: Viewing Your Portfolio To view your portfolio 1 2 Click the Account tab on the bottom of the worksheet. Override .Enter 1 to exercise the selected option. Ensure that TWS is running. Click the Clear Portfolio Data button to clear all data from the page. Exercise options. then click Request Account Updates on the toolbar.ActiveX for Excel Portfolio Page Portfolio Page Use the Portfolio page to: • • Displays all of your current positions. Click the Portfolio tab at the bottom of the worksheet to view your portfolio. To remove portfolio information 1 2 Click the Account tab on the bottom of the worksheet.Enter the number of contracts you wish to exercise or let lapse. To exercise an option or let an option lapse 1 2 Click the Portfolio tab at the bottom of the worksheet. The Status column updates. Enter values in the Exercise Options Parameters cells at the far right side of the page: • Exercise Action . 2 to not override. 2 to let the option lapse. and that you have connected the spreadsheet to TWS. then click Cancel Account Updates on the toolbar to stop receiving portfolio updates.

ActiveX for Excel Portfolio Page Portfolio Page Toolbar Buttons The toolbar on the Portfolio page includes the following buttons. Removes all data from the page. depending on the value in the Exercise Action cell. Clear Portfolio Data API Reference Guide 364 . Button Exercise Options Description Exercises the selected option or lets the selected option lapse.

ActiveX for Excel Executions Page Executions Page When you subscribe to executions. API Reference Guide 365 . the Executions page displays information about all completed trades.

security type. Clear Executions Table API Reference Guide 366 . To remove execution data 1 Click Clear Executions Table on the toolbar. exchange or side. After you subscribe to executions. this page updates each time an order executes. account code. All data is removed from the page. Executions Page Toolbar Buttons The toolbar on the Executions page includes the following buttons: Button Request Executions Description Queries TWS and returns information about all valid executions. 3 Click Request Executions on the toolbar. symbol. Removes all execution reports from the page. To view executions 1 2 Click the Executions tab at the bottom of the spreadsheet.ActiveX for Excel Executions Page Viewing Executions Note: Ensure that TWS is running. Optionally. and that you have connected the spreadsheet to TWS. date/time. filter your executions by entering values in the Execution Filter cells: • Filter executions by client ID.

Note: For a information about historical data request limitations. API Reference Guide 367 .ActiveX for Excel Historical Data Page 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. see Historical Data Limitations.

The status of your request displays in the Request Status cell. then click the Request Historical Data button. Enter FALSE to display the page on a separate tab in the spreadsheet without displaying on top of the current window. 3 4 2 3 4 API Reference Guide 368 . In the Activate Page cell. or by clicking the Create Ticker button on the toolbar and entering the required information in the Ticker box. 5 Historical data queries on expired contracts are limited to the last year of the life of the contract. Create a ticker by filling in the fields in the Contract Description section of the page. To request historical data for expired contracts 1 On the Historical Data page. The status of your request displays in the Request Status cell. the name of which is specified in the Page Name cell. Enter the parameters of your query in the Query Specification fields. Select the line. or by clicking the Create Ticker button on the toolbar and entering the required information in the Ticker box. The results are displayed on a new tabbed page in the spreadsheet. For complete descriptions of the query fields. The results are displayed on a new tabbed page in the spreadsheet. Historical Data Page Query Specification Fields. Enter FALSE to display the page on a separate tab in the spreadsheet without displaying on top of the current window. Enter the parameters of your query in the Query Specification fields. Select the line. create a ticker by filling in the fields in the Contract Description section of the page. In the Activate Page cell. and that you have connected the spreadsheet to TWS.ActiveX for Excel Historical Data Page Viewing Historical Data Note: Ensure that TWS is running. enter TRUE to display the results page on top of the current window. enter TRUE to display the results page on top of the current window. To request historical data 1 2 Click the Historical Data tab at the bottom of the spreadsheet. then click Request Historical Data on the toolbar. the name of which is specified in the Page Name cell. enter TRUE. In the Incl Expired cell in the Query Specification section.

API Reference Guide 369 .ActiveX for Excel Historical Data Page The following figure shows a typical historical data results page.

each "bar" is represented by a line in the spreadsheet. If no unit is specified. and the value in each line is equal to one second. where valid units are: • • • S (seconds) D (days) W (weeks) Duration • Y (years) This unit is currently limited to one. and is specified using the format integer {space} unit. API Reference Guide 370 . seconds are used. and are specified using the parametric value: Bar Size String Integer Value 1 second 1 5 seconds 2 15 seconds 3 30 seconds 4 1 minutes 5 2 minutes 6 3 minutes 16 5 minutes 7 15 minutes 8 30 minutes 9 1 hour 10 1 day 11 1 week 12 1 month 13 3 months 14 1 year 15 On the query return page. This is the time span the request will cover. Bar Size Specifies the size of the bars that will be returned.ActiveX for Excel Historical Data Page Historical Data Page Query Specification Fields Parameter End Date/Time Description Use the format yyyymmdd {space}hh:mm:ss{space}tmz where the time zone is allowed (optionally)after a space at the end. Note that you can use either the Integer value of the Bar Size String or the Integer Value to define the bar sizes. The following bar sizes may be used. and a bar size of "1" (one second) your return will include 300 lines. or is a one-second bar. If you specify a duration of 300 seconds.

low. including time intervals when the market in question was outside of regular trading hours. API Reference Guide 371 . close. Note that the new page is added to the right of the existing tabs on the worksheet. This appears in the tab for the results page at the bottom of the worksheet. • Date Format Style Valid values include: • • Page Name Activate page The name of the results page. Valid values include: • • • • Trades Midpoint Bid Ask • Bid/Ask All but the Bid/Ask data contain the start time. RTH Only Regular Trading Hours only. 1 .the dates are returned as an integer specifying the number of seconds since 1/1/1970 GMT.all data available during the time span requested is returned.only data within the regular trading hours for the product requested is returned.ActiveX for Excel Historical Data Page Parameter What to Show Description Determines the nature of the data extracted. 1 . Enter TRUE to display the results page on top of the current window.dates that apply to bars are returned in the format yyyymmdd{space}{space}hh:mm:dd (the same format used when reporting executions). the open and close values are the time-weighted average bid and the time-weighted average offer. Valid values include: • 0 . even if the time span falls partially or completely outside. 2 . respectively. These bars are identical to the TWS charts' candlestick bars. open. For the Bid/Ask query. volume and weighted average price during the time slice queried. high. Enter FALSE to display the results on a new page in the spreadsheet without appearing on top of the current window.

Cancels the historical data request. Request Historical Data Cancel Historical Data API Reference Guide 372 . Button Create Ticker Combo Legs Description Opens the Ticker box. Enter contract details to create legs of a combination order one by one. Submits your historical data query to TWS and displays the results on a separate worksheet page.ActiveX for Excel Historical Data Page Historical Data Page Toolbar Buttons The toolbar on the Historical Data page includes the following buttons. Enter information to create a market data line. Opens the Combination Legs box.

API Reference Guide 373 . To request contract details for an expired contract. Enter FALSE to display the page on a separate tab in the spreadsheet without displaying on top of the current window. valid exchanges.ActiveX for Excel Contract Details Page Contract Details Page Use the Contract Details page to request contract-specific information such as supported order types. Requesting Contract Details Note: Ensure that TWS is running. Select the row. In the Activate Page cell. then click Request Contract Details on the toolbar. and that you have connected the spreadsheet to TWS. The status of your request displays in the Request Status cell. type TRUE in the Incl Expired cell. Select or enter the ticker symbol for which you want to request contract details. the contract ID. and so on. enter TRUE to display the results page on top of the current window. To request details for a contract 1 2 3 4 Click the Contract Details tab at the bottom of the spreadsheet to open the Contract Details page.

API Reference Guide 374 .ActiveX for Excel Contract Details Page The results are displayed on a new tabbed page in the spreadsheet. Contract Details Page Toolbar Buttons The toolbar on the Contract Details page includes the following button: Button Request Contract Details Description Returns information on the selected contract. The following figure shows a typical contract details page. the name of which is specified in the Page Name cell.

ratings. and that you have connected the spreadsheet to TWS. maturity date. Requesting Bond Contract Details Note: Ensure that TWS is running. and so on. API Reference Guide 375 .ActiveX for Excel Bond Contract Details Page Bond Contract Details Page Use the Bond Contract Details page to request contract-specific information for bonds. enter TRUE to display the results page on top of the current window. then click Request Bond Contract Details on the toolbar. Select the row. bond type. The status of your request displays in the Request Status cell. To request details for a bond contract 1 2 3 Click the Bond Contract Details tab at the bottom of the spreadsheet to open the Bond Contract Details page. Select or enter the ticker symbol for which you want to request bond contract details. In the Activate Page cell. the name of which is specified in the Page Name cell. Enter FALSE to display the page on a separate tab in the spreadsheet without displaying on top of the current window. including the coupon. The results are displayed on a new tabbed page in the spreadsheet.

Bond Contract Details Page Toolbar Buttons The toolbar on the Bond Contract Details page includes the following button: Button Request Bond Contract Details Description Gets bond information data for the selected contract.ActiveX for Excel Bond Contract Details Page The following figure shows a typical bond contract details page. API Reference Guide 376 .

Click the Real Time Bars tab at the bottom of the spreadsheet to open the Real Time Bars page. Select or enter the ticker symbol for which you want to request real time bars. You request real time bars on the Real Time Bars page. To request real time bars Note: 1 2 Ensure that TWS is running. bids or asks. and that you have connected the spreadsheet to TWS.ActiveX for Excel Real Time Bars Page Real Time Bars Page Real time bars allow you to get a summary of real-time market data every five seconds. we call these five-second periods "bars"). API Reference Guide 377 . You can also get data showing trades. including the opening and closing price. and the high and the low within that five-second period (using TWS charting terminology. which is shown below. midpoints.

Real Time Bars Page Toolbar Buttons The toolbar on the Real Time Bars page includes the following buttons. The status of your request displays in the Subscription Status cell. ASK or MIDPOINT.ActiveX for Excel Real Time Bars Page 3 Enter the following information for the selected row: • • In the What to Show cell. including time intervals when the market in question was outside of regular trading hours. enter TRADES. Enter 1 to return only data within the regular trading hours for the product requested is returned. BID. Enter information to create a market data line. Clears all real time bar data from the page. Submits your real time bars request to TWS and displays the results in the dark gray cells the right side of the page. even if the time span falls partially or completely outside. then click Request Real Time Bars on the toolbar. Button Create Ticker Request Real Time Bars Description Opens the Ticker box. enter 0 to return all data available during the time span requested. Cancels the real time bars request. 4 Select the row. Cancel Real Time Bars Clear Real Time Bars Table API Reference Guide 378 . Results are displayed in the Real Time Bars cells on the right side of the page. In the RTH Only cell.

API Reference Guide 379 . The scan is continually updated in real time.ActiveX for Excel Market Scanner Page 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 x number of underlyings which meet all scan criteria. You can also display market scanner parameters from this page.

and that you have connected the spreadsheet to TWS. Setting this cell to TRUE forces the scan results page to pop to the front of your application every time it updates. Scanner parameters are returned to the spreadsheet from TWS as an XML file. Click OK to close the Scanner Parameters window. The Scanner Parameters window is shown on the next page. To stop this behavior. and that you have connected the spreadsheet to TWS. then copy and paste it into a separate text document.ActiveX for Excel Market Scanner Page Starting a Market Scanner Subscription Note: Ensure that TWS is running. 4 API Reference Guide 380 . You can get all of the scan codes from the market scanner parameters. Highlight an existing scanner row. manually select part or all of the contents of the XML file in the Scanner Parameters window. The entire scanner parameters XML file is displayed in a window. c 3 Type values for the rest of the scan parameters in the lightly shaded section of the page. A new page for the scanner is created and is displayed after the subscription is processed. 3 To save the parameters in a convenient file on your computer. Click Request Scanner Subscription on the toolbar. Type TRUE or FALSE in the Activate Page cell. To start a scanner subscription 1 2 Click the Market Scanner tab at the bottom of the spreadsheet. set the value of this field to FALSE. Note: Ensure that TWS is running. Market Scanner Parameters You can display all of the market scanner parameters from the Market Scanner page. or enter information for a different market scanner: a b Type the name of the scan results page in the Page Name cell. To view scanner parameters 1 2 Click the Market Scanner tab at the bottom of the spreadsheet. Click Request Scanner Parameters on the toolbar.

ActiveX for Excel Market Scanner Page API Reference Guide 381 .

Shows the top underlying contracts for highest options volume over a 10-day average.ActiveX for Excel Market Scanner Page Available Market Scanners The following table shows the available market scanners in the ActiveX for Excel API spreadsheet. Displays the most active contracts sorted descending by options volume. Shows the top underlying contracts (stocks or indices) with the largest divergence between implied and historical volatilities. Returns the top 50 contracts with the highest put/call ratio of outstanding option contracts. Market Scanner (Scan Code) Low Opt Volume P/C Ratio (LOW_OPT_VOL_PUT_CALL_RATIO)* High Option Imp Vol Over Historical (HIGH_OPT_IMP_VOLAT_OVER_HIST) * Low Option Imp Vol Over Historical (LOW_OPT_IMP_VOLAT_OVER_HIST) * Highest Option Imp Vol (HIGH_OPT_IMP_VOLAT)* Description Put option volumes are divided by call option volumes and the top underlying symbols with the lowest ratios are displayed. Shows the top underlying contracts (stocks or indices) with the highest vega-weighted implied volatility of near-the-money options with an expiration date in the next two months. Shows the top underlying contracts (stocks or indices) with the largest percent gain between current implied volatility and yesterday's closing value of the 15 minute average of implied volatility. Contracts whose last trade price shows the highest percent increase from the previous night's closing price. 382 Top Option Imp Vol % Gainers (TOP_OPT_IMP_VOLAT_GAIN)* Top Option Imp Vol % Losers (TOP_OPT_IMP_VOLAT_LOSE)* High Opt Volume P/C Ratio (HIGH_OPT_VOLUME_PUT_CALL_ RATIO) Low Opt Volume P/C Ratio (LOW_OPT_VOLUME_PUT_CALL_ RATIO) Most Active by Opt Volume (OPT_VOLUME_MOST_ACTIVE) Hot by Option Volume (HOT_BY_OPT_VOLUME) High Option Open Interest P/C Ratio (HIGH_OPT_OPEN_INTEREST_PUT_ CALL_RATIO) Low Option Open Interest P/C Ratio (LOW_OPT_OPEN_INTEREST_PUT_ CALL_RATIO) Top % Gainers (TOP_PERC_GAIN) API Reference Guide . Shows the top underlying contracts (stocks or indices) with the smallest divergence between implied and historical volatilities. Shows the top underlying contracts (stocks or indices) with the largest percent loss between current implied volatility and yesterday's closing value of the 15 minute average of implied volatility. Put option volumes are divided by call option volumes and the top underlying symbols with the highest ratios are displayed. Returns the top 50 contracts with the lowest put/call ratio of outstanding option contracts. Put option volumes are divided by call option volumes and the top underlying symbols with the lowest ratios are displayed.

Shows the top underlying contracts (stocks or indices) with the lowest vega-weighted implied volatility of near-the-money options with an expiration date in the next two months. Contracts with the highest number of trades in the past 60 seconds (regardless of the sizes of those trades). Top % Losers (TOP_PERC_LOSE) Hot Contracts by Volume (HOT_BY_VOLUME) Top % Futures Gainers (TOP_PERC_GAIN) Hot Contracts by Price (HOT_BY_PRICE) Futures whose last trade price shows the highest percent increase from the previous night's closing price. Contracts where: • • today's Volume/avgDailyVolume is highest. based on units used by TWS (lots for US stocks. which displays the most active contracts in the NASDAQ. The top volume rate per minute. Contracts where: • (lastTradePrice-prevClose)/avgDailyChan ge is highest in absolute value (positive or negative). avgDailyVolume is a 30-day exponential moving average of the contract's daily volume. contract for derivatives and non-US stocks). The avgDailyChange is defined as an exponential moving average of the contract's (dailyClose-dailyOpen) • Top Trade Count (TOP_TRADE_COUNT) Top Trade Rate (TOP_TRADE_RATE) Top Price Range (TOP_PRICE_RANGE) Hot by Price Range (HOT_BY_PRICE_RANGE) Top Volume Rate (TOP_VOLUME_RATE) Lowest Option Imp Vol (LOW_OPT_IMP_VOLAT) The top trade count during the day. The largest difference between today's high and low. The largest price range (from Top Price Range calculation) over the volatility. or yesterday's close if outside of today's range. and Most Active US. which displays the most active stocks in the United States. API Reference Guide 383 .ActiveX for Excel Market Scanner Page Market Scanner (Scan Code) Most Active (MOST_ACTIVE) Description Contracts with the highest trading volume today. Contracts whose last trade price shows the lowest percent increase from the previous night's closing price. NYSE and AMEX markets. The sample spreadsheet includes two Most Active scans: Most Active List.

Top Option Imp Vol % Gainers (TOP_OPT_IMP_VOLAT_GAIN)* Top Option Imp Vol % Losers (TOP_OPT_IMP_VOLAT_LOSE)* 13-Week High (HIGH_VS_13W_HL) 13-Week Low (LOW_VS_13W_HL) 26-Week High (HIGH_VS_26W_HL) 26-Week Low (LOW_VS_26W_HL) 52-Week High (HIGH_VS_52W_HL) 52-Week Low (LOW_VS_52W_HL) API Reference Guide 384 . Shows contracts with the highest percent price DECREASE between the previous close and today's opening prices. Shows contracts with the highest percent price DECREASE between the last trade and opening prices. Shows the top underlying contracts (stocks or indices) with the lowest vega-weighted implied volatility of near-the-money options with an expiration date in the next two months. Shows contracts with the highest percent price INCREASE between the previous close and today's opening prices. The lowest price for the past 26 weeks. Shows the top underlying contracts (stocks or indices) with the largest percent loss between current implied volatility and yesterday's closing value of the 15 minute average of implied volatility. The lowest price for the past 52 weeks. The highest price for the past 26 weeks. Shows contracts with the highest percent price INCREASE between the last trade and opening prices. Contracts for which trading has been halted. The lowest price for the past 13 weeks. Shows the top underlying contracts (stocks or indices) with the largest percent gain between current implied volatility and yesterday's closing value of the 15 minute average of implied volatility. The highest price for the past 13 weeks. The highest price for the past 52 weeks.ActiveX for Excel Market Scanner Page Market Scanner (Scan Code) Most Active by Opt Open Interest (OPT_OPEN_INTEREST_MOST_ ACTIVE) Not Open (NOT_OPEN) Halted (HALTED) Top % Gainers Since Open (TOP_OPEN_PERC_GAIN) Top % Losers Since Open (TOP_OPEN_PERC_LOSE) Top Close-to-Open % Gainers (HIGH_OPEN_GAP) Top Close-to-Open % Losers (LOW_OPEN_GAP) Lowest Option Imp Vol (LOW_OPT_IMP_VOLAT)* Description Returns the top 50 underlying contracts with the (highest number of outstanding call contracts) + (highest number of outstanding put contracts) Contracts that have not traded today.

as required) of the 30-day variance based on the squares of the at-market volatilities is performed. V30 is then the square root of the estimated variance. 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.High Synth Bid Rev Yield (HIGH_SYNTH_BID_REV_NAT_ YIELD) Description Highlights the highest synthetic EFP interest rates available. These rates are computed by taking the price differential between the SSF and the underlying stock and netting dividends to calculate an annualized synthetic implied interest rate over the period of the SSF. If there is no first expiration month with less than sixty calendar days to run. The implied volatilities are fit to a parabola as a function of the strike price for each expiry. The High rates may present an investment opportunity. Interest rates are calculated using the settlement prices from the day's Eurodollar futures contracts. The IB 30-day volatility is the at-market volatility estimated for a maturity thirty calendar days forward of the current trading day. Highlights the lowest synthetic EFP interest rates available. It is based on option prices from two consecutive expiration months. These rates are computed by taking the price differential between the SSF and the underlying stock and netting dividends to calculate an annualized synthetic implied interest rate over the period of the SSF. we do not calculate a V30. The first expiration month is that which has at least eight calendar days to run. and a Black-Scholes model for European style options. API Reference Guide 385 .Low Synth Bid Rev Yield (LOW_SYNTH_BID_REV_NAT_ YIELD) *30-day (V30) Implied Volatilities: Implied volatility is calculated using a 100-step binary tree for American style options. The implied volatility is estimated for the eight options on the four closest to market strikes in each expiry. and dividends are based on historical payouts. The Low rates may present a borrowing opportunity.ActiveX for Excel Market Scanner Page Market Scanner (Scan Code) EFP . EFP .

ActiveX for Excel Market Scanner Page Market Scanner Page Toolbar Buttons The toolbar on the Market Scanner page includes the following buttons. Cancels the market scanner. Button Request Scanner Parameters Request Scanner Subscription Cancel Scanner Subscription Description Displays all scanner parameters in an XML file in a separate window. API Reference Guide 386 . Creates and displays a new page for results of the selected market scanner.

Enter information about the contract for which you want fundamentals data or ratios into the Contract Description cells. Click the Fundamentals tab at the bottom of the spreadsheet to display the Fundamentals page.Financial Statement estimates . To receive Reuters global fundamental data and fundamental ratios Note: 1 2 3 Ensure that TWS is running.Summary API Reference Guide 387 . In the Report Type cell. enter the type of report you wish to view: • • • finstat . and that you have connected the spreadsheet to TWS.Estimates snapshot . There must be a paid subscription to Reuters Fundamental set up in Account Management before you can receive this data.ActiveX for Excel Fundamentals Page Fundamentals Page Use the Fundamentals page to receive Reuters global fundamental data and fundamental ratios.

Fundamentals Page Toolbar Buttons The toolbar on the Market Scanner page includes the following buttons. which displays on a new page in the spreadsheet based on the information you enter on the page.ActiveX for Excel Fundamentals Page 4 5 In the Generic Tick Type cell. Click Fundamentals Ratios on the toolbar to view fundamentals ratios. Cancels fundamentals ratios. Setting this cell to TRUE forces the results page to pop to the front of your application every time it updates. For details on generic tick type values. Button Request Fundamentals Description Requests fundamentals data. • The status of your request appears in the Subscription Status cell. Requests fundamentals ratios. Cancel Fundamentals Fundamental Ratios Cancel Fundamental Ratios API Reference Guide 388 . Enter the following information in the Fundamentals section of the page for fundamental data. To stop this behavior. or the Fundamental Ratios section for fundamental ratios: a b Fundamental data and ratio results display on a new page in the spreadsheet. 6 Do one of the following: • Click Request Fundamentals on the toolbar to view fundamentals data. which displays on a new page in the spreadsheet based on the information you enter on the page. see Generic Tick Types. Type the name of the results page in the Page Name cell. set the value of this field to FALSE. A new page for the results is created and is displayed after the request is processed. enter 258 as the tick type value. A new page for the results is created and is displayed after the request is processed. Cancels fundamentals data. Type TRUE or FALSE in the Activate Page cell.

use the Advisors page to create FA orders that: • • • allocate shares to a single managed account use FA account groups and methods use allocation profiles Note: You must set up your managed accounts.ActiveX for Excel Advisors Page Advisors Page If you are a Financial Advisor and manage multiple accounts. methods and allocation profiles in TWS before you can place FA orders in the ActiveX for Excel API sample spreadsheet. account groups. API Reference Guide 389 .

Click the Advisors tab at the bottom of the spreadsheet. then click the Apply Extended button to apply the Account order attribute value to the order. The Account value is applied to the selected order and displayed in the Extended Order Attributes section of the page. Deselect the check box to place your order without seeing the margin and commission information ahead of time. you can receive margin and commission information that would result from the order if you placed it by selecting the WhatIf check box on the toolbar.ActiveX for Excel Advisors Page Allocating Shares to a Single Account You can use the Advisors page to set up an order and allocate all shares in the order to a single account. Enter the account code in the Value cell for the Account (Institutional only) extended order attribute. Click the Place/Modify Order button. In this case. If you do not delete this value. API Reference Guide 390 . it will be applied to all subsequent orders placed from the ActiveX for Excel spreadsheet. Create an account group in TWS. your order is not actually placed. Click the Extended Order Attributes tab. delete the Account value from the Extended Order Attributes page. To allocate shares to a single account: Note: 1 2 3 4 5 6 Ensure that TWS is running. Click the Advisors tab. Enter the contract information in the Contract Description cells. then enter the order information in the Order Description cells. Highlight the order row. When you are done allocating shares to the account. and that you have connected the spreadsheet to TWS. 7 8 Optionally.

To place an order using an FA account group and FA method: 1 2 3 4 Create the FA account group(s) and FA method(s) in TWS.Enter the name of the account group. Enter values for the following extended order attributes: • • • FA Group . you can receive margin and commission information that would result from the order if you placed it by selecting the WhatIf check box on the toolbar. 5 6 Click the Advisors tab.ActiveX for Excel Advisors Page Placing an Order using an FA Account Group and Method You can also use the Advisors page to set up an order using an FA account group and FA method. Deselect the check box to place your order without seeing the margin and commission information ahead of time. API Reference Guide 391 . 7 8 Optionally. 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. When you are done allocating shares to the account.Enter the name of the allocation method to use for this order. Click the Place/Modify Order button. Click the Advisors tab at the bottom of the spreadsheet. FA Percentage . delete the values you entered on the Extended Order Attributes page. Enter the contract information in the Contract Description cells. they will be applied to all subsequent orders placed from the ActiveX for Excel spreadsheet. then click the Apply Extended button to apply the extended order attribute values to the order. In this case. Highlight the order row. FA Method . Click the Extended Order Attributes tab. your order is not actually placed.Enter the percentage used by the PctChange allocation method to use for this order. This attribute applies only to FA groups that use this method. If you do not delete these values. then enter the order information in the Order Description cells.

then click the Apply Extended button to apply the extended order attribute value to the order. Enter the contract information in the Contract Description cells. you can receive margin and commission information that would result from the order if you placed it by selecting the WhatIf check box on the toolbar. then enter the order information in the Order Description cells. 7 8 Optionally. delete the FA Profile value you entered on the Extended Order Attributes page. your order is not actually placed. API Reference Guide 392 . The value for FA Profile is applied to the selected order and displayed in the Extended Order Attributes section of the page. Highlight the order row. Enter the name of the allocation profile in the Value field for the FA Profile extended order attribute. Click the Advisors tab. Deselect the check box to place your order without seeing the margin and commission information ahead of time. To place an order using an FA allocation profile: 1 2 3 4 5 6 Create the FA allocation profile in TWS. it will be applied to all subsequent orders placed from the ActiveX for Excel spreadsheet.ActiveX for Excel Advisors Page Placing an Order using an Allocation Profile You can also use the Advisors page to set up an order using an FA allocation profile. Click the Extended Order Attributes tab. If you do not delete this value. In this case. When you are done allocating shares to the account. Click the Advisors tab at the bottom of the spreadsheet. Click the Place/Modify Order button.

Clears all information from the Order Status cells. After you have completed the Order Description fields. This button cancels the order(s) you have highlighted. Enter contract details to create legs of a combination order one by one. Opens the Combination Legs box. and defined any extended attributes.ActiveX for Excel Advisors Page Advisors Page Toolbar Buttons The toolbar on the Basic Orders page includes the following buttons: Button Create Ticker Combo Legs Apply Extended Template Place/Modify Orders Description Opens the Ticker box. click to create an order for the selected contract. Cancel Order Clear Order Statuses API Reference Guide 393 . Enter information to create a market data line. Applies the current values on the Extended Order Attributes page to the highlighted order row.

Here is an example of a typical Log page: API Reference Guide 394 .ActiveX for Excel Log Page Log Page The Log page displays all error messages received while logged into TWS and using the ActiveX for Excel spreadsheet. You can clear all the information on the page by clicking Clear Log on the toolbar.

To run the POSIX test client on a Windows machine. see Running the POSIX Client on a Windows Machine. The API installation directory includes these directories for the POSIX API: PosixSocketClient and TestPosixSocketClient. The POSIX API is based on our C++ API code. plus it exposes several extra methods that clients must call when data is available on a socket for read/write. you must recompile your client applications. The C++ code was refactored so it could be built on any POSIX-compliant platform. Note: We also include a POSIX test client. For real POSIX API applications. API Reference Guide 395 . Use this new POSIX API to build a TWS API on Linux.POSIX This chapter describes the POSIX API. Refer to TestPosixSocketClient as an example. Please note that this test client is greatly simplified. you will have to use a select system of some kind to manage several sockets and/or asynchronous events. 8 Although the pre-existing public interface has been preserved. and on Windows in non-MFC applications. The POSIX test client uses the same methods as the C++ Socket client.

. In the example below.POSIX Running the POSIX Client on a Windows Machine Running the POSIX Client on a Windows Machine To run the POSIX client on a Windows machine 1 Run vcvars32..win at the command prompt. 4 Type nmake -f Makefile.bat is located in C:\Program Files\Microsoft Visual Studio 8\VC\bin\. TestPosixSocketClient is located in the C:\IB_API_963.\TestPosixSocketClient directory.bat successfully. 5 Now run the POSIX sample application by running PosixSocketClientTest. 2 If you ran vcvars32..exe in the same C:\. the command prompt should look like this: 3 Navigate to C:\. In the example below.. \TestPosixSocketClient in the same command prompt window. vcvars32. API Reference Guide 396 .bat at the command prompt.

Reference Tables This chapter includes the following TWS API reference information: • • • • • • • • 9 API Message Codes Tick Types Generic Tick Types TAG Values for FUNDAMENTAL_RATIOS tickType Supported Order Types Extended Order Attributes Available Market Scanners IBAlgo Parameters API Reference Guide 397 .

Relative orders for US stocks can only be submitted to SMART. VWAP orders must be routed through the VWAP exchange. No request tag has been found for order: No record is available for conid: No market rule is available for conid: Buy price must be the same as the best asking price. Can't modify a filled order. INSTINET. The block order size must be at least 50. Duplicate order ID. SMART_ECN. API Reference Guide 398 . System and Warning message codes and their descriptions. Message codes shown below that end with a colon ( : ) display additional information. The price does not conform to the minimum price variation for this contract. The TIF (Tif type) and the order type are incompatible. Can't transmit order ID: Cannot transmit incomplete order. or PRIMEX. Invalid BD flag for the order. The Tif option should be set to DAY for MOC and LOC orders. It is too late to place a VWAP order for today. Check "Destination" and "BD" flag. Error Codes Code 100 101 102 103 104 105 106 107 109 110 111 113 114 115 116 117 118 119 120 121 122 123 124 125 126 129 Description Max rate of messages per second has been exceeded.Reference Tables API Message Codes API Message Codes This section lists all of the API Error. Price is out of the range defined by the Percentage setting at order defaults frame. Duplicate ticker ID. VWAP orders must be submitted at least three minutes before the start time. Relative orders are valid for stocks only. Sell price must be the same as the best bidding price. The order will not be transmitted. Order being modified does not match original order. The order cannot be transmitted to a dead exchange. Only VWAP orders may be placed on the VWAP exchange. Max number of tickers has been reached.

Cancel attempted when order is not in a cancellable state. Orders cannot be transmitted for a halted security. 399 145 146 147 148 151 152 153 154 155 156 157 158 159 160 161 162 163 API Reference Guide .” Error in validating entry fields Invalid trigger method. A conditional order can only be submitted when the order type is set to limit or market. Can't find order with ID = This order cannot be cancelled. A SizeOp order must go to IBSX An order can be EITHER Iceberg or Discretionary. The size value cannot be zero. The "hidden" order attribute may not be specified for this order. The price specified would violate the percentage constraint specified in the default order settings. To adjust the share allocation. The conditional contract info is incomplete. A sizeOp order must have a username and account. and will be ignored. This order cannot be transmitted without a clearing account. Modify order failed. You must specify an offset amount or a percent offset value. Submit new order failed. VWAP orders can only be cancelled up to three minutes before the start time. Order size does not match total share allocation. The percent offset value must be between 0% and 100%. EFPs can only be limit orders. Order permId = Historical market data Service error message. Please remove either the Discretionary amount or the Display size. This order cannot be transmitted without a user name. right-click on the order and select “Modify > Share Allocation.Reference Tables API Message Codes Code 131 132 133 134 135 136 137 138 139 140 141 142 143 144 Description The sweep-to-fill flag and display size are only valid for US stocks routed through SMART. Could not parse ticker request: Parsing error: The size value should be an integer: The price value should be a double: Institutional customer account does not have account info Requested ID is not an integer number.

the request has been ignored. HMDS Expired Contract Violation. Discretionary amount does not conform to the minimum price variation for this contract. Stock combo legs are restricted to SMART order routing. VWAP order time must be in the future.Reference Tables API Message Codes Code 164 165 166 167 168 Description There is no market data to check price percent violations.Reason: The security <security> is not available or allowed for this account. Can't find the subscribed market depth with tickerId: The origin is invalid. Code 200 201 202 203 Description No security definition has been found for the request. The combo details are invalid.Reason: Order cancelled . Historical market Data Service query message. The combo details for leg '<leg number>' are invalid. Code 300 301 302 303 304 305 306 307 308 309 Description Can't find EId with ticker Id: Invalid ticker action: Error parsing stop ticker string: Invalid action: Invalid account value action: Request parsing error. Error processing DDE request: Invalid request topic: Unable to create the 'API' page in TWS as the maximum number of pages already exists. however API clients may make multiple market depth requests for the same security. This same restriction applies to API clients. 310 311 312 313 314 315 API Reference Guide 400 . Note: TWS currently limits users to a maximum of 3 distinct market depth requests. Order rejected . Max number (3) of market depth requests has been reached. Security type 'BAG' requires combo leg details.

: 20031126 15:59:00 EST Note that there is a space between the date and time.: 15:59:00 EST Note that there is a space between the time and the time zone. local time is assumed. The time or time zone is invalid. Only FA or STL customers can request managed accounts list. Unable to connect as the client id is already in use. current date is assumed. The correct format is hh:mm:ss xxx where xxx is an optionally specified time-zone.%s Server error when reading a DDE client request (missing information). Server error when validating an API client request. Retry with a unique client id. Market depth data has been RESET. Invalid log level <log level> Server error when reading an API client request. and between the time and time-zone. If no time-zone is specified.g. E. Discretionary orders are not supported for this combination of exchange and order type. If no date is specified. Internal error. Please re-subscribe. Invalid Good Till Date order Invalid delta: The delta must be between 0 and 100. Please empty deep book contents before applying any new entries. Trailing stop orders can be attached to limit or stop-limit orders only. The date. E. local time-zone is assumed.Reference Tables API Message Codes Code 316 317 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 Description Market depth data has been HALTED. time. Cannot change to the new order type. Server error: cause . The account codes for the order profile are invalid.g. Server error when processing an API client request. Only API connections with clientId set to 0 can set the auto bind TWS orders property. Invalid share allocation syntax. Order modify failed. If no time zone is specified. or time-zone entered is invalid. The correct format is yyyymmdd hh:mm:ss xxx where yyyymmdd and xxx are optional. 337 API Reference Guide 401 . FA or STL does not have any managed accounts.

Not an institutional account or an away clearing account. Short sale slot value of 1 requires no location be specified. or time-zone entered is invalid. Short sale slot value must be 1 (broker holds shares) or 2 (delivered from elsewhere). and between the time and time-zone. local time-zone is assumed.type must be SSHORT to specify short sale slot. E. Generic combo does not support "Good After" attribute. 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 API Reference Guide 402 . Futures spread are no longer supported. Pegged order is not supported on this exchange. Valid values are from 1 to 100. Minimum quantity is not supported for best combo order. Not subscribed to requested market data. If no date is specified. Invalid trigger price. Short sale slot value of 2 (delivered from elsewhere) requires location. Please use combos instead. Invalid improvement amount for box auction strategy.: 20031126 15:59:00 EST Note that there is a space between the date and time. Invalid delta. Generic combo is not supported for FA advisor account. Smart combo child order not supported. Order size does not conform to market rule. current date is assumed. time. The "Regular Trading Hours only" flag is not valid for this order.Reference Tables API Message Codes Code 338 339 340 341 Description Good After Time orders are currently disabled on this exchange. Smart-combo order does not support OCA group. You can set the delta from the "Pegged to Stock" section of the Order Ticket Panel. If no time-zone is specified. Your client version is out of date. The correct format is yyyymmdd hh:mm:ss xxx where yyyymmdd and xxx are optional. or by selecting Page/Layout from the main menu and adding the Delta column. No whatif check support for smart combo order.g. The account logged into is not a financial advisor account. The date. Order not a short sale -. Invalid adjusted stop price. Combo order only supports reduce on fill without block(OCA).

Order size is smaller than the minimum requirement. Delta hedge order type requires that no delta hedge aux. price. price be specified. Do not set it for other order types. Duplicate ticker ID for API historical data query. Supplied routed order ID is not unique. No scanner subscription found for ticker id: No historical data query found for ticker id: Volatility type if set must be 1 or 2 for VOL orders. VOL order requires positive floating point value for volatility. The price specified violates the number of ticks constraint specified in the default order settings. Do not set it for other order types. Stock range attributes cannot be negative. Duplicate ticker ID for API scanner subscription. price to be specified. This order type is not allowed for delta hedge orders. If both are set. Invalid DDE array request. The size specified violates the size constraint specified in the default order settings. Unsupported order type for this exchange and security type. Do not set it for non-VOL orders. the lower stock range attribute must be less than the upper stock range attribute. Must specify valid delta hedge order aux. Reference Price Type must be 1 or 2 for dynamic volatility management. Supplied routed order ID is invalid. or trade on a Price Improvement Exchange.Reference Tables API Message Codes Code 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 Description Invalid adjusted stop limit price.dll needs to be upgraded. Delta hedge order type requires delta hedge aux. Volatility orders are only valid for US options. Invalid adjusted trailing amount. The order is not eligible for continuous update. Cannot set dynamic VOL attribute on non-VOL order. API Reference Guide 403 . The option must trade on a cheap-to-reroute exchange. Can only set stock range attribute on VOL or RELATIVE TO STOCK order. Your DDE. Dynamic Volatility orders must be SMART routed.

Found: Due to system problems. Invalid stop price. The symbol should contain valid non-unicode characters only. The contract is not available for trading. Conditions are not allowed for this contract. < > cannot be used as a condition trigger. Invalid subsequent component size for scale order. The "Outside Regular Trading Hours" flag is not valid for this order. Invalid scale order increment.: 15:59:00 EST. Shares for this order are not immediately available for short sale. Order message error 392 393 394 395 396 397 398 399 Code 400 401 402 403 404 Description Algo order error. Invalid Process Time: must be integer number of milliseconds between 100 and 2000. Note that there is a space between the time and the time zone. application is currently accepting only Market and Limit orders for this contract. Due to system problems. Due to system problems.Reference Tables API Message Codes Code 391 Description The time or time-zone entered is invalid. Length restriction. The order will be held while we attempt to locate the shares. application is currently accepting only Market and Limit orders for this contract. You must specify order component size. The child order quantity should be equivalent to the parent order size. local time is assumed.g. What-if order should have the transmit flag set to true. Invalid scale order. If no time zone is specified. Invalid order: contract expired. 405 406 407 408 409 410 411 412 413 API Reference Guide 404 . The currency < > is not allowed. orders with OCA groups are currently not being accepted. The correct format is hh:mm:ss xxx where xxx is an optionally specified time-zone. Short sale slot may be specified for delta hedge orders only. E.

FA Order requires per-account manual allocations because there is no common clearing instruction. Commission must not be negative.Reference Tables API Message Codes Code 414 415 416 417 418 419 420 421 422 423 Description Snapshot market data subscription is not applicable to generic ticks. Delta neutral orders are only supported for combos (BAG security type). group. but fundamentals data for the security specified is not available. Please open order dialog and verify liquidity allocation. The order size cannot be zero. Order modify failed. Invalid route. Order can have only one flag Outside RTH or Allow PreOpen. Wait until previous RFQ finishes and try again. FA Order requires allocation to be specified. Missing initial component size for scale order. You must specify an allocation (either a single account. You must specify an account. 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 API Reference Guide 405 . Algo attributes validation failed: Specified algorithm is not allowed for this order. None of the accounts have enough shares. or profile). Invalid real-time query. What to show field is missing or incorrect. The account and clearing attributes on this order may not be changed. Invalid scale order profit offset. Mutual Fund order requires monetary value to be specified. Cross order RFQ has been expired. Order processing failed. The application is now locked. Algorithm cannot be modified. Please use order dialog Adviser tab to enter the allocation. THI committed size is no longer available. Order processing failed. Invalid "Restore size after taking profit" for multiple account allocation scale order. Algorithm definition not found. RFQ is not applicable for the contract. Mutual Fund Sell order requires shares to be specified. Order ID: Invalid initial component size for scale order. Unknown algo attribute. We are sorry.

sending error: FA Information Request .sending error: API Reference Guide 406 . Missing scale price adjustment amount or interval.sending error: Cancel order .sending error: Cancel market depth .sending error: Cancel market data . Dividend schedule query failed. Invalid scale price adjustment interval. Cannot submit changes at this time.sending error: Request real-time bar data .sending error: Cancel Scanner subscription .sending error: Request Historical data . Request market data .Reference Tables API Message Codes Code 444 445 446 447 448 449 40 Description Volatility Combo order is not yet acknowledged.sending error: FA Information Replace .sending error: Unknown contract.sending error: Cancel Historical data .sending error: Order .sending error: Account update request .sending error: Request open order . Request contract data .sending error: Set server log level .sending error: Request market depth .sending error: Request Scanner parameter . Couldn't connect to TWS.sending error: Request for executions . Fatal error: Unknown message id. Confirm that API is enabled in TWS via the Configure>API menu command. Verify the contract details supplied. The RFQ for this order is no longer valid.sending error: Request Scanner subscription . Unexpected scale price adjustment amount or interval. Your version of TWS is out of date and must be upgraded. Not connected. Code 501 502 503 504 505 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 Description Already connected. Missing scale order profit offset.

API client has been unsubscribed from account data.Sending error: System Message Codes Code 1100 1101 1102 1300 Description Connectivity between IB and TWS has been lost. A historical data farm connection has become inactive but should be available upon demand. A market data farm is disconnected.data maintained.* Connectivity between IB and TWS has been restored. Unable to modify this order as it is still being processed.<port_num> *Market and account data subscription requests must be resubmitted Warning Message Codes Code 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 Description New account data requested from TWS.data lost. TWS socket port has been reset and this connection is being dropped. A historical data farm is connected. A market data farm connection has become inactive but should be available upon demand. A market data farm is connected. Connectivity between IB and TWS has been restored. Unable to subscribe to account as the following clients are subscribed to a different account.sending error: Request Current Time . PlaceOrder is now processed. Order Event Warning: Attribute “Outside Regular Trading Hours” is ignored based on the order type and destination. Please reconnect on the new port .Reference Tables API Message Codes Code 530 531 Description Cancel real-time bar data . A historical data farm is disconnected. API Reference Guide 407 .

C++ EWrapper functions. which is used in the following ActiveX events.Reference Tables Tick Types Tick Types The following table lists all possible values for the tickType parameter. and Java EWrapper methods: • • • • • • tickPrice() tickSize() tickOptionComputation() tickGeneric() tickString() tickEFP Tick Value 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Description BID_SIZE BID_PRICE ASK_PRICE ASK_SIZE LAST_PRICE LAST_SIZE HIGH LOW VOLUME CLOSE_PRICE BID_OPTION_COMPUTATION ASK_OPTION_COMPUTATION LAST_OPTION_COMPUTATION MODEL_OPTION_COMPUTATION OPEN_TICK LOW_13_WEEK HIGH_13_WEEK LOW_26_WEEK HIGH_26_WEEK LOW_52_WEEK HIGH_52_WEEK AVG_VOLUME OPEN_INTEREST Event/Function/Method tickSize() tickPrice() tickPrice() tickSize() tickPrice() tickSize() tickPrice() tickPrice() tickSize() tickPrice() tickOptionComputation() See Note 1 below tickOptionComputation() See Note 1 below tickOptionComputation() See Note 1 below tickOptionComputation() See Note 1 below tickPrice() tickPrice() tickPrice() tickPrice() tickPrice() tickPrice() tickPrice() tickSize() tickSize() API Reference Guide 408 .

Reference Tables Tick Types Tick Value 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 Description OPTION_HISTORICAL_VOL OPTION_IMPLIED_VOL OPTION_BID_EXCH OPTION_ASK_EXCH OPTION_CALL_OPEN_INTEREST OPTION_PUT_OPEN_INTEREST OPTION_CALL_VOLUME OPTION_PUT_VOLUME INDEX_FUTURE_PREMIUM BID_EXCH ASK_EXCH AUCTION_VOLUME AUCTION_PRICE AUCTION_IMBALANCE MARK_PRICE BID_EFP_COMPUTATION ASK_EFP_COMPUTATION LAST_EFP_COMPUTATION OPEN_EFP_COMPUTATION HIGH_EFP_COMPUTATION LOW_EFP_COMPUTATION CLOSE_EFP_COMPUTATION LAST_TIMESTAMP SHORTABLE FUNDAMENTAL_RATIOS RT_VOLUME HALTED BIDYIELD ASKYIELD LASTYIELD CUST_OPTION_COMPUTATION Event/Function/Method tickGeneric() tickGeneric() NOT USED NOT USED tickSize() tickSize() tickSize() tickSize() tickGeneric() tickString() tickString() NOT USED NOT USED NOT USED tickPrice() tickEFP() tickEFP() tickEFP() tickEFP() tickEFP() tickEFP() tickEFP() tickString() tickGeneric() tickString() tickGeneric() See Note 2 below. tickPrice() See Note 3 below tickPrice() See Note 3 below tickPrice() See Note 3 below tickOptionComputation() API Reference Guide 409 .

vega. Possible values for this new tick type are: 0 = Not halted 1 = Halted. TWS receives a special tick: haltedLast=1. A tick type. Note 2: When trading is halted for a contract. ASK_OPTION_COMPUTATION. LAST_OPTION_COMPUTATION. API Reference Guide 410 . gamma. Note 3: Applies to bond contracts only. theta). is now available in regular market data via the API to indicate this halted state. HALTED. MODEL_OPTION_COMPUTATION also returns model implied volatility. tick ID = 49. the underlying price and the stock and option reference price when requested.Reference Tables Tick Types Note 1: Tick types BID_OPTION_COMPUTATION. and MODEL_OPTION_COMPUTATION return all Greeks (delta. TWS receives haltedLast=0. When trading is resumed.

19. Requests for these ticks will be answered if the tick type requested pertains to the contract at issue.Reference Tables Generic Tick Types Generic Tick Types For all socket-based API technologies. 18. 30 27. 35. we provide several types of market data ticks that can be requested as a part of the market data request. including the socket client library. Note that Generic Tick Tags cannot be specified if you elect to use the Snapshot market data subscription. 28 23 24 31 15.0 (client version 30). 20. ActiveX and Java. 36 48 46 47 Tick Type Option Volume (currently for stocks) Option Open Interest (currently for stocks) Historical Volatility (currently for stocks) Option Implied Volatility (currently for stocks) Index Future Premium Miscellaneous Stats Mark Price (used in TWS P&L computations) Auction values (volume. 21 37 34. The generic market data tick types are: Integer ID Value 100 101 104 106 162 165 221 225 233 236 256 258 Resulting Tick Value (see list below) 29. 17. 16. Starting with API version 9. price and imbalance) RTVolume Shortable Inventory Fundamental Ratios API Reference Guide 411 . version 6 of the REQ_MKT_DATA message is sent containing a new field that specifies the requested ticks as a list of comma-delimited integer Ids (generic tick types).

0 // This contract will be available for short sale if shares can be // located // In TWS.Reference Tables Generic Tick Types Using the SHORTABLE Tick In TWS. this is identical to DARK GREEN status } else if (value > 0. this is identical to GREEN status } else if (value > 1. RED indicates that no shares are available for short sale.5) { // 3. The column describes number of shares with which the security can be sold short. you must include generic ticktype 236 in the argument to obtain the shortable value. For example: The Shortable tick determines if SHORT SELL orders for a contract will be accepted. and that the system is searching for shares. as shown below. this is identical to RED status } else { // unknown value } Note: This feature is supported as of server version 33 (872 release of TWS). int tickType. the shorting indicator is supported for all socket connections. With API 9.0 // There are at least 1000 shares available for a short sale // In TWS. API Reference Guide 412 . double value) as follows: if (value > 2. Analyze the value returned from tickGeneric(int tickerId. DARK GREEN indicates that this contract can be sold short but that at the moment there are no shares available for short sale. When invoking the reqMktDataEx()/reqMktData() methods.0 // Not available for short sale // In TWS.30 or higher.5) { // 2.5) { // 1. The color GREEN indicates that at least 1000 shares are available to sell short. The functionality equates to the SHORTABLE column in the TWS workstation. there is a SHORTABLE column.

TAG2=VALUE2. When this happens. Low Price This price is the lowest price the stock traded at in the last 12 months. Note: Most banks and insurance companies do not report revenues when they announce their preliminary quarterly financial results in the press. Note that some issues may not trade every day. Volume This is the daily average of the cumulative trading volume for the last ten days. Pricing date The pricing date is the date at which the issue was last priced. Trailing twelve months over trailing twelve months. EPS excluding extraordinary items This is the Adjusted Income Available to Common Stockholders for the trailing twelve months divided by the trailing twelve month Diluted Weighted Average Shares Outstanding. Market capitalization This value is calculated by multiplying the current Price by the current number of shares outstanding. This ratios are sent using the tickGeneric() callback. the trailing twelve month values will not be available (NA). EPS Normalized This is the Normalized Income Available to Common Stockholders for the most recent annual period divided by the same period's Diluted Weighted Average Shares Outstanding.Reference Tables TAG Values for FUNDAMENTAL_RATIOS tickType TAG Values for FUNDAMENTAL_RATIOS tickType The FUNDAMENTAL_RATIOS tickType (Tick Value 47) lets you request fundamental ratios in the form TAG=VALUE. Revenue/share This value is the trailing twelve month Total Revenue divided by the Average Diluted Shares Outstanding for the trailing twelve months. The following table lists all the TAG values for FUNDAMENTAL_RATIOS. High Price This price is the highest price the stock traded at in the last 12 months. TAG NPRICE Description Closing Price This is the closing price for the issue from the day it last traded. Three_Year_TTM_ Growth TTM_over_TTM NHIG NLOW PDATE VOL10DAVG MKTCAP TTMEPSXCLX AEPSNORM TTMREVPS API Reference Guide 413 . This could be an intra-day high. It is also referred to as the Current Price. 3 year trailing twelve months growth. and so on. and therefore it is possible for this price to come from a date prior to the last business day. This could be an intra-day low.

Dividends per share This is the sum of the Cash Dividends per share paid to common stockholders during the last trailing twelve month period. Cash per share This is the Total Cash plus Short Term Investments divided by the Shares Outstanding at the end of the most recent interim period. Tangible Book Value is the Book Value minus Goodwill and Intangible Assets for the same period. plus any recurring extra dividends. Dividend rate This value is the total of the expected dividend payments over the next twelve months. It is generally the most recent cash dividend paid or declared multiplied by the dividend payment frequency. P/E excluding extraordinary items This ratio is calculated by dividing the current Price by the sum of the Diluted Earnings Per Share from continuing operations BEFORE Extraordinary Items and Accounting Changes over the last four interim periods. Cash Flow is defined as the sum of Income After Taxes minus Preferred Dividends and General Partner Distributions plus Depreciation. QTANBVPS QCSHPS TTMCFSHR TTMDIVSHR IAD PEEXCLXOR APENORM API Reference Guide 414 . Depletion and Amortization. P/E Normalized This is the Current Price divided by the latest annual Normalized Earnings Per Share value. Cash Flow per share This value is the trailing twelve month Cash Flow divided by the trailing twelve month Average Shares Outstanding. Book Value is the Total Shareholder's Equity minus Preferred Stock and Redeemable Preferred Stock.Reference Tables TAG Values for FUNDAMENTAL_RATIOS tickType TAG QBVPS Description Book value (Common Equity) per share This is defined as the Common Shareholder's Equity divided by the Shares Outstanding at the end of the most recent interim period. Note: This does NOT include cash equivalents that may be reported under long term assets. Book value (tangible) per share This is the interim Tangible Book Value divided by the Shares Outstanding at the end of the most recent interim period.

NOTE: This item is Not Available (NA) for Banks. Tangible Book Value Per Share is defined as Book Value minus Goodwill and Intangible Assets divided by the Shares Outstanding at the end of the fiscal period. the revenue (sales) values from this announcement will be used in calculating the trailing twelve month revenue per share. Price to Cash Flow per share This is the current Price divided by Cash Flow Per Share for the trailing twelve months. Insurance companies and other companies that do not distinguish between current and long term assets and liabilities. If there is a preliminary earnings announcement for an interim period that has recently ended. NOTE: This is Not Meaningful (NM) for banks. Insurance companies and other companies that do not distinguish between current and long term assets and liabilities. NOTE: Most Banks and Finance companies do not report revenues when they announce their preliminary interim financial results in the press. Quick ratio Also known as the Acid Test Ratio. Current ratio This is the ratio of Total Current Assets for the most recent interim period divided by Total Current Liabilities for the same period. Depletion and Amortization. NOTE: This item is Not Available (NA) for Banks. LT debt/equity This ratio is the Total Long Term Debt for the most recent interim period divided by Total Shareholder Equity for the same period. Total debt/total equity This ratio is Total Debt for the most recent interim period divided by Total Shareholder Equity for the same period. PR2TANBK TTMPRCFPS PRICE2BK QCURRATIO QQUICKRATI QLTD2EQ QTOTD2EQ API Reference Guide 415 . the trailing twelve month values will not be available (NA) until the complete interim filing is released. Price to Tangible Book This is the Current Price divided by the latest annual Tangible Book Value Per Share. Price to Book This is the Current Price divided by the latest interim period Book Value Per Share.Reference Tables TAG Values for FUNDAMENTAL_RATIOS tickType TAG TMPR2REV Description Price to sales This is the current Price divided by the Sales Per Share for the trailing twelve months. this ratio is defined as Cash plus Short Term Investments plus Accounts Receivable for the most recent interim period divided by the Total Current Liabilities for the same period. Cash Flow is defined as Income After Taxes minus Preferred Dividends and General Partner Distributions plus Depreciation. When this happens.

Earnings before taxes Also known as Pretax Income and Earnings Before Taxes.Reference Tables TAG Values for FUNDAMENTAL_RATIOS tickType TAG TTMPAYRAT Description Payout ratio This ratio is the percentage of the Primary/Basic Earnings Per Share Excluding Extraordinary Items paid to common stockholders in the form of cash dividends during the trailing twelve months. EBITD Earnings Before Interest. this is Total Revenue for the most recent TTM period minus Total Expenses plus Non-operating Income (Expenses) for the same period. Gross Margin This value measures the percent of revenue left after paying all direct production expenses. General Partner Distributions and US GAAP Adjustments. NOTE: Most banks and Insurance companies do not report revenues when they announce their preliminary quarterly financial results in the press. When this happens. Depreciation and Amortization (EBITDA) is EBIT for the trailing twelve months plus the same period's Depreciation and Amortization expenses (from the Statement of Cash Flows). Net Income Available to Common. the quarterly value will not be available (NA). Normalized This is the annual dollar amount accruing to common shareholders for dividends and retained earnings excluding the impact of all unusual/one-time/special charges items. Taxes. It is calculated as the trailing 12 months Total Revenue minus the trailing 12 months Cost of Goods Sold divided by the trailing 12 months Total Revenue and multiplied by 100. Revenue This is the sum of all revenue (sales) reported for all operating divisions for the most recent TTM period. TTMREV TTMEBITD TTMEBT TTMNIAC AEBTNORM ANIACNORM TTMGROSMGN API Reference Guide 416 . NOTE: This item is only available for Industrial and Utility companies. NOTE: This item is only available for Industrial and Utility companies. Income Available to Common Shareholders is calculated as trailing twelve month Income After Taxes plus Minority Interest and Equity in Affiliates plus Preferred Dividends. NOTE: Any adjustment that is negative (ie. Earnings before taxes Normalized This is the Income Before Tax number excluding the impact of all unusual/one-time/special charges items for the most recent annual period. Preferred Stock Dividends) would be subtracted from Income After Taxes. Net Income available to common This is the trailing twelve month dollar amount accruing to common shareholders for dividends and retained earnings.

expressed as a percentage. this value is the Income After Taxes for the trailing twelve months divided by Total Revenue for the same period and is expressed as a percentage. Pretax margin This value represents Income Before Taxes for the most recent fiscal year expressed as a percent of Total Revenue for the most recent fiscal year.Reference Tables TAG Values for FUNDAMENTAL_RATIOS tickType TAG TTMNPMGN Description Net Profit Margin % Also known as Return on Sales. Average Common Equity is calculated by adding the Common Equity for the 5 most recent quarters and dividing by 5. Operating margin This value measures the percent of revenues remaining after paying all operating expenses. Operating Income is defined as Total Revenue minus Total Operating Expenses. When this happens. Return on average assets This value is the Income After Taxes for the trailing twelve months divided by the Average Total Assets. multiplied by 100. It is calculated as the trailing 12 months Operating Income divided by the trailing 12 months Total Revenue. Return on investment This value is the trailing twelve month Income After Taxes divided by the average Total Long Term Debt. multiplied by 100. Other Long Term Liabilities and Shareholders Equity. Average Total Assets is calculated by adding the Total Assets for the 5 most recent quarters and dividing by 5. TTMOPMGN APTMGNPCT TTMROAPCT TTMROEPCT TTMROIPCT REVCHNGYR TTMREVCHG REVTRENDGR API Reference Guide 417 . Revenue Change % This value is calculated as the most recent interim period Sales minus the Sales for the same interim period 1 year ago divided by the Sales for the same interim period one year ago. Return on average equity This value is the Income Available to Common Stockholders for the trailing twelve months divided by the Average Common Equity and is expressed as a percentage. multiplied by 100. Revenue Change % This is the percent change in the trailing twelve month Sales as compared to the same trailing twelve month period one year ago. NOTE: Most Banks and Finance companies do not report revenues when they announce their preliminary quarterly financial results in the press. the trailing twelve month value will not be available (NA). Revenue growth rate The Five Year Revenue Growth Rate is the annual compounded growth rate of Revenues over the last 5 years. expressed as a percentage. It is calculated as the trailing twelve month Sales minus the trailing twelve month Sales one year ago divided by the trailing twelve month Sales one year ago.

Reference Tables TAG Values for FUNDAMENTAL_RATIOS tickType TAG EPSCHNGYR Description EPS Change % This value is calculated as the most recent interim period EPS minus the EPS for the same interim period 1 year ago divided by the EPS for the same interim period one year ago. multiplied by 100. It is calculated as the trailing twelve month EPS minus the trailing twelve month EPS one year ago divided by the trailing twelve month EPS one year ago. NOTE: If the value for either the most recent year or the oldest year is zero or negative. the resulting value will be Not Meaningful (NM).dividend The Dividend Growth Rate is the compound annual growth rate in dividends per share. the growth rate cannot be calculated and a 'NA' (Not Available) code will be used. the result in Not Meaningful (NM). EPS Change % This is the percent change in the trailing twelve month EPS as compared to the same trailing twelve month period one year ago. Growth rate % . If either EPS value is negative. EPS growth rate This growth rate is the compound annual growth rate of Earnings Per Share Excluding Extraordinary Items and Discontinued Operations over the last 5 years. NOTE: If either value has a negative value. TTMEPSCHG EPSTRENDGR DIVGRPCT API Reference Guide 418 . NOTE: EPS must be positive for both periods. DIVGR% is calculated for 3 years whenever 4 years of dividends are available. multiplied by 100.

ensuring that you can successfully submit each one in TWS. Test each order type. before you submit the same order using the API.Reference Tables Supported Order Types Supported Order Types IB’s API technologies support the order types listed below. Order Type Limit Risk Bracket Market-to-Limit Market with Protection Request for Quote Stop Stop Limit Trailing Limit if Toucched Trailing Market If Touched Trailing Stop Trailing Stop Limit Speed of Execution At Auction Discretionary Market Market-if-Touched Market-on-Close Market-on-Open Pegged-to-Market Relative Sweep-to-Fill Price Improvement Box Top Price Improvement Auction Block Limit-on-Close Limit-on-Open Limit if Touched Pegged-to-Midpoint Abbreviation MTL MKT PRT QUOTE STP STP LMT TRAIL LIT TRAIL MIT TRAIL TRAIL LIMIT MKT MIT MOC MOO PEG MKT REL BOX TOP LOC LOO LIT PEG MID API Reference Guide 419 . API orders only mimic the behavior of Trader Workstation (TWS).

Best Effort Abbreviation VWAP GAT GTD GTC IOC OCA VOL API Reference Guide 420 .Guaranteed Time to Market All-or-None Fill-or-Kill Good-after-Time/Date Good-till-Date/Time Good-till-Canceled Immediate-or-Cancel Advanced Trading One-Cancels-All Spreads Volatility Algorithmic Trading (Algos) Arrival Price Balance Impact and Risk Minimize Impacet Percent of volume Scale TWAP VWAP .Reference Tables Supported Order Types Order Type Privacy Hidden Iceberg/Reserve VWAP .

where stop orders are triggered based on last two prices."last" method. Stop-Limit and Trailing Stop orders are triggered. used for bracket. If set to true. where stop orders are triggered based on the last price. Specifies whether the order will be transmitted by TWS. API Reference Guide 421 . specifies that the order is a block order. The order ID of the parent. If set to true. Institutional only. 2 . Institutional only. 1 . Institutional only. Valid values are: • O .the default value. 3 . If set to true. The "double bid/ask" method will be used for orders for OTC stocks and US options. order is created by not transmitted. where stop orders are triggered based on two consecutive bid or ask prices. The publicly disclosed order size to be used when placing iceberg orders. specifies that the order is a Sweep-to-fill order."double-last" method. Attribute string m_tif string m_ocaGroup string m_account string m_openClose int m_origin string m_orderRef boolean m_transmit Possible Values Day.use "double bid/ask" method. the order will not be visible when viewing the market depth. If set to false. IOC. All other orders will used the "last" method. auto stop and trailing stop orders. The only applies to orders routed to INet. GTD Identifies a member of a one-cancels-all group. allows triggering of orders outside of regular trading hours.Reference Tables Extended Order Attributes Extended Order Attributes The extended order attributes below can be used in all placeOrder functions and Open_Order events. Customer defined order ID tag. Specifies how Simulated Stop. int m_parentId boolean m_blockOrder boolean m_sweepToFill int m_displaySize int m_triggerMethod • • • boolean m_ignoreRth boolean m_hidden If set to true. GTC.

clearing broker 2 . If this value is used. retail customer or not sshort leg) 1 .Reference Tables Extended Order Attributes Attribute string m_goodAfterTime Possible Values Indicates that the trade should be submitted after the time and date set.e. Use an empty string if not applicable. Use an empty string if not applicable. To clarify any ambiguity for Smart-routed contracts. Use an empty string if not applicable. Cancel on Fill with Block = 1 Reduce on Fill with Block = 2 Reduce on Fill without Block = 3 Regular trading hours only. no=0 int rthOnly API Reference Guide 422 . The advisor percentage concerning the trade's allocation. yes=1. Use an empty string if not applicable. You must set the tif to GTD when using this string. The advisor allocation profile to which the trade will be allocated. with format YYYYMMDD HH:MM:SS (seconds are optional). Use an empty string if not applicable.third party. The advisor allocation method with which the trade will be allocated. For institutional customers only.unapplicable (i. include the primary exchange. • • • 0 . for the destination. along with the Smart designation. The advisor group to which the trade will be allocated. Otherwise leave blank or orders will be rejected. string m_goodTillDate string m_faGroup string m_faProfile string m_faMethod string m_faPercentage string m_primaryExch int m_shortSaleSlot string m_designatedLocation long ocaType Only valid when shortSaleSlot value = 2. Use an empty string if not applicable. with format YYYYMMDD HH:MM:SS (seconds are optional). Indicates that the trade should remain working until the time and date set. you must enter a designated location.

The percent offset for relative orders. no=0 Maximum SMART order distance from the NBBO. IB. For BOX exchange only. For BOX exchange only. Starting price. String clearingIntent int allOrNone long minQty double percentOffset int eTradeOnly int firmQuoteOnly double nbboPriceCap long auctionStrategy double startingPrice double stockRefPrice API Reference Guide 423 . The stock reference price. This value must be sent on FUT/FOP orders for reporting the exchange. match = 1 improvement = 2 transparent = 3 For BOX exchange only.Reference Tables Extended Order Attributes Attribute String rule80A Possible Values Individual = 'I' Agency = 'A'. Away. yes=1. or PTA yes=1. no=0 Identifies a minimum quantity order type. AgentOtherMember = 'W' IndividualPTIA = 'J' AgencyPTIA = 'U' AgentOtherMemberPTIA = 'M' IndividualPT = 'K' AgencyPT = 'Y' AgentOtherMemberPT = 'N' String settlingFirm Institutional only String clearingAccount The true beneficiary of the order. Trade with electronic quotes. yes=1. no=0 Trade with firm quotes.

LMT. For Scale orders: Defines the number of component orders into which the parent order will be split.Reference Tables Extended Order Attributes Attribute double delta double stockRangeLower double stockRangeUpper double m_volatility Possible Values For BOX exchange only. This value is expressed as a percent and is used to calculate the limit price sent to the exchange. 2 = BidorAsk Enter an accepted order type such as: MKT. EFP orders EFP orders int m_volatilityType m_continuousUpdate int m_referencePriceType String m_deltaNeutralOrderType double m_deltaNeutralAuxPrice int m_scaleNumComponents int m_scaleComponentSize double m_scalePriceIncrement double m_basisPoints int basisPointsType API Reference Guide 424 . The option price in volatility. as calculated by TWS' Option Analytics. For Scale orders: Defines the number of units per component. 1 = True 1 = Average. Enter the Aux Price for Hedge Delta order types that require one. REL etc. 1 = Daily. 2 = Annual 0 = false. For Scale orders: Defines the price increment per scale component. thereby backing into the number of units within each component. For BOX exchange only. The lower value of the acceptable stock range. The upper value of the acceptable stock range. backing into the number of components into which the parent order is split. For BOX exchange only.

Put option volumes are divided by call option volumes and the top underlying symbols with the lowest ratios are displayed. Shows the top underlying contracts (stocks or indices) with the largest percent loss between current implied volatility and yesterday's closing value of the 15 minute average of implied volatility. Top Option Imp Vol % Gainers (TOP_OPT_IMP_VOLAT_GAIN )* Top Option Imp Vol % Losers (TOP_OPT_IMP_VOLAT_LOSE )* High Opt Volume P/C Ratio (HIGH_OPT_VOLUME_PUT_C ALL_ RATIO) Low Opt Volume P/C Ratio (LOW_OPT_VOLUME_PUT_CA LL_ RATIO) Most Active by Opt Volume (OPT_VOLUME_MOST_ACTIV E) Hot by Option Volume (HOT_BY_OPT_VOLUME) High Option Open Interest P/C Ratio (HIGH_OPT_OPEN_INTEREST _PUT_CALL_RATIO) API Reference Guide 425 .Reference Tables Available Market Scanners Available Market Scanners The following table shows a list (current as of July 2008) of the available scanners. Shows the top underlying contracts for highest options volume over a 10-day average. Put option volumes are divided by call option volumes and the top underlying symbols with the highest ratios are displayed. Displays the most active contracts sorted descending by options volume. Shows the top underlying contracts (stocks or indices) with the largest divergence between implied and historical volatilities. Market Scanner (Scan Code) Low Opt Volume P/C Ratio (LOW_OPT_VOL_PUT_CALL_ RATIO)* High Option Imp Vol Over Historical (HIGH_OPT_IMP_VOLAT_OVE R_HIST)* Low Option Imp Vol Over Historical (LOW_OPT_IMP_VOLAT_OVE R_HIST)* Highest Option Imp Vol (HIGH_OPT_IMP_VOLAT)* Description Put option volumes are divided by call option volumes and the top underlying symbols with the lowest ratios are displayed. Shows the top underlying contracts (stocks or indices) with the highest vega-weighted implied volatility of near-the-money options with an expiration date in the next two months. Returns the top 50 contracts with the highest put/call ratio of outstanding option contracts. Shows the top underlying contracts (stocks or indices) with the smallest divergence between implied and historical volatilities. Shows the top underlying contracts (stocks or indices) with the largest percent gain between current implied volatility and yesterday's closing value of the 15 minute average of implied volatility.

The sample spreadsheet includes two Most Active scans: Most Active List. which displays the most active contracts in the NASDAQ. and Most Active US. based on units used by TWS (lots for US stocks. Contracts where: today's Volume/avgDailyVolume is highest. Contracts with the highest trading volume today.Reference Tables Available Market Scanners Market Scanner (Scan Code) Low Option Open Interest P/C Ratio (LOW_OPT_OPEN_INTEREST _PUT_ CALL_RATIO) Top % Gainers (TOP_PERC_GAIN) Most Active (MOST_ACTIVE) Description Returns the top 50 contracts with the lowest put/call ratio of outstanding option contracts. The avgDailyChange is defined as an exponential moving average of the contract's (dailyClose-dailyOpen) The top trade count during the day. Contracts whose last trade price shows the highest percent increase from the previous night's closing price. or yesterday's close if outside of today's range. contract for derivatives and non-US stocks). Contracts with the highest number of trades in the past 60 seconds (regardless of the sizes of those trades). Contracts whose last trade price shows the lowest percent increase from the previous night's closing price. Contracts where: (lastTradePrice-prevClose)/avgDailyCha nge is highest in absolute value (positive or negative). Futures whose last trade price shows the highest percent increase from the previous night's closing price. Top % Losers (TOP_PERC_LOSE) Hot Contracts by Volume (HOT_BY_VOLUME) Top % Futures Gainers (TOP_PERC_GAIN) Hot Contracts by Price (HOT_BY_PRICE) Top Trade Count (TOP_TRADE_COUNT) Top Trade Rate (TOP_TRADE_RATE) Top Price Range (TOP_PRICE_RANGE) API Reference Guide 426 . NYSE and AMEX markets. avgDailyVolume is a 30-day exponential moving average of the contract's daily volume. The largest difference between today's high and low. which displays the most active stocks in the United States.

Shows the top underlying contracts (stocks or indices) with the largest percent gain between current implied volatility and yesterday's closing value of the 15 minute average of implied volatility. Shows the top underlying contracts (stocks or indices) with the lowest vega-weighted implied volatility of near-the-money options with an expiration date in the next two months. Shows the top underlying contracts (stocks or indices) with the lowest vega-weighted implied volatility of near-the-money options with an expiration date in the next two months. Shows contracts with the highest percent price DECREASE between the last trade and opening prices. Shows contracts with the highest percent price INCREASE between the previous close and today's opening prices. Shows the top underlying contracts (stocks or indices) with the largest percent loss between current implied volatility and yesterday's closing value of the 15 minute average of implied volatility.Reference Tables Available Market Scanners Market Scanner (Scan Code) Hot by Price Range (HOT_BY_PRICE_RANGE) Top Volume Rate (TOP_VOLUME_RATE) Lowest Option Imp Vol (LOW_OPT_IMP_VOLAT) Description The largest price range (from Top Price Range calculation) over the volatility. Shows contracts with the highest percent price INCREASE between the last trade and opening prices. Returns the top 50 underlying contracts with the (highest number of outstanding call contracts) + (highest number of outstanding put contracts) Contracts that have not traded today. Shows contracts with the highest percent price DECREASE between the previous close and today's opening prices. The top volume rate per minute. Contracts for which trading has been halted. Most Active by Opt Open Interest (OPT_OPEN_INTEREST_MOS T_ ACTIVE) Not Open (NOT_OPEN) Halted (HALTED) Top % Gainers Since Open (TOP_OPEN_PERC_GAIN) Top % Losers Since Open (TOP_OPEN_PERC_LOSE) Top Close-to-Open % Gainers (HIGH_OPEN_GAP) Top Close-to-Open % Losers (LOW_OPEN_GAP) Lowest Option Imp Vol (LOW_OPT_IMP_VOLAT)* Top Option Imp Vol % Gainers (TOP_OPT_IMP_VOLAT_GAIN )* Top Option Imp Vol % Losers (TOP_OPT_IMP_VOLAT_LOSE )* API Reference Guide 427 .

Reference Tables Available Market Scanners Market Scanner (Scan Code) 13-Week High (HIGH_VS_13W_HL) 13-Week Low (LOW_VS_13W_HL) 26-Week High (HIGH_VS_26W_HL) 26-Week Low (LOW_VS_26W_HL) 52-Week High (HIGH_VS_52W_HL) 52-Week Low (LOW_VS_52W_HL) EFP . These rates are computed by taking the price differential between the SSF and the underlying 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. Highlights the highest synthetic EFP interest rates available. These rates are computed by taking the price differential between the SSF and the underlying stock and netting dividends to calculate an annualized synthetic implied interest rate over the period of the SSF. The highest price for the past 52 weeks. The lowest price for the past 13 weeks. The Low rates may present a borrowing opportunity.High Synth Bid Rev Yield (HIGH_SYNTH_BID_REV_NAT _ YIELD) Description The highest price for the past 13 weeks.Low Synth Bid Rev Yield (LOW_SYNTH_BID_REV_NAT _ YIELD) API Reference Guide 428 . EFP . The lowest price for the past 52 weeks. The highest price for the past 26 weeks. Highlights the lowest synthetic EFP interest rates available. The lowest price for the past 26 weeks.

01 to 0.01 to 0. Neutral.6. Aggressive. Matching Same Side. Passive) Attempt completion by EOD: forceCompletion (boolean) Target Percentage: pctVol (double in a range 0.Reference Tables IBAlgo Parameters IBAlgo Parameters Beginning with TWS API Release 9.5) Urgency/Risk aversion: riskAversion (Valid values: Get Done. the ActiveX. Neutral.5) Parameters Percentage of Volume (PctVol) Volume-Weighted Average Price (Vwap) Time-Weighted Average Price (Twap) For US Options: Balance Impact and Risk (BalanceImpactRisk) Minimize Impact (MinImpact) API Reference Guide 429 .5) Urgency/Risk aversion: riskAversion (Valid values: Get Done. Algo Strategy For US Stocks: Arrival Price (ArrivalPx) Max percentage: maxPctVol (double in a range 0.5) Max Percentage: maxPctVol (double in a range 0.01 to 0.01 to 0. Matching Last Max percentage: maxPctVol (double in a range 0.01 to 0.5) Trade when: strategyType (Valid values: Marketable. Matching Midpoint. The following table lists all of the IBAlgo strategies and parameters supported by the API. C++ and Java APIs support IBAlgo orders. Aggressive. Passive) Attempt completion by EOD: forceCompletion (boolean) Max Percentage: maxPctVol (double in a range 0.

Reference Tables IBAlgo Parameters API Reference Guide 430 .

using 1-14 API components. 3-147. 3-160. 7-328 API components. 7-344 basket orders. 3-172. 3-163. 3-159. 3-180. 3-181. Excel DDE support for 6-322 algo parameters 9-429 allocation methods for account groups 6-324 API recommendations 1-18 API components. for financial advisor accounts 6-321 Apply Extended Template button 2-47. 3-173. 3-135. 3-184. 7-357 available market scanners 9-425 available market scanners in ActiveX for Excel 7-382 available market scanners in Excel 2-87 AvailableEquity Method 6-324 B bar size settings for historical data 1-22 Basic Orders page 2-39 combination orders 7-342 in ActiveX for Excel 7-340 modifying orders 7-342 placing orders in ActiveX for Excel 7-341 toolbar buttons 2-45. 3-176. using 2-70 Account page. 3-149 ActiveX properties 3-199 ActiveX sample program 3-116 addComboLeg() 3-134 Advanced Orders 2-56 in ActiveX for Excel 7-349 Advanced Orders page toolbar buttons 2-62. 3-153. removing in Excel 2-70 account information. viewing in Excel 2-70 Account page 2-69 field values 2-71 in ActiveX for Excel 7-360 toolbar buttons 2-75. 3-144. 3-188. 3-154. 3-190. 7-355 advisors 6-321 financial reporting for 6-323 Advisors page 2-99 in ActiveX for Excel 7-389 toolbar buttons 2-103. 3-141. 3-186. 3-189. configurign in TWS 2-31 API overview 1-13. viewing in ActiveX for Excel 7-360 account information. 3-169. 3-170. 3-177. 7-362 Account page. 9-397 API software uninstalling 1-28 API. 3-175. 3-155. 3-179. in ActiveX for Excel 7-341 API Reference Guide 431 . 3-157. 7-393 advisors. 3-196 ActiveX events 3-152. 3-182 ActiveX factory methods 3-149. 3-143.Index A about the APIs 1-14 account details in ActiveX for Excel 7-360 account details in Excel DDE 2-69 account information. 3-171. about 1-14 API. 3-158. 3-145. 3-168. 3-151 ActiveX for Excel Account page 7-360 Advanced Orders page 7-349 Advisors page 7-389 allocating shares to a single account 7-390 Basic Orders page 7-340 Bond Contract Details page 7-375 bracket orders in 7-351 Bulletins page 7-337 connecting to TWS 7-332 Contract Details page 7-373 disconnecting from TWS 7-332 download API components 7-328 Executions page 7-365 Extended Order Attributes page 7-356 FA orders using account group and method 7-391 FA orders using allocation profile 7-392 Fundamentals page 7-387 General page 7-331 getting started 7-328 Historical Data page 7-367 Log page 7-394 Market Depth page 7-338 Market Scanner page 7-379 Open Orders page 7-358 opening sample spreadsheet 7-329 placing orders in 7-341 Real Time Bars page 7-377 relative orders in 7-355 requesting current time 7-333 scale orders in 7-354 setting server log level in 7-332 Tickers page 7-334 trailing stop limit orders in 7-353 ActiveX for Excel historical data expired contracts 7-368 ActiveX for Excel sample spreadsheet using 7-330 ActiveX methods 3-117. 3-174. 3-150. 3-148. 3-161. using in ActiveX for Excel 7-360 Active X 3-113 ActiveX linking to TWS 3-114 placing a combination order 3-204 registering third-party controls 3-115 ActiveX API on 64-bit systems 3-115 ActiveX COM objects 3-183. downloading 2-30. 3-119.

4-242. 5-274 cancelMktDepth() 3-133. 5-282. defined 2-29 delta-neutral RFQs 1-26 disconnect() 3-119 disconnecting from TWS using ActiveX for Excel 7-332 displaying lines of market depth in Excel 2-97 downloading API components 2-30. 7-346 Conditional Orders page 2-52. 4-220. examples of 2-53. 7-374 contract details. 5-273 eDisconnect() 4-216. 3-173. in C++ 4-259 combination orders. 5-280 checkMessages() 4-219 Class EClientSocket methods 4-215. 4-226. 5-278. in ActiveX for Excel 7-342 combination order. 7-376 bond contract details. 4-236. 5-283 cancelScannerSubscription() 3-147. 4-217. 4-244 Clear All Links button 2-37 clearComboLegs() 3-135 combination order.Index basket orders. 4-231. 4-226. 5-301 D DDE for Excel allocating shares to a single account 2-100 FA orders using account group and method 2-101 FA orders using allocation profile 2-102 DDE for Excel historical data expired contracts 2-79 DDE syntax 2-104 DDE syntax reference 2-107 DDE. 8-395 download API components 2-30 API Reference Guide 432 . 5-293 Contract 4-248. 5-307 conditional orders in Excel. in Excel 2-52. 4-217. 7-342 calendar spread order. 5-275 calendar spread order in Excel 2-41. 5-276. 4-237. 5-277. 4-225. in Java 5-317 ComboLeg 4-251. 5-296 contractDetailsEx() 3-172 createComboLegList() 3-149 createContract() 3-150 createExecutionFilter() 3-150 createOrder() 3-150 createScannerSubscription() 3-150 createTagValueList 3-150 createUnderComp() 3-151 creating a ticker in ActiveX for Excel 7-334 creating a ticker in Excel 2-35 current time requesting in ActiveX for Excel 7-333 currentTime() 3-182. modifying orders 2-54. 5-305 Contract Details page 2-92 in ActiveX for Excel 7-373 toolbar buttons 2-93. 5-274 calculateOptionPrice 4-218. requesting in Excel 2-94 bondContractDetails() 3-179. 4-219. 4-216. 5-280. requesting in ActiveX for Excel 7-375 bond contract details. 4-239. 5-274. 4-221. 5-282 cancelMktData() 3-122. 4-244. in C++ 4-259 cancelCalculateImpliedVolatility 3-122. 5-283. 4-240. 7-347 conditional orders. 4-234. 4-222. 4-235. 5-278 cancelOrder() 3-127. 4-221. 5-281. in Excel 2-57 Bulletins page in ActiveX for Excel 7-337 toolbar buttons 7-337 C C++ 4-207 Class EClientSocket methods 4-215 Class EWrapper functions 4-229 combinations orders 4-259 linking to TWS 4-208 using the sample program 4-213 C++ SocketClient properties 4-245 calcOptionPriceAndGreeks 3-122 calculateImpliedVolatility 3-122. 4-239. 4-230. 7-345 configure TWS 1-15 configuring TWS 2-31 connect() 3-119 connecting to TWS using ActiveX for Excel 7-332 connectionClosed() 3-158. 4-238. 5-277 cancelNewsBulletins() 3-135. 4-217. 4-227 Class EWrapper functions 4-229. in Excel 2-41 combination orders. 4-218. 4-226. 4-223. 7-328 E EClient Socket methods 5-272. 7-348 Conditional Orders page. 7-327. 7-345 toolbar buttons 2-55. 4-218. 4-242. 5-273. 5-275. 4-227. 4-218. 4-219. 5-284 EClientSocket functions 4-215 EClientSocket() 4-215. in ActiveX 3-204 combination order. 4-232. 5-296 bracket orders in ActiveX for Excel 7-351 in DDE for Excel 2-57 bracket orders. 5-279. 4-241. 5-306 contractDetails() 3-172. requesting in ActiveX for Excel 7-373 contract details. 4-221. in Excel 2-40 Bond Contract Details page 2-94 in ActiveX for Excel 7-375 toolbar buttons 2-95. 5-292 EWrapper methods 5-286 Excel 2007 Name Manager 2-106 Excel DDE 2-29. 4-243. 5-275 cancelCalculateOptionPrice 3-123. 5-275 cancelHistoricalData() 3-147. requesting in Excel 2-92 ContractDetails 4-250. 5-275 cancelRealTimeBars() 3-149. 5-273 eConnect() 4-216. 4-236. 5-273 EqualQuantity Method 6-324 errMsg() 3-158 error codes 9-398 error messages viewing in ActiveX for Excel 7-394 error() 4-235.

5-299 I IB Gateway running the API through 1-16 IBAlgo parameters 9-429 IComboLeg 3-189 IContract 3-186 IContractDetails 3-188 IExecution 3-184 IExecutionFilter 3-184 if-filled order. 4-225. 7-390 allocation profiles 2-102. in Excel DDE 2-67 executions. installing 2-30. in ActiveX for Excel 7-365 execution reporting. 7-344 execDetails() 3-174. 5-296 execDetailsEnd() 3-175. 5-273 F FA information in ActiveX for Excel 7-361 FA managed accounts. 7-357 extended order attributes in Excel 2-48 Extended Order Attributes page 2-46 in ActiveX for Excel 7-356 extended order attributes. 7-328 IOrder 3-190 IOrderState 3-196 isConnected() 4-216. 7-328 Excel DDE. in Excel 2-53. 7-392 using account group and method 2-101. 5-297 execDetailsEx() 3-173 Execution 4-246. 7-344 syntax 2-107 viewing sample spreadsheet code 2-104 Visual Basic Editor 2-104 Excel DDE API reference 2-104 Excel DDE sample spreadsheet. 7-370 toolbar buttons 2-83. manually programming in Excel 2-47 filtering execution reports in Excel DDE 2-67 Financial Advisors allocation methods for account groups 6-324 financial advisors 6-321 execution reporting for 6-323 orders and account configuration 6-322 financial advisors. Extended Order attributes page 2-46. 7-356 Excel DDE. 7-330 placing orders in 2-40 supported order types 2-43. Excel DDE support for 6-322 financial advisors. in ActiveX for Excel 7-361 Portfolio page 7-363 FA managed accounts. 5-303 execution reporting. 7-391 FA orders in ActiveX for Excel 7-389 FA orders in DDE for Excel 2-99 API Reference Guide 433 . 5-303 Executions page 2-65. 4-242. support by other API technologies 6-322 fundamental data in ActiveX for Excel 7-387 report types 7-387 fundamental ratios in ActiveX for Excel 7-387 FUNDAMENTAL_RATIOS tickType 9-413 Fundamentals page in ActiveX for Excel 7-387 toolbar buttons 7-388 G General page toolbar buttons 7-333 generic ticktypes SHORTABLE 9-412 getting started with ActiveX for Excel sample spreadsheet with Excel DDE 2-30 7-328 H historical data duration and bar size settings 1-22 viewing in ActiveX for Excel 7-368 viewing in Excel 2-79 historical data limitations 1-21 Historical Data page 2-78 in ActiveX for Excel 7-367 query specification fields 2-81. 7-366 executions reporting. in Excel DDE 2-65 execution reports types of 2-68 execution reports. for financial advisors 6-323 execution reporting. financial advisor support 6-322 Excel DDE. extended order attributes 2-46. viewing in Excel 2-65 exerciseOptions() 3-144. 7-346 Index Premium data 1-27 installing Excel DDE sample spreadsheet 2-30. 7-372 historicalData 4-242 historicalData() 3-177. 2-67 in ActiveX for Excel 7-365 toolbar buttons 2-66. manually programming in ActiveX for Excel 7-357 extended order attributes. in Excel 2-70 FA orders allocating shares to a single account 2-100. 5-284 exerciseOptionsEx() 3-143 exercising options in ActiveX for Excel 7-363 extended order attributes applying to individual or groups of orders 2-47. 7-356 Excel DDE. viewing in ActiveX for Excel 7-366 executions. running in Excel 2-68 ExecutionFilter 4-246. 4-240. supported order types 2-43. 4-239.Index getting started 2-30 macros in 2-106 named ranges in 2-105 opening sample spreadsheet 2-33 pages 2-34.

in Excel 2007 2-106 named ranges 2-105 NetLiq Method 6-324 nextValidId() 3-171. 5-306. 5-303. 5-275 placeOrder2() 3-126 placeOrderEx() 3-123 placing orders basket 2-40. 5-293 openOrder1() 3-159 openOrder2() 3-160 openOrder3() 3-161 openOrder4() 3-163 openOrderEx() 3-159 options exercising in ActiveX for Excel 7-363 Order 4-252. starting in ActiveX for Excel 7-380 market scanner subscription. 2-57. available in Excel 2-87 Message codes 9-407 message codes 9-398 modifying orders in ActiveX for Excel 7-342 modifying orders in Excel 2-41 modifying orders. using ActiveX 3-114 log level. on Conditional Orders page 2-54. 5-292. displaying more lines in Excel 2-97 Market Scanner page 2-84 in ActiveX for Excel 7-379 supported market scanners 9-425 toolbar buttons 2-91. 5-314 orderStatus() 3-157. 7-386 market scanner parameters in ActiveX for Excel 7-380 market scanner subscription. viewing in Excel 2-64 opening the ActiveX sample program 3-116 openOrder() 4-236. 7-359 open orders. 9-397 L limitations of historical data requests 1-21 linking to TWS. 7-344 order types supported 9-419 order types. 5-294. viewing in ActiveX for Excel 7-359 open orders. 5-315 Java Test Client 5-269 overview 5-269 running 5-265 N Name Manager. 5-307. 4-239. 5-309.Index J Java 5-261 combination orders 5-317 linking to TWS 5-262 sample program 5-265 Java EClient Socket methods 5-272 Java EWrapper methods 3-173. 7-330 PctChange Method 6-324 permId() 3-171 placeOrder() 3-123. 4-239. 7-345 placing orders in ActiveX for Excel 7-341 placing orders in Excel 2-40 434 API Reference Guide . setting in Excel 2-37 Log page in ActiveX for Excel 7-394 M macros in Excel 2-106 managedAccounts() 3-177. modifying in ActiveX for Excel 7-342 orders. 5-314. 5-309 order attributes in Excel 2-44 order IDs 1-25 order types in Excel DDE 2-43. 5-289. 5-299. 4-234. 5-295. 5-296. 5-291. 7-347 modules in Excel VB code 2-105 P pages 2-34. available in ActiveX for Excel 7-382 market scanners. 5-293 market depth requesting in ActiveX for Excel 7-339 requesting in Excel 2-97 Market Depth page 2-96 in ActiveX for Excel 7-338 toolbar buttons 2-98 toolbar buttons in ActiveX for Excel 7-339 using 2-97 using ActiveX for Excel 7-339 market depth. 5-288. 5-287. 7-341 combination order in ActiveX for Excel 7-342 combination order in Excel 2-41 conditional orders in Excel 2-52. 7-344 orders 1-23 placing in ActiveX for Excel 7-341 placing in Excel 2-40 orders and account configuration. 5-293. 5-291 overview 1-13. 5-298. 5-297. 5-305. 5-301 java sample program 5-269 classes 5-269 Java SocketClient properties 5-302. for financial advisors 6-322 Orders page combination orders 2-41 modifying orders 2-41 placing basket orders 2-57 placing orders 2-40 orders. 5-286. modifying in Excel 2-41 OrderState 4-256. 4-218. 5-300. starting in Excel 2-85 market scanners. 5-295 O open orders removing in Excel 2-64 Open Orders page 2-63 ActiveX for Excel 7-358 toolbar buttons 2-64. in Excel 2-43. 4-236.

in Excel 2-64 replaceFA() 4-223. 7-328 scale orders in ActiveX for Excel 7-354 API Reference Guide 435 . 7-345 Contract Details page 2-92 Executions page 2-65 Executions Reporting page 2-67 Extended Order Attributes page 2-46 Historical Data page 2-78 macros in 2-106 Market Depth page 2-96 Market Scanner page 2-84 Open Orders page 2-63 opening 2-33. 4-227. installing 2-30. 5-277 reqContractDetails2() 3-131 reqContractDetailsEx() 3-129 reqCurrentTime() 3-149. 4-226. viewing in FA managed accounts. on ActiveX for Excel Tickers page 7-336 refresh rate. 4-242. 5-281 reqHistoricalDataEx() 3-138 reqIDs() 4-220 reqIds() 3-129 reqManagedAccts() 3-136. viewing in Excel 2-76 portfolio. 4-217. in Excel 2-36 requesting market depth in ActiveX for Excel 7-339 in Excel 2-97 Reuters global fundamentals in ActiveX for Excel 7-387 RFQs 1-26 running execution reports in Excel 2-68 running the API through IB Gateway 1-16 S sample program ActiveX 3-116 C++ 4-213 Java 5-265 sample spreadsheet Account page 2-69 Advanced Orders page 2-56 Advisors page 2-99 Basic Orders page 2-39 Bond Contract Details page 2-94 bracket orders in 2-57 Conditional Orders page 2-52. in ActiveX for Excel 7-363 toolbar buttons 2-77. 7-339 refresh rate. 4-219. 5-277 reqMktDepth2() 3-133 reqMktDepthEx() 3-131 reqNewsBulletins() 3-135. 4-223. 5-276 reqRealTimeBars() 3-148. in Excel 2-54. 7-329 pages in 2-34. 5-274 reqMktData2() 3-121 reqMktDataEx() 3-119 reqMktDepth() 3-132. 4-222. in DDE for Excel spreadsheet 2-61 removing open orders. 5-276 reqAllOpenOrders 5-278 reqAllOpenOrders() 3-128.Index portfolio data in Excel DDE 2-76 portfolio data in FA managed accounts. on Historical Data page in ActiveX for Excel 7-370 query specification fields. 4-225. for market depth in Excel 2-97. 5-279 requesting bond contract details in ActiveX for Excel 7-375 requesting bond contract details in Excel 2-94 requesting contract details in ActiveX for Excel 7-373 requesting contract details in Excel 2-92 requesting market data. 4-220. 7-347 processing rate. 7-364 portfolio. 5-284 reqExecutions() 3-128. 4-225. on Tickers page 2-37 Q query specification fields. 5-280 reqScannerSubscription() 3-145. 5-279 reqMktData() 3-120. 5-279 reqAccountUpdates() 3-136. in ActiveX for Excel 7-355 relative orders. 4-222. 5-301 receiveFA() 3-177. 5-283 reqRealTimeBarsEx() 3-147 reqScannerParameters() 3-144. 5-280 reqScannerSubscriptionEx() 3-145 Request for Quote 1-26 requestFA() 3-136. 4-220. 7-330 Portfolio page 2-76 relative orders in 2-61 scale orders in 2-60 Tickers page 2-35 trailing stop limit orders in 2-59 using 2-34 viewing VB code 2-104 sample spreadsheet. on Tickers page 2-37 registering third-party ActiveX controls 3-115 relative orders. 5-277 reqOpenOrders() 3-128. 4-222. 5-299 recommendations for using API 1-18 reference tables 9-397 refresh rate. in ActiveX for Excel 7-335 requesting market data. 4-219. in ActiveX for Excel 7-363 Portfolio page 2-76 in FA managed accounts. 4-221 reqAutoOpenOrders() 3-128. 5-276 reqExecutionsEx() 3-128 reqHistoricalData() 3-141. 4-221. 4-220. 5-278 reqContractDetails() 3-130. 4-244. in ActiveX for Excel 7-363 POSIX running client on Windows machine 8-396 premium data 1-27 price-change order. on Historical Data page in Excel 2-81 R real time bars in ActiveX for Excel 7-377 Real Time Bars page toolbar buttons 7-378 realtimeBar() 3-181.

4-240 updateNewsBulletin() 3-176.Index scale orders. 5-287 tickPrice()Class EWrapper Functions 4-230 tickSize() 3-153. 5-284 setLogLevel() 4-221 setServerLogLevel() 3-135. 4-256. 4-238. 5-294 updateMktDepth() 3-175. 7-348 Contract Details page 2-93 Executions page 2-66 FA managed accounts. 4-250. in DDE for Excel spreadsheet 2-59 TWS linking from Java 5-262 TWS precautionary settings 1-23 TWS. 4-257 SocketClient properties. 4-232. 5-278 setting log level. 5-300 scannerDataEnd() 4-243. 4-251. 4-231. on ActiveX for Excel Tickers page 7-336 toolbar buttons. on Tickers page 2-37 setting the processing rate on Tickers page 2-37 SHORTABLE tick 9-412 SocketClient Properties 4-245 SocketClient properties 4-246. in ActiveX for Excel 7-353 trailing stop limit orders. 2-31 TWS. using ActiveX for Excel 7-334 tickGeneric() 3-154. 5-289 toolbar buttons on Account page 2-75 on ActiveX for Excel Advanced Orders page 7-355 on ActiveX for Excel Advisors page 7-393 on ActiveX for Excel Basic Orders page 7-344 on ActiveX for Excel Bond Contract Details page 7-376 on ActiveX for Excel Contract Details page 7-374 on ActiveX for Excel Executions page 7-366 on ActiveX for Excel Fundamentals page 7-388 on ActiveX for Excel Historical Data page 7-372 ActiveX for Excel Market Depth page 7-339 ActiveX for Excel Market Scanner page 7-386 ActiveX for Excel Open Orders page 7-359 ActiveX for Excel Portfolio page 7-364 ActiveX for Excel Real Time Bars page 7-378 Advanced Orders page 2-62 Advisors page 2-103 Basic Orders page 2-45 Bond Contract Details page 2-95 Conditional Orders page 2-55. 4-243. on ActiveX for Excel Bulletins page 7-337 toolbar buttons. 4-238. 4-237. using 2-35 Tickers page. 5-289 tickOptionComputation() 3-154. 5-295 updatePortfolioEx() 3-169 using Account page in ActiveX for Excel 7-360 using Account page in Excel 2-70 using API components 1-14 using the ActiveX for Excel sample spreadsheet 7-330 using the ActiveX for Excel Tickers page 7-334 using the Market Depth page in ActiveX for Excel 7-339 using the Market Depth page in Excel 2-97 using the sample spreadsheet 2-34 using the Tickers page 2-35 API Reference Guide 436 . 4-230. linking from C++ 4-208 TWS. 5-284 TwsSocketClient. 5-297 updateMktDepthL2 5-298 updateMktDepthL2() 3-176. for ActiveX 3-115 tickEFP() 3-155. 4-231. 5-300 ScannerSubscription 4-257. in ActiveX for Excel Account page 7-362 on Historical Data page 2-83 on Market Depth page 2-98 on Market Scanner page 2-91 on Open Orders page 2-64 on Portfolio page 2-77 toolbar buttons. 4-248.dll 4-208 linking to 4-208 on on on on on on on on on on on on on U udpateMktDepthL2() 5-298 uninstalling the API software 1-28 updateAccountTime() 3-171. creating in ActiveX for Excel 7-334 ticker. linking using ActiveX 3-114 TwsConnectionTime() 4-227. 4-241. 5-298 updatePortfolio() 3-170. configuring for API 1-15. 4-252. in Java API 5-302 starting market scanner in ActiveX for Excel 7-380 starting market scanner in Excel 2-85 T TAG values for FUNDAMENTAL_RATIOS tickType 9-413 TestJavaClient 5-265 third-party controls. 5-288 tickString() 4-232. 4-240. 5-289 ticker. on ActiveX for Excel General page 7-333 toolbar buttons. 5-300 scannerDataEx() 3-180 scannerParameters() 3-180. creating in Excel 2-35 Tickers page 2-35 clearing all links 2-37 in ActiveX for Excel 7-334 requesting market data 2-36 requesting market data in ActiveX for Excel 7-335 setting log level 2-37 setting the processing rate 2-37 setting the refresh rate 2-37 setting the refresh rate in ActiveX for Excel 7-336 toolbar buttons 2-38 toolbar buttons in ActiveX for Excel 7-336 Tickers page. 5-295 updateAccountValue() 3-168. on Tickers page 2-38 trailing stop limit orders. 4-243. 5-288 tickPrice() 3-153. in DDE for Excel spreadsheet 2-60 scannerData() 3-180. 5-315 server log level setting in ActiveX for Excel 7-332 serverVersion() 4-227.

vbp opening 3-116 VBE 2-104 viewing executions. in Excel 2-65 viewing historical data in ActiveX for Excel 7-368 viewing historical data in Excel 2-79 viewing open orders in ActiveX for Excel 7-359 viewing open orders in Excel 2-64 viewing portfolio data in Excel 2-76 viewing portfolio data in FA managed accounts. in ActiveX for Excel 7-363 Visual Basic Editor 2-104 Visual Basic sample program. in sample spreadsheet 2-104 VB modules 2-105 VB_API_sample. for ActiveX 3-116 VOL orders in ActiveX for Excel 7-352 W winError() 4-235 API Reference Guide 437 .Index V VB code. in ActiveX for Excel 7-366 viewing executions.

Sign up to vote on this title
UsefulNot useful