TWS Users' Guide
February 17, 2006
Table Of Contents
Get Started ................................................................................................................1 Order Management Modules........................................................................................ 15 Use the Trading Window .......................................................................................... 16 Use the Order Ticket ............................................................................................... 29 Rapid Order Entry ................................................................................................... 41 BookTrader............................................................................................................ 45 OptionTrader ......................................................................................................... 53 BasketTrader ......................................................................................................... 59 SpreadTrader ......................................................................................................... 75 Volatility Trading .................................................................................................... 84 Calculate Order Quantity.......................................................................................... 86 Multi-client Trade Allocation ..................................................................................... 91 Change Order Defaults & Assign Shortcuts ............................................................... 101 Left Pane - Instrument Types............................................................................... 102 Right Pane - Default Order Type........................................................................... 103 ChartTrader ......................................................................................................... 118 DepthTrader ........................................................................................................ 121 Rebalance & Portfolio Allocation .............................................................................. 127 Order Types and Properties....................................................................................... 131 Basic Order Types................................................................................................. 132 Times in Force...................................................................................................... 153 Order Attributes ................................................................................................... 160 Advanced Order Types .......................................................................................... 169 Market Data Tools ................................................................................................... 175
iii
TWS Users' Guide
Price/Risk Analytics ................................................................................................. 177 Portfolio Analytics ................................................................................................. 182 Option Analytics ................................................................................................... 198 Option Modeler..................................................................................................... 203 Charting .............................................................................................................. 226 Chart Basics...................................................................................................... 227 Chart Types ...................................................................................................... 240 Chart Indicators................................................................................................. 244 Market Scanners................................................................................................... 262 Other Technical Analysis Tools ................................................................................ 267 Configure TWS ........................................................................................................ 269 Global Configuration.............................................................................................. 270 Page Layout......................................................................................................... 306 Workspaces ......................................................................................................... 315 Customize the Main Trading Window ....................................................................... 317 Feature Selector ................................................................................................... 327 Exercise and Rollover ............................................................................................... 331 DVP/RVP ............................................................................................................. 332 Option Exercise .................................................................................................... 336 Real-time Activity Monitoring .................................................................................... 341 Text Colors .......................................................................................................... 357 Background colors on a Market Data line.................................................................. 357 Background colors on an Order Management line ...................................................... 358 Order Status Colors .............................................................................................. 358 Alerts and Notifications.......................................................................................... 361 Application Program Interface ................................................................................... 379
iv
Table Of Contents
ActiveX ............................................................................................................... 394 C++ ................................................................................................................... 437 DDE.................................................................................................................... 467 Java ................................................................................................................... 488 Advisors .............................................................................................................. 519 TWS Menus Reference.............................................................................................. 523
v
Get Started
Log in
You can run the application from your Internet browser or you can download it to your PC and launch it directly from your desktop. The browser-based version allows you to access your account and execute trades from any Java™-enabled internet browser, and is always running the latest release. The installed version uses less memory and may run faster, but requires you to download each release to take advantage of new features. To download to your PC, see the Installation Instructions on the website. To log in from your browser 1. In the Login box in the upper right corner of the IB homepage, select TWS from the drop-down list. NOTE: If you are a first-time user, select Account Management, enter your username and password, and click Login. 2. Enter your user name and password. If you want to change the directory in which your settings reside, click the Browse button and select a new drive. 3. For added security, use Secure Socket Layer (SSL) by checking Use SSL. Note that your identity and trading information are always protected. Using SSL gives added privacy and integrity to your order information as it travels over the internet. Minor performance impacts may be experienced depending on the capabilities of your PC.
To use SSL, you must be running version 1.4.2_03 or higher of the Java runtime environment. To see what version of Java you are currently running, click in any row and press Ctrl +Alt + V. To log in from your desktop 1. 2. 3. Double-click the application icon on your desktop. Enter your username and password. If you are prompted to install the free Java™ Runtime plug-in, see the Java™ Plug-In installation document. This plug-in enables your PC to run the advanced technology that powers the application.
Copyrights and Trademarks
1
TWS Users' Guide
Add a Market Data Line
Before you can trade, you need to add market data lines for your assets. A market data line represents an individual ticker, and displays the product type, order destination, ask and bid prices, and other defining attributes. You can add a market data line by typing directly in the Underlying column of the trading screen, or by using the Request Ticker by Underlying box. NOTE: Advanced/options traders can add security definitions by entering the exchange contract class or contract symbol. To add a ticker line directly to the trading screen 1. 2. 3. 4. Click in an empty row in the Underlying column. Enter the instrument's underlying ticker symbol and press ENTER. Select the instrument type from the list. In the Contract Description box, select a contract and click OK. You can limit the contracts displayed in the right pane by selecting an exchange or a currency from the Filter section. Choose Smart to use SmartRouting.
• • •
Market data lines are active when visible, regardless of where they originate. Each alarm always uses one line of market data whether or not you are viewing the asset that contains the alarm. Market data requested through an API has top priority, followed by data requested by alarms, and finally basic market data display. This means that if you have are viewing a trading page that includes 100 lines of market data, and you also have priceactivated alarms set for 6 other contracts, those 6 contracts will receive market data, and your trading page will only show data for 96 contracts. The option chains on Option Trader do not count against available market data lines.
•
To add an asset using the Request Ticker by Underlying box 1. Do one of the following to open the Request Ticker by Underlying box:
• •
2
Click the Ticker icon on the Trading toolbar. On the Ticker menu select Add Symbol.
Get Started
•
2. 3. 4.
Select Ticker from the right-click menu anywhere on the trading screen.
Enter the underlying ticker symbol. Select the instrument type from the list. From the Contract Selection window, select "Smart" to use IB SmartRouting, or choose a specific order destination. NOTE: If you add a market data line for an option, a new line for the option's underlying asset is automatically created at the top of the page. This price of the underlying is used for model pricing and risk analysis calculations. This line cannot be deleted until all corresponding options have been deleted.
Copyrights and Trademarks
3
TWS Users' Guide
Create an Order
This procedure describes one method of sending an order. To review other techniques for completing actions, see Navigate the Application. To create and transmit an order from a market data line 1. Click the "Ask" or "Bid" price of an asset (or use your buy or sell hot key on the selected Market Data line) to create an Order Management line directly below the selected asset. Click the Ask Price to create a Buy order. Click the Bid Price to create a Sell order. 2. On the Order Management line, modify the order parameters Time in Force, Action, Quantity, Price, Order Type, or Destination, if needed. Set the Limit Price to automatically update to the bid, ask, midpoint, last or closing price. NOTE: To trade more efficiently, set the Quantity and Order Type defaults using the Order Defaults window. 3. To transmit your order, use the right-click menu and select Transmit, click the XMIT icon on the Trading toolbar, or use your Transmit hot key or mouse shortcut.
NOTE: Unless you specify otherwise, all of the orders for a specific ticker are displayed on each page on which that ticker appears. To modify this setting to only display working orders on the page on which they were created, on the Page menu select Settings. Uncheck the Show all orders checkbox. This setting does not affect the Pending page. All orders are always displayed on the Pending page.
Copyrights and Trademarks
4
Get Started
Modify an Order
You can modify an order up until the time it has been executed at the order destination. Until this occurs, the order remains visible and editable on both the asset's order management line and the Pending page. An order is "working" if the order status is green. Note that VWAP orders are accepted immediately and cannot be modified. NOTE: If you want to modify parameters other than Price and Quantity, you must cancel this working order, and create and transmit a new order. This practice is commonly required by order destinations.
To modify price and quantity in a working order
1. 2. On the Order Management line, click in the Price or Quantity fields and make your change. Use the right-click menu and select Transmit, click the XMIT icon on the Trading toolbar or use your Transmit hot key to transmit your modified order.
To undo changes before you transmit, right-click and choose Restore. NOTE: You may receive an execution on the original order before your modified order has replaced it on the exchange. Please see the Customer Agreement for specific details on modifying and canceling an order.
Copyrights and Trademarks
5
TWS Users' Guide
Transmit an Order
Once you have verified the order parameters on an order management line, you are ready to transmit your order. To transmit an order
• • • •
Use the right-click menu on the order management line and select Transmit, or Use your "Transmit" hot key, or Click in the Transmit column on your trading screen Click the Transmit icon on the Trading toolbar
After a transmitted order is accepted at the order destination, it becomes a "working" order. All working orders appear on the Pending page and on each page that displays the asset. The page name on any page that displays the asset will turn red. To transmit all orders on a page
•
On the Order menu select Transmit Page . Note: The dollar value in parenthesis reflects the value of all orders on the active page.
The color of the Status field on an order management line conveys the following information:
LIGHT GRAY indicates that you are in the process of creating an order and you have not yet transmitted it.
LIGHT BLUE indicates that you have transmitted your order, but have not yet received confirmation that it has been accepted by the order destination. GREEN indicates that your order has been accepted at the order destination and is working. MAGENTA 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. RED indicates that the balance of your order has been confirmed as canceled by the system. This could occur unexpectedly when the system or the destination has rejected your order. Once the order is confirmed canceled, the Order Management line will disappear from your trading screen after 30 seconds. Please see the Customer Agreement for further information on order confirmation and order cancellation.
6
Get Started
DARK BLUE 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 (and the status remains DARK BLUE) until the election criteria are met. At that time the order is transmitted to the order destination as specified (and the order status color will change).
MAROON indicates that an attached simulated order type has been accepted by the system and has yet to be elected. The order is held in the system (and the status remains MAROON) until the election criteria are met. At that time the order is transmitted to the order destination specified and the order status color will change appropriately.
Copyrights and Trademarks
7
TWS Users' Guide
Cancel an Order
For a non-transmitted order, the Cancel command deletes the selected order from your trading screen. For a working order, the Cancel command sends a cancellation request to the order destination. See the table below for the meaning of status colors on an order management line. You can cancel a working order up until the time it has been executed at an order destination. You can also choose to cancel all orders on a page or all orders on your workstation. When you choose a "Cancel all" command, both non-transmitted and working orders are cancelled. To cancel either a non-transmitted or a working order
• • • •
Right click on the order management line you want to cancel and select Cancel , or Select the order you want to cancel and from the Order menu select Cancel, or Select the order you want to cancel and use your "Cancel" hot key, or Select the order you want to cancel and click the Cancel Icon on the trading toolbar.
To cancel all orders (working and non-transmitted) on a trading page 1. 2. 3. Open the page that contains the orders you want to cancel. On the Order menu, select Cancel Page. At the prompt asking if you want to cancel all orders on the page, click Yes.
To cancel all orders (working and non-transmitted) on your workstation 1. 2. On the Order menu, select Cancel All. At the prompt asking if you want to cancel all orders, click Yes.
The Status field on an order management line uses color to convey the following order status information:
LIGHT GRAY indicates that you are in the process of creating an order and you have not yet transmitted it.
LIGHT BLUE indicates that you have transmitted your order, but have not yet received confirmation that it has been accepted by the order destination. GREEN indicates that your order has been accepted at the order destination and is working. MAGENTA 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
8
Get Started
execution while your cancellation request is pending. RED indicates that the balance of your order has been confirmed as canceled by the system. This could occur unexpectedly when the system or the destination has rejected your order. Once the order is confirmed canceled, the Order Management line will disappear from your trading screen after 30 seconds. Please see the Customer Agreement for further information on order confirmation and order cancellation.
DARK BLUE 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 (and the status remains DARK BLUE) until the election criteria are met. At that time the order is transmitted to the order destination as specified (and the order status color will change).
MAROON indicates that an attached simulated order type has been accepted by the system and has yet to be elected. The order is held in the system (and the status remains MAROON) until the election criteria are met. At that time the order is transmitted to the order destination specified and the order status color will change appropriately.
NOTE: Your working order is not confirmed CANCELED until the status field turns red. Please see the Customer Agreement for further information on order confirmation/cancellation.
Copyrights and Trademarks
9
TWS Users' Guide
TWS Trading Window
The Trading window comprises:
• • • • •
The Menus, located at the top of the page below the title The dockable Trading toolbar, located immediately below the menus The Pages tabset, located below the Trading toolbar and along the top of the column headings The Rapid Order Entry panel The Order Management panel, which encompass the Contract Description columns (Underlying, Exch and Description) and the Market Data and Order Management columns described in the tables below.
The Contract Description columns display information about the asset on a market data line. The Underlying column contains the asset's underlying symbol. The Exch column displays the default order destination you set for this asset. The Description column holds a summary of other contract parameters, including the instrument type, expiration date, strike price, option right and market segment when appropriate. The Trading screen pictured below is in the default entry mode (Underlying), and shows all market data lines. The column headings in the top-most row above the trading area (Position, P&L, Bid Size, Bid Price, Ask Price, Ask Size, Last Price, Change, and Last Size) apply to information on the Market Data line. The table below has field names and descriptions.
A Market Data line provides real-time data specific to the product represented in the Underlying column. All available columns are described in the table below, although they may not appear in the graphic. To hide and display columns, use the Page Layout Manager.
Available Market Data Columns
Column Name Underlying (Symbol) Exch Description The underlying symbol or exchange symbol for the contract. To toggle between underlying and symbol mode, on the View menu select the desired mode. The exchange to which orders for the contract will be routed. Select SMART order routing to route directly to the best available market.
10
Get Started
Column Name Description Position Avg cost P&L
Description Identifies the instrument type and other descriptive contract information. Your current position in the selected contract. The average cost of the current position. Displays unrealized gains or losses. To modify the P&L calculation used, on the Page menu click Layout. On the Columns tab, select P&L in the Market Data Row section and click Customize. Select either New Position P&L or Daily P&L. Displays unrealized gains or losses. Calculates unrealized P&L for stocks, stock options and futures options. Unrealized P&L is calculated using the formula: (current market price - average cost/share) x total number of shares The average cost per share is updated in realtime.
Unrealized P&L
Bid Exch Bid Size Bid Price Model
Used only for options. Identifies the exchange(s) posting the best bid price on the options contract. The approximate depth of the current bid. The best bid price for a contract. This is the best price at which you could currently SELL. For options. The option model price is calculated using the underlying price, interest rate, dividends and other data that you enter using the Option Modeler. The best ask price for a contract. This is the best price at which you could currently BUY. The approximate depth of the current offer. Used only for options. Identifies the exchange(s) posting the best ask price on the options contract. The last price at which the contract traded. A "C" in front of the last price indicates that this is the previous day's closing price. How much the current price has risen or declined from the previous day's closing price. If the price has declined, the background is red. If the price has risen, the background is blue. To toggle between dollar change and percent change, click the column title. The percentage that the current price has risen or declined from the previous day's closing price. If the price has declined, the background is red. If the price has risen, the background is blue. To toggle between percent change and dollar change, click the column title.
Ask Price Ask Size Ask Exch Last Price
Change
Change (%)
11
TWS Users' Guide
Column Name Last Size
Description The size of the last contract traded. If the last contract traded is larger than the previous one, the font is green. If it's smaller, the font is red. For options. The implied volatility is based on the average of the best bid and offer for an option. This calculation is non-linear, and may not converge for low vega options. In such cases, no implied volatility estimate will be displayed. High price for the day for the selected contract. Low price for the day for the selected contract. Trading volume for the day for the selected contract.
Imp Vol (%)
High Low Volume
The Trading window below is operating in Symbol entry mode and shows both a Buy and Sell Order Management line. Column headings in the bottom-most row above the trading area (Time in Force, Action, Quantity, Lmt. Price, Aux. Price, Type, Transmit, Cancel, Status and Destination) apply to information on an Order Management line. The table below has field names and descriptions.
An Order Management line contains information about the order you have created, and appears immediately below the Market Data line for the asset you're trading. All available columns are described in the table below, although they may not appear in the graphic. To hide and display columns, use the Page Layout Manager.
Order Management Columns
Column Name Trailing Key Description System-created key to identify pieces of a bundled limit, bracket or trailing stop order.
12
Get Started
Column Name Account (Allocation)
Description Displays the account number of the beneficial account. (For FA accounts, the Allocation column lets you select an account, create a new allocation profile, allocate shares based on percent of equity in each account, or define an absolute number of shares to be allocated to specified accounts. Allows you to create a one-cancels-all advanced order group without opening the Order Ticket window. The time period during which your order remains active: Day order or Good-Til-Canceled. Keeps the order active until the close of market on the date you enter. Date format is YYYY/MM/DD. The order action. BUY, SELL or SELL SHORT. The number of units in your order. The limit price for order types to which this price applies, including Limit, Stop Limit, and Relative orders. This field reflects the Election price for Stop and Stop Limit orders, and the Offset Amount for Relative and Trailing Stop orders. You can set these auxiliary amounts in the Default Order Settings box. The Election price for Stop and Stop Limit orders. The order type. Click to transmit the order. Click to cancel the transmitted order. The order status. See Guide to System Colors for details. The order destination. Check to create a sweep-to-fill order. Enter a display size to create an iceberg order. The customer type from which the order originated. Mainly used for institutional accounts. Check to create a hidden order. Enter a discretionary amount with a limit order to create a discretionary order. Displays volatility for the option at a specific strike price.
OCA Group Time in Force GTD Expire Action Quantity Lmt Price Aux. Price
Stop Price Type Transmit Cancel Status Dest. Swp Fill Disp Size Origin Hidden Discretionary Volatility
The Trading Toolbar The Trading toolbar is movable and configurable. To add or remove buttons, rightclick in the toolbar and select Configure Toolbar.
To move and dock the toolbar, click and drag on the textured drag bar to the left of the first toolbar icon.
13
TWS Users' Guide
The Trading Pages
You can create up to 24 trading pages, each of which can hold up to 40 market data lines. Navigate between pages by clicking the appropriate tab in the Pages tabset. Each Trading page lists Contract, Exchange, and Description on the left. Each contract contains a Market Data line that displays the Bid Exchange, Bid Size, Bid Price, Ask Exchange, Ask Size, Ask Price, Last Price, Change, and Last Size. When you create an order, an Order Management line appears directly below the asset's Market Data line.
Copyrights and Trademarks
14
Order Management Modules
ORDER MANAGEMENT MODULES
Copyrights and Trademarks
15
TWS Users' Guide
Use the Trading Window
USE THE TRADING WINDOW
Copyrights and Trademarks
16
Order Management Modules
Add a Market Data Line in Symbol Mode
Advanced options traders can use Symbol mode to enter security definitions for options directly into a market data line. Symbol mode requires that you enter the contract symbol or class as defined by the exchange on which it's trading. To change to Symbol mode, on the Configure menu select View and then select Contract Display View both the Underlying and contract Symbol by adding the market data Symbol column using the Page Layout. To add an options security definition directly to the trading screen 1. 2. Click in an empty row in the Symbol column. Enter the security definition by contract class or contract symbol, and press ENTER. Use the formats in the table below.
Symbol Entry Formats contract class contract symbol @ # exchange acronym exchange acronym
To add an options security definition using the Request Ticker by Exchange Symbol form 1. In symbol mode, do one of the following to open the Request Ticker by Exchange Symbol form:
• • •
2. 3.
Click the Ticker icon on the Trading toolbar. On the Ticker menu select Add Symbol. Right click anywhere on the trading screen and select Insert Ticker.
In the Instrument Type field select Option. Select the Symbol Type. Do this
If you select
Class Contract
Enter the contract class symbol, exchange, expiration date and strike price, and select the right. Enter the exchange local symbol and the exchange.
Copyrights and Trademarks
17
TWS Users' Guide
Create an Order
This procedure describes one method of sending an order. To review other techniques for completing actions, see Navigate the Application. To create and transmit an order from a market data line 1. Click the "Ask" or "Bid" price of an asset (or use your buy or sell hot key on the selected Market Data line) to create an Order Management line directly below the selected asset. Click the Ask Price to create a Buy order. Click the Bid Price to create a Sell order. 2. On the Order Management line, modify the order parameters Time in Force, Action, Quantity, Price, Order Type, or Destination, if needed. Set the Limit Price to automatically update to the bid, ask, midpoint, last or closing price. NOTE: To trade more efficiently, set the Quantity and Order Type defaults using the Order Defaults window. 3. To transmit your order, use the right-click menu and select Transmit, click the XMIT icon on the Trading toolbar, or use your Transmit hot key or mouse shortcut.
NOTE: Unless you specify otherwise, all of the orders for a specific ticker are displayed on each page on which that ticker appears. To modify this setting to only display working orders on the page on which they were created, on the Page menu select Settings. Uncheck the Show all orders checkbox. This setting does not affect the Pending page. All orders are always displayed on the Pending page.
Copyrights and Trademarks
18
Order Management Modules
Modify an Order
You can modify an order up until the time it has been executed at the order destination. Until this occurs, the order remains visible and editable on both the asset's order management line and the Pending page. An order is "working" if the order status is green. Note that VWAP orders are accepted immediately and cannot be modified. NOTE: If you want to modify parameters other than Price and Quantity, you must cancel this working order, and create and transmit a new order. This practice is commonly required by order destinations.
To modify price and quantity in a working order
1. 2. On the Order Management line, click in the Price or Quantity fields and make your change. Use the right-click menu and select Transmit, click the XMIT icon on the Trading toolbar or use your Transmit hot key to transmit your modified order.
To undo changes before you transmit, right-click and choose Restore. NOTE: You may receive an execution on the original order before your modified order has replaced it on the exchange. Please see the Customer Agreement for specific details on modifying and canceling an order.
Copyrights and Trademarks
19
TWS Users' Guide
Transmit an Order
Once you have verified the order parameters on an order management line, you are ready to transmit your order. To transmit an order
• • • •
Use the right-click menu on the order management line and select Transmit, or Use your "Transmit" hot key, or Click in the Transmit column on your trading screen Click the Transmit icon on the Trading toolbar
After a transmitted order is accepted at the order destination, it becomes a "working" order. All working orders appear on the Pending page and on each page that displays the asset. The page name on any page that displays the asset will turn red. To transmit all orders on a page
•
On the Order menu select Transmit Page . Note: The dollar value in parenthesis reflects the value of all orders on the active page.
The color of the Status field on an order management line conveys the following information:
LIGHT GRAY indicates that you are in the process of creating an order and you have not yet transmitted it.
LIGHT BLUE indicates that you have transmitted your order, but have not yet received confirmation that it has been accepted by the order destination. GREEN indicates that your order has been accepted at the order destination and is working. MAGENTA 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. RED indicates that the balance of your order has been confirmed as canceled by the system. This could occur unexpectedly when the system or the destination has rejected your order. Once the order is confirmed canceled, the Order Management line will disappear from your trading screen after 30 seconds. Please see the Customer Agreement for further information on order confirmation and order cancellation.
20
Order Management Modules
DARK BLUE 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 (and the status remains DARK BLUE) until the election criteria are met. At that time the order is transmitted to the order destination as specified (and the order status color will change).
MAROON indicates that an attached simulated order type has been accepted by the system and has yet to be elected. The order is held in the system (and the status remains MAROON) until the election criteria are met. At that time the order is transmitted to the order destination specified and the order status color will change appropriately.
Copyrights and Trademarks
21
TWS Users' Guide
Cancel an Order
For a non-transmitted order, the Cancel command deletes the selected order from your trading screen. For a working order, the Cancel command sends a cancellation request to the order destination. See the table below for the meaning of status colors on an order management line. You can cancel a working order up until the time it has been executed at an order destination. You can also choose to cancel all orders on a page or all orders on your workstation. When you choose a "Cancel all" command, both non-transmitted and working orders are cancelled. To cancel either a non-transmitted or a working order
• • • •
Right click on the order management line you want to cancel and select Cancel , or Select the order you want to cancel and from the Order menu select Cancel, or Select the order you want to cancel and use your "Cancel" hot key, or Select the order you want to cancel and click the Cancel Icon on the trading toolbar.
To cancel all orders (working and non-transmitted) on a trading page 1. 2. 3. Open the page that contains the orders you want to cancel. On the Order menu, select Cancel Page. At the prompt asking if you want to cancel all orders on the page, click Yes.
To cancel all orders (working and non-transmitted) on your workstation 1. 2. On the Order menu, select Cancel All. At the prompt asking if you want to cancel all orders, click Yes.
The Status field on an order management line uses color to convey the following order status information:
LIGHT GRAY indicates that you are in the process of creating an order and you have not yet transmitted it.
LIGHT BLUE indicates that you have transmitted your order, but have not yet received confirmation that it has been accepted by the order destination. GREEN indicates that your order has been accepted at the order destination and is working. MAGENTA 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.
22
Order Management Modules
RED indicates that the balance of your order has been confirmed as canceled by the system. This could occur unexpectedly when the system or the destination has rejected your order. Once the order is confirmed canceled, the Order Management line will disappear from your trading screen after 30 seconds. Please see the Customer Agreement for further information on order confirmation and order cancellation.
DARK BLUE 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 (and the status remains DARK BLUE) until the election criteria are met. At that time the order is transmitted to the order destination as specified (and the order status color will change).
MAROON indicates that an attached simulated order type has been accepted by the system and has yet to be elected. The order is held in the system (and the status remains MAROON) until the election criteria are met. At that time the order is transmitted to the order destination specified and the order status color will change appropriately.
NOTE: Your working order is not confirmed CANCELED until the status field turns red. Please see the Customer Agreement for further information on order confirmation/cancellation.
Copyrights and Trademarks
23
TWS Users' Guide
Deactivate an Order
When you deactive an order, the order is cancelled at the exchange, but it remains on your trading screen for you to resubmit. To deactivate an order 1. Right-click an order management line and select Deactive.
Copyrights and Trademarks
24
Order Management Modules
Bond Market Data
Information displayed on the trading screen for bonds, including the ask and bid prices, is calculated differently than for other securities. The table below defines market data fields whose values are unique to corporate bonds. Field name Bid and Ask Prices Description The price for bonds is quoted as a percentage of its face relative to 100. A bid of 95 means the bond is trading at 95% of its face value. The yield-to-worst. This is the lower of yield to maturity and yields to all calls. The yield is only shown if it is offered on the exchange. These are optional fields that you can hide or display using the Layout Manager. Bond attributes of last sale price which may include:
Bid, Ask, and Last Yields
Bond Attributes
•
Non-standard settlement date (normal settlement for bonds is T + 3), including
• • • • • •
C - cash trade ND - next day trade S# - seller's option
Other Attributes W - weighted average trade A - afterhours trade
This is an optional field that you can hide or display using the Layout Manager. Last price Last price may have:
• •
a "c" following the price indicating that the price includes commission. an asterisk "*" following the price indicating a special price typically due to an arranged trade taking place outside prevailing market bid/ask.
Last size
Last size may show "est" following the size indicating that the size is an estimate, for trades with size greater than one million.
Copyrights and Trademarks
25
TWS Users' Guide
Add a Trading Page
You can create up to 24 trading pages. You can enter as many lines of market data as you want, but at any one time you will only be able to see 40 active market data lines. Use the trading pages to sort your assets by instrument type, exchange, or your own trading system categories. Use the tabset to navigate between pages. You can also use a page-level feature called Quick Stock Entry, which will automatically complete a market data line for a stock using the set of order destinations you set up. Use the Page menu commands to add, edit and delete trading pages, and edit the page's layout. To add a page 1. 2. 3. 4. On the Page menu, select New. Enter a page name. In the Layout dropdown, select a page layout. Click OK.
To edit page settings 1. 2. On the Page menu, select Settings. Modify the page name or assigned layout and click OK.
To delete a page 1. 2. On the Page menu, select Delete. At the prompt asking if you want to delete the page, click Yes.
NOTE: The Pending page is a system page that displays all of your working orders. You cannot delete or rename the Pending page, but you can edit order parameters. To edit a page layout 1. 2. On the Page menu, select Layout. Modify the desired characteristics and click OK.
NOTE: Before you modify the page layout be aware that you are not simply changing the look of the active page, you are modifying an applied layout which may also be associated with other pages. To create a populated page using current positions
•
On the Page menu select Create Portfolio Page.
This creates a page with market data lines for each position you hold. These positions are displayed in the Portfolio section of the Account window. Each time you take a position, the Portfolio page is automatically updated to include market data for the new position. You can
26
Order Management Modules
remove zero position tickers from this and other pages using the right-click menu on a page and clicking Clear Zero Positions.
Copyrights and Trademarks
27
TWS Users' Guide
Trading Bonds
Our bond-trading feature gives you direct access to US traded corporate bonds through the NYSE and Bond Desk ECN. To ensure that you have bond trading permissions, use Account Management on the website's Login menu. Create Market Data Line for Bonds 1. 2. Enter an underlying symbol and select Bond as the instrument type. In the contract selection box choose the bond asset(s) for which you want to display market data and click OK.
3.
Market data for the bond is displayed on the trading page. The following information is available on the market data line:
• •
CUSIP number - a nine-character ID for a specific security. Bond rating - identifies the credit rating of the issuer. A higher credit rating generally indicates a less risky investment. The bond ratings are from Moody's and S&P, respectively. Coupon - the interest rate used to calculate the amount you will receive as interest payments over the course of a year. Maturity date - the date on which the issuer must repay the face value of the bond. Issuer - the company who issued the bond instrument.
• • •
NOTE: To see Details using the Details button, or using the right-click menu from a market data line, you must be running Java version 1.5 or higher. For instructions on downloading this latest version of Java, see Upgrading Java on the website. To see which version of Java you are currently using, on the TWS Help menu select About Trader Workstation.
Copyrights and Trademarks
28
Order Management Modules
Use the Order Ticket
USE THE ORDER TICKET
Copyrights and Trademarks
29
TWS Users' Guide
Order Ticket Window
Select from the available fields to create an order. The fields are context-sensitive, which means that only valid selections will be active. For example, if you select "Stock" as the security type, any fields specific to options and futures will be grayed out (inactive). NOTE: To automatically update contract information with the currently selected asset on the trading screen, click the Refresh Target icon in the upper right corner. A red target indicates that automatic refresh is activated.
To remove tabs and view all fields on a single large page in TWS, select the Comprehensive view.
30
Order Management Modules
Field Contract radio button
Description Select Regular to create a single contract order. Select Combo to modify the interface and create a combination strategy or spread order.
Notes You will only see this field if you open the order ticket independent of a market data line. to do this, right click in a blank line and select Order.
Underlying Exchange
Displays the asset's underlying ticker symbol. Used in conjunction with the underlying symbol to identify the asset. To route your order to a different exchange, use the Destination field in the Order Description section.
Primary Exchange Security Type Prem. Currency Exp. date Strike Option Type Action Order Type
Identifies the asset's primary exchange. Select the instrument type. Select the currency delivered against the purchase of the underlying currency. The option's expiration date. The option's strike price. Select the option type. Choose Buy or Sell Select an order type. Valid order types are determined by the underlying, exchange and security type selected. The number of units in the order. Enter a display size to create an Iceberg order. Enter the minimum quantity that must be available for the order to execute. Enter the limit price for Limit, Stop Limit and For Stop and Stop limit orders, this is the Stop election price. For Options relative to stock For options routed through Smart.
Quantity Display size Min. Quantity
Limit Price Aux. Price
31
TWS Users' Guide
Field
Description orders, this is the starting price. For trailing stop orders, this is the trailing amount.
Notes
Percent Offset
For Relative orders, sets the offset amount based on a percentage of the bid price for Buy orders or the Ask price for sell orders. The amount off the limit price at which the order is still eligible to execute. For Pegged to Stock orders, select from Match, Improve or Transparent. Enter an amount to create a Discretionary order. Available for options orders routed to BOX. For details see the Pegged to Stock order topic. For pegged to Stock orders on BOX Defaults to the value in the Exchange field. Only editable for orders initiated from a market data line.
Discretionary Amount Auction Strategy
Improvement Cap Destination
Set a cap on the price improvement amount. Specifies the order destination.
Copyrights and Trademarks
32
Order Management Modules
Order Ticket Window - Time in Force
Select from the available fields to create an order. The fields are context-sensitive, which means that only valid selections will be active. For example, if you leave the Good After time checkbox empty, the date/time field is not writable (inactive).
Field Time in Force
Description The time period during which your order will remain active. Select DAY (day order), GTC (order remains active until it is cancelled), OPG (market or limit at the open order), or GTD (order remains working until the date/time specified in the two fields below. When checked, you can set a date/time
Notes
Good After
33
TWS Users' Guide
Field Time Exp. Date
Description after which the order will be submitted. Enter the expiration date for the order. Use the format YY:MM:DD. Order continues to work until close of market on that day. Enter the expiration time for the order. Use the format HH:MM:SS. Order continues to work up until the time and date specified. Checked by default. If unchecked, trading hours are determined by the opening/closing times of the order destination.
Notes
Valid for GTD/GTT times in force.
Exp. Time
Valid for GTD/GTT times in force.
Regular Trading Hours Only
Valid for US stocks listed on major exchanges. Not available for IOC, OPG (MOO and LOO), FOK, MOC or LOC orders.
Copyrights and Trademarks
34
Order Management Modules
Order Ticket Window - Pegged
Select from the available fields to create an order. The fields are context-sensitive, which means that only valid selections will be active. For example, if you are creating any kind of order other than a Pegged to Stock options order routed through BOX, this page will be inactive.
Field Stock Ref Price
Description Enter a stock price.
Notes If you do not enter a value, the midpoint of the NBBO at the time of the order is used.
Stock Range
Define the lower portion of the stock 35
TWS Users' Guide
Field (Lower)
Description range outside of which your order will be cancelled. Define the higher portion of the stock range outside of which your order will be cancelled. Enter a value (which will be used as a percent, ie. ".5" equal 50%) that will be multiplied by the change in the underlying stock price. The product is added to the starting price to determine the option price.
Notes
Stock Range (Higher)
Delta
Copyrights and Trademarks
36
Order Management Modules
Order Ticket Window - Conditional
A conditional order is an order that will automatically be submitted or cancelled ONLY IF specified criteria for one or more defined contracts are met. You can use stocks, options, futures or security indexes to trigger a conditional order.
To create a conditional order 1. 2. 3. 4. 5. a. Select an order management line. From the right-click menu, select Modify and then select Condition. From the Conditional tab on the order ticket click Add Condition. Enter contract information for the contingent asset in the Conditional Order box. Enter the trigger information for the contingent asset: Select the trigger method.
b. Select whether the price of the contingent asset should be less than or equal to (=) the trigger price. c. Enter the trigger price. NOTE: If you select the double bid/ask trigger method, the greater than or equal to operator (>=) will use the BID price and the less than or equal to operator (Save as Basket command, or directly from a spreadsheet. You can modify a basket order before you send it by adding or removing assets, changing the multiplier and quantities, and reversing the order sides and then converting limit orders to market, relative or VWAP orders. You can also elect to create a basket file based on a selected index using the index composition or statistical composition. Use the criteria selections to fine-tune your index basket. If you choose to base your index basket on the index composition, the system automatically keeps the basket in line with the index composition as it changes. For detailed field-level information on the Basket Order window, click a field in the image below. When you send a basket order, each order in the basket is cleared individually. If your account does not meet margin requirements, it is possible that only a portion of the basket order will execute. To send a basket order 1. 2. On the Order menu, select Basket. From the Basket Order dialog, select a Basket File using the drop-down or the Browse button. If you created a basket file using Excel, browse to the saved .csv file. When you load the basket the Excel file is read into the trading screen. 3. Modify the Multiplier if necessary. This value multiplies the quantity of each order in the basket. 4. Click Load to populate the Orders panel with the basket order.
5. Modify order parameters if necessary, and click Transmit in the Execute Basket panel to transmit the entire basket order. You can transmit individual orders within the basket using the market data lines in the Orders panel.
60
Order Management Modules
The fields below are available through the Orders panel. To hide or display fields, right click in any column title Customize Layout. Check fields to display, uncheck fields to hide them. Fields unique to the basket page are in bold type. Column Name Underlying Description The underlying symbol for the contract. To toggle between underlying and symbol mode, on the View menu select the desired mode. The exchange symbol for the contract. To toggle between underlying and symbol mode, on the View menu select the desired mode. The exchange to which orders for the contract will be routed. Select SMART order routing to route directly to the best available market. Identifies the instrument type and other descriptive contract information. System-created key to identify bundled limit, bracket and trailing stop orders. Displays the account number of the beneficial account. (For FA accounts, the Allocation column lets you select an account, create a new allocation profile, allocate shares based on percent of equity in each account, or define an absolute number of shares to be allocated to specified accounts. Allows you to create a one-cancels-all advanced order group without opening the Order Ticket window. 61
Symbol
Exch Description Trailing Key Account (Allocation)
OCA Group
TWS Users' Guide
Column Name Time in Force Exp. Date Exp. Time
Description The time span over which your order remains active. For GTD time-in-force, keeps the order active until the close of market on the date you enter. Date format is YYYY/MM/DD. For the the the GTD time-in-force, keeps the order active until the time on date you enter. Time format is hh:mm:ss xxx where xxx is three letter time zone acronym. If no time zone is entered, local time zone is used.
Action Total Quan Transmit Quan Quantity % Lmt Price
The order action. BUY, SELL or SELL SHORT. The total quantity of units in the order line. The quantity of units you want to transmit in the current order The number of units in your order. The percent of the total order you want to transmit in the current order. The limit price for order types to which this price applies, including Limit, Stop Limit, and Relative orders. You can elect to automatically update the limit price to reflect the current bid, ask, midpoint, last or closing price. This field reflects the Election price for Stop and Stop Limit orders, and the Offset Amount for Relative and Trailing Stop orders. You can set these auxiliary amounts in the Default Order Settings box. Creates an offset price based on a percentage off the best bid or ask. Use a decimal value between 0 - 1. The Election price for Stop and Stop Limit orders. The order type. Click to transmit the order. Click to cancel the transmitted order. The order status. See Guide to System Colors for details. The order destination. Check to create a sweep-to-fill order. Enter a display size to create an iceberg order. The customer type from which the order originated. Mainly used for institutional accounts. Check to create a hidden order. Enter a discretionary amount with a limit order to create a discretionary order. Displays volatility for the option at a specific strike price.
Aux. Price
Pct Offset Stop Price Type Transmit Cancel Status Dest. Swp Fill Disp Size Origin Hidden Discretionary Volatility
Copyrights and Trademarks
62
Order Management Modules
Create Basket File through TWS
The Basket Order feature lets you save a group of orders in one file, and transmit that file as a single order. Once you have created a basket file, you can create a basket order. Create a basket file automatically using the Save Orders as Basket command, or manually using any text editor. To automatically create a basket file Note that when you create a basket file automatically, you can only include orders from the same Trading page. 1. Create Buy and/or Sell orders for all assets on a page that you want to include in the basket.
• •
Click the Ask Price on a market data line to create a Buy order. Click the Bid Price on a market data line to create a Sell order. DO NOT TRANSMIT THESE ORDERS.
2. After you create the orders, modify the order parameters Time in Force, Action, Quantity, Price, Order Type, or Destination, if needed. 3. 4. On the File menu, select Save Orders as Basket. In the dialog box, view or edit the .bsk filename and click OK. Note: The system uses the Trading page name as the default basket name. You may change the basket name, but must keep the directory structure and the .bsk filename extension in order to import the file and submit a basket order. 5. Cancel the orders you created. Use the Order menu and select Cancel Page.
Copyrights and Trademarks
63
TWS Users' Guide
Create Basket File Manually
Create a manual basket file by entering a list of order rows, each composed of a series of comma-delimited (separated by commas) fields of data that define an order. TWS reads these fields in a specific sequence to populate the TWS fields, so it is critical that you put the data in order according to the order in which it occurs in the tables below. Because the fields in each order line are interpreted based on their order in the string, some of the fields are required even though they may include a null value. These are required as placeholders to ensure the order parameters are read correctly. For example, if you are entering an options order, you must include the expiry, strike and put-or-call fields, and each of these must include a valid value. If however you are entering a stock order, you do not need to include any of those fields in your string. To manually create a basket file 1. 2. Use any word processor or text editor tool to open a new file. For each order you want to include in the basket file, create one line of text and observe the following rules:
• • •
Include one value, when required or when appropriate for the instrument type, for each field described in the table below. Separate field values by commas. If you want to leave a field blank, include a blank space followed by a comma. List field values in the order in which they're listed in the table below
Table 1 - Required Basket File Fields (in order) Field action quantity underlying symbol security type expiry strike put-or-call exchange Data Type constant integer string constant date/time number character string Possible Values or Example BUY or SELL e.g. 100 e.g. IBM stk, opt, war, fop, fut YYYYMM e.g. 200610 (for Oct. 2006 expiry) e.g. 42.5 or 37.0 P or C Any valid destination, e.g. Smart, or NYSE or PHLX or VWAP. Req. Field? Yes Yes Yes Yes For futures and options. For options. For options. Yes Req. Value? Yes Yes Yes Yes Yes
Yes Yes Yes
64
Order Management Modules
Table 1 - Required Basket File Fields (in order) NOTE: To clarify any ambiguity for Smart routed contracts, include the primary exchange along with Smart for the destination, for example: Smart/NYSE. order type constant LMT or MKT or REL or VWAP (a VWAP order type must also have a destination value of VWAP and the price field must be left blank) or MOO or LOO or MOC or LOC e.g. 96.47 or 85 1/2 (fraction or decimal value) Leave blank for a VWAP aux. price number e.g. .15, 1/8 (fraction or decimal value) Yes Yes
limit price
number
For Limit, Relative and Stop Limit orders only. For Relative, Stop and Stop Limit orders only. Relative orders Yes Yes
Yes
Yes. Value may be 0.
percent offset currency basket tag
number constant string
Any decimal value between 0 and 1, e.g. .05 USD, GBP, etc. Any unique string of alpha or numeric characters used to identify the basket order. This tag appears in the Order Reference field of the Execution report. day, gtc, gtd, ioc, fok, opg, auc YYYYMMDD hh:mm:ss [zzz] where zzz is an optional time zone. If you do not designate a time zone, TWS uses the time zone from which the order originated. YYYYMMDD hh:mm:ss [zzz] where zzz is an optional time zone. If you do not designate a time zone, TWS uses the time zone from which the order originated.
No Yes No
time-in-force goodTilTime
constant date/time
Yes Yes
Yes No
goodAfterTime
date/time
Yes
No
The fields below are optional in the sense that they are not required for a basic order. However, if you want to use any fields, you must also includes values in any preceeding fields.
65
TWS Users' Guide
Table 2 - Optional Basket File Fields (in order, continued from Table 1 above) Field group Data Type string Possible Values or Example existing group name Req. Field? for Advisors only for Advisors only Required Value? No
method
string
• • • • •
PctChange AvailableEquity NetLiq EqualQuantity PctOfPortfolio
only if group is specified
percent
percent
number in range 1-100, i.e. 100
for Advisors only for Advisors only for Advisors only for noncleared customers only for noncleared customers only for noncleared customers only for noncleared customers only for noncleared customers only
only if method is PctChange no
profile
string
existing profile name
account
string
existing account name
no
account
string
free text
openClose
string
open, close
yes
settlingFirm
string
free text
shortSaleSlot
number
-1 (cust. has shares) -2 (shares are with 3rd party)
shortSaleLocation
string
MPID of third party
66
Order Management Modules
Table 2 - Optional Basket File Fields (in order, continued from Table 1 above) origin character c, f for noncleared customers only only if exchange is BOX
auctionStrategy
number
-1 (match) -2 (improvement) -3 (transparent) i.e. 3.00
startingPrice
number
only if exchange is BOX only if exchange is BOX only if exchange is BOX only if exchange is BOX only if exchange is BOX yes
no
stockRefPrice
number
i.e. 25.00
no
delta
percent
number in range 1-100
yes
stockRangeLower
number
i.e. 20.00
no
stockRangeUpper
number
i.e. 30.00
no
discretionaryAmt
number
i.e. 0.25
no
displaySize
integer
i.e. 100
yes
no
RTHOnly
boolean
true, false
yes
no
blockOrder
boolean
true, false
yes
no
67
TWS Users' Guide
Table 2 - Optional Basket File Fields (in order, continued from Table 1 above) sweepToFill boolean true, false yes no
hidden
boolean
true, false
yes
no
allOrNone
boolean
true, false
yes
no
minQty
number
integer, i.e. 100
yes
no
orderGroup
string
free text, i.e. group1
yes
no
*NOTE: These orders types can only be used in baskets created from a text file. You cannot create MOO and LOO basket order entries from the trading screen. The lines below illustrate how three possible order lines in a basket file would look.
•
A limit order to buy one IBM Oct 2003 call option for $6.70 (times the contract multiplier of 100) with a strike price of $95.00, using IB SmartRouting for the order destination would look like:
BUY, 1, IBM, OPT, 200310, 95.0, C, SMART, LMT, 6.7, •
A VWAP order to sell 100 shares of IBM stock would look like:
SELL, 100, IBM, STK, VWAP, VWAP, , •
A limit order to buy 100 shares of Microsoft stock for $52.85/share using IB SmartRouting would look like:
BUY, 100, MSFT, STK, SMART, LMT, 52.85,
3. Save the file in your directory (it may be in C:\jts). Give the file a meaningful name and use a .bsk file extension. 68
Order Management Modules
To save a basket file in your word processing application a. From the File menu select Save. b. In the Save in field, use the drop-down box to select the directory (i.e. C:\jts). c. In the File name field enter filename.bsk d. In the Save as type field, choose "text only" or ".txt" or "Text Document" (depending on your application). e. Click Save.
Copyrights and Trademarks
69
TWS Users' Guide
Create a Basket File using Excel
You can use Excel to create a basket file which you can easily open as a basket order in TWS. Create a basket file with Excel 1. 2. Open a blank Excel worksheet. Create the orders you want to include in your basket, one per line. Enter a parameter in each successive cell. You must use the following guidelines for creating an Excel basket file:
• •
Include one value, when required or when appropriate for the instrument type, for each field described in the table below. List field values in the order in which they appear below:
Table 1 - Required Basket File Fields (in order) Field action quantity underlying symbol security type expiry strike put-or-call exchange Data Type constant integer string constant date/time number character string Possible Values or Example BUY or SELL e.g. 100 e.g. IBM stk, opt, war, fop, fut YYYYMM e.g. 200610 (for Oct. 2006 expiry) e.g. 42.5 or 37.0 P or C Any valid destination, e.g. Smart, or NYSE or PHLX or VWAP. NOTE: To clarify any ambiguity for Smart routed contracts, include the primary exchange along with Smart for the destination, for example: Smart/NYSE. order type constant LMT or MKT or REL or VWAP (a VWAP order type must also have a destination value of VWAP and the price field must be left blank) or MOO or LOO or MOC or LOC e.g. 96.47 or 85 1/2 (fraction or decimal value) Leave blank for a VWAP aux. price number e.g. .15, 1/8 Yes Yes Req. Field? Yes Yes Yes Yes For futures and options. For options. For options. Yes Req. Value? Yes Yes Yes Yes Yes
Yes Yes Yes
limit price
number
For Limit, Relative and Stop Limit orders only. For Relative,
Yes
Yes. Value may be 0.
70
Order Management Modules
(fraction or decimal value)
Stop and Stop Limit orders only. Relative orders Yes Yes No Yes No
percent offset currency basket tag
number constant string
Any decimal value between 0 and 1, e.g. .05 USD, GBP, etc. Any unique string of alpha or numeric characters used to identify the basket order. This tag appears in the Order Reference field of the Execution report. day, gtc, gtd, ioc, fok, opg, auc YYYYMMDD hh:mm:ss [zzz] where zzz is an optional time zone. If you do not designate a time zone, TWS uses the time zone from which the order originated. YYYYMMDD hh:mm:ss [zzz] where zzz is an optional time zone. If you do not designate a time zone, TWS uses the time zone from which the order originated.
time-in-force goodTilTime
constant date/time
Yes Yes
Yes No
goodAfterTime
date/time
Yes
No
The fields below are optional in the sense that they are not required for a basic order. However, if you want to use any fields, you must also includes values in any preceeding fields.
Table 2 - Optional Basket File Fields (in order, continued from Table 1 above) Field group Data Type string Possible Values or Example existing group name Req. Field? for Advisors only for Advisors only Required Value? No
method
string
• • • • •
PctChange AvailableEquity NetLiq EqualQuantity PctOfPortfolio
only if group is specified
71
TWS Users' Guide
Table 2 - Optional Basket File Fields (in order, continued from Table 1 above) percent percent number in range 1-100, i.e. 100 for Advisors only for Advisors only for Advisors only for noncleared customers only for noncleared customers only for noncleared customers only for noncleared customers only for noncleared customers only for noncleared customers only only if exchange is BOX yes only if method is PctChange no
profile
string
existing profile name
account
string
existing account name
no
account
string
free text
openClose
string
open, close
settlingFirm
string
free text
shortSaleSlot
number
-1 (cust. has shares) -2 (shares are with 3rd party)
shortSaleLocation
string
MPID of third party
origin
character
c, f
auctionStrategy
number
-1 (match) -2 (improvement) -3 (transparent) i.e. 3.00
startingPrice
number
only if exchange is BOX
no
72
Order Management Modules
Table 2 - Optional Basket File Fields (in order, continued from Table 1 above) stockRefPrice number i.e. 25.00 only if exchange is BOX only if exchange is BOX only if exchange is BOX only if exchange is BOX yes no
delta
percent
number in range 1-100
yes
stockRangeLower
number
i.e. 20.00
no
stockRangeUpper
number
i.e. 30.00
no
discretionaryAmt
number
i.e. 0.25
no
displaySize
integer
i.e. 100
yes
no
RTHOnly
boolean
true, false
yes
no
blockOrder
boolean
true, false
yes
no
sweepToFill
boolean
true, false
yes
no
hidden
boolean
true, false
yes
no
allOrNone
boolean
true, false
yes
no
73
TWS Users' Guide
Table 2 - Optional Basket File Fields (in order, continued from Table 1 above) minQty number integer, i.e. 100 yes no
orderGroup
string
free text, i.e. group1
yes
no
3. Save the file with a .csv file extension, for example excelBasket.csv. You can save the file to any directory. You may get several messages when you save, the first saying that the selected file type does not support workbooks with multiple sheets. Click OK at this message. The second tells you your file may contain features not compatible with CSV. Click Yes at this message. For example, a 2-order basket with the first order a limit order to buy 100 shares of IBM at $91.95 using SMART as the destination, and the second a limit order to sell 1 IBM July05 95.00 call option for $2.00 would look like this:
To transmit this order, open the file from your Basket orders pages.
Copyrights and Trademarks
74
Order Management Modules
SpreadTrader
SPREADTRADER
Copyrights and Trademarks
75
TWS Users' Guide
Spread Orders
Create combination limit orders for options (which can include stock legs if routed through SmartRouting) and spread orders for futures. Although a combination/spread order is constructed of separate legs, it is executed as a single transaction if it is routed directly to an exchange. For combination orders that are SmartRouted, each leg may be executed separately to ensure best execution. You can create a unique combination by manually defining an order leg by leg, or create a named strategy using a template. To use stock legs in the order, you must create the combination manually. Currently TWS provides templates to construct the following named option strategies:
•
Vertical spread - An order to simultaneously purchase and sell options at different strike prices, where both have the same underlying, right (call or put) and expiration date. This spread is sometimes referred to as a price spread. Call vertical spread example: Buy 1 June02 100 call, Sell 1 June02 105 call. Put vertical spread example: Buy 1 March02 105 put, Sell 1 March02 95 put Calendar spread - An order to simultaneously purchase and sell options with different expiration dates, where both have the same underlying, right (call or put) and strike price. This spread is sometimes referred to as a time spread. A calendar spread whose options have different expiration dates and different strike prices is sometimes referred to as a diagonal spread. For example: Buy 1 June02 100 call, Sell 1 March02 100 call. Futures Calendar spread - An order to simultaneously purchase and sell futures with different expiration dates, where both have the same underlying. This spread is sometimes referred to as a time spread. For example: Buy 1 FUT Sept03, Sell 1 FUT June03. Diagonal spread - An order to simultaneously purchase and sell options with different expiration dates and different strike prices, where both have the same underlying and right (call or put). For example: Buy 1 June03 100 call, Sell 1 Sept03 105 call. Straddle - An order to simultaneously purchase (or sell) a call and a put in identical numbers, where both have the same underlying, expiration date and strike price. For example: Sell 1 Dec02 90 call, Sell 1 Dec02 90 put. Strangle - An order to simultaneously purchase a call and a put with different strike prices, where both have the same underlying and expiration date. In the case where both the call and the put are out of the money, this order is referred to as an inside strangle. For example: Buy 1 June02 95 put, Buy 1 June02 105 call. Butterfly - An order to simultaneously purchase an option with one strike price, purchase an option with a second strike price, and sell two options with a third strike price that is midway between the prices of the first two options. The ratio for a butterfly is always 1 x 2 x 1. For example: Buy 10 March02 95 calls, Sell 20 March02 100 calls, Buy 10 March02 105 calls. Synthetic - An order to simultaneously purchase a call and sell a put in identical numbers (or sell a call and purchase a put in identical numbers), where both have the same underlying, expiration date and strike price. Purchase a synthetic: Buy 1 April02 100 call, Sell 1 April02 100 put. Sell a synthetic: Sell 1 April02 100 call, Buy 1 April02 100 put.
•
•
•
•
•
•
•
76
Order Management Modules
•
Box - An order to simultaneously purchase and sell two synthetics in identical numbers at different strike prices. For example: Buy 1 April02 95 call, Sell 1 April02 95 put, Sell 1 April02 100 call, Buy 1 April02 100 put. Synthetic Put - An order to simultaneously purchase (or sell) a call option and sell (or purchase) stock where both have the same underlying. Purchase a synthetic put: Buy 1 XYZ April03 75 call, Sell 100 shares XYZ Sell a synthetic put: Sell 1 XYZ April03 75 call, Buy 100 shares XYZ. Synthetic Call - An order to simultaneously purchase (or sell) a put option and purchase (or sell) stock where both have the same underlying. Purchase a synthetic call: Buy 1 XYZ April03 75 put, Buy 100 shares XYZ Sell a synthetic put: Sell 1 XYZ April03 75 put, Sell 100 shares XYZ. Conversion - An order to simultaneously sell (or purchase) a call option and purchase (or sell) a put option in identical numbers where both have the same underlying, expiration date and strike price, and purchase stock of the same underlying. Purchase a conversion: Sell 1 XYZ April04 75 call, Buy 1 XYZ April04 75 put, Buy 100 shares XYZ Sell a conversion: Buy 1 XYZ April04 75 call, Sell 1 XYZ April04 75 put, Sell 100 shares XYZ Reversal- An order to simultaneously purchase (or sell) a call option and sell (or purchase) a put option in identical numbers where both have the same underlying, expiration date and strike price, and sell stock of the same underlying. Purchase a reversal: Buy 1 XYZ April04 75 call, Sell 1 XYZ April04 75 put, Sell 100 shares XYZ Sell a reversal: Sell 1 XYZ April04 75 call, Buy 1 XYZ April04 75 put, Buy 100 shares XYZ Risk Reversal- An order to simultaneously purchase (or sell) a put option and sell (or purchase) a call option in identical numbers where both have the same underlying and expiration date, but the call generally has a higher strike price. Purchase a risk reversal: Buy 1 XYZ April04 75 put, Sell 1 XYZ April04 95 call Sell a risk reversal: Sell 1 XYZ April04 75 put, Buy 1 XYZ April04 95 call Buy Write - An order to simultaneously purchase (sell) a stock and sell (purchase) a call option of the same underlying. Purchase a Buy Write: Sell 1 XYZ April06 95 call, Buy 100 shares XYZ Sell a Buy Write: Buy 1 XYZ April06 95 call, Sell 100 shares XYZ
•
•
•
•
•
•
For more information on combination orders and margin requirements for combination orders, see U.S. Equity Options Margin Requirements on the IB website.
Copyrights and Trademarks
77
TWS Users' Guide
Create a Spread Order
You can create any kind of combination spread order using the Combination Composition box, including futures spreads and inter-market Smart combos.
To create an Inter-market spread or Smart Combo order 1. Right click on a blank line and select Generic Combo, or right click on a blank line and select Order then click the Combo radio button at the top of the page, or create a market data line with the instrument type Comb. In the Leg Query section, enter the underlying symbol for the first leg of the order.
2.
Use the Leg Definition section to define parameters of the leg. When finished click Add Leg. 3. 4. Or simply drag a market data line from the trading screen into the bottom of the Leg Definition area. After you have added all desired legs click OK, and the spread appears as a market data line on your trading screen.
The implied price is calculated based on the underlying price of each leg, and changes with variations in the price of each underlying. Based on the implied price, SmartRouting will route each leg of the order separately to get the best price. NOTE: To see individual leg prices for a combination or spread order, open the Execution reports window by clicking the Trades icon on the Trading Toolbar. Double-click the desired combination execution report line in the Execution window (or right-click on the line and select Show Legs) to open the Execution Window for Legs.
78
Order Management Modules
To create a combination strategy 1. 2. 3. 4. Right-click on a blank line and select Generic Combo, or create a market data line with the instrument type Comb. In the Leg Query section, enter the underlying symbol for the first leg of the order. Use the Combo Template tab to select a strategy. Select data for all legs of the order and click OK. The combination order strategy appears on your trading screen as a market data line.
Copyrights and Trademarks
79
TWS Users' Guide
Using the Combination Composition Window
Use the Combo Template tab to select a recognized combination order and define the necessary parameters. Use the Generic Combo tab to create the combination one leg at a time.
Combo Template
Field Name Leg Type Description The order type, Option or Future, is selected based on the underlying and exchange you entered. If both choices are active, select the order type you want to create. Combination strategies are listed based on the Leg Type you selected. For descriptions of option combination strategies, see the Combination Orders topic. Use the Help button for strategy descriptions. Select the contract multiplier. Select Sell Combo or Buy Combo in the graph drop-down to see what the combination order looks like. The worksheet categories display drop-down list boxes each time you need to make a selection. Move through the worksheet and select choices as needed. Reset Request market data for all legs Click Reset to start over, either by selecting another strategy or editing the legs of the chosen strategy. Check to create a market data line for each leg of the order, to be displayed on the trading screen.
Strategy
Multiplier Worksheet
Generic Combo
Field Name Leg Definition Description Select values to define a specific leg of the combination order. The values displayed in the selection fields are context-sensitive. To ensure that all information is valid, the value in each field is locked in as you move to the next field. To modify criteria, click Reset. Leg Type - The instrument type. Expiry - Select the expiry for the current leg. Right - Select the right (call or put) for the current leg. Strike - Select a strike price for the current leg. Ratio - Select the relative number of contracts for the leg you are constructing. To help determine the ratio for a specific combination order, use Interactive Analytics. First, edit the Interactive Analytics option model, then view model outputs using option analytics. Action - Select Buy or Sell as the action for the current leg. Button Name Add Leg Reset Help Delete Leg 80 Description Adds the leg you just defined to the combination order. The leg is displayed in the table below the buttons. Clears all values from the Leg Definition fields above. Displays button help. Deletes the highlighted leg from the leg table.
Order Management Modules
Field Name Request market data for all legs OK/Cancel
Description Check to create a market data line for each leg of the order, to be displayed on the trading screen. Click OK to save the combination order. The current order is highlighted on the trading page, and named if the combination you created was a recognized strategy.
Copyrights and Trademarks
81
TWS Users' Guide
Transmit a Spread Order
To create a combination order Before you transmit a combination order, you carefully review your order parameters on the order management line, or from the Order Ticket window by clicking Accept. 1. From the market data line, click the "Ask" or "Bid" price for the combination order you want to create.
• •
2.
Click the Ask Price to create a Buy order. Click the Bid Price to create a Sell order.
On the Order Management line, modify order parameters, if needed. Note on pricing: If you buy a spread and you owe cash (debit spread), enter a positive limit price. If you buy a spread and you receive cash (a credit spread), you must enter a negative limit price. Conversely, if you sell a spread and receive cash, enter a positive limit price. If you sell a spread and owe cash, you must enter a negative limit price. For example, an April 20 xyz call shows a BID price of 6.60 and an ASK price of 6.70. An April 30 xyz call shows a BID price of 0.15 and an ASK price of 0.20.
If you buy a "debit" call vertical spread with the following legs: Buy 1 OPT APR02 20.0 CALL (6.70) Sell 1 OPT APR02 30.0 CAL L (0.15) For this transaction you pay: 6.55 (a debit transaction) If you buy a "credit" call vertical Sell 1 OPT APR02 20.0 CALL Buy 1 OPT APR02 30.0 CALL For this transaction you receive 3. Transmit the order. spread with the following legs: (6.60) (0.20) 6.40 (a credit transaction; enter a negative limit price).
Copyrights and Trademarks
82
Order Management Modules
Notes on Spread Orders
This page contains notes and tips on creating and transmitting combination orders.
• •
Use SmartRouting to execute legs separately to ensure you get the best price on all legs of your order. Exchanges that currently support native combination orders (which means they execute the legs together as one transaction) include:
• • • •
ISE ONE DTB (Euro)
To help determine the ratio for a specific combination order, use our Price/Risk Analytics tools. First, edit the model using the Option Modeler, then view model outputs using Option Analytics. Note on pricing: If you buy a spread and you owe cash (debit spread), enter a positive limit price. If you buy a spread and you receive cash (a credit spread), you must enter a negative limit price. Conversely, if you sell a spread and receive cash, enter a positive limit price. If you sell a spread and owe cash, you must enter a negative limit price. For example, an April 20.0 xyz call shows a BID price of 6.60 and an ASK price of 6.70. An April 30 xyz call shows a BID price of 0.15 and an ASK price of 0.20.
•
If you buy a "debit" call vertical spread with the following legs: Buy 1 OPT APR02 20.0 CALL (6.70), Sell 1 OPT APR02 30.0 CAL L (0.15) For this transaction you pay: 6.55 (a debit transaction) If you invert the legs and buy a legs: Sell 1 OPT APR02 20.0 CALL Buy 1 OPT APR02 30.0 CALL For this transaction you receive price) "credit" call vertical spread with the following (6.60) (0.20) 6.40 (a credit transaction, enter a negative
• •
When you create a combination order using the Order Ticket window, click Accept (rather than Transmit) to verify your order parameters. Before you transmit a combination order, carefully review the order parameters from the Order Management line.
Copyrights and Trademarks
83
TWS Users' Guide
Volatility Trading
VOLATILITY TRADING
Copyrights and Trademarks
84
Order Management Modules
Volatility Trading
You can apply a volatility page layout that lets you create option orders based on volatility instead of price. To use the Volatility layout for an existing page 1. 2. On the Page menu select Settings. In the Layout drop-down, select Volatility and click OK.
When you apply the Volatility layout, the Bid Price and Ask Price fields display volatility instead of price. You will also see several volatility columns including the Model price and Implied Volatility fields on the Market Data row, and the Volatility field on the Order Management row. NOTE: If you have options listed on the same trading page as stocks, when you switch to Volatility layout you will still see the normal bid/ask prices for your equity contracts. For pages using the Volatility layout, you can elect to toggle the view for an individual order between price-based and volatility-based. To toggle between price- and volatility-based order
•
Right click on an order management line and select the active view option, either Convert to price based or Convert to volatility based. Note: You can only toggle between views on pages that are using the Volatility layout.
Copyrights and Trademarks
85
TWS Users' Guide
Calculate Order Quantity
CALCULATE ORDER QUANTITY
Copyrights and Trademarks
86
Order Management Modules
Determine Order Quantity
When you create an order, you can define the order size several different ways. You can set a general default order size that is used for all orders. You can set specific default sizes for instrument types, for example a quantity of 500 for all stock orders. You can even get more specific and set the default order size for a specific contract, for example set the quantity for all stock orders for underlying XYZ to 1000.
Alternatively, you can set a default currency amount that will be used to calculate the order size. For example, set the default amount for stocks to $5000.00. The order quantity is then calculated based on the stock price, and is rounded to the nearest 100 for U.S. stocks. You can also have TWS calculate the order quantity by Deliverable value amount, a percent of your Net Liquidation value, or based on a percentage of your current position.
Copyrights and Trademarks
87
TWS Users' Guide
Calculate Order Quantity
Use the Quantity Type and Quantity Value fields to calculate your order quantity based on:
• • • •
Currency- assumes the base currency DLV Amount - Deliverable Value % of NLV - percent of Net Liquidation Value % Change in Position - percent of the change for your position in the underlying.
For example, say you have a Net Liquidation Value of 40,000. XYZ shows a current ask price of 80.00. If you create a buy order for XYZ, select "% of NLV" as the Quantity Type and enter "20" in the Quantity Value field, you're telling TWS to calculate the number of shares you could buy for 20% of $40,000 or $8000.00, based on the Ask price of $80.00. The calculated Order Quantity value of "100" is then displayed in the Quantity field. To display the Quantity Type and Quantity Value fields 1. Right-click on any column name in the Order Management section of the trading screen, and click Customize Layout. In the Order Row section of the Layout Manager, check Quantity Type and Quantity Value and click OK.
2.
88
Order Management Modules
To calculate order quantity by currency 1. 2. 3. Create an order by clicking the bid or ask price. In the Quantity Type field, select the currency type. This field assumes the base currency. In the Quantity Value field, enter a currency amount. For a buy order, enter the amount you want to spend. For a sell order, enter the amount you want to make. Based on the current bid/ask, TWS rounds your value up or down.
The order quantity is calculated and displayed in the Quantity field.
To calculate order quantity by Deliverable Value (DLV Amount) 1. 2. Create an order by clicking the bid or ask price. In the Quantity Type field, select DLV Amount. For stocks, the deliverable value is the value of the stock converted to the base currency. For options, it is the value of the underlying stock represented in base currency (i.e. stock price * options multiplier). 3. In the Quantity Value field, enter the dollar amount of your deliverable value you want to use to calculate the order quantity. The order quantity is calculated and displayed in the Quantity field. To calculate order quantity as a % of your Net Liquidation Value (% NLV ) 1. 2. Create an order by clicking the bid or ask price. In the Quantity Type field, select % NLV The Net Liquidation value is the first value in the upper left Balance area of the Account window.
89
TWS Users' Guide
3. In the Quantity Value field, enter a percent value that will multiplied by your NLV to calculate a dollar amount. The order quantity is calculated and displayed in the Quantity field.
To calculate order quantity as a % of position change 1. 2. Create an order by clicking the bid or ask price. In the Quantity Type field, select % Change in Position. If you do not hold a position in the selected underlying, you will not see this selection. 3. In the Quantity Value field, enter a percent value that will multiplied by your position to calculate the order quantity. Note that if your position is negative, you must enter a negative percent value to calculate a positive order quantity. The order quantity is displayed in the Quantity field.
Copyrights and Trademarks
90
Order Management Modules
Multi-client Trade Allocation
MULTI-CLIENT TRADE ALLOCATION
Copyrights and Trademarks
91
TWS Users' Guide
Advisors - Allocating Shares
We provide several ways to distribute shares among accounts when you create an order. You can select an Account Group, which comprises a pre-defined group of accounts and an associated allocation method. The Account Group allocates shares based on a ratio calculated by the system, or by a percentage. The numbers used to calculate the ratio derive from the method you chose when you created the group, or by the percent change you set. A second way to allocate shares is through an Allocation Profile, which distributes shares to each account in a profile based on a percentage, ratio or absolute number that you define. Both of these methods require that you create a group, assign accounts to the group, and define the group's allocation method. You can also direct an order to a single account by selecting that account from the Allocation field on the order management line.
Copyrights and Trademarks
92
Order Management Modules
Create an Order for Multiple Clients
Advisors can trade stock, options, futures, options on futures and foreign exchanges for Separately Managed Accounts (SMAs) using the Allocation column on an Order Management line. To create an order for multiple clients 1. Click the "Ask" or "Bid" price on a market data line to create an order.
• •
2. 3.
Click the Ask Price to create a Buy order. Click the Bid Price to create a Sell order.
Right-click on the order and select Modify then select Share Allocation. In the Allocation dialog box, select an Account Group in the Automatic Allocation area, an Account Profile in the Manual Allocation area, or select a single account. You can also use the drop-down list in the Allocation field on the trading screen to select an Account Group, an Allocation Profile or an individual account. a. For the Account Group, modify the allocation method if necessary. If you choose the PctChange method, enter a positive or negative value in the Percentage field. All other automatic allocation methods are calculated using the order size. If you use an Allocation Profile, select a group name. To allocate all shares to one account, select a single account.
b. c. 4. 5.
Click OK to complete the order. To Transmit, click the red "T" in the Transmit field.
Copyrights and Trademarks
93
TWS Users' Guide
Create Account Aliases
You can assign recognizable names to accounts using the Account Aliases dialog box. When you create an order, the account alias appears in the Allocation list instead of the individual account number. To create an account alias 1. 2. On the Configure menu select Advisor then select Account Aliases. Enter a recognizable name in the Alias column for the selected account. Note that when you create an order, the choices displayed in the Allocation list are grouped by Account Groups, then Allocation Profiles, and then individual accounts. However, they are not identified in any other way. When you create an account alias, you may want to include a prefix such as "IA" to identify the selection as an individual account.
Copyrights and Trademarks
94
Order Management Modules
Create a Share Allocation Profile
You can create profiles that allocate specific percentages or shares of each order to individual accounts based on the rules you set and values you input. To create a share allocation profile 1. 2. On the Configure menu, select Advisor, then select Allocation Profiles. Click Create and enter a profile name, preferably one based on the way you plan to allocate shares between clients. Note that when you create an order, the choices displayed in the Allocation list are grouped by Account Groups, then Allocation Profiles, and then individual accounts. However, they are not identified in any other way. When you create a profile, you may want to include a prefix such as "P" in the name to identify the choice as a profile. 3. In the Allocation Profile specifies area, select a method of allocating shares between accounts:
•
Percentages - this method will split the total number of shares in the order between listed accounts based on the percentages you indicate. For example, an order for 1000 shares using a profile with four accounts at 25% each would allocate 250 shares to each listed account in the profile. Ratios - this method calculates the allocation of shares based on the ratios you enter. For example, an order for 1000 shares using a profile with four accounts set to a ratio of 4, 2, 1, 1 would allocate 500, 250, 125 and 125 shares to the listed accounts, respectively. Shares - this method allocates the absolute number of shares you enter to each account listed. If you use this method, the order size is calculated by adding together the number of shares allocated to each account in the profile.
•
•
4. Click in the Account field to view all accounts. Select an account and tab over to the Value field. 5. Enter the percent, ratio or number of shares to be allocated to the selected account (you may need to delete the current value). Tab to create a new account line. NOTE: If you use percentages to allocate shares, percentages allocated must equal 100. If you use ratios, The system automatically calculates these percentages. 6. OK. Continue until you have listed all the desired accounts for the current profile, and click
Copyrights and Trademarks
95
TWS Users' Guide
Create an Account Group for Share Allocation
You can use an Account Group to automatically calculate ratios and allocate order shares to a pre-defined group of accounts based on a selected allocation method. When you create an order and choose a group, the order uses the default method to allocate shares amongst the accounts in the group. To create an Account Group 1. 2. On the Configure menu, select Advisor, then select Account Groups, and click Create. Enter an Account Group name. Do not use the name "All" since this is reserved by the system. Note that when you create an order, the choices displayed in the Allocation list are grouped first by Account Groups, then Allocation Profiles, and then individual accounts. However, they are not identified in any other way. When you create an account group, you may want to include a prefix such as "AG" in the name to identify the choice as an Account Group. 3. Select a default allocation method. You can change the allocation method for each order.
•
EqualQuantity - Requires you to specify an order size. This method distributes shares equally between all accounts in the group. Example: You transmit an order for 400 shares of stock ABC. If your Account Group includes four accounts, each account receives 100 shares. If your Account Group includes six accounts, each account receives 66 shares, and then 1 share is allocated to each account until all are distributed.
•
NetLiq - Requires you to specify an order size. This method distributes shares based on the net liquidation value of each account. The system calculates ratios based on the Net Liquidation value in each account and allocates shares based on these ratios. Example: You transmit an order for 700 shares of stock XYZ. The account group includes three accounts, A, B and C with Net Liquidation values of $25,000, $50,000 and $100,000 respectively. The system calculates a ratio of 1:2:4 and allocates 100 shares to Client A, 200 shares to Client B, and 400 shares to Client C.
• •
AvailableEquity - Requires you to specify an order size. This method distrib utes shares based on the amount of equity with loan value currently available in each account. The system calculates ratios based on the Equity with Loan value in each account and allocates shares based on these ratios. Example: You transmit an order for 700 shares of stock XYZ. The account group includes three accounts, A, B and C with available equity in the amounts of $25,000, $50,000 and $100,000 respectively. The system calculates a ratio of 1:2:4 and allocates 100 shares to Client A, 200 shares to Client B, and 400 shares to Client C.
96
Order Management Modules
•
PctChange - Do not specify an order size. Since the quantity is calculated by the system, the order size is displayed in the Quantity field after the order is acknowledged. This method increases or decreases an already existing position. Positive percents will increase a position, negative percents will decrease a position. BUY ORDER Long Position Short Position Negative Percent No effect Decreases position
Positive Percent Increases position No effect
SELL ORDER Long Position Short Position
Positive Percent No effect Increases position
Negative Percent Decreases position No effect
Example 1: Assume that three of the six accounts in this group hold long positions in stock XYZ. Client A has 100 shares, Client B has 400 shares, and Client C has 200 shares. You want to increase their holdings by 50%, so you enter "50" in the percentage field. The system calculates that your order size needs to be equal to 350 shares. It then allocates 50 shares to Client A, 200 shares to Client B, and 100 shares to Client C. Example 2: You want to close out all long positions for three of the five accounts in a group. You create a sell order and enter "-100" in the Percentage field. The system calculates 100% of each position for every account in the group that holds a position, and sells all shares to close the positions. 4. The list of accounts in the Non Group Account section includes all accounts available to you. To add an account to the group, select a Non Group account and click Add. 5. Click OK to save the group and its settings.
Copyrights and Trademarks
97
TWS Users' Guide
Edit a Share Allocation Profile
After you have created share profiles, you can select one when you create an order. To edit a share allocation profile 1. 2. 3. 4. From the Configure menu, select Advisor then select Allocation Profiles. Select an Allocation Profile and click Edit. In the Allocation Profile window, you can add or delete accounts, select a different allocation method, or modify the allocated percentage or ratio for any accounts. Click OK to save the edited profile. NOTE: Percentages allocated must equal 100. If you use ratios, the system will automatically calculate share percentages based on the ratios.
Copyrights and Trademarks
98
Order Management Modules
Advisors - View Execution Reports for SMAs
The Executions window lets you see execution reports for all SMAs (Separately Managed Accounts) or for a selected account. To view execution reports for a specific account 1. 2. Open the Executions window by clicking the Trades icon on the toolbar, or selecting Executions from the View menu. In the Account drop-down field, select the account for which you want to view execution reports.
Copyrights and Trademarks
99
TWS Users' Guide
Advisors Account Window
To select an account 1. 2. Open the Account window by clicking the Account icon on the toolbar, or use the Configure menu to select Advisors, then select Accounts. In the Multiple Account Name area, use the Account drop-down to select the managed account whose information you want to view. Use the Groups selection to choose one group which includes all accounts.
Copyrights and Trademarks
100
Order Management Modules
Change Order Defaults & Assign Shortcuts
ORDER DEFAULTS AND HOT KEYS
Copyrights and Trademarks
101
TWS Users' Guide
Default Order Settings Window
A "default" order parameter is the value that automatically appears on your order management line when you create an order. The system uses default values to help save time. Instead of invoking a completely blank order management line, when you instigate an order each field is filled in with a default value. Each of these parameters can be manually changed on your trading screen before you transmit an order, but if you use certain parameters for most of your orders, you will save time by making that value your default order value. For example, if you use VWAP orders 95% of the time, you can change your Default Order Type to VWAP. Now each time you click on the Bid or Ask price to create an order, the order type and order destination are automatically set to VWAP. You use the Default Order Settings window to modify the default order values, including order type, order size, offset amounts and time in force, for specific instrument types. You can also set order defaults that will only be applied to a specific contract. To change order defaults for an instrument type 1. 2. 3. 4. On the Configure menu, Global Configuration. In the left pane, click Order and then Order Defaults. If desired, in the center pane select a specific instrument type. If not instrument is selected, the defaults you set will apply across all asset classes. In the right pane, set order defaults by choosing from selections.
• •
Default Order Type - use the Type drop-down to choose an order type. Default Order Sizes and Offsets - to edit values in the table, triple-click an entry and type your new data over the existing value. Alternatively, set the system up to automatically save a modified order size as the default order size for that instrument type. On the Order menu select Auto-Save Default Size.
•
Other Default Order Settings
Left Pane - Instrument Types
Instrument Type Abbreviation STK IND OPT FUT FOP WAR SPRD BAG Market Data Line Equivalent Stock Index Option Future FutOpt Warrant FutSprd Comb Full Name
Stock Index Option Future Futures Option Warrant Futures Spread Combination order
102
Order Management Modules
Instrument Type Abbreviation CASH
Market Data Line Equivalent Cash
Full Name
Cash
Right Pane - Default Order Type
Type LMT MKT STP Order Type Limit Market Stop Description An order to buy or sell a contract at a specified price or better. An order to buy or sell a contract at the bid or offer price currently available in the marketplace. An order to buy or sell a contract which becomes a market order once the specified stop price is attained or penetrated. An order to buy or sell a contract which becomes a limit order once the specified stop price is attained or penetrated. Allows the customer to enter a more aggressive price than the current market price, and have the entered price stay within a fixed interval to the market should prices deteriorate. Your order is pegged to buy on the best offer, and sell on the best bid. The Volume Weighted Average Price for a stock. VWAP is calculated by adding the dollars traded for every transaction in that stock and dividing the total shares traded. An order submitted no later than 15 minutes prior to the close of the market, that will execute as a market order as close to the closing price as possible. An order submitted no later than 15 minutes prior to the close of the market, that will execute at the closing price if the closing price is equal to or better than the submitted limit price. A sell (buy) order where the stop price is set at some fixed amount below (above) the market price. If the market price rises (falls), the stop loss price rises (falls) by this amount, but if the stock price falls (rises), the stop loss price doesn't change. This technique allows an investor to specify a limit on the maximum possible loss, without setting a limit on the maximum possible gain.
STP LMT REL
Stop Limit
Relative
PEG MKT VWAP
Pegged Market VWAP
MKT CLS
Market-onclose (MOO)
LMT CLS
Limit-onclose (LOO)
TRAIL
Trailing stop
For more detailed order type descriptions, refer to the order types page in the User's Guide.
103
TWS Users' Guide
Right Pane - Default Order Sizes and Offsets Field Use closing position size if possible Description When checked, if you hold a position in the asset, the system will create the order equal to the quantity of your open position on the assumption that you want to close out your position. If you hold no position, the system will use the default order size. If checked, when you create an order from any line in the market depth window, the order size is set to the total cumulative size available for that asset. Otherwise, the order size will be equal to the quantity in the Size field of the order line from which the order is created. If checked, the default order size will be calculated based on the dollar amount you enter in the Def Amount field on this page. The calculated order size is then displayed in the Quantity field on the trading page as the default amount. Default Size - the default order size. Size Increment - the interval by which the order size increases/decreases are displayed when using the size wand, or the amount by which the quantity will increase/decrease when using the hotkeys. The default amount that will be displayed for Iceberg orders. The amount off the current market price that will be used for auto stop orders to set the stop election price. This value is used to calculate the stop price and the limit price for attached bracket orders. The amount off the current market price by which you want the stop price to trail. The amount that will be added to the best bid (for a buy order) and subtracted from the best ask (for a sell order) to create the limit price at which the relative order will be submitted. The Notes
Use cumulative size for Market Depth
We do not recommend creating orders from the Market Depth window.
Use Default Amount to Calculate Size
This is a different way to set the default order size. You can still modify the order size on the trading page.
Def Size Size Inc
Display Size Stp Offset
Trailing Amt
Relative Amt
Discretionary Amt
Right Pane - Other Default Order Settings Field Order Origin 104 Description Notes Defines the origin of your order in relation to the market.
Order Management Modules
Field Time in Force
Description Select from
Notes
• • • • •
Percentage
Day GTC (good 'till cancelled) OPG (at the open, valid with Limit and Market orders IOC (Immediate or cancel) AUC (Price Improvement Auction)
Size Limit
Number of ticks
Regular Trading Hours only
This option was created as a safety net to prevent you from transmitting a limit order that has a mistyped limit price. If you attempt to transmit a limit order with a price outside of this calculated percent off the market price, you will receive a message asking you to verify that you meant to enter that offpercentage price before it will transmit the order. The market price used is the price displayed in either the bid (sell) or ask (buy) field at the time you transmit the order. This option can be left blank. Limits the value in the Quantity field. If you enter a higher value, you can override the default size limit by clicking Yes in the warning box. Like the Percentage option above, number of ticks is also a safety net to prevent you from transmitting a limit order that has a mistyped limit price. If you attempt to transmit a limit order with a price outside of this calculated number of ticks off the market price, you will get a message asking you to verify that you meant to enter the off-percentage price before it will transmit the order. The market price used is the price displayed in either the bid (sell) or ask (buy) field at the time you transmit the order. This option can be left blank. Valid for US stocks Checked by default. If unchecked, listed on major trading hours are determined by the exchanges. opening/closing times of the order destination. Not available for IOC, OPG (MOO and LOO), FOK, MOC or LOC orders. Right Pane - OCA Group
•
Partially filled instructions - Set instructions on how to behave when order is partially filled. The default is to have other orders in the OCA group proportionately reduced in size based on the quantity of the filled portion. Overfill Protection - Dictates that only 1 order in the group will be routed to an exchange at a time. This completely removes the possibility of an overfill.
•
Copyrights and Trademarks
105
TWS Users' Guide
Default Offset Amount
An offset amount is the amount off the current price used for the order. Using the default offset amount of 1.0, a bracket order with a price of $50.00 would create high side and low side orders at $51.00 and $49.00. You can modify the default offset amount of 1.0 that is currently used to set the price for auto stop, trailing stop and bracket orders. To modify the default offset amount 1. 2. On the Configure menu, click Order and then click Order Defaults In the Default Order Sizes area, change the offset amount (in the last column) for the selected specific instrument type. NOTE: To set a default offset for a specific contract rather than an instrument type, select an instrument type and click Add. Enter an underlying symbol and click OK.
Copyrights and Trademarks
106
Order Management Modules
Modify the Stop Trigger Method
By default, the double bid/ask trigger method is used to trigger simulated stop, simulated stop-limit, and trailing stop orders for OTC stocks and U.S. options. Use the Trigger Configuration box to modify the trigger method for these order types. All other order types must use the last method. NOTE: Cash contracts must always use the double bid/ask trigger method. To modify the stop trigger method 1. 2. Right-click on the market data line for a stop, stop-limit, or trailing stop order and select Trigger Method. Select the trigger method to use for the current transaction. Description For a sell (buy) order to be triggered:
Trigger Method
•
Last
One last price value must be less than (greater than) or equal to the trigger price The exchange or other market center where the order is to be executed must also publish (and the system must also receive) an ask price equal to or higher than, and a bid price equal to or lower than, the trigger price.
•
Double bid/ask (Default)
For a sell (buy) order to be triggered:
•
Two consecutive ask price (bid price) values must be less than (greater than) or equal to the trigger price.
NOTE: The Last method has leeway to trigger up to 0.5% above the ask price or up to 0.5% below the bid price. This 0.5% amount of leeway is subject to change at any time without notice.
Copyrights and Trademarks
107
TWS Users' Guide
Edit SmartRouting Directives
You can define event-specific directives for contracts routed through IB SmartRouting, specifically excluding exchanges and setting a price cap by defining the acceptable distance from the NBBO. To modify SmartRouting functionality 1. 2. 3. On the Configure menu select Global Configuration. Click Smart Routing in the left pane. Use the right panel to set these parameters:
Excluded Exchanges Use this area to direct SmartRouting NOT to route to a specific exchange for a specific contract. Enter the underlying and select the security type. Valid exchanges that may be excluded are available in the Exchange drop down list. Excluded Quotes
• •
Exclude exchanges with non-firm quotes - if the available quantity is over 100, the quote is considered firm. Exclude exchanges whose quotes are not automatically executable. If this option is selected, IB will use its best efforts to determine which exchanges’ quotes are immediately automatically executable, and which exchanges’ quotes would require manual (human) handling, and IB will route only to those exchanges offering automatic execution. Please note that while IB will use its best efforts, it is not always possible to determine whether a quote is automatically executable.. Define the NBBO price cap by entering the "maximum allowable distance from NBBO." Note that NBBO price capping supersedes the exclusion of non-firm quotes, i.e. your order will be routed to a non-firm quote within the price cap over a firm quote outside the price cap.
•
Pre-Open Re-route This allows you to route orders to major exchanges three minutes before the open. For orders submitted before the open, checking this box ensures your orders are routed prior to the open. This directive only applies to stocks listed on a major exchange. IMPORTANT NOTE: If you choose to: 1) exclude quotes from certain exchanges; 2) exclude non-firm quotes; or 3) exclude exchanges whose quotes are not automatically executable, your order may not be executed at the best posted price nationally (the “NBBO”). This is because one of the exchanges that you chose to exclude might have the best posted price but that exchange will be bypassed by the IB SmartRouting system on your instruction. In addition, if you exclude certain exchanges from the eligible SmartRouting destinations and your order is routed to another exchange with an inferior posted price, your order may not be executed by the exchange to which it is sent because that exchange or ECN may not be willing to execute at an inferior price, or your order may not be marketable at that exchange. You should carefully evaluate all of these factors before deciding whether to exclude certain exchanges from the eligible IB SmartRouting destinations.
Copyrights and Trademarks
108
Order Management Modules
Update Limit Price
You can automatically update the limit price for an order (or all orders) to coincide with the ask, bid, midpoint, closing or last price. Automatically update the limit price 1. 2. On the Order menu select Update Limit Prices. Set update parameters:
• • •
Update price for a single order or all current orders. Set the update parameters for Buy orders and include an offset amount if desired. Set the update parameters for Sell orders. If you check Mirror image of buy orders, parameters are set reversed from the Buy orders selections. The mirror images of Midpoint, Last and Close would be the negative values for each of these prices.
Copyrights and Trademarks
109
TWS Users' Guide
Assign Quick-Action Hot Keys
Assigning actions to specific keys and key combinations helps you rapidly create and transmit orders to the marketplace. You can assign any keystroke, or a combination of the "Ctrl" and "Shift" keys with one of the 26 keyboard letters, to map specific order creation and order transmission commands, such as buy, sell, transmit and cancel. To record hot keys 1. 2. 3. 4. On the Configure menu, select Global Configuration, then select Hot Keys from the left pane. In the Possible Actions area, choose an action to which you want to assign a hot key and click Create Shortcut. In the Keyboard area, click Record. If you already have a hot key recorded for the selected action, it is displayed in the Current Key Shortcut field. Press the actual keystroke or keystroke combination you will use to complete this action. The system records your keystroke and displays it in the Current Key Shortcut field.
NOTE: If the Customize tab is visible, you can customize your hot key to be more specific. For example, after you record a Buy hot key, customize it to create a bracket or trailing stop limit order. After you record the desired hot keys and click Close, the mapped keys are displayed on the status line at the bottom of the screen. To re-record a hot key assignment, follow steps 1-4 above. To remove a hot key assignment from an action, click Clear. Specific Hot Key Procedures and Information
• •
View a table of field definitions for buy/sell hotkeys. Create a Buy/Sell hot key for a specific order type (i.e. Buy Limit Order, Sell Stop Order) 1. 2. 3. 4. 5. 6. 7. 8. On the Configure menu click Hot Keys Select Buy or Sell as the Action and click Create Shortcut. Click the Customize tab. In the Order Type drop-down select the order type for which you want to create a hot key. Populate any necessary order type-related fields. Click the Shortcuts tab. Click Record and press the keystroke combination that will represent the order type hot key. Verify that the hot key has been properly recorded in the Shortcuts section.
•
Instantaneous transmission When you create a buy or sell hot key for any order type, you can elect to "Transmit the order instantaneously" by checking this feature at the bottom of the Customize page. When you activate instantaneous transmission, using the hot key combination creates and transmits the order without giving you time to review and modify order parameters.
110
Order Management Modules
Leave this feature unchecked to have the hot key combination create an order and leave it on the trading screen for you to manually transmit.
•
Attach bracket orders 1. 2. 3. 4. 5. On the Configure menu, select Hot Keys Select Buy or Sell as the Action and click Create Shortcut. Click the Customize tab. In the Attached Orders area, check Add Simple Bracket. In the Bracket Orders area: • In the Lmt Price (+/- offset) field select Bid, Ask, Last or None as the basis for the Limit Price portion of the bracket order, and enter an offset amount if desired. • Select a Stop Type. • Set the Stop price and offset for the stop trigger price. • For Stop Limit orders, set the Stop Limit price and offset. On the Shortcuts page record the hot key combination, and click OK.
6.
•
Create Increase (Decrease) Order Size hot key 1. 2. 3. 4. 5. 6. On the Configure menu select Hot Keys. Select Increase (Decrease) price or size and click Create Shortcut. On the Customize tab select Size in the Field drop-down. Set the Num Ticks value to represent the increment by which to increase (decrease) the default order size. On the Shortcuts page, click Record and press the hot key combination to represent Increase (Decrease) order size. Close the dialog box.
•
Create Increase (Decrease) Limit (Aux.) Price hot key 1. 2. 3. 4. 5. 6. On the Configure menu select Hot Keys. Select Increase (Decrease) price or size and click Create Shortcut. On the Customize tab select Limit Price (Aux. Price) in the Field drop-down. Enter the Num Ticks increment by which you want the hot key to increase (decrease) the price value. On the Shortcuts page, click Record and press the hot key combination to represent Increase (Decrease) Limit (Aux.) Price. Close the dialog box.
•
Use All Available for Buy/Sell Order Quantity 1. 2. 3. 4. On the Configure menu click Hot Keys Select Buy or Sell as the Action and click Create Shortcut. Click the Customize tab. In the Size field, select Available, then click OK.
Now when you use the Buy or Sell hotkey, the order quantity will be determined by the number of available contracts as shown in the Ask Size or Bid Size field.
•
Change order type/time in force 111
TWS Users' Guide
1. 2. 3. 4.
On the Configure menu select Hot Keys. In the Modify/Transmit Order section, select Modify Order Type or Modify Time in Force and click Create Shortcut. On the Shortcuts page, click Record and press the hot key combination. Close the dialog box.
•
Open the Alerts box to view/set alerts 1. 2. 3. 4. 5. On the Configure menu select Hot Keys. In the Real-time Activity Monitoring section, select View Alerts and click the Create Shortcut button. On the Shortcuts page, click Record and press the hot key combination, for example Ctrl + A. Close the dialog box. Click OK.
When you use Ctrl + A from the TWS, the Alerts box opens displaying your current alerts. To create an alert, click the New button.
Several keyboard keys cannot be used as hot keys, including: Alt, Page Up, Page Down, Print Screen, Home, Backspace, and the Windows key. We reserve the right to activate these keys or to remove hot key functionality from a key at any time without notice. Attempted use of invalid keys invokes the message "The hot key you selected is not valid. Please select another hot key combination." NOTE: The standard hot keys do not function within the Rapid Order Entry panel. When you record a hot key for one of the rapid order entry actions, you must use "Ctrl" plus a character key, or the Escape key.
Copyrights and Trademarks
112
Order Management Modules
Customize Hot Keys
After you map a hot key, use options on the Customize tab to make your hot key action more specific. To customize a hot key 1. 2. 3. On the Configure menu, click Hot Keys. In the Shortcuts area, choose an action to whose hot key you want to customize and click Configure. Click the Customize tab and set parameters to support the customized hot key.
The customized mapped keys are displayed on the status line at the bottom of the application.
Copyrights and Trademarks
113
TWS Users' Guide
Create "Instantaneous Transmit" Hot Key
You use hot keys to perform common trading functions, such as creating specific order types. Once you have created an order, you must still select Transmit to send the order. You now have the option to enhance the Buy and Sell hot keys by adding "instantaneous transmit" functionality. To add instantaneous transmit functionality to a hotkey 1. 2. 3. 4. On the Configure menu, select Hot keys. In the Shortcuts area select the Buy or Sell action and press Configure. Click the Customize tab. At the bottom of the page check Transmit the order instantaneously and click OK.
NOTE: To use this feature, you will be asked to sign an agreement stating that you understand its implications. Under the terms of the Customer agreement, you are responsible for all orders entered in your account. Consider carefully whether setting a hot key to instantaneously transmit orders is the best for the way you trade.
Copyrights and Trademarks
114
Order Management Modules
Assign Mouse Shortcuts
You can record mouse-click shortcuts to specific order creation and transmission commands, such as buy, sell, transmit and cancel and many others. To assign a mouse shortcut 1. 2. On the Configure menu, select Global Configuration, then select Hot Keys. In the Possible Actions list, choose an action to which you want to assign a mouse shortcut and click Create Shortcut.
3.
In the Mouse area, use the Market Data Field drop-down to choose the field you click in to activate the shortcut.
115
TWS Users' Guide
4. In the Click Event drop-down, choose the click method you will use in the selected field to initiate the shortcut.
116
Order Management Modules
5.
Click Apply, then click Close.
Example: If you choose Cancel Order in Possible Actions, Bid Size in Market Data Field, and Left Click as the Click Event, when you use your mouse to click (Left Click) in the Bid Size column, you will cancel the order. Note that you must have the appropriate field displayed to use this mouse shortcut! To hide and display fields, use the Layout Manager. NOTE: Mouse shortcuts will override default mouse actions. To return to default mouse action, you must re-set the action as a shortcut in the Hot Keys and Mouse Shortcuts box.
Copyrights and Trademarks
117
TWS Users' Guide
ChartTrader
CHARTTRADER
Copyrights and Trademarks
118
Order Management Modules
ChartTrader
You can trade directly from a real-time chart using ChartTrader, which you display from the Charts menu. Once you create an order, you can transmit it, cancel it or modify it directly on the chart, or using the order management line on the Orders tab. To open ChartTrader 1. 2. 3. Open an interactive chart by selecting a contract on the trading screen and clicking the Charts icon on the trading toolbar. On the Charts menu, select ChartTrader and then select Show/Hide ChartTrader. The ChartTrader tool displays directly below the Quote line of the chart.
To use ChartTrader to create an order 1. 2. Click the blue Buy button to create a buy order, or the Red sell button to create a sell order. Move your cursor into the chart and position the broken blue line at the order price you want. Note that your exact price position is displayed in blue to the left of the broken line, along the price axis. Click to create an order. The order management line appears below the Quote line, in the Orders section of the ChartTrader, and the broken line becomes a solid line. The order parameter defaults are the same as those you set for your trading window using the Order Defaults window. Click the "T" in the Transmit field to submit the order. You can also submit an order directly from the chart.
3.
4.
Transmit an order from the chart 1. To transmit directly from the chart, click the green Transmit button, and position the IB cursor over the order you want to send. You can tell that an order is properly selected as the solid order line becomes broken.
119
TWS Users' Guide
2.
Click on the order to transmit. NOTE: You can modify order parameters in the Order Management line before you transmit the order from the chart.
Modify order price from the chart 1. You can modify the order price directly from the chart by clicking the Modify button, and positioning the modify cursor over the selected order until the solid order line becomes broken. Click the order and drag it up or down to the desired price.
2.
Orders that you create using ChartTrader also display on the Trading page that displays the contract data. Trading pages that hold an order display the page title in red.
Copyrights and Trademarks
120
Order Management Modules
DepthTrader
DEPTHTRADER
Copyrights and Trademarks
121
TWS Users' Guide
Market Depth
The Market Depth window displays the alternative bids and offers away from the inside quote to allow you to better gauge market liquidity. You can create and transmit orders from the Underlying panel by clicking the bid or ask price, just as you do from the main trading window. Also send orders by clicking the bid or ask price in the Bid and Ask columns. For Nasdaq stocks you can elect to display the Level II window, and NYSE listed equities with market data allow access to the NYSE Open Book.
• •
We cannot guarantee that every price quoted for a particular security/commodity will be displayed in the Market Depth window. Cumulative size represents the total contract size available at a particular price or better. For example, using the image above, the cumulative contract size available on the bid at a price of 13.88 would be 11 contracts (1 contract at 13.89, 10 contracts at 13.88). If you have the default order size set to 100, the order will be for the cum size times the default order size, in this case 1100. Average Price is the average execution price received when transacting the cumulative contract size. You receive multiple executions as your order goes through the order book. Executions will appear in the Execution window that you access using the Executions tab.
NOTE: Exercise particular caution when trading from the Market Depth screen since the order size may be larger than you intended. We recommend you use the Market Depth information only as a trading tool to help gauge market liquidity.
122
Order Management Modules
•
For the Smart Market Depth window, we aggregate and display the best bids and offers available from all markets for the particular product.
NOTE: You can display a maximum of three (3) Market Depth, Level II or NYSE Open Book windows simultaneously.
Copyrights and Trademarks
123
TWS Users' Guide
Monitor the Market Depth
The Market Depth window displays the alternative bids and offers away from the inside quote, to allow you to better gauge market liquidity. Market Depth is not available for all products or exchanges. You may open up to three Market Depth windows simultaneously. You can also view market depth for NYSE-listed products through the NYSE Open Book*. To view market depth or Open Book for an asset
•
Right-click on a market data line and select Show Market Depth or Show NYSE Open Book . Note: To view Level II quotes, you must subscribe to Level II market data services. Click Subscribe to Market Data on the Ticker menu.
*display edited by
Copyrights and Trademarks
124
Order Management Modules
Create an Order from the Market Depth Window
Although you can trade from the Market Depth window, we recommend that you use the market depth as an evaluative tool only. When you initiate an order from the Market Depth window, your order management line is created in the main Trading window, and uses the average price shown in the Market Depth window. Modify and transmit the order just as you would any other. To create and transmit an order from the Market Depth window 1. Click on the "Ask" or "Bid" price of an asset to create an Order Management line in the main Trading window, directly below the selected asset.
• •
2.
Click on the Ask Price to create a Buy order. Click on the Bid Price to create a Sell order.
In the Order Management line, modify the order parameters Time in Force, Action, Quantity, Price, Order Type, or Destination, if needed. NOTE: When you create an order from the Market Depth window, the order size is derived from the cumulative size column; it is not the default quantity size that is used when you create an order from the main Trading window. IT IS IMPORTANT THAT YOU REVIEW THE ORDER PRICE AND SIZE ON THE TRADING SCREEN BEFORE YOU TRANSMIT YOUR ORDER.
3.
To transmit your order, click the red "T" in the Transmit field.
Copyrights and Trademarks
125
TWS Users' Guide
View Level II Quotes
If you subscribe to the Level II market data service, you can view Level II quotes for selected Nasdaq securities. You may open up to three Level II quote windows simultaneously. To view Level II quotes for a Nasdaq security
•
Right-click on a market data line and select Show Level II Quotes WARNING: If you click in the Bid or Ask areas of the Level II Quotes window, you are creating an order on the main Trading window with a size and price derived from this data.
Note: To subscribe to a market data service, on the Ticker menu click Subscribe to Market Data.
Copyrights and Trademarks
126
Order Management Modules
Rebalance & Portfolio Allocation
REBALANCE YOUR PORTFOLIO
Copyrights and Trademarks
127
TWS Users' Guide
Rebalance Your Portfolio
Use the Rebalance window to redistribute percentages of positions in your portfolio that make up your current (signed) net liquidation value. TWS automatically opens and closes positions to rebalance your portfolio based on the new percentages you enter. You can add contracts and create orders just as you would from the main trading screen.
Rebalance your portfolio 1. 2. On the View menu, select Rebalance. The Rebalance window shows three columns that are different from those on your trading screen:
•
Deliv Value - this is the deliverable value of the position, which is the same as the Market Value for the position shown in the Portfolio section of the Account window. Current % - this is the current signed percent of the position to your net liquidation value shown in the Balance section of the Account window. This figure is calculated by dividing the DLV by the NLV (Net Liq. Value). Rebal % - use this field to enter a new percentage of the NLV that you want the position to have.
•
•
3. 4. 5.
In the Rebal % field, enter a new percent of the NLV that you want the position to have. Click the Create Orders button to instruct TWS to automatically create the orders to achieve the percent change. Use the Transmit All button to send all orders, or click "T" on an order line to transmit a single order.
Open positions from the Rebalance window 1. First, add a ticker line to the Rebalance window by selecting the market data line on your trading screen, and then clicking the selection arrow attached to the Rebalance icon on the trading toolbar. Click Add to Rebalance Window. Or, enter an underlying
128
Order Management Modules
symbol into a blank row on the Rebalance screen as you would on the main trading window. 2. 3. Enter a value in the Rebal % column and click the Create Orders button. Transmit the order.
Copyrights and Trademarks
129
Order Types and Properties
ORDER PROPERTIES
Copyrights and Trademarks
131
TWS Users' Guide
Basic Order Types
BASIC ORDER TYPES
Copyrights and Trademarks
132
Order Types and Properties
Create a Limit Order
A limit order is an order to buy or sell a contract at a specified price or better. Using a Limit order ensures that the order will only execute at the price you specified or better, however, it does not guarantee that your order will execute. To create a Limit order 1. 2. 3. 4. Click the Ask price to create a BUY order, or the Bid price to create a SELL order. In the Type field select LMT as the order type. In the Lmt Price field, enter the price at which you want the order to execute. To transmit the order, click the red "T" in the Transmit field.
For a more detailed description of limit orders and the products and exchanges on which they're supported, visit the Order Types information page.
Copyrights and Trademarks
133
TWS Users' Guide
Create a Limit if Touched Order
A limit if touched order is an order designed to buy (or sell) a contract below (or above) the market, at the limit price or better. To create a Limit if Touched order 1. 2. 3. 4. 5. Click the Ask price to create a BUY order, or the Bid price to create a SELL order. In the Type field select LIT as the order type. In the Lmt Price field, enter the price at which you want the order to execute. In the Aux. Price field, enter the "touched" price to trigger the order. To transmit the order, click the red "T" in the Transmit field.
For a more detailed description of Limit if Touched orders and the products and exchanges on which they're supported, visit the Order Types information page.
Copyrights and Trademarks
134
Order Types and Properties
Create a Market Order
A market order is an order to buy or sell an asset at the bid or offer price currently available in the marketplace. When you submit a market order, you have no guarantee that the order will execute at any specific price. To create a Market order 1. 2. 3. Click the Ask price to create a BUY order, or the Bid price to create a SELL order. In the Type field select MKT as the order type. To transmit the order, click the red "T" in the Transmit field.
For a more detailed description of market orders and the products and exchanges on which they're supported, visit the Order Types information page.
Copyrights and Trademarks
135
TWS Users' Guide
Create a Market if Touched Order
A Market if Touched order is an order designed to buy (or sell) a contract below (or above) the market. To create a Market if Touched order 1. 2. 3. 4. Click the Ask price to create a BUY order, or the Bid price to create a SELL order. In the Type field select MIT as the order type. In the Aux. Price field, enter the "touched" price to trigger the order. To transmit the order, click the red "T" in the Transmit field.
For a more detailed description of Market if Touched orders and the products and exchanges on which they're supported, visit the Order Types information page.
Copyrights and Trademarks
136
Order Types and Properties
Create a Limit-On-Close Order
A LOC (limit-on-close) order must be submitted no later than 15 minutes prior to the close of the market. It will execute at the closing price if the closing price is at or better than the submitted limit price, according to the rules of the specific exchange. Otherwise the order will be cancelled. To create a LOC order 1. 2. Click the Ask price to create a BUY order, or the Bid price to create a SELL order. In the Type field, select LOC as the order type. NOTE: An LOC order must be routed direct to the exchange (Amex, NYSE or SuperSOES). Select an exchange from the Dest. field on the order line. 3. To transmit the order, click the red "T" in the Transmit field.
For a more detailed description of LOC orders, visit the Order Types information page.
Copyrights and Trademarks
137
TWS Users' Guide
Create a Market-On-Close Order
A MOC (market-on-close) order will execute as a market order as close to the closing price as possible. To create a MOC order 1. 2. 3. Click the Ask price to create a BUY order, or the Bid price to create a SELL order. In the Type field, select MOC as the order type. To transmit the order, click the red "T" in the Transmit field.
For a more detailed description of MOC orders and the products and exchanges on which they're available, visit the Order Types information page.
Copyrights and Trademarks
138
Order Types and Properties
Market with Protection Order
A Market with Protection order is sent in as a market order to execute at the current best price. If the entire order does not immediately execute at the market price, the remainder of the order is re-submitted as a limit order with the limit price set by Globex to a price slightly higher/lower than the current best price. To create a market with protection order 1. 2. 3. Click the Ask price to create a BUY order, or the Bid price to create a SELL order. In the Type field select MKT PRT as the order type. To transmit the order, click the red "T" in the Transmit field.
For a more detailed description of market with protection orders and the products and exchanges on which they're supported, visit the Order Types information page.
Copyrights and Trademarks
139
TWS Users' Guide
Create a Market-to-Limit Order
A market-to-limit order is sent in as a market order to execute at the current best price. If the entire order does not immediately execute at the market price, the remainder of the order is re-submitted as a limit order with the limit price set to the price at which the market order portion of the order executed. To create a market-to-limit order 1. 2. 3. Click the Ask price to create a BUY order, or the Bid price to create a SELL order. In the Type field select MTL as the order type. To transmit the order, click the red "T" in the Transmit field.
For a more detailed description of market-to-limit orders, visit the Order Types information page.
Copyrights and Trademarks
140
Order Types and Properties
Pegged to Stock Orders
Sometimes referred to as Relative to Stock, a pegged to stock order specifies that the option price will adjust automatically relative to the stock price, using a calculated value based on data you enter. Note that choosing a Pegged to Stock order on BOX indicates that you want to participate in BOX's Price Improvement auction. You can enter this order type using the Trading screen or the Order Ticket. To create a Pegged to Stock order from the Trading Screen 1. 2. Create an option order and select PEG STK in the Type field. On the Page menu select Layout. At the bottom of the Columns - Order Row section, check Stock Ref. Price, Stock Range (Low), Stock Range (High) and Delta. You may need these fields to complete your order.
4. If desired, enter a price in the Stock Ref. Price field. If you do not enter a value, the midpoint of the NBBO at the time of the order is used. 5. If desired, enter a stock range. If the stock price moves outside of the range, your order will be cancelled. Use the Stock Range (High) and Stock Range (Low) fields. 6. If desired, enter a starting price in the Aux. Price field. If you don't enter a value, the current stock price is used as the starting price. 7. In the Delta field, enter a value which will be used as a percent, ie. ".5" equal 50%. This percent value is multiplied by the change in the underlying stock price. The product is added to the starting price to determine the option price. When you created a pegged to stock order using the Order Ticket, use the Basic tab to select the order type and set the Starting price. Use the Pegged tab to set the Stock Ref. price, the high and low stock ranges and the delta value. If you're using BOX, select an Auction Strategy. For a more detailed description of pegged-to-stock orders and the products and exchanges on which they're supported, visit the Order Types information page.
141
TWS Users' Guide
Copyrights and Trademarks
142
Order Types and Properties
Pegged-to-Market Order
You can submit an order that is pegged to buy on the best offer and sell on the best bid. To create a Pegged-to-Market order 1. 2. 3. 4. 5. Click the Ask price to create a BUY order, or the Bid price to create a SELL order. In the Dest. field ensure that the destination is Brut. In the Type drop-down select PEG MKT. If desired, modify the offset amount in the Aux. Price field. To transmit, click the red "T" in the Transmit field.
For a more detailed description of pegged-to-market orders and the products and exchanges on which they're available, visit the Order Types information page.
Copyrights and Trademarks
143
TWS Users' Guide
Pegged-to-Primary Order
A Pegged-to-Primary order is an advanced order type whose price is dynamically derived from a combination of the market quote and a user-defined offset amount. To enter a Pegged-to-Primary order 1. 2. 3. Click in the Ask Price field to initiate a BUY order, or the Bid Price field to initiate a SELL order. Click in the Type field and select PEG PRIM as the order type. Enter the offset amount in the Aux. Price field, or set a percent using the Pct. Offset field. If both fields have values TWS will use the higher of the two as the offset. To display the Pct. Offset field: a. On the Page menu, click Layout.
b. In the Columns - Order Row section on the right side of the page, check Pct. Offset and click OK.
For a more detailed description of Pegged-to-Primary orders and the products and exchanges on which they're available, visit the Order Types information page.
Copyrights and Trademarks
144
Order Types and Properties
Create a Box Top Order
A BOX TOP order is sent in as a market order to execute at the current best price. If the entire order does not immediately execute at the market price, the remainder of the order is resubmitted as a limit order with the limit price set to the price at which the market order portion of the order executed. To create a BOX TOP order 1. 2. 3. Click the Ask price to create a BUY order, or the Bid price to create a SELL order. In the Type field select BOX TOP as the order type. To transmit the order, click the red "T" in the Transmit field.
Available for options routed to BOX.
For a more detailed description of Boxtop orders, visit the Order Types information page.
Copyrights and Trademarks
145
TWS Users' Guide
Price Improvement Auction
For options routed through BOX, you may elect to participate in the Price Improvement Auction to better your price. You can submit nine different types of Price Improvement Auction orders by combining one of three order types (Limit, Relative, Pegged to Stock) with one of three Auction Strategies (Match, Improve, Transparent) described below. To submit a Price Improvement Auction order 1. 2. Create an options order routed to BOX. In the Type field, select either LMT, REL, or PEG STK.
• • •
For Limit orders, enter the limit price in the Lmt. Price field in penny increments. For Relative orders, set a relative offset amount (in penny increments) in the Aux. Price field. For PEG STK orders, you enter the starting price in the Aux. Price field, auction strategy in the Auc. Strat. field, the delta in the Delta field, the optional stock reference price in the Stock Ref. Price field, the low side of the optional stock range in the Stock Range (Low) field, the high side of the optional stock range in the Stock Range (High) field.
3.
In the Auc. Strat. field, select from one of three strategies:
• •
Match - matches the current auction price, but will not exceed the calculated price improvement amount. Improve - enters a bid higher (for SELL order) or lower (for BUY order) than the current auction price, but will not exceed the calculated price improvement amount. Transparent - enters a price that includes the full calculated price improvement amount.
•
4.
Transmit the order.
For a more detailed description of pegged to stock orders and the products and exchanges on which they're supported, visit the Order Types information page.
146
Order Types and Properties
Copyrights and Trademarks
147
TWS Users' Guide
Create a Relative Order
A Relative order is an advanced order type whose price is dynamically derived from a combination of the market quote and a user-defined offset amount. The order is submitted as a limit order and modified according to the pricing logic until it is executed or you cancel the order. You can also set an optional price cap, which keeps your order from executing at a price inferior to the cap. Use the Lmt Price and Aux. Price fields to enter orders requiring multiple prices or values. To enter a Relative order 1. 2. Click in the Ask Price field to initiate a BUY order, or the Bid Price field to initiate a SELL order. Click in the Type field and select REL as the order type. NOTE: A BUY relative order is pegged to the bid, although the displayed Limit price reflects the ASK price. A SELL relative order is pegged to the ask, although the displayed Limit price reflects the BID. 3. Enter the offset amount in the Aux. Price field, or set a percent using the Pct. Offset field. If both fields have values the higher of the two will be used as the offset. To display the Pct. Offset field: a. b. On the Page menu, click Layout. In the Columns - Order Row section on the right side of the page, check Pct. Offset and click OK.
You can modify the offset amount for several relative orders on the same trading page at one time. To do this, select multiple relative orders by holding the Ctrl key and clicking on each order. After you have selected all relative orders, right-click on one of the selected orders and select Modify. In the Relative Order Modification box, define an offset or percent offset amount and click OK. All selected orders will be changed. For a more detailed description of relative orders and the products and exchanges on which they're supported, visit the Order Types information page.
Copyrights and Trademarks
148
Order Types and Properties
Create a VWAP Order
VWAP (Volume-Weighted Average Price) orders are supported for large cap securities only. To create a VWAP order 1. 2. 3. Click the Ask price to create a BUY order, or the Bid price to create a SELL order. In the Type field select VWAP as the order type. To transmit the order, click the red "T" in the Transmit field.
NOTE: A transmitted VWAP order is accepted immediately and CANNOT BE CANCELLED. VWAP orders are automatically routed. For a more detailed description of scale orders and the products and exchanges on which they're supported, visit the Order Types information page.
Copyrights and Trademarks
149
TWS Users' Guide
Create a Stop Order
A Stop order becomes a market order to buy or sell securities or commodities once the specified stop price is attained or penetrated. A Stop order is not guaranteed a specific execution price. To create a Stop order 1. 2. 3. 4. Click the Ask price to create a BUY order, or the Bid price to create a SELL order. In the Type field select STP as the order type. Enter the Stop Election price in the Aux. Price field. To transmit the order, click the red "T" in the Transmit field.
For a more detailed description of stop orders and the products and exchanges on which they're supported, visit the Order Types information page.
Copyrights and Trademarks
150
Order Types and Properties
Create a Stop Limit Order
A Stop Limit order is similar to a stop order in that a stop price will activate the order. However, the stop order becomes a market order when elected, but the stop limit order becomes a limit order. Use the Lmt Price and Aux. Price fields on the trading screen to enter orders requiring multiple prices or values. To enter a Stop Limit order 1. 2. 3. 4. Click in the Ask Price field to initiate a BUY order, or the Bid Price field to initiate a SELL order. Click in the Type field and select STP LMT as the order type. Enter the Limit price in the Lmt Price field. Enter the Stop Election price in the Aux. Price field.
NOTE: You can enable the system to automatically adjust the limit price if you change the stop price. To activate this feature, on The Configure menu select Order, then select Auto-Adjust Stop-Lmt Price. The limit price will move based on the offset you defined when you set the original limit and stop election prices. For a more detailed description of stop limit orders and the products and exchanges on which they're supported, visit the Order Types information page.
Copyrights and Trademarks
151
TWS Users' Guide
Create a Trailing Stop Order
A trailing stop for a sell order sets the stop price at a fixed amount below the market price. If the market price rises, the stop loss price rises by this amount, but if the stock price falls, the stop loss price remains the same. Reverse this for a buy trailing stop order. This strategy supposedly allows an investor to limit the maximum possible loss without limiting possible gain. NOTE: We do not recommend using trailing stop orders, as there is no guarantee that your order will be filled at or near the designated stop price, which is especially dangerous in rapidly rising or falling markets. In addition, trailing stop orders will accentuate volatility in rough markets. To enter a trailing stop order 1. 2. 3. 4. Click in the Ask Price field to initiate a BUY order, or the Bid Price field to initiate a SELL order. Click in the Type field and select TRAIL. Enter the amount by which you want the stop price to trail the market price in the Aux. Price field. To transmit the order, click the red "T" in the Transmit field.
For a more detailed description of scale orders and the products and exchanges on which they're supported, visit the Order Types information page.
Copyrights and Trademarks
152
Order Types and Properties
Times in Force
TIMES IN FORCE
Copyrights and Trademarks
153
TWS Users' Guide
Create a "Good After Time" Order
A "good after time" order is held in the system and sent to the exchange on the date and time you enter. To create a "good after time" order 1. a. b. Display the Good After Time field on an order management line: On the Page menu, click Layout. In the Columns - Order Row section on the right side of the page, check Good After Time and click OK.
2.
On the TWS screen, create an order (click in the Ask Price to create a BUY order, or the Bid Price to create a Sell order).
In the Good After Time field, enter the date and time after which you want TWS to submit your order. Use the format YYYYMMDD hh:mm:ss (where :ss is optional).
Use military time to set the hour, minute and seconds. 4. If necessary, enter a time zone using an accepted three-letter acronym. Note that if you do not enter a specific time zone, the time zone to which your computer is set is the one used. 5. Transmit the order. The order is held in the IB system until the time and date you set.
For a more detailed description of GAT orders and the products and exchanges supported, visit the Order Types information page.
Copyrights and Trademarks
154
Order Types and Properties
Create a Fill or Kill Order
Mark an order as "fill or kill" to specify that the order must execute entirely as soon as it becomes available, or be canceled. To tag an order as having fill-or-kill time in force, select FOK from the Time in Force field. To create a FOK order 1. 2. 3. Create an options order (click the Ask Price to create a BUY order, or the Bid Price to create a Sell order) routed to ISE or Smart. In the Time in Force field, select FOK. Transmit the order.
For a more detailed description of Fill or Kill orders and the products and exchanges supported, visit the Order Types information page.
Copyrights and Trademarks
155
TWS Users' Guide
Auction Order
An auction order is submitted at the Calculated Opening Price (COP). If the order doesn't execute, it is resubmitted as a limit order at the COP or best bid/ask. To create an auction order 1. 2. 3. 4. 5. Click the Ask price to create a BUY order, or the Bid price to create a SELL order. This action will open the Order Ticket window. In the Order Type field, select MTL (Market-to-Limit). In the Time in Force field, select AUC (auction). Modify any other order parameters. To transmit the order, click Transmit. To put the order on your trading page without transmitting, click Accept. To cancel the order, click Abort.
For a more detailed description of auction and other order types, visit the Order Types information page.
Copyrights and Trademarks
156
Order Types and Properties
Create a Market-on-Open Order
MOO (market-on-open) is a market order executed at the market's open at the market price. To create a MOO order 1. 2. 3. 4. Click the Ask price to create a BUY order, or the Bid price to create a SELL order. In the Type field, select MKT as the order type. In the TIF field, select OPG as the time in force. To transmit the order, click the red "T" in the Transmit field.
For a more detailed description of MOO orders and the products and exchanges on which they're available, visit the Order Types information page.
Copyrights and Trademarks
157
TWS Users' Guide
Create a Limit-On-Open Order
A LOO (limit-on-open) order is a limit order executed at the market's open if the opening price is equal to or better than the limit price. To create a LOO order 1. 2. 3. 4. Click the Ask price to create a BUY order, or the Bid price to create a SELL order. In the Type field, select LMT as the order type. In the TIF field, select OPG as the time in force. To transmit the order, click the red "T" in the Transmit field.
For a more detailed description of LOO orders and the products and exchanges on which they're supported, visit the Order Types information page.
Copyrights and Trademarks
158
Order Types and Properties
Time in Force for Orders
The time in force for an order defines the length of time over which an order will continue working before it is canceled. We support the following time in force options:
• •
DAY - A Day order is canceled if it does not execute by the close of the trading day. Unless otherwise specified, every order is a Day order. GTC - A Good-Til-Canceled order will continue to work within the system and in the marketplace until it executes or is canceled by the customer. Customers who trade U.S. equities may use GTC for Limit, Stop, and Stop-Limit orders. Note that GTC orders will also automatically be cancelled under the following conditions: if any type of corporate action is taken on a security if you do not log in to your account for 90 days OPG - Use OPG to send a market-on-open (MOO) or limit-on-open (LOO) order. GTD - A Good-Til-Date order will remain working within the system and in the marketplace until it executes or until the close of the market on the date specified. When you select GTD as the time in force, both an Exp. Date and Exp. Time field is displayed on the order management line. Enter the date up until which you want the order to continue to work in the format YYYYMMDD. To set a time, enter the time in the format HH:MM(:SS). If desired, enter a time zone using an accepted three-letter acronym. Note that if you do not enter a specific time zone, the time zone to which your computer is set will be used. IOC - Any portion of an Immediate-or-Cancel order that is not filled as soon as it becomes available in the market is canceled. IOC is valid for market or limit orders. FOK - If the entire Fill-or-Kill order does not execute as soon as it becomes available, the entire order is canceled.
• •
• •
• •
NOTE: For market centers that do not accept "native" GTC orders, the order type is
simulated by resubmitting the relevant order each business day upon opening of the market center. For a list of market centers that both do and do not accept GTC orders, see the Order Types page.
Copyrights and Trademarks
159
TWS Users' Guide
Order Attributes
ORDER ATTRIBUTES
Copyrights and Trademarks
160
Order Types and Properties
Create a Hidden Order
A Hidden order (generally a large volume order) shows no evidence of its existence in either the market data or the deep book. To create a Hidden order 1. Display the Hidden field on an order management line: a. On the Page menu, click Layout.
b. In the Columns - Order Row section on the right side of the page, check Hidden and click OK. 2. On the TWS screen, create an order (click in the Ask Price to create a BUY order, or the Bid Price to create a Sell order). 3. 4. In the Destination field of the Order Mgmt. row, choose INet as your order destination. Check the Hidden field.
5.
To transmit the order, click the red "T" in the Transmit field.
For a more detailed description of hidden orders and the products and exchanges supported, visit the Order Types information page.
Copyrights and Trademarks
161
TWS Users' Guide
Create a Discretionary Order
A Discretionary Order is a limit order for which you define a discretionary amount (which is added to or subtracted from the limit price) that increases the price range over which the order is eligible to execute. The original limit price is displayed to the market. To create a Discretionary order 1. Display the Discretionary field on an order management line: a. On the Page menu, click Layout.
b. In the Columns - Order Row section on the right side of the page, check Discr Amt and click OK. 2. 3. 4. 5. Click the Ask price to create a BUY order, or the Bid price to create a SELL order. In the Type field, select LMT as the order type. Set a discretionary amount in the Discr Amt field of the order management line. To transmit the order, click the red "T" in the Transmit field.
For a more detailed description of discretionary orders and the products and exchanges supported, visit the Order Types information page.
Copyrights and Trademarks
162
Order Types and Properties
Create an Iceberg Order
An Iceberg order allows you to submit an order (generally a large volume order) while publicly disclosing only a portion of the submitted order. To create an Iceberg order 1. Show the Disp. Size field on an order management line: a. On the Page menu, click Layout.
b. In the Columns - Order Row section on the right side of the page, check Disp. Size and click OK. 2. On the TWS screen, create an order (click the Ask Price to create a BUY order, or the Bid Price to create a Sell order). 3. In the Disp. Size field, enter the number of shares you want publicly disclosed.
For a more detailed description of iceberg orders and the products and exchanges on which they're supported, visit the Order Types information page.
Copyrights and Trademarks
163
TWS Users' Guide
Create an All or None Order
Mark an order as "all or none" to specify that the order must execute entirely. Use the Order Ticket, or display the optional AON checkbox using Page Layout to send the order directly from the trading screen. To create an AON order from the trading screen 1. Display the AON field on an order management line: a. On the Page menu, click Layout.
b. In the Columns - Order Row section on the right side of the page, check AON and click OK. 2. On the TWS screen, create an order (click the Ask Price to create a BUY order, or the Bid Price to create a Sell order). 3. Check the AON checkbox to tag the order as All or None.
Or, use the Order Ticket to create an order, and check the All or none checkbox in the Miscellaneous section.
For a more detailed description of All or None orders and the products and exchanges supported, visit the Order Types information page.
Copyrights and Trademarks
164
Order Types and Properties
Minimum Quantity Orders
Use the Minimum Quantity order attribute to ensure at least a minimum specified number of units is filled for your order. To create a Minimum Quantity order 1. Show the Min. Quantity field on an order management line: a. On the Page menu, click Layout.
b. In the Columns - Order Row section on the right side of the page, check Min. Quantity and click OK. 2. On the trading screen, create an order (click the Ask Price to create a BUY order, or the Bid Price to create a Sell order). 3. In the Min. Quantity field enter the minimum number of contracts that must be available for any part of the order to execute. Available for options orders routed to Smart.
Copyrights and Trademarks
165
TWS Users' Guide
Create Block Orders
A block order is a high volume order that consists of a minimum of 50 contracts at a specific limit price. To submit a block order 1. 2. 3. 4. 5. 6. 7. Select the option for which you want to submit a block order. On the Order menu select Ticket. In the Exchange field, select ISE. In the Price field enter a limit price. Go to the Misc tab. Check Block Order. Choose Transmit to send, or Accept to display the order on the trading screen before you transmit.
For a more detailed description of block orders and the products and exchanges on which they're supported, visit the Order Types information page.
Copyrights and Trademarks
166
Order Types and Properties
Create a Sweep-to-Fill Order
A sweep-to-fill order identifies the best price and the exact quantity offered/available at the price, and transmits the corresponding portion of your order for immediate execution. Simultaneously it is identifying the next best price and quantity offered/available, and submits the matching quantity of your order for immediate execution. To create a sweep-to-fill order 1. Display the Swp Fill field for an order management line: a. On the Page menu, click Layout.
b. In the Columns - Order Row section on the right side of the page, check Swp Fill and click OK. 2. On the trading screen, click the Ask Price to create a BUY order, or the Bid Price to create a Sell order. 3. 4. Check the Swp Fill field. To transmit the order, click the red "T" in the transmit field.
For a more detailed description of sweep-to-fill orders and the products and exchanges on which they're supported, visit the Order Types information page.
Copyrights and Trademarks
167
TWS Users' Guide
Create a One-Cancels-All (OCA) Order
A One-Cancels-All (OCA) order is a combination of separate orders that are worked in conjunction with one another in the marketplace. A customer enters orders as part of an OCA group, and when an order is executed, the remaining orders in the group are canceled. If an order is partially executed, the remaining orders in the group are reduced proportionately to the amount that was executed. If an order is canceled before execution, the remaining orders in the group are canceled. To create an OCA order 1. Display the OCA group field on an order management line: a. On the Page menu, click Layout.
b. In the Columns - Order Row section on the right side of the page, check OCA Group and click OK. 2. On the TWS screen, create an order (click in the Ask Price to create a BUY order, or the Bid Price to create a Sell order). 3. Identify the order as part of an OCA group by entering a group name in the OCA Group field (you can use any descriptive name that you want).
4. Continue to create orders, and identify each as part of the group by entering the same name in the OCA Group field for each order you create. 5. After you have created all orders for a group, transmit the OCA order by clicking Transmit Page on the Order menu. NOTE: Because the OCA procedure is an automated process, cannot guarantee that requested cancellations and modifications will reach the specific exchange before an order has been executed. For a more detailed description of OCA orders and the products and exchanges on which they're available, visit the Order Types information page.
Copyrights and Trademarks
168
Order Types and Properties
Advanced Order Types
ADVANCED ORDER TYPES
Copyrights and Trademarks
169
TWS Users' Guide
Create an Auto Trailing Stop Order
You can attach a trailing stop order to a limit order. The attached stop order is automatically activated when the limit order is filled. To attach a trailing stop to a limit order 1. 2. Right-click on a limit order. Select Attach and then select Auto Trailing Stop.
• • •
To modify the trailing amount, use the Aux. Price field. To modify the stop trigger method, right-click on the attached trailing stop order and select Modify and then select Trigger Method. To view/modify the stop election price, display the Stop Price column from the Order Row section by checking Stop Price.
Copyrights and Trademarks
170
Order Types and Properties
Create a Bracket Order
Bracket orders are designed to limit your loss and lock in a profit by "bracketing" an order with two opposite-side orders. A BUY order is bracketed by a high-side sell limit order and a lowside sell stop (or stop-limit) order. A SELL order is bracketed by a high-side buy stop (or stoplimit) order and a low side buy limit order. The order quantity for the bracketing orders is the same as that of the original order. By default, the amount off the current price to which a bracket order is set is 1.0. This offset amount can be manually changed on the order management line for a specific order, or you can modify the default offset amount using the Default Order Settings box. To create a Bracket order 1. Click the "Ask" or "Bid" price of an asset to create an Order Management line.
•
Click the Ask Price to create a Buy order.
•
Click the Bid Price to create a Sell order.
2. On the right-click menu, select Attach and then select Bracket Orders. 1. 2. 3. Verify that the order parameters are correct. 4. Transmit the order.
NOTE: The "bracketing" or "child" orders are not transmitted until the original or "parent" order has executed.
For a more detailed description of bracket orders and the products and exchanges supported, visit the Order Types information page.
Copyrights and Trademarks
171
TWS Users' Guide
Create a Conditional Order
A conditional order is an order that will automatically be submitted or cancelled ONLY IF specified criteria for one or more defined contracts are met. You can use stocks, options, futures or security indexes to trigger a conditional order. To create a conditional order 1. 2. 3. 4. Right-click on an order and select Modify, then select Condition. From the Conditional tab on the order ticket click Add Condition. Enter contract information for the contingent asset. Enter the trigger information for the contingent asset:
a. Select whether the price of the contingent asset should be less than or equal to (=) the trigger price. b. c. Enter the trigger price. Select the trigger method. NOTE: If you select the double bid/ask method, the greater than or equal to operator (>=) will use the BID price and the less than or equal to operator (' are invalid. Security type 'BAG' requires combo leg details. Stock combo legs are restricted to SMART order routing. Market depth data has been HALTED. Please re-subscribe. Market depth data has been RESET. Please empty deep book
310 311 312 313 314 315 316 317 384
Application Program Interface
Code
Description contents before applying any new entries.
318 319 320 321 322 324 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
Advisors cannot modify partially filled orders. Attempt to set the server log level failed as the log level was invalid. Server error when reading an API client request. Server error when validating an API client request. Server error when processing an API client request. Server error when reading a DDE client request - missing data. Unable connect as the client id is already in use. Retry with a unique client id. Only API connections with clientId set to 0 can set the auto bind TWS orders property. Only support trailing stop order on limit or stop limit order. Order modify failed. Cannot change to the new order type. Only FA customers can request managed accounts list. Internal error. FA does not have any managed accounts. The account codes for the order profile are invalid. Invalid share allocation syntax. Invalid Good Till Date order Invalid delta: The delta must be between 0 and 100. Invalid Expiration Time Invalid Good After Time Good After Time Disabled Futures Spread Not Supported Any More Invalid Improvement Amount Invalid delta Invalid Peg Invalid Good Till Date
385
TWS Users' Guide
Code 344
Description The account is not a financial advisor account
System Message Codes
Code 1100 1101 1102 1300 Description Connectivity between IB and TWS has been lost. Connectivity between IB and TWS has been lost - data lost. Connectivity between IB and TWS has been lost - data maintained. TWS socket port has been reset and this connection is being dropped. Please reconnect on the new port -
Warning Message Codes
Code 2100 2101 2102 2103 2104 2105 2106 2107 2108 Description New account data requested from TWS. API client has been unsubscribed from account data. Unable to subscribe to account as the following clients are subscribed to a different account. Unable to modify this order as it is still being processed. A market data farm is disconnected. A market data farm is connected. A historical data farm is disconnected. A historical data farm is connected. A historical data farm connection has become inactive but should be available upon demand. A market data farm connection has become inactive but should be available upon demand.
Copyrights and Trademarks
386
Application Program Interface
Extended Order Attributes
The extended order attributes below can be used in all placeOrder functions and Open_Order events. Possible Values
Attribute
string m_tif
Day, GTC, IOC, GTD
string m_ocaGroup
Identifies a member of a one-cancels-all group.
Institutional only. string m_account
string m_openClose
Institutional only.
int m_origin
Institutional only.
string m_orderRef
Customer defined order ID tag.
boolean m_transmit
Specifies whether the order will be transmitted by TWS. If set to false, order is created by not transmitted.
int m_parentId
The order ID of the parent, used for bracket, auto stop and trailing stop orders.
boolean m_blockOrder
If set to true, specifies that the order is a block order.
boolean m_sweepToFill
If set to true, specifies that the order is a Sweep-tofill order.
int m_displaySize
The publicly disclosed order size to be used when placing iceberg orders.
387
TWS Users' Guide
Specifies how Simulated Stop, Stop-Limit and Trailing Stop orders are triggered. Valid values are: 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. int m_triggerMethod 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.
boolean m_ignoreRth
If set to true, allows triggering of orders outside of regular trading hours.
boolean m_hidden
If set to true, the order will not be visible when viewing the market depth. The only applies to orders routed to INet.
string m_goodAfterTime
Indicates that the trade should be submitted after the time and date set, with format YYYYMMDD HH:MM:SS (seconds are optional). Use an empty string if not applicable.
string m_goodTillDate
Indicates that the trade should remain working until the time and date set, with format YYYYMMDD HH:MM:SS (seconds are optional). You must set the tif to GTD when using this string. Use an empty string if not applicable.
388
Application Program Interface
string m_faGroup
The advisor group to which the trade will be allocated. Use an empty string if not applicable.
string m_faProfile
The advisor allocation profile to which the trade will be allocated. Use an empty string if not applicable.
string m_faMethod
The advisor allocation method with which the trade will be allocated. Use an empty string if not applicable.
string m_faPercentage
the advisor percentage concerning the trade's allocation. Use an empty string if not applicable.
string m_primaryExch
Identifies the asset's primary exchange.
int m_shortSaleSlot
Valid values include 1, 2
Only valid when shortSaleSlot value = 2. string m_designatedLocation
Cancel on Fill with Block = 1 long ocaType Reduce on Fill with Block = 2 Reduce on Fill without Block = 3
Regular trading hours only. int rthOnly yes=1, no=0
389
TWS Users' Guide
Individual = 'I' Agency = 'A', AgentOtherMember = 'W' IndividualPTIA = 'J' AgencyPTIA = 'U' String rule80A AgentOtherMemberPTIA = 'M' IndividualPT = 'K' AgencyPT = 'Y' AgentOtherMemberPT = 'N'
String settlingFirm (pertains to institutional only)
int allOrNone
yes=1, no=0
long minQty
Identifies a minimum quantity order type.
double percentOffset
The percent offset for relative orders.
Trade with electronic quotes. int eTradeOnly yes=1, no=0
Trade with firm quotes. int firmQuoteOnly yes=1, no=0
double nbboPriceCap
Maximum SMART order distance from the NBBO.
match = 1 improvement = 2 long auctionStrategy transparent = 3 For BOX exchange only.
double startingPrice
Starting price. For BOX exchange only.
390
Application Program Interface
double stockRefPrice
The stock reference price. For BOX exchange only.
double delta
For BOX exchange only.
double stockRangeLower
The lower value of the acceptable stock range. For BOX exchange only.
double stockRangeUpper
The upper value of the acceptable stock range. For BOX exchange only.
Copyrights and Trademarks
391
TWS Users' Guide
API Logging
As client requests are processed (both system and API clients) it logs certain information to its 'log.txt' log file, which is located in the installation directory. The purpose of this file is to help resolve problems by providing some insight into the state of the program before the problem occurred. API clients can specify how detailed they want these log entries to be by setting the log level. Log levels are: 1 = SYSTEM (least detailed) 2 = ERROR (default, if no level is specified) 3 = WARNING 4 = INFORMATION 5 = DETAIL (most detailed) NOTE: Setting the log level to 5 will have a performance overhead, and should only be used when trying to resolve an issue. The log entries for API requests have the format:
[ClientID:ClientVersion:ServerVersion:ClientType:Request:Response:Versi on:LogEntryType]
where
ClientID - the clientId used when connecting. ClientVersion - identifies the client's request stream (for internal use). ServerVersion - identifies the server's response stream (for internal use). ClientType - the type of API connection: DDE = 0, Socket = 1. Request - If greater than 0, indicates that the log entry is the result of an API client request. The number shown is the request identifier as listed in the "Outgoing Request Identifiers" section below. Response - If greater than 0, indicates that the log entry is the result of a server response to the API. The number shown is the response identifier as listed in the "Incoming Response Identifiers" section below. Version - identifies the version of the request or response message. The version changes when the message format changes.
392
Application Program Interface
LogEntryLevel - identifies the type of log entry (i.e. the log level as listed above) Example Log Entry: [0:9:9:1:1:0:3:DET]Socket request [3;52;IBM;STK;null;0.0;2;SMART;null;null]
From this example, we can tell that a socket client with clientId=0 connected and made a request for market data. The version of the market data request, which was 3,implies what data should have been sent. 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 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
NOTE: this information, along with the various request/response message versions, can be found in the EClientSocket implementation file supplied with the API installation.
Copyrights and Trademarks
393
TWS Users' Guide
ActiveX
ACTIVE X API
Copyrights and Trademarks
394
Application Program Interface
Link to the application using ActiveX
Before you can use third-party ActiveX controls, you must register them with Visual Basic. To link using the ActiveX control and VB, VBA or C++ 1. 2. Drop the application control onto a form or dialog box. Call the following methods:
• •
Call the connect() method to connect to the running aplication. Call the methods you need to perform whatever operations you require, such as the reqMktData() method to request market data.
3. Call the placeOrder() method to place an order. Orders using extended attributes require that ActiveX properties representing them be set first. 4. Handle the following events:
• • • • •
Handle the nextValidId() event to receive the next available valid order ID. Increment the ID by one for successive orders. Handle the tickPrice() and tickSize() events to receive the market data. Handle the orderStatus() event to receive status information about orders. Handle the error() event to receive error information. Handle the connectionClosed() event to be notified in case the application stops communicating with the ActiveX control.
Copyrights and Trademarks
395
TWS Users' Guide
Registering Third Party ActiveX Controls
To use a third-party ActiveX control in Visual Basic it must be registered first. To register the ActiveX control with Visual Basic, follow these instructions: 1. 2. 3. From the Components menu in your VB project, select the TWS ActiveX control. Press Apply. Verify that the TWS control appears in the toolbar with all standard controls.
Copyrights and Trademarks
396
Application Program Interface
ActiveX Events
ActiveX events receive information from the system and make it available to an application. The tables below define ActiveX events you can receive. The list of events includes:
• • • • • • • • • • • • • • • • • • • • •
tickPrice() tickSize() orderStatus() errMsg() connectionClosed() openOrder1() openOrder2() updateAccountValue() updatePortfolio() updateAccountTime() nextValidId() permId() contractDetails() execDetails() updateMktDepth() updateMktDepthL2() updateNewsBulletin() managedAccounts() openOrder3() openOrder4() receiveFA()
Event Parameters
void tickPrice(long id, long tickType, double price, long canAutoExecute)
id - the ticker ID that was specified previously in the call to reqMktData() tickType - specifies the type of price. Possible values are:
• • •
1 = bid 2 = ask 4 = last
397
TWS Users' Guide
• • •
6 = high 7 = low 9 = close
price - could be the bid, ask or last price, the daily high, daily low or last day close, depending on tickType value. canAutoExecute - specifies whether the price tick is available for automatic execution. Possible values are:
• •
Notes
0 = not eligible for automatic execution 1 = eligible for automatic execution
This function is called when the market data changes. Prices are updated immediately with no delay.
Event Parameters
void tickSize(long id, long tickType, float long size)
id - the ticker ID that was specified previously in the call to reqMktData() tickType - specifies the type of price. Possible values are:
• • • •
0 = bid size 3 = ask size 5 = last size 8 = volume
size - could be the bid size, ask size, last size or trading volume, depending on the tickType value. Notes This function is called when the market data changes. Sizes are updated immediately with no delay.
Event
void orderStatus(long id, String status, long filled, long remaining, double avgFillPrice, long permId, long parentId, double lastFillPrice, long clientId)
id - the order ID that was specified previously in the call to placeOrder() status - the order status. Possible values include:
Parameters
•
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 the application, 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,
398
Application Program Interface
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 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 (and the status remains DARK BLUE) until the election criteria are met. At that time the order is transmitted to the order destination as specified (and the order status color will change). 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 - the order has been completely filled.
•
filled - specifies the number of shares that have been executed. remaining - specifies the number of shares still outstanding. avgFillPrice - 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. permId - the id used to identify orders. Remains the same over sessions. parentId - The order ID of the parent order, used for bracket and auto trailing stop orders. lastFilledPrice 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. clientId - 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. Notes This event is called whenever the status of an order changes. It is also fired after reconnecting if the client has any open orders.
Event Parameters
void errMsg(long id, long errorCode, String errorString)
id- this is the orderId or tickerId of the request that generated the error errorCode - error codes are documented in the Error Codes topic. errorString - this is the textual description of the error, also documented in the Error Codes topic.
Notes
This event is called when there is an error with the communication or when TWS wants to send a message to the client.
399
TWS Users' Guide
Event Parameters Notes
void connectionClosed()
This event is triggered when TWS closes the sockets connection with the ActiveX control, or when TWS is shut down.
Event
void openOrder1(long id, string symbol, string secType, string expiry, double strike, string right, string exchange, string currency, string local symbol)See Extended Order Attributes.
id - The assigned order id. Use this id to cancel or modify the order. symbol - The underlying symbol. secType - The security type. Valid values are:
Parameters
• • • • • •
STK OPT FUT IND FOP CASH
expiry - The expiration date. Use the format YYYYMM. strike - The strike price. right - Specifies a Put or Call. Valid values are: P, PUT, C, CALL. exchange - The order destination, such as Smart. currency - Specifies the currency. This field is only required when the secType = CASH. Otherwise it is ignored. local symbol - the local exchange symbol for the underlying asset. Notes This event sends the contract description of the open order.
Event
void openOrder2(long id, string action, long quantity, string orderType, double lmtPrice, double auxPrice, string tif, string ocaGroup, string account, string openClose, long origin, string orderRef, long clientId)
id - The order id. This is the same value that was passed in openOrder1. action - Identifies the side. Valid values are: BUY, SELL, SSHORT quantity - The order quantity.
Parameters
400
Application Program Interface
orderType -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. auxPrice -This is the STOP price for stop limit orders, and the offset amount for relative orders. In all other cases, specify zero. tif -The time in force. Valid values are DAY, GTC, IOC ocaGroup -Identifies a one-cancels-all group. account -The account. For institutional customers only. openClose -Specifies whether the order is an open or close order. For institutional customers only. origin -The order origin. For institutional customers only. Valid values are: 0 = Customer, 1 = Firm. orderRef -The order reference. For institutional customers only. clientId - 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. Notes This event sends the order description of the open order.
Event Parameters
void updateAccountValue (string key, string value, string currency, string accountName)
key- A string that indicates one type of account value. Below are some of the keys sent by TWS.
• • • • • • • •
Account Type Account Code Available Funds Buying Power CashBalance - Account cash balance Currency - Currency string DayTradesRemaining - Number of day trades left EquityWithLoanValue - Equity with Loan Value 401
TWS Users' Guide
• • • • • • • • • • • • • • • • • • • • • • • • • • • •
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 - 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 - Long option value MaintMarginReq - Current maintenance margin NetLiquidation - Net liquidation value OptionMarketValue - Option market value Realized PNL Settled Cash ShortOptionValue - Short option value StockMarketValue - Stock market value Total Cash Balance Total Cash Value UnalteredInitMarginReq - Overnight initial margin requirement UnalteredMaintMarginReq - Overnight maintenance margin requirement Unrealized PNL
value- The value associated with the key. currency- Defines the currency of the value, if the value is a monetary amount. account- states the account the message applies to. Useful for Financial Advisor sub-account messages. Notes This event updates a single account value.
Event
void updatePortfolio (string symbol, string secType, string expiry, double strike, string right, string currency, string localSymbol, long position, double marketPrice, double marketValue, double averageCost, double unrealizedPNL, double realizedPNL, String account)
symbol - The symbol of the underlying asset. secType - The security type. Valid values are:
Parameters
• •
STK OPT
402
Application Program Interface
• • • • •
FUT IND FOP CASH BAG
expiry - The expiration date. Use the format YYYYMM. strike - The strike price. right - Specifies a put or call. Valid values are: P, PUT, C, CALL currency - Specifies the currency. This field is only required when the secType = CASH. Otherwise it is ignored. localSymbol - the local exchange symbol of the asset. position - Indicates the position on the contract. If the value is 0, it means the position has just cleared. marketPrice - The unit price of the instrument. marketValue - The total market value of the instrument. averageCost - The average cost per share is calculated by dividing your cost (execution price + commission) by the quantity of your position. unrealizedPNL - The difference between the current market value of your open positions and the average cost, or (Value - Average Cost). realizedPNL- 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 costs (execution price + commissions to close the position). account- states the account the message applies to. Useful for Financial Advisor sub-account messages. Notes This event updates a single holding in your portfolio.
Event Parameters Notes
void updateAccountTime (string timeStamp)
timeStamp -This indicates the last update time of the account information. This event sends the time at which the account values and portfolio market prices were calculated.
Event Parameters
void nextValidId(long id)
id - The next available order ID received from TWS upon connection. Increment all successive orders by one based on this ID. This event is called after a successful connection to TWS.
Notes
403
TWS Users' Guide
Event Parameters
void permId(long id, long permId)
id - The next available order ID received from TWS upon connection. Increment all successive orders by one based on this ID. permId - this id will remain the same from session to session This event is always received after an order Status event. It gives the permId for the spsecified order id. The permId will remain the same from session to session.
Notes
Event
void contractDetails(String symbol, String secType, String expiry, double strike, String right, String exchange, String currency, String localsymbol, String marketName, String tradingClass, long conId, double minTick, String multiplier, String orderTypes, String validExchanges)
symbol - The underlying symbol. secType - The security type. Valid values are:
Parameters
• • • • • •
STK OPT FUT IND FOP CASH
expiry - The expiration date. Use the format YYYYMM. strike - The strike price. right - Specifies a put or call. Valid values are: P, PUT, C, CALL exchange - The order destination, such as Smart. currency - Specifies the currency. This field is only required when the secType = CASH. Otherwise it is ignored. localSymbol - the local exchange symbol of the asset. marketName - the market name for this contract. tradingClass - the trading class name for this contract. condId - the unique contract identifier.
404
Application Program Interface
minTick - the minimum price tick. multiplier - the order size multiplier. orderTypes - the list of valid order types for this contract. validExchanges - the list of exchanges on which this contract is traded. Notes This event is fired when the reqContractDetails() or reqContractDetails2() methods are invoked.
Event
void execDetails (long id, String symbol, String secType, String expiry, double strike, String right, String cExchange, String curency, String localSymbol, String execId, String time, String acctNumber, String side, long shares, double price, long permId, long clientId, int liquidation)
id - the order id. This is the same value that was passed in openOrder1. Note: TWS orders have a fixed orderId of 0, which distinguishes them from API client orders. symbol - The underlying symbol. secType - The security type. Valid values are:
Parameters
• • • • • •
STK OPT FUT IND FOP CASH
expiry - The expiration date. Use the format YYYYMM. strike - The strike price. right - Specifies a put or call. Valid values are: P, PUT, C, CALL cExchange - The order destination, such as Smart. currency - Specifies the currency. This field is only required when the secType = CASH. Otherwise it is ignored. localSymbol - the local exchange symbol for the underlying asset. execId - the order execution id. time - time of order execution. acctNumber - the customer account number. side - Specifies if the transaction was a purchase or a sale. Valid values are:
• •
BOT SLD
shares - the number of shares filled. price - the order execution price. 405
TWS Users' Guide
permId - the TWS id used to identify orders, remains the same over TWS sessions. clientId - The ID of the client that placed the order. Note that TWS orders have a fixed ID of 0. liquidation - specifies whether an execution is the result of a liquidation. Possible values are:
• •
Notes
0 = execution is not the result of liquidation 1 = execution is the result of a liquidation
This event is fired when the reqExecutions() methods is invoked, or when an API order is filled or partially filled.
Event Parameters
void updateMktDepth(long id, long position, long operation, long side, double price, long size)
id - the ticker ID that was specified previously in the call to reqMktDepth() position - specifies the row id of this market depth entry. operation - identifies the how this order should be applied to the market depth. 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. Valid values are:
• •
0 = ask 1 = bid
price - the order price. size - the order size. Notes This function is called when the market depth changes.
Event
void updateMktDepthL2(long id, long position, String marketMaker, long operation, long side, double price, long size)
id - the ticker ID that was specified previously in the call to reqMktDepth() position - specifies the row id of this market depth entry. marketMaker - specifies the exchange hosting this order.
Parameters
406
Application Program Interface
operation - identifies the how this order should be applied to the market depth. 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. Valid values are:
• •
0 = ask 1 = bid
price - the order price. size - the order size. Notes This function is called when the Level II market depth changes.
Event
void updateNewsBulletin(short msgId, short msgType, String message, String origExchange)
msgId - the bulletin ID, increments for each new bulletin. msgType - specifies the type of bulletin. Valid values include: 1 = Regular IB news bulletin 2 = Exchange no longer available for trading. 3 = Exchange is available for trading.
Parameters
message - the bulletins message text. origExchange - the exchange from which this message originated. Notes This event is triggered for each new bulletin if the client has subscribed (i.e. by calling the reqNewsBulletins() method).
407
TWS Users' Guide
Event Parameters Notes
void managedAccounts(string accountsList)
accountsList - the comma delimited list of FA-managed accounts. This event id is fired when a successful connection is made to a Financial Advisor account. It is also fired when the reqManagedAccts() method is invoked.
Event
void openOrder3(long id, string symbol, string secType, string expiry, double strike, string right, string exchange, string currency, string local symbol, string action, long quantity, string orderType, double lmtPrice, doubleAuxPrice, str tif, str ocaGroup, str account, str openclose, long origin, string orderRef, long clientId, long permId, string sharesAllocation, string faGroup, string faMethod, string faPercentage, string faProfile, string goodAfterTime, string goodTillDate)See Extended Order Attributes.
id - The assigned order id. Use this id to cancel or modify the order. symbol - The underlying symbol. secType - The security type. Valid values are:
Parameters
• • • • • •
STK OPT FUT IND FOP CASH
expiry - The expiration date. Use the format YYYYMM. strike - The strike price. right - Specifies a Put or Call. Valid values are: P, PUT, C, CALL. exchange - The order destination, such as Smart. currency - Specifies the currency. This field is only required when the secType = CASH. Otherwise it is ignored. local symbol - the local exchange symbol for the underlying asset. action - Identifies the side. Valid values are: BUY, SELL, SSHORT quantity - The size of the order. orderType - Identifies the order type. Valid values are:
• •
MKT MKTCLS
408
Application Program Interface
• • • • • • • •
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. AuxPrice - This is the STOP price for stop limit orders, and the offset amount for relative orders. In all other cases, specify zero. Notes This event sends the contract description of the open order.
Event
void openOrder4(long id, string symbol, string secType, string expiry, double strike, string right, string exchange, string currency, string local symbol, string action, long quantity, string orderType, double lmtPrice, doubleAuxPrice, str tif, str ocaGroup, str account, str openclose, long origin, string orderRef, long clientId, long permId, string sharesAllocation, string faGroup, string faMethod, string faPercentage, string faProfile, string goodAfterTime, string goodTillDate, long ocaType, int rthOnly, string rule80A, string settlingFirm, int allOrNone, long minQty, double percentOffset, int eTradeOnly, int firmQuoteOnly, double nbboPriceCap, long auctionStragegy, double startingPrice, doublestockRefPrice, double delta, double stockRangeLower, double stockRangeUpper, int blockOrder, int sweepToFill, int ignoreRth, int hidden, double discretionaryAmt, long displaySize, long parentId, long triggerMethod, long shortSaleSlot, string designatedLocation)See Extended Order Attributes.
id - The assigned order id. Use this id to cancel or modify the order. symbol - The underlying symbol. secType - The security type. Valid values are:
Parameters
• • • • •
STK OPT FUT IND FOP 409
TWS Users' Guide
•
CASH
expiry - The expiration date. Use the format YYYYMM. strike - The strike price. right - Specifies a Put or Call. Valid values are: P, PUT, C, CALL. exchange - The order destination, such as Smart. currency - Specifies the currency. This field is only required when the secType = CASH. Otherwise it is ignored. local symbol - the local exchange symbol for the underlying asset. action - Identifies the side. Valid values are: BUY, SELL, SSHORT quantity - The size of the order. orderType - 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. AuxPrice - This is the STOP price for stop limit orders, and the offset amount for relative orders. In all other cases, specify zero. Notes This event sends the contract description of the open order.
Event
receiveFA(long faDataType, string XML)
410
Application Program Interface
Parameters
faDataType - specifies the type of Financial Advisor configuration data being received from TWS. Valid values include: 1 = GROUPS 2 = PROFILE 3 =ACCOUNT ALIASES
XML- the XML string containing the previously requested FA configuration information. Notes This event receives previously requested FA configuration information from TWS.
Copyrights and Trademarks
411
TWS Users' Guide
ActiveX Methods
ActiveX methods allow an application to call functions in another application. The tables below define the ActiveX methods you can call when connected. The list of methods includes:
• • • • • • • • • • • • • • • • • • • • • • • • • • • • • •
connect() disconnect() reqMktData() reqMktData2() cancelMktData() placeOrder() placeOrder2() cancelOrder() reqOpenOrders() reqAccountUpdates() reqExecutions() reqIds() reqContractDetails() reqContractDetails2() reqMktDepth() reqMktDepth2() cancelMktDepth() addComboLeg() clearComboLegs() reqNewsBulletins() cancelNewsBulletins() setLogLevel() reqAllOpenOrders() reqAutoOpenOrders() reqManagedAccts() reqAccountUpdates() requestFA() replaceFA() requestHistoricalData() OpenOrder4()
412
Application Program Interface
Method Parameters
void connect(String host, long port, long clientId)
host - host name or IP address of the machine where the application is running. Leave blank to connect to the local host. port - must match the port specified on the Configure>API>Socket Port field. clientId - A number used to identify this client connection. All orders placed/modified from this client will be associated with this client identifier. Note: Each client MUST connect with a unique clientId.
Notes
This method must be called before any other method. There is no feedback for a successful connection, but a subsequent attempt to connect will return the message "Already connected."
Method Parameters Notes
void disconnect()
Call this method to terminate the connections the host application. Calling this method does not cancel orders that have already been sent.
Method
void reqMktData(long id, String symbol, String secType, String expiry, double strike, String right, String multiplier String exchange, String currency)
Parameters
id - the ticker id. Must be a unique value. When the market data returns, it will be identified by this tag. This is also used when canceling the market data. symbol - the symbol of the underlying for which you are requesting market data. secType - the security type. Valid values are:
• • • • • •
STK OPT FUT IND FOP CASH
expiry - the expiration data. Use the format YYYYMM.
413
TWS Users' Guide
strike - the strike price. right - specifies a Put or Call. Valid values are: P, PUT, C, CALL. multiplier - allows you to specify a futures or options multiplier in cases where multiple possibilities exist. exchange - the order destination, such as Smart. currency - specifies the currency. Ambiguities may require that this field be specified, for example, when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). Given the existence of this kind of ambiguity, it is a good idea to always specify the currency. Notes Call this method to request market data. The market data will be returned by the tickPrice and tickSize events.
Method
void reqMktData2(long id, String localSymbol, String secType, String exchange, String currency)
Parameters
id - the ticker id. Must be a unique value. When the market data returns, it will be identified by this tag. This is also used when canceling the market data. localSymbol - the local exchange symbol of the underlying for which you are requesting market data. secType - the security type. Valid values are:
• • • • • •
STK OPT FUT IND FOP CASH
exchange - the order destination, such as SMART. currency - specifies the currency. Ambiguities may require that this field be specified, for example, when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). Given the existence of this kind of ambiguity, it is a good idea to always specify the currency. Notes Call this method to request market data using the exchange symbol. The market data will be returned by the tickPrice and tickSize events.
414
Application Program Interface
Method Parameters Notes
void cancelMktData(long id)
id- the ID that was specified in the call to reqMktData(). After calling this method, market data for the specified id will stop flowing.
Method
void placeOrder(long id, String action, long quantity, String symbol, String secType, String expiry, double strike, String right,String multiplier, String exchange, String currency, String orderType, double lmtprice, double auxPrice, String goodAfterTime, String faGroup, String faMethod, String faPercentage, String faProfile, String goodTillDate) See Extended Order Attributes.
id - the order id. You must specify a unique value. When the order status returns, it will be identified by this tag. This tag is also used when canceling the order. action - identifies the side. Valid values are:
Parameters
• • •
BUY SELL SSHORT
quantity - The order quantity. symbol - the symbol of the underlying asset. secType - the security type. Valid values are:
• • • • •
STK OPT FUT FOP CASH
expiry - the expiration date. Use the format YYYYMM. strike - the strike price right - specifies a Put or Call. Valid values are: P, PUT, C, CALL. multiplier - allows you to specify a futures or options multiplier in cases where multiple possibilities exist. exchange - the order destination, such as Smart. currency - specifies the currency. Ambiguities may require that this field be specified, for example, when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). Given the existence of this kind of ambiguity, it is a good idea to always specify the currency. 415
TWS Users' Guide
orderType - identifies the order type. Valid values are:
• • • • • • • • • •
MKT MKTCLS LMT LMTCLS PEGMKT STP STPLMT TRAIL REL VWAP
lmtPrice - the LIMIT price, used for limit, stop-limit and relative orders. In all other cases specify zero. For relative orders with no limit price, also specify zero. auxPrice - identifies the STOP price for stop-limit orders, and the offset amount for relative orders. In all other cases, specify zero. goodAfterTime - specifies that the order becomes active after the time set. Send an empty string if not applicable. faGroup - specifies the order's "Financial Advisor Group." Send an empty string if not an FA. faMethod - specifies the order's "Financial Advisor Allocation Method." Send an empty string if not an FA. faPercentage - specifies the order's "Financial Advisor Percentage." Send an empty string if not an FA. faProfile - specifies the order's "Financial Advisor Profile." Send an empty string if not an FA. goodTillDate - specifies the order's "Good Till Date." Send an empty string if not applicable. Notes Call this method to place an order. The order status will be returned by the orderStatus event. For more details see Active X Properties.
Method
void placeOrder2(long id, String action, long quantity, String localSymbol, String secType, String exchange, String currency, String orderType, double lmtprice, double auxPrice, String goodAfterTime, String faGroup, String faMethod, String faPercentage, String faProfile, String goodTillDate)
id - the order id. You must specify a unique value. When the order status returns, it will be identified by this tag. This tag is also used when canceling the order.
Parameters
416
Application Program Interface
action - identifies the side. Valid values are:
• • •
BUY SELL SSHORT
quantity - The order quantity. localSymbol - the local exchange symbol of the underlying asset. secType - the security type. Valid values are:
• • • • •
STK OPT FUT FOP CASH
exchange - the order destination, such as Smart. currency - specifies the currency. Ambiguities may require that this field be specified, for example, when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). Given the existence of this kind of ambiguity, it is a good idea to always specify the currency.
417
TWS Users' Guide
orderType - identifies the order type. Valid values are:
• • • • • • • • • •
MKT MKTCLS LMT LMTCLS PEGMKT STP STPLMT TRAIL REL VWAP
lmtPrice - the LIMIT price, used for limit, stop-limit and relative orders. In all other cases specify zero. For relative orders with no limit price, also specify zero. auxPrice - identifies the STOP price for stop-limit orders, and the offset amount for relative orders. In all other cases, specify zero. goodAfterTime - specifies that the order becomes active after the time set. Send an empty string if not applicable. faGroup - specifies the order's "Financial Advisor Group." Send an empty string if not an FA. faMethod - specifies the order's "Financial Advisor Allocation Method." Send an empty string if not an FA. faPercentage - specifies the order's "Financial Advisor Percentage." Send an empty string if not an FA. faProfile - specifies the order's "Financial Advisor Profile." Send an empty string if not an FA. goodTillDate - specifies the order's "Good Till Date." Send an empty string if not applicable. Notes Call this method to place an order using the exchange symbol. The order status will be returned by the orderStatus event.
Method
void cancelOrder(long id)
418
Application Program Interface
Parameters Notes
id- the order ID that was specified previously in the call to placeOrder() Call this method to cancel an order.
Method Parameters Notes
reqOpenOrders()
Call this method to request the open orders that were p, laced from this client. Each open order will be fed back through the openOrder1(), openOrder2(), openOrder3(), and orderStatus() events. NOTE: The client with a clientId of 0 will also receive the application-owned open orders. These orders will be associated with the client and a new orderId will be generated. This association will persist over multiple API and application sessions.
Method Parameters Notes
reqAllOpenOrders()
Call this method to request the open orders that were placed from all clients and also from the application. Each open order will be fed back through the openOrder1(), openOrder2(), openOrder3(), and orderStatus() events. NOTE: No association is made between the returned orders and the requesting client.
Method Parameters
reqAutoOpenOrders(boolean bAutoBind)
bAutoBind - If set to TRUE, newly created application orders will be implicitly associated with the client. If set to FALSE, no association will be made. Call this method to request that newly created application orders be implicitly associated with the client. When a new application order is created, the order will be associated with the client, and fed back through the openOrder1(), openOrder2(), and orderStatus() events. NOTE: This request can only be made from a client with a clientId of 0.
Notes
419
TWS Users' Guide
Method Parameters Notes
reqExecutions()
When this method is called, all execution reports are downloaded to the client via the the execDetails event.
Method Parameters Notes
void reqIds(int numIds)
numIds - the number of ids you want to reserve. Call this function to request the next valid ID that can be used when placing an order. After calling this method, the nextValidId() event will be triggered, and the id returned is that next valid ID. That ID will reflect any autobinding that has occurred (which generates new IDs and increments the next valid ID therein).
Method
void reqContractDetails(String symbol, String secType, String expiry, double strike, String right, String multiplier, String exchange, String currency)
Parameters
symbol - the symbol of the underlying for which you are requesting market data. secType - the security type. Valid values are:
• • • • • •
STK OPT FUT IND FOP CASH
expiry - the expiration data. Use the format YYYYMM. strike - the strike price. right - specifies a Put or Call. Valid values are: P, PUT, C, CALL.
420
Application Program Interface
multiplier - allows you to specify a futures or options multiplier in cases where multiple possibilities exist. exchange - the order destination, such as SMART. currency - specifies the currency. Ambiguities may require that this field be specified, for example, when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). Given the existence of this kind of ambiguity, it is a good idea to always specify the currency. Notes Call this method to request details for a particular underlying or security. The contract details data will be returned by the contractDetails event.
Method
void reqContractDetails2(String localSymbol, String secType,String exchange, String currency)
localSymbol - the local exchange symbol of the underlying for which you are requesting market data. secType - the security type. Valid values are:
Parameters
• • • • • •
STK OPT FUT IND FOP CASH
exchange - the order destination, such as SMART. currency - specifies the currency. Ambiguities may require that this field be specified, for example, when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). Given the existence of this kind of ambiguity, it is a good idea to always specify the currency. Notes Call this method to request details for a particular security using the exchange symbol. The contract details data will be returned by the contractDetails event.
421
TWS Users' Guide
Method
void reqMktDepth(long id, String symbol, String secType, String expiry, double strike, String right, String multiplier, String exchange, String curency, String number of Rows Subscribed to)
id - the ticker id. Must be a unique value. When the market data returns, it will be identified by this tag. This is also used when canceling the market data. symbol - the symbol of the underlying for which you are requesting market data. secType - the security type. Valid values are:
Parameters
• • • • • •
STK OPT FUT IND FOP CASH
expiry - the expiration data. Use the format YYYYMM. strike - the strike price. right - specifies a Put or Call. Valid values are: P, PUT, C, CALL. multiplier - allows you to specify a futures or options multiplier in cases where multiple possibilities exist. exchange - the order destination, such as SMART. curency - specifies the currency. Ambiguities may require that this field be specified, for example, when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). Given the existence of this kind of ambiguity, it is a good idea to always specify the currency. number or rows subscribed to - specifies the number of market depth rows you want to display. Notes Call this method to request market depth details for a particular underlying or security. The market depth data will be returned by the updateMktDepth and updateMktDepthL2 events.
422
Application Program Interface
Method
void reqMktDepth2(long id, String localSymbol, String secType, String exchange, String curency)
id - the ticker id. Must be a unique value. When the market data returns, it will be identified by this tag. This is also used when canceling the market data. localSymbol - the local exchange symbol of the underlying for which you are requesting market data. secType - the security type. Valid values are:
Parameters
• • • • • •
STK OPT FUT IND FOP CASH
exchange - the order destination, such as SMART. curency - specifies the currency. Ambiguities may require that this field be specified, for example, when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). Given the existence of this kind of ambiguity, it is a good idea to always specify the currency. Notes Call this method to request market depth details for a particular underlying or security. The market depth data will be returned by the updateMktDepth and updateMktDepthL2 events.
Method Parameters Notes
void cancelMktDepth (long id)
id - the ID that was specified in the call to reqMktDepth() or reqMktDepth2(). After calling this method, market depth for the specified id will stop flowing.
423
TWS Users' Guide
Method
void addComboLeg(long conid, String action, long ratio, String exchange, long openClose))
conid - the unique contract identifier specifying the security. action- Select the side (buy or sell) for the leg you are constructing. ratio- Select the relative number of contracts for the leg you are constructing. To help determine the ratio for a specific combination order, use Interactive Analytics (see Interactive Analytics in the User's Guide). exchange- The exchange to which the complete combination order will be routed. openClose- Specifies whether the order is an open or close order. Valid values are:
Parameters
• • •
Same - (0) same as the parent security. This is the only option for retail customers. Open - (1) This option is for Institutional Customers only. Close - (2) This option is for Institutional Customers only.
Notes
This method adds a leg definition to an order and must be called for each leg before the combination order can be placed. NOTE: Combination orders must have a secType of 'BAG."
Method Parameters Notes
void clearComboLegs()
This method must be called to remove all leg definitions from a combination order before constructing a new combination order.
Method Parameters
void reqNewsBulletins(boolean AllMsgs)
allMsgs - 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.
424
Application Program Interface
Notes
Call this method to start receiving news bulletins. Each bulletin will be returned by the updateNewsBulletin() event.
Method Parameters Notes
void cancelNewsBulletins())
Call this method to stop receiving news bulletins.
Method Parameters
void setLogLevel(long logLevel)
logLevel - specifies the level of log entry detail used by the server when processing API requests. Valid values include: 1 = SYSTEM 2 = ERROR 3 = WARNING 4 = INFORMATION 5 = DETAIL
Notes
The default level is ERROR. Refer to the API logging page for more details.
Method Parameters Notes
reqManagedAccts()
Call this method to request the list of managed accounts. The list will be returned by the managedAccounts() event. Note: This request can only be made when connected to a Financial Advisor account.
425
TWS Users' Guide
Method Parameters
reqAccountUpdates(boolean subscribe, string acctCode)
subscribe - If set to TRUE, the client will start receiving account and portfolio updates. If set to FALSE, the client will stop receiving this information. acctCode- the account code for which to receive account and portfolio updates.
Notes
Call this method to request account updates. The account data will be fed back through the updateAccountTime, updateAccountValue and update Portfolio events.
Method Parameters
requestFA(long faDataType)
faDataType - specifies the type of Financial Advisor configuration data being requested. Valid values include: 1 = GROUPS 2 = PROFILE 3 =ACCOUNT ALIASES
Notes
Call this method to request FA configuration information from the server. The data returns in an XML string via a "receiveFA" ActiveX event.
Method Parameters
replaceFA(long faDataType, string XML)
faDataType - specifies the type of Financial Advisor configuration data being modified via the API. Valid values include: 1 = GROUPS 2 = PROFILE 3 =ACCOUNT ALIASES XML- the XML string containing the new FA configuration information.
Notes
Call this method to modify FA configuration information from the API. Note that this can also be done manually.
426
Application Program Interface
Method
void reqHistoricalData(long id, String symbol, String secType, String expiry, double strike, String right, String multiplier, String exchange, String curency, String endDateTime, String durationStr, long barSizeSetting, String whatToShow, long useRTH, long formatDate)
id - the ticker id. Must be a unique value. When the market data returns, it will be identified by this tag. This is also used when canceling the market data. symbol - the symbol of the underlying for which you are requesting market data. secType - the security type. Valid values are:
Parameters
• • • • • •
STK OPT FUT IND FOP CASH
expiry - the expiration data. Use the format YYYYMM. strike - the strike price. right - specifies a Put or Call. Valid values are: P, PUT, C, CALL. multiplier - allows you to specify a futures or options multiplier in cases where multiple possibilities exist. exchange - the order destination, such as Smart. curency - specifies the currency. Ambiguities may require that this field be specified, for example, when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). Given the existence of this kind of ambiguity, it is a good idea to always specify the currency. endDateTime - defines a query end date and time at any point during the past 6 mos. Valid values include any date/time within the past six months in the format: yyyymmdd HH:mm:ss zzz where "zzz" is the optional time zone. durationStr - set the query duration up to one week, using a time unit of seconds, days or weeks. Valid values include any integer followed by a space and then S(seconds), D (days) or W (week). If no unit is specified, seconds is used. barSizeSetting - specifies the size of the bars that will be returned (within IB/TWS limits). Valid values include:
427
TWS Users' Guide
1 sec 5 sec 15 sec 30 sec 1 minute 2 minutes 5 minutes 15 minutes 30 minutes 1 hour
1 2 3 4 5 6 7 8 9 10
whatToShow - determines the nature of data being extracted. Valid values include:
• • • • •
TRADES MIDPOINT BID ASK BID/ASK
useRTH - determines whether to return all data available during the requested time span, or only data that falls within regular trading hours. Valid values include:
• •
0 - all data is returned even where the market in question was outside of its regular trading hours. 1 - only data within the regular trading hours is returned, even if the requested time span falls partially or completely outside of the RTH.
formatDate - determines the date format applied to returned bars. Valid values include:
• •
1 - dates applying to bars returned in the format: yyyymmdd{space}{space}hh:mm:dd 2 - dates are returned as a long integer specifying the number of seconds since 1/1/1970 GMT.
Notes
428
Application Program Interface
Method
void openOrder4 (long id, BSTR symbol, BSTR secType, BSTR expiry, double strike, BSTR right, BSTR exchange, BSTR curency, BSTR localSymbol, BSTR action, long quantity, BSTR orderType, double lmtPrice, double auxPrice, BSTR tif, BSTR ocaGroup, BSTR account, BSTR openClose, long origin, BSTR orderRef, long clientId, long permId, BSTR sharesAllocation, BSTR faGroup, BSTR faMethod, BSTR faPercentage, BSTR faProfile, BSTR goodAfterTime, BSTR goodTillDate, long ocaType, int rthOnly, BSTR rule80A, BSTR settlingFirm, int allOrNone, long minQty, double percentOffset, int eTradeOnly, int firmQuoteOnly, double nbboPriceCap, long auctionStrategy, double startingPrice, double stockRefPrice, double delta, double stockRangeLower, double stockRangeUpper, int blockOrder, int sweepToFill, int ignoreRth, int hidden, double discretionaryAmt, long displaySize, long parentId, long triggerMethod, long shortSaleSlot, BSTR designatedLocation))
Parameters
429
TWS Users' Guide
Notes
Copyrights and Trademarks
430
Application Program Interface
Place 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 buy a calendar spread you would:
• •
Buy 1 OPT JUL03 17.5 CALL (100) Sell 1 OPT AUG03 17.5 CALL (100)
The following example walks you through the steps to place a hypothetical calendar spread order for XYZ on ISE: 1. Get the contract IDs for both leg definitions.
• •
2.
Call the reqContractDetails("XYZ", "OPT", 200305, 17.5, "C", "ISE", "") ActiveX method to get the contract id. The conid returned is 12345678. Call the reqContractDetails("XYZ", "OPT", 200304, 17.5, "C", "ISE", "") ActiveX method to get the contract id. The conid returned is 12345679.
Add the first leg.
•
3.
Call the 'addComboLeg(12345678, 1, "BUY", "ISE", 0) ActiveX method to add the leg definition to the order.
Add the second leg.
•
4.
Call the 'addComboLeg(12345679, 1, "SELL", "ISE", 0) ActiveX method to add the leg definition to the order.
Set and send the combination order details.
•
Call the 'placeOrder(10, "BUY", 1, "XYZ", "BAG", "", 0, "", "ISE", "", "LMT", 1, 0, "", "", "", "", "", "")' ActiveX method to place the order.
NOTE: For combination orders, the secType must always be set to 'BAG'. If the order legs do not constitute a valid combination, one of the following errors will be returned: 312 = The combo details are invalid. 313 = The combo details for '' are invalid. 314 = Security type 'BAG' requires combo leg details. 315 = Stock combo legs are restricted to SMART exchange. NOTES: (1) The exchange for the leg definition must match that of the combination order. The exception is for a STK leg definition, which must specify the SMART exchange. (2) The openClose leg definition value is always 'SAME' (i.e.0) for retail accounts. For institutional accounts, the value may be any of the following: (SAME, OPEN, CLOSE). 431
TWS Users' Guide
For more information on Combination orders, see the user guide topics Combination Orders and Notes on Combination Orders.
Copyrights and Trademarks
432
Application Program Interface
ActiveX Properties
The table below defines properties you can use when connecting to a server using ActiveX. Property String tif boolean transmit String oca String account String orderRef long origin String openClose long parentId boolean blockOrder boolean sweepToFill long displaySize Description The time in force. Valid values are: DAY, GTC, IOC, GTD Specifies whether the order will be transmitted by the server. If set to false, the order will be created but will not be sent. Identifies an OCA (one cancels all) group. Identifies the account. For institutional customers only. Customer-defined order identification field. Enter a reference string to help identify orders. Identifies the order origin. For institutional customers only. Valid values are: 0 = customer, 1 = firm Specifies whether the order is an open or close. For institutional customers only. Valid values are O, C. The order ID of the parent order, used for bracket and auto trailing stop orders. If set to true, specifies that the order is an ISE Block order. If set to true, specifies that the order is a Sweep-to-Fill order. The publicly disclosed order size, used when placing Iceberg orders. Specifies how Simulated Stop, Stop-Limit and Trailing Stop orders are triggered. Valid values are: 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. boolean ignoreRth boolean hidden String sharesAllocation long clientIdFilter String acctCodeFilter If set to true, allows triggering of orders outside of regular trading hours. If set to true, the order will not be visible when viewing the market depth. this option only works with orders routed to the ISLAND exchange. Deprecated. Upgrade to new FA functionality must be done. Filter the results of the reqExecutions() method based on the clientId. Filter the results of the reqExecutions() method based on an account code.
long triggerMethod
433
TWS Users' Guide
Property String timeFilter String symbolFilter
Description Note: this is only relevant for FA managed accounts. Filter the results of the reqExecutions() method based on execution reports received after the specified time. Filter the results of the reqExecutions() method based on the order symbol. Filter the results of the reqExecutions() method based on the order security type.
String secTypeFilter Note: Refer to the ActiveX methods section for the list of valid security types. String exchangeFilter Filter the results of the reqExecutions() method based on the order exchange. Filter the results of the reqExecutions() method based on the order action. String sideFilter Note: Refer to the ActiveX methods sections for the list of valid order actions. double discretionaryAmt long shortSaleSlot String designatedLocation String goodAfterTime Set an order's discretionary amount. Valid values include 1 or 2. Only valid when shortSaleSlot value = 2. The trade's "Good After Time," format "YYYYMMDD hh:mm:ss (optional time zone)" Use an empty String if not applicable. You must enter a tif value of GTD. The trade's "Good Till Date," format "YYYYMMDD hh:mm:ss (optional time zone)" Use an empty String if not applicable. long ocaType boolean rthOnly Cancel on Fill with Block = 1 Reduce on Fill with Block = 2 Reduce on Fill without Block = 3 Regular trading hours only. 0 = no 1 = yes. Individual = 'I' Agency = 'A', AgentOtherMember = 'W' IndividualPTIA = 'J' String rule80A AgencyPTIA = 'U' AgentOtherMemberPTIA = 'M' IndividualPT = 'K' AgencyPT = 'Y' AgentOtherMemberPT = 'N' String settlingFirm boolean allOrNone long minQty double percentOffset boolean eTradeOnly Institutional only. 0 = no, 1 = yes Identifies a minimum quantity order type. The percent offset for relative orders. Trade with electronic quotes. yes = 1, no = 0
String goodTillDate
434
Application Program Interface
Property boolean firmquoteOnly double nbboPriceCap
Description Trade with firm quotes. yes = 1, no = 0 Maximum Smart order distance from the NBBO. match = 1 improvement = 2 transparent = 3 For orders on BOX only. Starting price. For BOX orders only. The stock reference price. For BOX orders only. The stock delta. For BOX orders only. The lower value of the acceptable stock range. For BOX orders only. The upper value of the acceptable stock range. For BOX orders only. Server Version.
long auctionStrategy
double startingPrice double stockRefPrice double delta double stockRangeLower double stockRangeUpper long serverVersion
String TwsConnectionTime Connection time.
NOTE: The filter properties may be combined in any combination to further reduce the results of the reqExecutions() method.
Copyrights and Trademarks
435
TWS Users' Guide
Use the Visual Basic VBClient Sample Program
You can access the server through the ActiveX interface using the Visual Basic sample application. 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.0 or higher) installed on your PC.
The VBClient program is a sample program that shows you how to use the TWS ActiveX control to connect to the server from a Visual Basic application. To use the VBClient program 1. 2. 3. 4. From MS Visual Basic, open the project file VB_API_sample.vbp. On the Projects menu, select Components. In the Components dialog box, select TWS ActiveXControl module and click OK. Press Ctrl + F5 to compile and run the project.
Copyrights and Trademarks
436
Application Program Interface
C++
C++ API
Copyrights and Trademarks
437
TWS Users' Guide
Link to TWS using the TwsSocketClient dll
To link to TWS using the TwsSocketClient.dll 1. 2. 3. Create a Windows application using MS Visual Studio (version 5.0 or higher). Add C :\jts\SocketClient\include to your project's include path. This should be done for any individual project that accesses the TwsSocketClient library's header files. Add the C :\jts\SocketClient\lib\TwsSocketclient.lib file to your project's libraries path. This should be done for any individual project that accesses the TwsSocketClient library. Include EWrapper.h and EClientSocket.h in any Visual C++ source code that accesses their functionality and data structures. Subclass the EWrapper class. Override the following functions:
4. 5. 6.
• • • •
7. 8.
Override tickPrice() and tickSize() functions to handle the market data. Override the orderStatus() function to receive order status. Override the error() and winError() functions to receive error information. Override the connectionsClosed() function to be notified when TWS terminates the connection.
Instantiate the EClientSocket class. Call the following functions:
• • • • • •
Call the connect() function to connect to TWS. Call the reqMktData() function to request market data. Call the placeOrder() function to place an order. Call the checkMessages() function frequently (every 1 second) to process data received from TWS. Call the reqOpenOrders() function to request open orders. Call the reqAccountUpdates() function to request account data.
To run the program, ensure that the TwsSocketClient.dll is in the same directory as your executable, or in your path. By default, the TwsSocketClient.dll file installs into your C:\Windows\system or C:\WINNT\system32 directory.
Copyrights and Trademarks
438
Application Program Interface
Use the C++ TestSocketClient Sample Program
You can access TWS through a Microsoft Windows-based C++ application using the TWSSocketClient.dll component. Before you can connect to TWS using the SocketClient component, you must:
• • •
Install the socketclient component and sample programs Configure TWS to support the API components Have Microsoft Visual Studio (Visual C++ 5.0 or higher) installed on your PC.
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. To use the TestSocketClient program
• •
From Microsoft Visual C++, open the project file client2.dsp from the c:/jts/TestSocketClient directory. Build that project, and run it.
Copyrights and Trademarks
439
TWS Users' Guide
Class EClientSocket Functions
The tables below define the class EClientSocket functions you can use when connecting to TWS. The list of functions includes:
• • • • • • • • • • • • • • • • • • • • • • • • • •
EClientSocket() eConnect() eDisconnect() reqMktData() cancelMktData() placeOrder() cancelOrder() checkMessages() reqOpenOrders() reqAccountUpdates() reqExecutions() reqIds () reqContractDetails() reqMktDepth() cancelMktDepth() reqNewsBulletins() cancelNewsBulletins() setLogLevel() reqAllOpenOrders() reqAutoOpenOrders() reqManagedAccts() requestFA() replaceFA() reqHistoricalData() serverVersion() TwsConnectionTime()
Function Parameters
EClientSocket( EWrapper *ptr)
ptr- the pointer to an object that was derived from the EWrapper base class.
440
Application Program Interface
Notes
This is the constructor.
Function Parameters
bool eConnect( const char *host, UINT port, int clientId=0)
host - host name or IP address of the machine where TWS is running. Leave blank to connect to the local host. port - must match the port specified in TWS on the Configure>API>Socket Port field. clientId - A number used to identify this client connection. All orders placed/modified from this client will be associated with this client identifier. Note: Each client MUST connect with a unique clientId.
Notes
This function must be called before any other. There is no feedback for a successful connection, but a subsequent attempt to connect will return the message "Already connected."
Function Parameters Notes
void eDisconnect()
ptr- the pointer to an object that was derived from the EWrapper base class. Call this method to terminate the connections with TWS. Calling this method does not cancel orders that have already been sent.
Function Parameters
void reqMktData(TickerID id, const Contract &contract)
id - the ticker id. Must be a unique value. When the market data returns, it will be identified by this tag. This is also used when canceling the market data. contract- this structure contains a description of the contract for which market data is being requested.
Notes
Call this method to request market data. The market data will be returned by the tickPrice and tickSize events.
441
TWS Users' Guide
Function Parameters Notes
void cancelMktData(TickerID id)
id- the ID that was specified in the call to reqMktData(). After calling this method, market data for the specified id will stop flowing.
Function Parameters
void placeOrder( OrderID id, const Contract &contract, const Order &order)See Extended Order Attributes.
id - the order id. You must specify a unique value. When the order status returns, it will be identified by this tag. This tag is also used when canceling the order. contract - this structure contains a description of the contract which is being traded. order - this structure contains the details of the order.Note: Each client MUST connect with a unique clientId.
Notes
Call this method to place an order. The order status will be returned by the orderStatus event.
Function Parameters Notes
void cancelOrder(OrderID id)
id- the order ID that was specified previously in the call to placeOrder() Call this method to cancel an order.
Function
void checkMessages()
442
Application Program Interface
Parameters Notes This method should be called frequently (every 1 second) to check for messages received from TWS.
Function Parameters Notes
void reqOpenOrders()
Call this method to request the open orders that were placed from this client. Each open order will be fed back through the openOrder() and orderStatus() functions on the EWrapper. Note: The client with a clientId of 0 will also receive the TWS-owned open orders. These orders will be associated with the client and a new orderId will be generated. This association will persist over multiple API and TWS sessions.
Function Parameters
void reqAccountUpdates(bool subscribe, const CString& acctCode)
subscribe - If set to TRUE, the client will start receiving account and portfolio updates. If set to FALSE, the client will stop receiving this information. acctCode - the account code for which to receive account and portfolio updates.
Notes
Call this function to start getting account values, portfolio, and last update time information.
Function Parameters
void reqExecutions(const ExecutionFilter& filter)
filter - the filter criteria used to determine which execution reports are returned.
443
TWS Users' Guide
Notes
When this method is called, the execution reports that meet the filter criteria are downloaded to the client via the execDetails() method.
Function Parameters Notes
void reqIds(int numIds)
numIds - the number of ids you want to reserve. Call this function to request from TWS the next valid ID that can be used when placing an order. After calling this method, the nextValidId() event will be triggered, and the id returned is that next valid ID. That ID will reflect any autobinding that has occurred (which generates new IDs and increments the next valid ID therein).
Function Parameters Notes
void reqContractDetails (const Contract &contract)
Contract- summary description of the contract being looked up. Call this function to download all details for a particular underlying. The contract details will be received via the contractDetails() function on the EWrapper.
Function Parameters
void reqMktDepth (TickerID id, const Contract &contract, number or rows subscribed to)
id - 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 contract- this structure contains a description of the contract for which market depth data is being requested. number of rows subscribed to - specified the number of market depth rows to display.
444
Application Program Interface
Notes
Call this method to request market depth for a specific contract. The market depth will be returned by the updateMktDepth() and updateMktDepthL2() events.
Function Parameters Notes
void cancelMktDepth (TickerID id)
id - the ID that was specified in the call to reqMktDepth(). After calling this method, market depth data for the specified id will stop flowing.
Function Parameters
void reqNewsBulletins(bool allMsgs)
allMsgs- 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. Call this method to start receiving news bulletins. Each bulletin will be returned by the updatedNewsBulletin() event.
Notes
Function Parameters Notes
void cancelNewsBulletins()
Call this method to stop receiving news bulletins.
Function
void setLogLevel(int logLevel)
445
TWS Users' Guide
Parameters
logLevel - 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
Notes
The default detail level is ERROR. Refer to the API Logging page for more details.
Function Parameters Notes
void reqAllOpenOrders()
Call this method to request the open orders placed from all clients and also from TWS. Each open order will be fed back through the openOrder() and orderStatus() functions on the EWrapper. Note: No association is made between the returned orders and the requesting client.
Function Parameters
reqAutoOpenOrders (bool bAutoBind)
bAutoBind - If set to TRUE, newly created TWS orders will be implicitly associated with the client. If set to FALSE, no association will be made. 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 fed back through the openOrder() and orderStatus() functions on the EWrapper. Note: This request can only be made from a client with clientId of 0.
Notes
446
Application Program Interface
Function Parameters Notes
void reqManagedAccts()
Call this method to request the list of managed accounts. The list will be returned by the managedAccounts() function on the EWrapper. Note: This request can only be made when connected to a FA managed account.
Function Parameters
requestFA(long faDataType)
faDataType - specifies the type of Financial Advisor configuration data being requested. Valid values include: 1 = GROUPS 2 = PROFILE 3 = ACCOUNT ALIASES
Notes
Call this method to request FA configuration information from TWS. The data returns in an XML string via a "receiveFA" ActiveX event.
Function Parameters
replaceFA(long faDataType, string XML)
faDataType - specifies the type of Financial Advisor configuration data being modified via the API. Valid values include: 1 = GROUPS 2 = PROFILE 3 =ACCOUNT ALIASES XML- the XML string containing the new FA configuration information.
Notes
Call this method to modify FA configuration information from the API. Note that this can also be done manually in TWS itself.
447
TWS Users' Guide
Function
void reqHistoricalData (TickerID id, const Contract &contract, String endDateTime, String durationStr, long barSizeSetting String whatToShow, int useRTH, int formatDate)
Parameters
id - the ticker id. Must be a unique value. When the market data returns, it will be identified by this tag. This is also used when canceling the market data. contract- this structure contains a description of the contract for which market data is being requested. endDataTime - defines a query end date and time at any point during the past 6 mos. Valid values include any date/time within the past six months in the format: yyyymmdd HH:mm:ss ttt where "ttt" is the optional time zone. durationStr - set the query duration up to one week, using a time unit of seconds, days or weeks. Valid values include any integer followed by a space and then S(seconds), D (days) or W (week). If no unit is specified, seconds is used. barSizeSetting - specifies the size of the bars that will be returned (within IB/TWS limits). Valid values include:
Bar Size
1 sec
Parametric Value 1 2 3 4 5
6 7 8 9 10 11
5 secs 15 secs 30 secs 1 min.
2 mins 5 mins. 15 mins 30 mins 1 hour 1 day
whatToShow - determines the nature of data being extracted. Valid values include:
• • • •
448
TRADES MIDPOINT BID ASK
Application Program Interface
•
BID/ASK
useRTH - determines whether to return all data available during the requested time span, or only data that falls within regular trading hours. Valid values include:
• •
0 - all data is returned even where the market in question was outside of its regular trading hours. 1 - only data within the regular trading hours is returned, even if the requested time span falls partially or completely outside of the RTH.
formatDate - determines the date format applied to returned bars. Valid values include:
• •
1 - dates applying to bars returned in the format: yyyymmdd{space}{space}hh:mm:dd 2 - dates are returned as a long integer specifying the number of seconds since 1/1/1970 GMT.
Notes
Function Parameters Notes
serverVersion()
Function Parameters Notes
TwsConnectionTime()
Copyrights and Trademarks
449
TWS Users' Guide
SocketClient Properties
The tables below define properties for the Execution, Contract and Order classes, and classes that are closely related to them.
Execution properties
Property CString execId CString time CString acctNumber CString exchange Description Unique order execution id. The order execution time. The customer account number. Exchange that executed the order. Specifies if the transaction was a sale or a purchase. Valid values are:
CString side
• •
BOT SLD
int shares double price int permId long clientId
The number of shares filled. The order execution price. The TWS id used to identify orders, remains the same over TWS sessions The id of the client that placed the order. Note: TWS orders have a fixed client id of 0. The order id.
long orderId Note: TWS orders have a fixed order id of 0.
ExecutionFilter properties
Property long m_clientId CString m_acctCode Description Filter the results of the reqExecutions() method based on the clientId. Filter the results of the reqExecutions() method based on an account code. Note: this is only relevant for FA managed accounts. Filter the results of the reqExecutions() method based on execution reports received after the specified time. The format for timeFilter is "yyyymmdd-hh:mm:ss" Filter the results of the reqExecutions() method based on the order symbol. Filter the results of the reqExecutions() method based on the order security type. Note: Refer to the Contract struct for the list of valid security types. Filter the results of the reqExecutions() method based on the order exchange. Filter the results of the reqExecutions() method based on the order
CString m_time
CString m_symbol
CString m_secType
CString m_exchange CString m_side 450
Application Program Interface
action. Note: Refer to the Order struct for the list of valid order actions.
Contract properties
Property CString symbol Description This is the symbol of the underlying asset. This is the security type. Valid values are
• •
CString secType
STK OPT FUT IND FOP CASH BAG
• • • • •
CString expiry double strike
The expiration date. Use the format YYYYMM. The strike price. Specifies a Put or Call. Valid values are: P, PUT, CString right C, CALL. Allows you to specify a futures or options CString multiplier multiplier. This is only necessary when multiple possibilities exist.; CString exchange The order destination, such as Smart. specifies the currency. Ambiguities may require that this field be specified, for example, when SMART is the exchange and IBM is being CString currency requested (IBM can trade in GBP or USD). Given the existence of this kind of ambiguity, it is a good idea to always specify the currency. This is the local exchange symbol of the CString localSymbol underlying asset. Dynamic memory structure used to store the vector* comboLegs; leg definitions for this contract.
ContractDetails properties
Property Contract summary CString marketName CString tradingClass int conId double minTick CString multiplier CString orderTypes CString validExchanges Description A contract structure. The market name for this contract. The trading class name for this contract. The unique contract identifier. The minimum price tick. The order size multiplier. The list of valid order type for this contract The list of exchanges on which this contract is traded. 451
TWS Users' Guide
Order properties
Property long orderId long clientId CString action long quantity Description The id for this order. The id of the client that placed this order. Identifies the side. Valid values are: BUY, SELL, SSHORT The order quantity. Identifies the order type. Valid values are:
• • • •
CString orderType
MKT MKTCLS LMT LMTCLS PEGMKT STP STPLMT TRAIL REL VWAP
• • • • • •
double lmtPrice double auxPrice CString sharesAllocation CString tif CString ocaGroup CString account CString openClose Order origin CString orderRef bool transmit long parentId bool blockOrder bool sweepToFill int displaySize
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. Deprecated. Upgrade to new FA functionality must be done. The time in force. Valid values are: DAY, GTC, IOC, GTD. Identifies an OCA (one cancels all) group. The account. For institutional customers only. Specifies whether the order iepricated. Upgrade to new FA functionality must be done. s an open or close order. For institutional customers only. Valid values are O, C. The order origin. For institutional customers only. Valid values are 0 = customer, 1 = firm The order reference. For institutional customers only. Specifies whether the order will be transmitted by TWS. If set to false, the order will be created at TWS but will not be sent. The order ID of the parent order, used for bracket and auto trailing stop orders. If set to true, specifies that the order is an ISE Block order. If set to true, specifies that the order is a Sweep-to-Fill order. The publicly disclosed order size, used when placing Iceberg orders. Specifies how Simulated Stop, Stop-Limit and Trailing Stop orders are triggered. Valid values are: O - the default value. The "double bid/ask" method will be used for orders for OTC stocks and US options. All other
int triggerMethod
452
Application Program Interface
Property
Description 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. If set to true, allows triggering of orders outside of regular trading hours. 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. The amount off the limit price allowed for discretionary orders. Valid values are 1 or 2. Used only when shortSaleSlot = 2. The trade's "Good After Time," format "YYYYMMDD hh:mm:ss (optional time zone)" Use an empty String if not applicable. You must enter GTD as the time in force to use this string. The trade's "Good Till Date," format "YYYYMMDD hh:mm:ss (optional time zone)" Use an empty String if not applicable. Cancel on Fill with Block = 1 Reduce on Fill with Block = 2 Reduce on Fill without Block = 3 1 = yes, 2 = no Individual = 'I' Agency = 'A', AgentOtherMember = 'W' IndividualPTIA = 'J'
bool ignoreRth boolean hidden double discretionaryAmt int shortSaleSlot CString designatedLocation CString m_goodAfterTime
CString m_goodTillDate
int ocaType bool rthOnly
CString rule80A
AgencyPTIA = 'U' AgentOtherMemberPTIA = 'M' IndividualPT = 'K' AgencyPT = 'Y' AgentOtherMemberPT = 'N'
CString settlingFirm bool allOrNone int minQty double percentOffset
Institutional only. 0 = no, 1 = yes Identifies a minimum quantity order type. The percent offset amount for relative orders. Trade with electronic quotes. bool eTradeOnly 0 = no, 1 = yes Trade with firm quotes. bool firmQuoteOnly 0 = no, 1 = yes double nbboPriceCap Maximum smart order distance from the NBBO. int auctionStrategy match = 1 improvement = 2
453
TWS Users' Guide
Property
Description transparent = 3 For orders on BOX only.
double startingPrice double stockRefPrice double delta double stockRangeLower double stockRangeUpper CString CString CString CString
The auction starting price. For orders on BOX only. The stock reference price. For orders on BOX only. The stock delta. For orders on BOX only. The lower value for the acceptable stock range. For orders on BOX only. The upper value for the acceptable stock range. For orders on BOX only. The Financial Advisor group the trade will be allocated to -faGroup use an empty String if not applicable. The Financial Advisor allocation profile the trade will be faProfile allocated to -- use an empty String if not applicable. The Financial Advisor allocation method the trade will be faMethod allocated with -- use an empty String if not applicable. The Financial Advisor percentage concerning the trade's faPercentage allocation -- use an empty String if not applicable.
ComboLeg properties
Property long conId long ratio Description The unique contract identifier specifying the security. Select the relative number of contracts for the leg you are constructing. To help determine the ratio for a specific combination order, refer to the Interactive Analytics section of the User's Guide. The side (buy or sell) for the leg you are constructing. The exchange to which the complete combination order will be routed. openClose - Specifies whether the order is an open or close order. Valid values are:
CString action CString exchange
•
long openClose
Same - (0) same as the parent security. This is the only option for retail customers. Open - (1) this option is only valid for institutional customers. Close - (2) this option is only valid for institutional customers.
• •
Copyrights and Trademarks
454
Application Program Interface
Place 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 buy a calendar spread you would:
• •
Buy 1 OPT JUL03 17.5 CALL (100) Sell 1 OPT AUG03 17.5 CALL (100)
The following example walks you through the hypothetical steps to place a calendar spread order for XYZ on ISE: 1. Using the reqContractDetails() method, get the contract id for both leg definitions.
• •
2.
The conid for XYZ option JUL03 17.5 CALL on ISE is "12345678". The conid for XYZ option AUG03 17.5 CALL on ISE is "12345679".
Create and add the first leg.
•
Create a new ComboLeg structure containing the following data:
conid=112345678, ratio=1, action="BUY", exchange="ISE", openClose=0
3. Create and add the second leg.
•
Create a new ComboLeg structure containing the following data:
conid=12345679, ratio=1, action="SELL", exchange="ISE", openClose=0
4. Add each leg to the list of definitions maintained by the contract. Refer to the C++ socket sample to see how this is done. 5. Set and send the combination order details.
•
Call the 'placeOrder' method with the following contract details: symbol = "XYZ" secType = "BAG" exchange = "ISE"
NOTE: For combination orders, the secType must always be set to 'BAG'. If the order legs do not constitute a valid combination, one of the following errors will be returned: 312 = The combo details are invalid. 313 = The combo details for '' are invalid. 314 = Security type 'BAG' requires combo leg details.
455
TWS Users' Guide
315 = Stock combo legs are restricted to SMART exchange. NOTES: (1) The exchange for the leg definition must match that of the combination order. The exception is for a STK leg definition, which must specify the SMART exchange. (2) The openClose leg definition value is always 'SAME' (i.e.0) for retail accounts. For institutional accounts, the value may be any of the following: (SAME, OPEN, CLOSE). For more information on Combination orders, see the user guide topics Combination Orders and Notes on Combination Orders.
Copyrights and Trademarks
456
Application Program Interface
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:
• • • • • • • • • • • • • • • • • •
tickPrice() tickSize() orderStatus() error() winError() connectionClosed() openOrder() updateAccountValue() updatePortfolio() updateAccountTime() nextValidId() contractDetails execDetails() updateMktDepth() updateMktDepthL2() updateNewsBulletin() managedAccounts() receiveFA()
Function Parameters
virtual void tickPrice(TickerID id, TickType field, double price, int canAutoExecute)
id - the ticker ID that was specified previously in the call to reqMktData() tickType - specifies the type of price. Possible values are:
• • • • • •
1 = bid 2 = ask 4 = last 6 = high 7 = low 9 = close
price - could be the bid, ask, last price, daily high, daily low or last day close, depending on tickType value. 457
TWS Users' Guide
canAutoExecute - specifies whether the price tick is available for automatic execution. Possible values are:
• •
Notes
0 = not eligible for automatic execution 1 = eligible for automatic execution
This function is called when the market data changes. Prices are updated immediately with no delay.
Function Parameters
virtual void tickSize(TickerID id, TickType field, int size)
id - the ticker ID that was specified previously in the call to reqMktData() tickType - specifies the type of size. Possible values are:
• • • •
0 = bid size 3 = ask size 5 = last size 8 = volume
size - could be the bid size, ask size, last size or trading volume, depending on the tickType value. Notes This function is called when the market data changes. Sizes are updated immediately with no delay.
Function
virtual void orderStatus(OrderId id, const CString &status, int filled, int remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId)
id - the order ID that was specified previously in the call to placeOrder() status - the order status. Possible values include:
Parameters
•
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
458
Application Program Interface
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 (and the status remains DARK BLUE) until the election criteria are met. At that time the order is transmitted to the order destination as specified (and the order status color will change). 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 - the order has been completely filled.
•
filled - specifies the number of shares that have been executed. remaining - specifies the number of shares still outstanding. avgFillPrice - 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. permId - the TWS id used to identify orders. Remains the same over TWS sessions. parentId - The order ID of the parent order, used for bracket and auto trailing stop orders. lastFilledPrice 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. clientId - 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. Notes 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.
Function Parameters
virtual void error(const int id, const int errorCode, const CString errorString) = 0;
id- this is the orderId or tickerId of the request that generated the
459
TWS Users' Guide
error errorCode - error codes are documented in the Error Codes topic. errorString - this is the textual description of the error, also documented in the Error Codes topic. Notes This event is called when there is an error with the communication or when TWS wants to send a message to the client.
Function Parameters Notes
virtual void Winerror(const CString &str, int lastError)
str - this is the error message text lastError - the error code returned by GetLastError() This event is called when there is an error on the client side.
Function Parameters Notes
virtual void connectionClosed()
This function is called when TWS closes the sockets connection with the ActiveX control, or when TWS is shut down.
Function Parameters Notes
virtual void managedAccounts(const CString& accountsList)
accountsList - the comma delimited list of FA managed accounts. This function is called when a successful connection is made to a Financial Advisor account. It is also called when the reqManagedAccts() method is invoked.
460
Application Program Interface
Function
virtual void openOrder(OrderId orderId, const Contract &contract, const Order &order)See Extended Order Attributes.
orderID - The order ID assigned by TWS. Use to cancel or update the order. contract - Describe the contract for the open order. order - Gives the details of the open order.
Parameters
Notes
This function is called to feed in open orders.
Function
virtual void updateAccountValue(const CString& key, const CString& value, const CString& currency, const CString& accountName)
key- A string that indicates one type of account value. Below is a set of keys sent by TWS.
Parameters
• • • • • • • • • • • • •
CashBalance - Account cash balance Currency - Currency string DayTradesRemaining - Number of day trades left EquityWithLoanValue - Equity with Loan Value InitMarginReq - Current initial margin requirement LongOptionValue - Long option value MaintMarginReq - Current maintenance margin NetLiquidation - Net liquidation value OptionMarketValue - Option market value ShortOptionValue - Short option value StockMarketValue - Stock market value UnalteredInitMarginReq - Overnight initial margin requirement UnalteredMaintMarginReq - Overnight maintenance margin requirement
value- The value associated with the key. currency- Defines the currency type, in case the value is a currency type. account- states the account the message applies to. Useful for Financial Advisor sub-account messages. Notes This function is called only when ReqAccountUpdates on EClientSocket object has been called.
461
TWS Users' Guide
Event
virtual void updatePortfolio(const Contract& contract, int position, double marketPrice, double marketValue, double averageCost, double unrealizedPNL, double realizedPNL, const CString& accountName)
contract - This structure contains a description of the contract which is being traded. The exchange field in a contract is not set for portfolio update. position - This integer indicates the position on the contract. If the position is 0, it means the position has just cleared. marketPrice - Unit price of the instrument. marketValue - The total market value of the instrument. averageCost- The average cost per share is calculated by dividing your cost (execution price + commission) by the quantity of your position. unrealizedPNL - The difference between the current market value of your open positions and the average cost, or Value - Average Cost. realizedPNL- 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) account- states the account the message applies to. Useful for Financial Advisor sub-account messages.
Parameters
Notes
This function is called only when reqAccountUpdates on EClientSocket object has been called.
Function Parameters Notes
virtual void updateAccountTime(const CString& timeStamp)
timeStamp - This indicates the last update time of the account information This function is called only when reqAccountUpdates on EClientSocket object has been called.
Function Parameters 462
virtual void nextValidId(OrderID id)
id - The next available order ID received from TWS upon
Application Program Interface
connection. Increment all successive orders by one based on this ID. Notes This function is called after a successful connection to TWS.
Function Parameters Notes
virtual void contractDetails(const ContractDetails &contractDetails)
contractDetails- This structure contains a full description of the contract being looked up. This function is called only when reqContractDetails method on the EClientSocket object has been called.
Function
virtual void execDetails( OrderId orderId, const Contract& contract, const Execution& execution, long liquidation)
id - the order ID that was specified previously in the call to placeOrder(). contract - This structure contains a full description of the contract that was executed. NOTE: Refer to the SocketClient Properties page for more information. execution - This structure contains addition order execution details. NOTE: Refer to the SocketClient Properties page for more information. liquidation - specifies whether an execution is the result of a liquidation. Possible values are:
Parameters
• •
Notes
0 = execution is not the result of liquidation 1 = execution is the result of a liquidation
This event is fired when the reqExecutions() methods is invoked, or when an order is filled.
463
TWS Users' Guide
Event Parameters
virtual void updateMktDepth(TickerId id, int position, int operation, int side, double price, int size)
id - the ticker ID that was specified previously in the call to reqMktDepth() position - specifies the row id of this market depth entry. operation - identifies the how this order should be applied to the market depth. 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. Valid values are:
• •
0 = ask 1 = bid
price - the order price. size - the order size. Notes This function is called when the market depth changes.
Event
virtual void updateMktDepthL2(TickerId id, int position, CString marketMaker, int operation, int side, double price, int size)
id - the ticker ID that was specified previously in the call to reqMktDepth() position - specifies the row id of this market depth entry. marketMaker - specifies the exchange hosting this order. operation - identifies the how this order should be applied to the market depth. Valid values are:·
Parameters
• • •
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. Valid 464
Application Program Interface
values are:
• •
0 = ask 1 = bid
price - the order price. size - the order size. Notes This function is called when the Level II market depth changes.
Function
virtual void updateNewsBulletin(int msgId, int msgType, const CString& message, const CString& origExchange
msgId - the bulletin ID, incrementing for each new bulletin. msgType - specifies the type of bulletin. Valid values include: 1 = Reqular news bulletin 2 = Exchange no longer available for trading 3 = Exchange is available for trading message - the bulletin's message text. origExchange - the exchange from which this message originated.
Parameters
Notes
This event is triggered for each new bulletin if the client has subscribed (i.e. by calling the reqNewsBulletins() method.
Function Parameters
receiveFA(long faDataType, string XML)
faDataType - specifies the type of Financial Advisor configuration data being received from TWS. Valid values include: 1 = GROUPS 2 = PROFILE 3 =ACCOUNT ALIASES XML- the XML string containing the previously requested FA configuration information.
Notes
This event receives previously requested FA configuration information 465
TWS Users' Guide
from TWS.
Copyrights and Trademarks
466
Application Program Interface
DDE
DDE API
Copyrights and Trademarks
467
TWS Users' Guide
Using the DDE API with Excel®
The DDE API allows you to link to the application using an Excel spreadsheet. To connect using the DDE, you must first:
• •
Download the API components and sample Excel spreadsheet. Ensure that the application server is running and that it is configured to support DDE.
To open the sample spreadsheet After you have downloaded the sample spreadsheet and configured the application, open the spreadsheet and save it as your personal file. 1. 2. Go to C:\Jts\Excel and double-click TwsDde.xls. In the macro warning message box, click Enable Macros. Note: To use the spreadsheet macros, your Excel® macro security must be set to Medium or Low. If you cannot open the spreadsheet or if the macros described in Use the Sample DDE Spreadsheet don't work, you need to modify your macro security level. On the Excel® Tools menu select Macro, and then select Security. Set security to Medium or Low. Keep in mind that different version of Microsoft Excel have different ways of enabling macros and setting macro security.
3. If you receive a message asking if you want to link to information in another worksheet, click Yes. 4. In the User Name field in the Which Trader Workstation? area, enter your account user name. Note that you must enter your User Name on each page of the worksheet to properly connect. 5. If you want to use this spreadsheet as a starting point for your permanent API, on the Excel File menu select Save As and rename the file.
Copyrights and Trademarks
468
Application Program Interface
Using the Sample Spreadsheet
The sample DDE/Excel spreadsheet (TwsDde.xls) contains seven pages. The Tickers page holds pre-defined tickers, and allows you to request market data. The Orders page includes sample orders to illustrate the DDE functionality, and allows you to request orders that are still open since your last TWS session, request Executions, and set Extended Order Attributes. The Conditional Orders page lets you create an order whose submission is contingent on other conditions being met, for example a trailing stop or an order based on a prior fill. You can also use the Account, Contract Details, Executions and Market Depth pages. NOTE: The procedures below describe using macros through the Tools menu. You can also run these macros using the buttons at the top of each spreadsheet, or by creating a custom toolbar and assigning macros to the toolbar buttons.
Copyrights and Trademarks
469
TWS Users' Guide
Create Your Own DDE-Linked Spreadsheet
This topic supplies the syntax you will need to link a spreadsheet via DDE. It does not address Excel® or Visual Basic® issues. DDE Syntax for Excel The table below defines possible field values for DDE-supported functionality. The basic syntax is:
=server|topic!id?reqType?field2
or
=server|error!error (for an optional tag that will display errors)
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
Server server server server server server server server
Topic ord ord ord ord ord ord ord idn idn idn idn idn idn idn
id
reqType place modify cancel status open executed sharesFilled
field2 orderDescription orderModification
server
ord
idn
sharesRemaining
server
ord
idn
price
server server server server
ord ord ord ord
idn idn idn idn
symbol secType expiry strike
470
Application Program Interface
Description Right Specify contract multiplier for options and futures
Server server server
Topic ord ord idn idn
id
reqType right multiplier
field2
Order destination Currency Order side Order quantity Order type Limit price Auxiliary price Local symbol Last fill price Create ticker Request bid price Request ask price Request last price Request bid size Request ask size Request last size Request today's high price Request today's low
server server server server server ord server server server server server server server server server server server
ord ord ord ord ord
idn idn idn idn idn idn
exchange currency side size orderType limitPrice auxPrice localSymbol lastFillPrice req bid ask last bidSize askSize lastSize high
ord ord ord tik tik tik tik tik tik tik tik
idn idn idn idn idn idn idn idn idn idn idn
server
tik
idn
low
471
TWS Users' Guide
Description price Request today's volume size Request last close price Description Account statement control key
Server
Topic
id
reqType
field2
server
tik
idn
volume
server Server server
tik Topic acct
idn id idn
close reqType acctv field2 Account code (for Advisor-managed accounts only)
Request one account value string Account value Account currency Account portfolio control key
server
acct
idn
key
server server server
acct acct acct
idn idn idn
value keyCurrency acctp Account code (for Advisor-managed accounts only)
Account portfolio underlying symbol Account portfolio security type Account portfolio expiry Account portfolio strike price Account portfolio right Account portfolio currency
server
acct
idn
symbol
server
acct
idn
secType
server
acct
idn
expiry
server
acct
idn
strike
server
acct
idn
right
server
acct
idn
currency
472
Application Program Interface
Description Account portfolio position Account portfolio market price Account portfolio market value Account portfolio average cost Account portfolio realized PNL Description Request contract details Market name Trading class Contract identifier Minimum tick Order multiplier Valid order types Valid exchanges Description Execution order id Underlying Security type Expiry
Server server
Topic acct idn
id
reqType position
field2
server
acct
idn
marketPrice
server
acct
idn
marketValue
server
acct
idn
avgCost
server
acct
idn
realizedPNL
Server server
Topic contract idn
id req
reqType
field2 contractDescription
server server server server server server server Server server server server server
contract contract contract contract contract contract contract Topic exec exec exec exec
idn idn idn idn idn idn idn id idn idn idn idn
marketName tradingClass conid minTick multiplier orderTypes validExchanges reqType orderId symbol secType expiry field2
473
TWS Users' Guide
Description Strike Right Order destination Currency Local symbol Execution id Execution time Account number Exchange where executed Side Shares filled in order Execution (average) price Order ID Request execution details Description Request list of Advisormanaged accounts List of Advisormanaged accounts Description
Server server server server server server server server server server
Topic exec exec exec exec exec exec exec exec exec idn idn idn idn idn idn idn idn idn
id
reqType strike right exchange currency localSymbol execId time acctnNumber eExchange
field2
server server server
exec exec exec
idn idn idn
side shares price
server server
exec exec
idn idn
permId Req executionFilter
Server server
Topic FAaccts idn
id Req
reqType
field2
server
FAaccts
idn
Value
Server
Topic
id
reqType
field2
474
Application Program Interface
Description Request market depth
Server server
Topic mktDepth idn
id req
reqType
field2 contractDescripton? num_display_rows Refer to note (1) below.
Market maker
server
mktDepth
idn
mktMaker
rowId_side Refer to note (2) below.
Order price
server
mktDepth
idn
price
rowId_side Refer to note (2) below.
Order size
server
mktDepth
idn
size
rowId_side Refer to note (2) below.
Market data refresh rate 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
refreshRate news
idn sub
millisec 0
Number of milliseconds Refer to note 3 below
server
news
newsID
server
news
newsType
Refer to note 4 below
server
news
msg
server
news
exchange
server
logLevel
Refer to note 5 below.
475
TWS Users' Guide
server = the username ExecutionFilter = clientId_accountCode_date_time_symbol_secType_exchange_side id = idn, where 'n' is some integer number. For orders, 'n' must always increase, even from session to session. orderDescription = side_quantity_symbol_secType_exp_strike_right_exchange_orderType_lmtPrice_auxPrice _timeInForce_ocaGroup_account_open/close_origin_orderRef_transmit_parentId_blockOrder _sweepToFill_displaySize_triggerMethod_ignoreRth_hidden_ orderModification = quantity_orderType_lmtPrice_auxPrice_timeInForce_ocaGroup_account_open/close _origin_orderRef_transmit_parentId_blockOrder_sweepToFill_displaySize_triggerMethod_ignor eRth contractDescription - symbol_secType_exp_strike_right_exchange NOTE: The highlighted attributes in both orderDescription and orderModification (shown above) comprise the Extended Order Attributes. These values optional. When appended to orderDescription or orderModification, the number and order of attributes cannot be changed. For any attribute that is not defined, use the value 'EMPTY." tickerDescription = symbol_secType_exp_strike_right_exchange Note (1) : When requesting market depth you can specify the number of rows to display. If not supplied, the default number of rows is five (5) rows. This parameter can be used to optimize performance, as a low number of display rows requires less CPU overhead. For example. =edemo|mktDepth!id0?req?MSFT_STK_SMART?10 will request 10 rows of market depth orders.
Note (2) : Field 2 of the market depth 'price' and 'size' reqTypes contain additional information to specify the order row and side that the data applies to. Market depth orders are divided into two sides, BID and ASK, and order entries start from the offset 0. E.g. =edemo|mktDepth!id0?price?0_ASK will request the ASK price for the order entry 0 =edemo|mktDepth!id0?size?2_BID will request the BID size for the order entry 2
Note (3): When subscribing to news bulletins, the request should look as follows: =edemo|news!sub?0 where the request type is a zero. To unsubscribe simply clear the subscription cell.
Note (4): The valid news bulletin types are: 1 = Reqular news bulletin
476
Application Program Interface
2 = Exchange no longer available for trading 3 = Exchange available for trading.
Note (5): The valid log levels are: 1 = SYSTEM (least detailed) 2 = ERROR (default, if no level is specified) 3 = WARNING 4 = INFORMATION 5 = DETAIL (most detailed)
Order Attributes
Field side Valid Values
• •
Buy Sell
quantity symbol secType
number value (1, 2, 3, etc) any valid underlying symbol
• • •
STK OPT FUT
exp strike right
use the format: YYYYMM number value (120, 65, etc.)
• •
P C
for put or call
exchange
•
Smart
any valid exchange/ECN symbol
477
TWS Users' Guide
Field orderType
Valid Values
• • • • • • • • • •
LMT LMTCLS MKT MKTCLS PEGMKT STP STPLMT TRAIL VWAP REL
lmtPrice auxPrice timeInForce
number value number value
• • • •
DAY GTC OPG IOC
ocaGroup account open/close origin orderRef transmit
String String (for institutions) O, C (for institutions) 0, 1 (for institutions) String
• •
0 (don't transmit) 1 (transmit)
parentId
String (the order ID used for the parent order, use for bracket and auto trailing stop orders)
478
Application Program Interface
Field blockOrder
Valid Values
• •
0 (not a block order) 1 (this is a block order)
sweepToFill
• •
0 (not a sweep-to-fill order) 1 (this is a sweep-to-fill order)
displaySize
String (publicly disclosed order size)
Extended Order Attributes
Field 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.
ignoreRth
• •
0 (do not ignore regular trading hours when triggering stop orders) 1 (trigger stop orders outside of regular trading hours)
479
TWS Users' Guide
Field hidden
Valid Values For order routed to Island.
• •
0 1 (order not visible when viewing market depth)
clientId
The ID of the client who placed the order. NOTE: The DDE client ID is always "0."
accountCode
The account code for an advisor-managed account. 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. The name of the Account Group.
Good After Time Good 'Till Date
FA Group FA Method
• • • •
EqualQuantity NetLiq AvailableEquity PctChange
FA Percentage FA Profile Short Sales Slot The name of the Allocation Profile.
• •
1 2
Execution Filter Criteria
Field date time Valid Values The date with the format yyyy\mm\dd The time with the format hh.mm.ss
480
Application Program Interface
Field symbol secType
Valid Values The valid underlying symbol.
• • •
STK OPT FUT
exchange
•
Smart
Any valid exchange/ECN symbol.
side
• • • • • • • • • •
LMT LMTCLS MKT MKTCLS PEGMKT STP STPLMT TRAIL VWAP REL
Copyrights and Trademarks
481
TWS Users' Guide
Download API Components and Spreadsheet
Browser-based users need to save the latest DDE dynamic link library file (ddedll.dll) to their Windows® directory to ensure that all DDE functionality is supported. To install the ddedll.dll file to your Windows directory 1. 2. 3. 4. 5. 6. From the homepage, hold your mouse over the Software menu, select TWS API, then select Software. In the appropriate column for your operating system, click Download latest version. Elect to Save the file to your computer and select a directory in which to save the InstallAX.exe program, and click Save. Close any versions of the application and Excel you have running. Double-click the InstallAX.exe program to install the application. Follow the instructions to move through the installation wizard. The dde file will be saved to C:/Jts/Excel/TwsDde.xls.
Note: If a new version of the dll file has been released, you will be notified when you log in that the latest version of the file must be downloaded from the website. To upgrade, doubleclick Upgrade ActiveX control and DDE dll.
Copyrights and Trademarks
482
Application Program Interface
Using the Conditional Orders Tab
Use the Conditional Orders tab to create an order whose submission is contingent on other conditions being met, for example, a trailing stop or an order based on a prior fill. Complete the necessary fields on the Conditional Orders page according to the syntax below. Field Statement Comments 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 only be activated with the "ADD" or "MOD" tags. Action BUY SELL Quantity Order Type Enter the quantity of the order MKT MKTCLS LMT LMTCLS PEGMKT STP STPLMT REL TRAIL VWAP Lmt Price Aux. Price The limit price for Limit and Stop Limit order types. The stop-election price for Stop and Stop Limit order types.
ADD/MOD
All of the fields described above may be variables that depend on other cells, and so any type of conditional order may be created.
483
TWS Users' Guide
Examples
Trailing Stop Order A trailing stop is a stop order which continues to modify its stop price as the market moves away from the current stop price. No modification to the stop price is made when the market moves toward the stop price. To create a 1 point trailing stop sell order for 100 shares, first create an initial stop order, then enter the following in the Conditional Statements cells:
Field Statement ADD/MOD Action Quantity Order Type Lmt Price Aux. Price
Value (Bid price cell) - (current stop price cell)>1 MOD SELL 100 - Remaining STP empty (bid price cell) - 1
"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 Order Type Lmt Price Aux. Price Value Filled cell = 100 ADD SELL 100 LMT 50 empty
484
Application Program Interface
Copyrights and Trademarks
485
TWS Users' Guide
Place 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 buy a calendar spread you would:
• •
Buy 1 OPT JUL03 17.5 CALL (100) Sell 1 OPT AUG03 17.5 CALL (100)
The following example walks you through the steps to place a hypothetical calendar spread order for XYZ on ISE: 1. Use the Contract Details tab to get the contract id for both of the leg definitions.
• •
2.
The conid for XYZ option JUL03 17.5 CALL on ISE is "12345678". The conid for XYZ option AUG03 17.5 CALL on ISE is "12345679".
Build the combo leg definitions request substring. You can use the Combo Legs button on the Tickers or Orders toolbar. The format of the combolegs definition string is:
[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, and each leg
definition consists of
[conid]_[ratio]_[action]_[exchange]_[openClose], so the
resulting combo substring looks as follows:
CMBLGS_2_17496957_1_BUY_EMPTY_0_15910089_1_SELL_EMPTY_0_CM BLGS
3. The combination leg definitions must occur before the extended order attributes. The full place order DDE request string will look as follows: =acctName|ord!id12345?place?BUY_1_XYZ_BAG_ISE_LMT_1_CMBLGS_2_12345678 _1_BUY_EMPTY_0_12345679_1_SELL_EMPTY_0_CMBLGS_DAY_EMPTY_0_O_0_EMP TY _0_EMPTY_0_0_0EMPTY_0_0 If the order legs do not constitute a valid combination, one of the following errors will be returned: 312 = The combo details are invalid. 313 = The combo details for '' are invalid.
486
Application Program Interface
314 = Security type 'BAG' requires combo leg details. 315 = Stock combo legs are restricted to SMART exchange. NOTES: (1) The exchange for the leg definition must match that of the combination order. The exception is for a STK leg definition, which must specify the SMART exchange. (2) The openClose leg definition value is always 'SAME' (i.e.0) for retail accounts. For institutional accounts, the value may be any of the following: (SAME, OPEN, CLOSE). For more information on Combination orders, see the user guide topics Combination Orders and Notes on Combination Orders.
Copyrights and Trademarks
487
TWS Users' Guide
Java
JAVA API
Copyrights and Trademarks
488
Application Program Interface
Java API
To link to TWS using the Java API 1. 2. 3. Import com.ib.client.* into your source code file. Subclass the EWrapper class. This subclass will receive messages from the socket. Override the following functions:
• • • • • • • • • • •
4. 5.
Override tickPrice() and tickSize() functions to handle the market data. Override the orderStatus() function to receive order status. Override the error() function to receive error information. Override the connectionClosed() function to be notified when TWS terminates the connection. Override the updateAccountValue() function to receive current account value information. Override the updateAccountTime() function to receive the last update time of account information. Override the updatePortfolio() function to receive current portfolio information. Override the contractDetails() function to receive contract information. Override the execDetails() function to receive execution report information. Override the updateNewsBulletin() function to receive news bulletins. Override the managedAccounts() function to see a list of the Financial Advisor (FA) managed accounts.
Instantiate the EClientSocket class. This object will be used to send messages to TWS. Call the following functions:
• • • • • • • •
Call the eConnect() function to connect to TWS and eDisconnect() to disconnect from TWS. Call the reqMktData() function to request market data and the cancelMktData() function to stop receiving market data. Call the reqMktDepth() function to request deep book or Level II quotes and the cancelMktDepth() function to stop receiving market data. Call the reqContractDetails() function to request contract details. Call the placeOrder() function to place an order and the cancelOrder() function to cancel an order. Call the reqAccountUpdates() function to start receiving account values, portfolio, and account update time information. Call the reqExecutions() function to receive a list of the day's execution reports. Call the reqOpenOrders() function to receive a list of current open orders for the requesting client and associate TWS open orders with the client. Note: The association only occurs if the requesting client has client id of 0. Call the reqAllOpenOrders() function to receive a list of all the current open orders.
•
489
TWS Users' Guide
•
Call the reqAutoOpenOrders() function to automatically associate a new TWS with the client. Note: The association only occurs if the requesting client has client id of 0. Call the reqNewsBulletin() function to start receiving news bulletins and the cancelNewsBulletins() function to stop receiving news bulletins. Call the setServerLogLevel() function to set the degree of API request/processing logging. Call the reqManagedAccts() function to get the list of Financial Advisor (FA) managed account codes.
• • •
Copyrights and Trademarks
490
Application Program Interface
Java Class EClientSocket Functions
The tables below define the class EWrapper functions you can use when connecting to TWS. The list of functions includes:
• • • • • • • • • • • • • • • • • • • • • • • • •
EClientSocket() eConnect() eDisconnect() reqMktData() cancelMktData() placeOrder() cancelOrder() checkMessages() reqOpenOrders() reqAccountUpdates() reqExecutions() reqContractDetails() reqMktDepth() cancelMktDepth() reqNewsBulletins() cancelNewsBulletins() setLogLevel() reqAllOpenOrders() reqAutoOpenOrders() reqManagedAccts() requestFA() replaceFA() requestHistoricalData() serverVersion() TwsConnectionTime()
Function Parameters
EClientSocket( EWrapper eWrapper)
eWrapper- the reference to an object that was derived from the EWrapper base class
491
TWS Users' Guide
Notes
This is the constructor.
Function Parameters
void eConnect( String host, int port, int clientId)
host - host name or IP address of the machine where TWS is running. Leave blank to connect to the local host. port - must match the port specified in TWS on the Configure>API>Socket Port field. clientId - A number used to identify this client connection. All orders placed/modified from this client will be associated with this client identifier. Note: Each client MUST connect with a unique clientId.
Notes
This function must be called before any other. There is no feedback for a successful connection, but a subsequent attempt to connect will return the message "Already connected."
Function Parameters Notes
void eDisconnect()
Call this method to terminate the connections with TWS. Calling this method does not cancel orders that have already been sent.
Function Parameters
void reqMktData(int id, Contract contract)
id - the ticker id. Must be a unique value. When the market data returns, it will be identified by this tag. This is also used when canceling the market data. contract- this structure contains a description of the contract for which market data is being requested.
Notes
Call this function to request market data. The market data will be returned by the tickPrice and tickSize events.
492
Application Program Interface
Function Parameters Notes
void cancelMktData(int id)
id- the ID that was specified in the call to reqMktData(). After calling this method, market data for the specified id will stop flowing.
Function Parameters
void placeOrder( int id, Contract contract, Order order)See Extended Order Attributes.
id - the order id. You must specify a unique value. When the order status returns, it will be identified by this tag. This tag is also used when canceling the order. contract - this structure contains a description of the contract which is being traded. order - this structure contains the details of the order.Note: Each client MUST connect with a unique clientId.
Notes
Call this method to place an order. The order status will be returned by the orderStatus event.
Function Parameters Notes
void cancelOrder(int id)
id- the order ID that was specified previously in the call to placeOrder() Call this method to cancel an order.
Function Parameters Notes
void checkMessages()
This method should be called frequently (every 1 second) to check for messages received from TWS.
493
TWS Users' Guide
Function Parameters Notes
void reqOpenOrders()
Call this method to request the open orders that were placed from this client. Each open order will be fed back through the openOrder() and orderStatus() functions on the EWrapper. Note: The client with a clientId of "0" will also receive the TWSowned open orders. These orders will be associated with the client and a new orderId will be generated. This association will persist over multiple API and TWS sessions.
Function Parameters Notes
void reqAllOpenOrders()
Call this method to request the open orders that were placed from all clients and also from TWS. Each open order will be fed back through the openOrder() and orderStatus() functions on the EWrapper. Note: No association is made between the returned orders and the requesting client.
Function Parameters
void reqAutoOpenOrders(boolean bAutoBind)
bAutoBind - If set to TRUE, newly created TWS orders will be implicitly associated with the client. If set to FALSE, no association will be made. 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 fed back through the openOrder() and orderStatus() functions on the EWrapper.
Notes
494
Application Program Interface
Function Parameters Notes
void reqManagedAccts()
Call this method to request the list of managed accounts. The list will be returned by the managedAccounts() function on the EWrapper. Note: This request can only be made when connected to a Financial Advisor (FA) account.
Function Parameters
void reqAccountUpdates(boolean subscribe, String acctCode)
subscribe - If set to TRUE, the client will start receiving account and portfolio updates. If set to FALSE, the client will stop receiving this information. acctCode - the account code for which to receive account and portfolio updates.
Notes
Call this function to start getting account values, portfolio, and last update time information.
Function Parameters Notes
reqExecutions(ExecutionFilter filter)
filter - the filter criteria used to determine which execution reports are returned. When this method is called, the execution reports that meet the filter criteria are downloaded to the client via the execDetails() method.
Function Parameters Notes
void reqContractDetails (Contract contract)
Contract- summary description of the contract being looked up. Call this function to download all details for a particular underlying. the contract details will be received via the contractDetails() 495
TWS Users' Guide
function on the EWrapper.
Function
void reqMktDepth(int id, Contract contract, number or rows subscribed to)
id - 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.
Parameters
contract- this structure contains a description of the contract for which market depth data is being requested. number of rows subscribed to - specifies the number of market depth rows to display. Notes Call this method to request market depth for a specific contract. The market depth will be returned by the updateMktDepth() and updateMktDepthL2() events.
Function Parameters Notes
void cancelMktDepth(int id)
id -the ID that was specified in the call to reqMktDepth(). After calling this method, market depth data for the specified id will stop flowing.
Function Parameters
void reqNewsBulletins(boolean AllMsgs)
allMsgs - 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. Call this method to start receiving news bulletins. Each bulletin will be returned by the updateNewsBulletin() event.
Notes
496
Application Program Interface
Function Parameters Notes
void cancelNewsBulletins()
Call this method to stop receiving news bulletins.
Function Parameters
void setLogLevel(int logLevel)
logLevel - 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
Notes
The default level is ERROR. Refer to the API logging page for more details.
Function Parameters
requestFA(long faDataType)
faDataType - specifies the type of Financial Advisor configuration data being requested. Valid values include: 1 = GROUPS 2 = PROFILE 3 =ACCOUNT ALIASES
Notes
Call this method to request FA configuration information from TWS. The data returns in an XML string via a "receiveFA" ActiveX event.
497
TWS Users' Guide
Function Parameters
replaceFA(long faDataType, string XML)
faDataType - specifies the type of Financial Advisor configuration data being requested. Valid values include: 1 = GROUPS 2 = PROFILE 3 =ACCOUNT ALIASES
XML- the XML string containing the new FA configuration information. Notes Call this method to request FA configuration information from TWS. The data returns in an XML string via a "receiveFA" ActiveX event.
Function
void reqHistoricalData (int id, Contract contract, String endDateTime, String durationStr, long barSizeSetting, String whatToShow, int useRTH, int formatDate)
Parameters
id - the ticker id. Must be a unique value. When the market data returns, it will be identified by this tag. This is also used when canceling the market data. contract- this structure contains a description of the contract for which market data is being requested. endDataTime - defines a query end date and time at any point during the past 6 mos. Valid values include any date/time within the past six months in the format: yyyymmdd HH:mm:ss ttt where "ttt" is the optional time zone. durationStr - set the query duration up to one week, using a time unit of seconds, days or weeks. Valid values include any integer followed by a space and then S(seconds), D (days) or W (week). If no unit is specified, seconds is used. barSizeSetting - specifies the size of the bars that will be returned (within IB/TWS limits). Valid values include:
Bar Size
Parametric Value
498
Application Program Interface
1 sec
1 2 3 4 5
6 7 8 9 10 11
5 secs 15 secs 30 secs 1 min.
2 mins 5 mins. 15 mins 30 mins 1 hour 1 day
whatToShow - determines the nature of data being extracted. Valid values include:
• • • • •
TRADES MIDPOINT BID ASK BID/ASK
useRTH - determines whether to return all data available during the requested time span, or only data that falls within regular trading hours. Valid values include:
• •
0 - all data is returned even where the market in question was outside of its regular trading hours. 1 - only data within the regular trading hours is returned, even if the requested time span falls partially or completely outside of the RTH.
formatDate - determines the date format applied to returned bars. Valid values include:
• •
1 - dates applying to bars returned in the format: yyyymmdd{space}{space}hh:mm:dd 2 - dates are returned as a long integer specifying the number of seconds since 1/1/1970 GMT.
Notes
499
TWS Users' Guide
Function Parameters Notes
serverVersion()
Function Parameters Notes
TwsconnectionTime()
Copyrights and Trademarks
500
Application Program Interface
Java EWrapper Functions
The tables below define the class EWrapper functions you can use when connecting to TWS. The list of functions includes:
• • • • • • • • • • • • • • • • •
tickPrice() tickSize() orderStatus() error() connectionClosed() managedAccounts() openOrder() updateAccountValue() updatePortfolio() updateAccountTime() nextValidId() contractDetails() execDetails() updateMktDepth() updateMktDepthL2() updateNewsBulletin() receiveFA()
Function Parameters
void tickPrice(int id, TickType field, double price, int canAutoExecute)
id - the ticker ID that was specified previously in the call to reqMktData() tickType - specifies the type of price. Possible values are:
• • • • • •
1 = bid 2 = ask 4 = last 6 = high 7 = low 9 = close
501
TWS Users' Guide
price - could be the bid, ask, last price, daily high, daily low or last day close, depending on tickType value. canAutoExecute - specifies whether the price tick is available for automatic execution. Possible values are:
• •
Notes
0 = not eligible for automatic execution 1 = eligible for automatic execution
This function is called when the market data changes. Prices are updated immediately with no delay.
Function Parameters
virtual void tickSize(int id, TickType field, int size)
id - the ticker ID that was specified previously in the call to reqMktData() tickType - specifies the type of size. Possible values are:
• • • •
0 = bid size 3 = ask size 5 = last size 8 = volume
size - could be the bid size, ask size, last size or trading volume, depending on the tickType value. Notes This function is called when the market data changes. Sizes are updated immediately with no delay.
Function
void orderStatus(int id, String status, int filled, int remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId)
id - the order ID that was specified previously in the call to placeOrder() status - the order status. Possible values include:
Parameters
•
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,
502
Application Program Interface
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 (and the status remains DARK BLUE) until the election criteria are met. At that time the order is transmitted to the order destination as specified (and the order status color will change). 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 - the order has been completely filled.
•
filled - specifies the number of shares that have been executed. remaining - specifies the number of shares still outstanding. avgFillPrice - 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. permId - the TWS id used to identify orders. Remains the same over TWS sessions. parentId - The order ID of the parent order, used for bracket and auto trailing stop orders. lastFilledPrice 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. clientId - 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. Notes 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.
Function Parameters
void error(int id, int errorCode, String errorString)
id- this is the orderId or tickerId of the request that generated the error errorCode - error codes are documented in the Error Codes topic. errorString - this is the textual description of the error, also documented in the Error Codes topic.
Notes
This event is called when there is an error with the communication or when TWS wants to send a message to the client.
503
TWS Users' Guide
Function Parameters Notes
void connectionClosed()
This function is called when TWS closes the sockets connection, or when TWS is shut down.
Function Parameters Notes
void managedAccounts(String accountsList)
accountsList - the comma delimited list of FA managed accounts. This function is called when a successful connection is made to a Financial Advisor account. It is also called when the reqManagedAccts() method is invoked.
Function Parameters
void openOrder(int orderId, Contract contract, Order order)See Extended Order Attributes.
orderID - The order ID assigned by TWS. Use to cancel or update the order. contract - Describe the contract for the open order. order - Gives the details of the open order.
Notes
This function is called to feed in open orders.
Function Parameters
void updateAccountValue(String key, String value, String currency, String accountName)
key- A string that indicates one type of account value. Below is a set of keys sent by TWS.
• • • • • •
CashBalance - Account cash balance Currency - Currency string DayTradesRemaining - Number of day trades left EquityWithLoanValue - Equity with Loan Value InitMarginReq - Current initial margin requirement LongOptionValue - Long option value
504
Application Program Interface
• • • • • • •
MaintMarginReq - Current maintenance margin NetLiquidation - Net liquidation value OptionMarketValue - Option market value ShortOptionValue - Short option value StockMarketValue - Stock market value UnalteredInitMarginReq - Overnight initial margin requirement UnalteredMaintMarginReq - Overnight maintenance margin requirement
value- The value associated with the key. currency- Defines the currency type, in case the value is a currency type. account- states the account the message applies to. Useful for Financial Advisor sub-account messages. Notes This function is called only when ReqAccountUpdates on EClientSocket object has been called.
Event
void updatePortfolio(Contract contract, int position, double marketPrice, double marketValue, double averageCost, double unrealizedPNL, double realizedPNL, String accountName)
contract - This structure contains a description of the contract which is being traded. The exchange field in a contract is not set for portfolio update. position - This integer indicates the position on the contract. If the position is 0, it means the position has just cleared. marketPrice - Unit price of the instrument. marketValue - The total market value of the instrument. averageCost- The average cost per share is calculated by dividing your cost (execution price + commission) by the quantity of your position. unrealizedPNL - The difference between the current market value of your open positions and the average cost, or Value - Average Cost. realizedPNL- Shows your profit on closed positions, which is the difference between your entry execution cost (execution price + commissions to open the position) and exit execution cost ((execution price + commissions to close the position) accountName - the name of the account the message applies to. Useful for Financial Advisor sub-account messages.
Parameters
Notes
This function is called only when reqAccountUpdates on EClientSocket object has been called.
505
TWS Users' Guide
Function Parameters Notes
void updateAccountTime(String timeStamp)
timeStamp - This indicates the last update time of the account information This function is called only when reqAccountUpdates on EClientSocket object has been called.
Function Parameters
void nextValidId(long id)
id - The next available order ID received from TWS upon connection. Increment all successive orders by one based on this ID. This function is called after a successful connection to TWS.
Notes
Function Parameters Notes
void contractDetails(ContractDetails contractDetails)
contractDetails- This structure contains a full description of the contract being looked up. This function is called only when reqContractDetails method on the EClientSocket object has been called.
Function Parameters
void execDetails( int id, Contract contract, Execution execution, int liquidation)
id - the order ID that was specified previously in the call to placeOrder(). contract - This structure contains a full description of the contract that was executed. NOTE: Refer to the Java Java SocketClient Properties page for more information. execution - This structure contains addition order execution details. NOTE: Refer to the Java SocketClient Properties page for more information. liquidation - specifies whether an execution is the result of a
506
Application Program Interface
liquidation. Possible values are:
• •
Notes
0 = execution is not the result of liquidation 1 = execution is the result of a liquidation
This event is fired when the reqExecutions() methods is invoked, or when an order is filled.
Event Parameters
void updateMktDepth(int id, int position, int operation, int side, double price, int size)
id - the ticker ID that was specified previously in the call to reqMktDepth() position - specifies the row id of this market depth entry. operation - identifies the how this order should be applied to the market depth. 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. Valid values are:
• •
0 = ask 1 = bid
price - the order price. size - the order size. Notes This function is called when the market depth changes.
Event
void updateMktDepthL2(int id, int position, String marketMaker, int operation, int side, double price, int size)
id - the ticker ID that was specified previously in the call to reqMktDepth() position - specifies the row id of this market depth entry. marketMaker - specifies the exchange hosting this order. operation - identifies the how this order should be applied to the 507
Parameters
TWS Users' Guide
market depth. 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. Valid values are:
• •
0 = ask 1 = bid
price - the order price. size - the order size. Notes This function is called when the Level II market depth changes.
Function Parameters
virtual void updateNewsBulletin(int msgId, int msgType, String message, String origExchange
msgId - the bulletin ID, incrementing for each new bulletin. msgType - specifies the type of bulletin. Valid values include: 1 = Reqular news bulletin 2 = Exchange no longer available for trading 3 = Exchange is available for trading message - the bulletin's message text. origExchange - the exchange from which this message originated.
Notes
This event is triggered for each new bulletin if the client has subscribed (i.e. by calling the reqNewsBulletins() method.
Function Parameters
receiveFA(long faDataType, string XML)
faDataType - specifies the type of Financial Advisor configuration data being received from TWS. Valid values include: 1 = GROUPS
508
Application Program Interface
2 = PROFILE 3 =ACCOUNT ALIASES XML- the XML string containing the previously requested FA configuration information. Notes This event receives previously requested FA configuration information from TWS.
Copyrights and Trademarks
509
TWS Users' Guide
Java SocketClient Properties
The tables below define properties for the Execution, Contract and Order structures.
Class Execution properties
Property String m_execId String m_time String m_acctNumber String m_exchange Description Unique order execution id. The order execution time. The customer account number. Exchange that executed the order. Specifies if the transaction was a sale or a purchase. Valid values are:
String m_side
• •
BOT SLD
int m_shares Double m_price int m_permId int m_clientId
The number of shares filled. The order execution price. The TWS id used to identify orders, remains the same over TWS sessions. The id of the client that placed the order. Note: TWS orders have a fixed client id of "0." The order id.
int m_orderId Note: TWS orders have a fixed order id of "0."
Class ExecutionFilter properties
Property int m_clientId Description Filter the results of the reqExecutions() method based on the clientId. Filter the results of the reqExecutions() method based on an account code. Note: this is only relevant for Financial Advisor (FA) accounts. Filter the results of the reqExecutions() method based on xecution reports received after the specified time. The format for timeFilter is "yyyymmdd-hh:mm:ss" String m_symbol Filter the results of the reqExecutions() method based on the order symbol. Filter the results of the reqExecutions() method based on the order security type. Note: Refer to the Contract struct for the list of valid security types. Filter the results of the reqExecutions() method based on theorder exchange.
String m_acctCode
String m_time
String m_secType
String m_exchange 510
Application Program Interface
Property
Description Filter the results of the reqExecutions() method based on the order action. Note: Refer to the Order struct for the list of valid order actions.
String m_side
Class Contract properties
Property String m_symbol Description This is the symbol of the underlying asset. This is the security type. Valid values are
• •
String m_secType
STK OPT FUT IND FOP CASH BAG
• • • • •
String m_expiry double m_strike String m_right String m_multiplier String m_exchange
String m_currency
String m_localSymbol Vector m_comboLegs
The expiration date. Use the format YYYYMM. The strike price. Specifies a Put or Call. Valid values are: P, PUT, C, CALL. Allows you to specify a future or option contract multiplier. This is only necessary when multiple possibilities exist. The order destination, such as Smart. Specifies the currency. Ambiguities may require that this field be specified, for example, when SMART is the exchange and IBM is being requested (IBM can trade in GBP or USD). Given the existence of this kind of ambiguity, it is a good idea to always specify the currency. This is the local exchange symbol of the underlying asset. Dynamic memory structure used to store the leg definitions for this contract.
Class ComboLeg properties
Property int m_conId String m_action int m_ratio Description The unique contract identifier specifying the security. The side (buy or sell) for the leg you are constructing. Select the relative number of contracts for the leg you are constructing. To help determine the ratio for a specific combination order, refer to the Interactive Analytics section of the User's Guide. The exchange to which the complete combination order will be routed. 511
String m_exchange
TWS Users' Guide
Property
Description openClose - Specifies whether the order is an open or close order. Valid values are:
•
int m_openClose
Same - (0) same as the parent security. This is the only option for retail customers. Open - (1) this option is only valid for institutional customers. Close - (2) this option is only valid for institutional customers.
• •
Class ContractDetails
Property Contract m_summary String m_marketName String m_tradingClass int m_conId double m_minTick String m_multiplier String m_orderTypes String m_validExchanges Description A contract summary. The market name for this contract. The trading class name for this contract. The unique contract identifier. The minimum price tick. The order size multiplier. The list of valid order types for this contract. The list of exchanges this contract is traded on.
Class Order properties
Property int orderId int clientId String m_action long m_quantity Description The id for this order. The id of the client that placed this order. Identifies the side. Valid values are: BUY, SELL, SSHORT The order quantity. The order type. identifies the order type. Valid values are:
• • •
String m_orderType
MKT MKTCLS LMT LMTCLS PEGMKT STP STPLMT TRAIL REL VWAP
• • • • • • •
double m_lmtPrice 512
This is the LIMIT price, used for limit, stop-limit
Application Program Interface
Property
double m_auxPrice String m_sharesAllocation String m_tif String m_ocaGroup String m_account String m_openClose int m_origin String m_orderRef bool m_transmit int m_parentId boolean m_blockOrder boolean m_sweepToFill int m_displaySize
Description 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. Deprecated. Upgrade to new FA functionality must be done. The time in force. Valid values are: DAY, GTC, IOC, GTD. Identifies an OCA (one cancels all) group. The account. For institutional customers only. Specifies whether the order is an open or close order. For institutional customers only. Valid values are O, C. The order origin. For institutional customers only. Valid values are 0 = customer, 1 = firm The order reference. For institutional customers only. Specifies whether the order will be transmitted by TWS. If set to false, the order will be created at TWS but will not be sent. The order ID of the parent order, used for bracket and auto trailing stop orders. If set to true, specifies that the order is an ISE Block order. If set to true, specifies that the order is a Sweepto-Fill order. The publicly disclosed order size, used when placing Iceberg orders. Specifies how Simulated Stop, Stop-Limit and Trailing Stop orders are triggered. Valid values are: 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. If set to true, allows triggering of orders outside of regular trading hours. 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. The amount off the limit price allowed for discretionary orders. The trade's "Good After Time," format
int m_triggerMethod
boolean m_ignoreRth boolean m_hidden double m_discretionaryAmt String m_goodAfterTime
513
TWS Users' Guide
Property
Description "YYYYMMDD hh:mm:ss (optional time zone)" Use an empty String if not applicable. You must enter a tif value of GTD. The trade's "Good Till Date," format "YYYYMMDD hh:mm:ss (optional time zone)" Use an empty String if not applicable. The Financial Advisor group the trade will be allocated to -- use an empty String if not applicable. The Financial Advisor allocation profile the trade will be allocated to -- use an empty String if not applicable. The Financial Advisor allocation method the trade will be allocated with -- use an empty String if not applicable. The Financial Advisor percentage concerning the trade's allocation -- use an empty String if not applicable. Identifies the asset's primary exchange. Values are 1 or 2. Use only when shortSaleSlot value = 2. Cancel on Fill with Block = 1 Reduce on Fill with Block = 2 Reduce on Fill without Block = 3 Regular trading hours only. yes=1, no=0 Individual = 'I' Agency = 'A', AgentOtherMember = 'W' IndividualPTIA = 'J'
String m_goodTillDate
String m_faGroup
String m_faProfile
String m_faMethod
String m_faPercentage String m_primaryExchange int m_shortSaleSlot String m_designatedLocation int m_ocaType
string m_rule80A
AgencyPTIA = 'U' AgentOtherMemberPTIA = 'M' IndividualPT = 'K' AgencyPT = 'Y' AgentOtherMemberPT = 'N'
string m_settlingFirm boolean m_allOrNone int m_minQty double m_percentOffset boolean m_eTradeOnly
Institutional only. yes=1, no=0 Identifies a minimum quantity order type. The percent offset amount for relative orders. Trade with electronic quotes. yes = 1, no = 0 Trade with firm quotes.
boolean m_firmQuoteOnly double m_nbboPriceCap yes = 1, no = 0 The maximum Smart order distance from the NBBO.
514
Application Program Interface
Property
Description match = 1 improvement = 2 transparent = 3 For BOX exchange only. The starting price. Valid on BOX orders only. The stock reference price. Valid on BOX orders only. The stock delta. Valid on BOX orders only. The lower range of the acceptable stock range. Valid on BOX orders only. The upper range of the acceptable stock range. Valid on BOX orders only.
int m_auctionStrategy
double m_startingPrice double m_stockRefPrice double m_delta double m_stockRangeLower double m_stockRangeUpper
Copyrights and Trademarks
515
TWS Users' Guide
Use the TestJavaClient Sample Program
You can access TWS through a Java application using the socketclient component. Before you can connect to TWS, you must:
• • •
Install the socketclient component and sample programs Configure TWS to support the API components Have Java 2 SDK v1.3.0 or higher installed on your PC.
The TestJavaClient program is a sample program that shows you how to use sockets to connect to TWS from a Java application. To use the TestJavaClient program
•
Compile the sample java files:
• •
javac TestJavaClient/Main.java
Run the program
•
java TestJavaClient/Main
Copyrights and Trademarks
516
Application Program Interface
Place 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 buy a calendar spread you would:
• •
Buy 1 OPT JUL03 17.5 CALL (100) Sell 1 OPT AUG03 17.5 CALL (100)
The following example walks you through the hypothetical steps to place a calendar spread order for XYZ on ISE: 1. Using the reqContractDetails() method, get the contract id for both leg definitions.
• •
2.
The conid for XYZ option JUL03 17.5 CALL on ISE is "12345678". The conid for XYZ option AUG03 17.5 CALL on ISE is "12345679".
Create and add the first leg.
•
Create a new ComboLeg object containing the following data:
conid=12345678, ratio=1, action="BUY", exchange="ISE", openClose=0
3. Create and add the second leg.
•
Create a new ComboLeg object containing the following data:
conid=12345679, ratio=1, action="SELL", exchange="ISE", openClose=0
4. Add each leg to the list of definitions maintained by the contract. Refer to the C++ socket sample to see how this is done. 5. Set and send the combination order details.
•
Call the 'placeOrder' method with the following contract details: symbol = "XYZ secType = "BAG" exchange = "ISE"
NOTE: For combination orders, the secType must always be set to 'BAG'. If the order legs do not constitute a valid combination, one of the following errors will be returned: 312 = The combo details are invalid. 313 = The combo details for '' are invalid. 314 = Security type 'BAG' requires combo leg details.
517
TWS Users' Guide
315 = Stock combo legs are restricted to SMART exchange. NOTES: (1) The exchange for the leg definition must match that of the combination order. The exception is for a STK leg definition, which must specify the SMART exchange. (2) The openClose leg definition value is always 'SAME' (i.e.0) for retail accounts. For institutional accounts, the value may be any of the following: (SAME, OPEN, CLOSE). For more information on Combination orders, see the user guide topics Combination Orders and Notes on Combination Orders.
Copyrights and Trademarks
518
Application Program Interface
Advisors
ADVISOR API
Copyrights and Trademarks
519
TWS Users' Guide
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. API FA functionality became significantly more powerful in TWS release 821 and higher, in that the now deprecated "allocation string" method was replaced by the much more powerful Financial Advisor order allocation methods. Prior to those new methods being used, TWS had to be configured to understand the desired FA order groups, profiles, and account aliases. This can be done manually in TWS, or via the API, or via both.
Excel DDE Support
Starting with TWS release 824, DDE orders now have six new Extended Attributes: Good After Time, Good Till Date, FA Group, FA Method, FA Percentage, and FA Profile. These can be left empty if they do not apply to an order. TWS Financial Advisor account configuration should be done manually for DDE access.
Support by Other API Technologies
For all ActiveX, Java, or C++ based API technologies, TWS Financial Advisor account configuration is done via two new methods and one new event. The methods are called replaceFA, and requestFA. The event is called receiveFA. These methods and that event pertain to the following three parts of TWS FA account configuration: creating groups, profiles, and account aliases.
• •
requestFA(int faDataType) is a method that is called by an API application to request one of those types of FA configuration data. receiveFA(int faDataType, string XML) receives the requested data from TWS, via an event that TWS sends that contains the data requested. The event includes an XML string containing the requested information. replaceFA(int faDataType, string XML) can be called from the API if the API application wishes to replace the previous FA configuration information with a new XML string.
•
In accordance with the existence of this new functionality, all placeOrder methods, whether ActiveX, Java, or C++ based, have four new parameters pertaining to Financial Advisor order placement: faGroup, faMethod, faPercentage, and faProfile. When one or more of these new values is not relevant to an order, simply pass in an empty string.
Improved Financial Advisor Execution Reporting
When using TWS version 823 or higher, the execution messages resulting from a new FA order will report both the initial execution of the order, as well as its being allocated to its various subaccounts. 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, and who wants them allocated with Equal Quantity to each. The following seven execution messages will occur: -- FA Account: Order filled on NYSE to BUY 100 IBM
520
Application Program Interface
-- FA Account: allocation of 34 shares out of FA account and into sub account 1. Message says "BUY -34 IBM." The negative quantity reflects the fact that the execution being reported is reducing the purchase. -- SUB1 Account: BUY 34 IBM. -- FA Account: allocation of 33 shares out of FA account and into sub account 2. Message says "BUY -33 IBM." -- SUB2 Account: BUY 33 IBM. -- FA Account: allocation of 33 shares out of FA account and into sub account 3. Message says "BUY -33 IBM." -- SUB3 Account: BUY 33 IBM."
Copyrights and Trademarks
521
TWS Menus Reference
MENU REFERENCE
Copyrights and Trademarks
523
TWS Users' Guide
File Menu
Use the File menu commands to export reports to your PC, save settings and create a basket file. The File menu commands are described in the table below.
Menu Command
Description Exports the day's execution reports as a text file to the directory on your PC that you set.
Export Today's Reports
Export Previous Day's Reports
Exports the execution report (as a text file) for the selected day to a directory on your PC that you set.
Export Page in Excel Format
Exports the active trading page as a text file to a selected file directory. You can open this text file within Excel and copy the data to a spreadsheet.
Save Settings
Saves any changes you made to your trading screen layout, defaults, and menu selections.
Restore Settings
Opens the Restore Settings box, where you can choose to restore a saved setting from a previous day.
Manage Workspaces
Opens the Manage Workspaces dialog box.
Save Orders As Basket
Saves all orders on the active Trading page in a basket file. Use a Basket to trade a saved set of orders with one action.
Exit
Closes Trader Workstation and saves your settings.
524
TWS Menus Reference
Copyrights and Trademarks
525
TWS Users' Guide
Page Menu
Use the Page menu to create, edit and delete trading pages, and to modify the page layout. Menu commands are described in the table below.
Menu Command New Create Portfolio Page
Description Creates a new trading page. Creates a new trading page called Portfolio complete with market data lines for all assets in which you hold a position. These are displayed in the Portfolio section of the Account window. Creates a new trading page called Scanner where you can view the top 20 contracts based on many different parameters such as most active, top gainers, top losers, etc. Let's you rename a page and change page settings, including the assigned layout, whether the page is enabled for Rapid Stock Entry, and whether or not to show an order for an underlying on each page on which the symbol appears. Opens the Page Layout editor to the Default page layout. Use this window to determine which columns are visible on your trading screen, and the text, background and other characteristics of rows and columns. Alphabetically sorts market data lines on the open trading page. Removes all market data lines from the Portfolio page for contracts in which you no longer hold a position. This ensures that the Portfolio page only includes assets in which you hold a position. Let's you delete the selected page. Gives a warning message before deleting. Use the Rapid Order Entry submenus to Show or Hide the Rapid Order Entry panel, and to define the available instrument types. Use the Configure submenu to open
Create Market Scanner
Settings
Layout
Sort Tickers Clear Zero Position
Delete Rapid Order Entry
526
TWS Menus Reference
Menu Command
Description the Rapid Order Entry configuration page in the Global Configuration box.
Detach Page
Undocks the active trading page and recreates the page as a separate window on your desktop. To re-dock, on the Page menu of the detached page select Attach Page. Detaches all trading pages from the toolbar into separate windows. Reattaches the trading page to the trading toolbar.
Detach All Pages Attach Page
Copyrights and Trademarks
527
TWS Users' Guide
Ticker Menu
Use the Ticker menu to add a market data line and invoke actions related to the selected market data line. Menu commands are described in the table below.
Menu Command Add Symbol Edit
Description Opens the Request Ticker box where you enter contract information. This creates a new market data line. Let's you cut, copy or paste a market data line between pages. If you select any field in the line, the entire line is cut/copied. If you try to paste a duplicate market data line on the same page, the Paste command is grayed out. Opens the Account Management login screen. From here you can perform all of your account management tasks, such as subscribing to market data services, transferring funds, and viewing account statements. You must subscribe to market data services to receive market data and view Level II, NYSE Deep Book quotes and Market Depth.
Subscribe to Market Data
RFQ - Request for Quote Lookup Symbol Set Alarm
Use to request market data for instruments not showing data. Opens the Contracts and Securities search page on the IB website. Opens the Alarm Settings box where you can set a price movement or volume change activated alarm for the selected asset. To ensure you don't lose alarms when you log out of TWS, select Preserve the alarm between sessions when you set the alarm. Opens a Book Trader window for the selected asset. Opens a Option Trader window for the selected asset. If you have futures contracts that will be expiring, use this feature to roll them over prior to expiration.
Book Trader Option Trader Future Rollover
528
TWS Menus Reference
Menu Command Show Market Depth
Description Displays the market depth window for a selected asset. Market depth shows the alternative bids and offers
away from the inside quote to allow you to better gauge market liquidity.
Show Level II Quotes Historical Charts Show Real-Time Charts News and Research Show Positions Show Description Show Details Insert Row Level II quotes for Nasdaq securities are available by subscription. To subscribe, click Subscribe on the Ticker menu. Create a chart for the selected underlying. Opens the New Chart window where you define parameters to create a custom chart. Industry-related news and commentary based on the selected underlying. Shows current positions for the selected asset. Displays the Ticker Description box which contains information about the selected underlying. Shows details for the selected underlying. Inserts a blank line above the selected line.
Copyrights and Trademarks
529
TWS Users' Guide
Order Menu
Use the Order menu to create, transmit, cancel and restore orders. The menu commands are described in the table below.
Menu Command Buy Sell Scale Orders Close Position Basket Auto Stop Auto Trailing Stop Trigger Method
Description Creates a Buy order on the selected market data line, or opens the Order Ticket window if no asset is selected. Creates a Sell order on the selected market data line, or opens the Order Ticket window if no asset is selected. Create orders that specify the total amount to be bought/sold at incrementally decreasing/increasing price intervals. Creates an opposite-side order for a selected asset in which you hold a position. You must manually transmit the order. Import a basket file to submit. Use a Basket order to trade a saved set of orders with one action. Attach a stop order to the limit order. Attach a trailing stop to a limit order. Select a stop trigger method for simulated stop, simulated stop limit, and trailing stop order types. This setting applies only to the currently selected order. To change the trigger method default for all orders, use the Configure menu. To allow stop-limit and eligible simulated stop orders to trigger after hours, select the "Allow triggering outside of regular trading hours" checkbox.
Bracket Orders
Creates a pair of orders that bracket your original order. Bracket orders are designed to limit your loss and lock in a profit by "bracketing" an order with two opposite-side orders. A BUY order is bracketed by a high-side sell limit order and a low-side sell stop order. A SELL order is bracketed by a highside buy stop order and a low side buy limit order.
Update Limit Prices
Opens the Update Limit Price dialog box where you define parameters to automatically update limit prices for the
530
TWS Menus Reference
Menu Command
Description selected order(s) or all orders on a page.
Cancel
For non-working orders, cancels the order and deletes it from the order management line. For working orders, sends a cancellation request to the order destination. A working order is not confirmed cancelled until the Status field turns red.
Transmit Transmit Page
Transmits the selected order to the order destination. Transmits all orders on the active trading page to their order destinations. The value in parenthesis shows the value of all orders on the page. Used to undo changes to a working order on an order management line BEFORE YOU RE-TRANSMIT THE ORDER. Shows your margin requirements as a "what if" scenario for the selected non-submitted order. Cancels a transmitted order at the exchange, but leaves it on the trading page for later re-submission. Cancels all transmitted orders on the page, but leaves them on the trading page for later re-submission. Sends a cancellation request for each non-transmitted and working order on the active trading page. Working orders are not confirmed cancelled until the Status field turns red.
Restore Check Margin Deactivate Deactivate Page Cancel Page
Cancel All
Sends a cancellation request for every non-transmitted and working order on all of your trading pages. Working orders are not confirmed cancelled until the Status field turns red.
Remove Filled Orders Close All Positions
If you de-select Auto-Remove Orders on the Settings menu, use this command to remove all executed and canceled orders from your trading and Pending pages. Creates and transmits an opposite side limit order at the market price for each open position. If no market data is available, creates an opposite side market order, and you must transmit it manually. Enter a percentage of open positions you want to close. Creates and transmits an opposite side limit order at the market price for this percentage of open positions. If no market data is available, creates an opposite side market order, and you must transmit it manually. Creates and transmits an opposite side limit order at the market price for each open position on the active trading page. If no market data is available, creates an opposite side market order, and you must transmit it manually. Selects all orders on the page.
Close Portion of Positions
Close Positions on Page
Select All
531
TWS Users' Guide
Menu Command Ticket
Description Opens the Order Ticket window which you use to create and transmit an order. If you have selected a market data line, the Order Ticket window displays the selected asset and order destination.
Copyrights and Trademarks
532
TWS Menus Reference
Analytics Menu
Interactive Analytics is IB's risk assessment suite.
Menu Command
Description
Portfolio Analytics
Opens the Portfolio Analytics window.
Option Analytics
Opens the Option Analytics window.
Option Modeler
Opens the Option Modeler window.
Copyrights and Trademarks
533
TWS Users' Guide
View Menu
Use the View menu to see reports, pending orders, and bulletins and status. The menu commands are described in the table below.
Menu Command Executions Bulletins Account Statements Option Exercise
Description View execution reports for the current day. View bulletins and system status. View account information including positions and account balance. View your latest account statement. Use the Option Exercise window to exercise an option position prior to expiration date, or on expiration date if the option is less than $.25 in the money at expiration. Or, allow option to lapse without exercising for options that are in the money by more than $.25. Opens the Alerts window where you can modify or create time, price or margin-based alerts. Opens the Rebalance window where you can trade by redistributing percentages of positions in your portfolio that make up your current (signed) net liquidation value. View a log of your daily trading activity saved in an html file. Each week's audit trail reports overwrite those from the previous week. If grayed out, you are already in Underlying entry mode, which mean you enter a ticker symbol and choose the instrument type and exchange in the normal manner. Symbol entry mode is for advanced options traders. This mode requires that you enter the contract definition by the class or symbol defined by the exchange on which it's
Alerts Rebalance
Audit Trail (Expanded or Condensed views) Underlying Mode
Symbol Mode
534
TWS Menus Reference
Menu Command trading. Market Data and Historical Data Connections
Description
Displays the purpose and status of your market data connections.
Copyrights and Trademarks
535
TWS Users' Guide
Configure Menu
Use the Configure menu to modify defaults, set display options and show or hide features. The menu commands are described in the table below.
Menu Command Global Configuration
Description Opens the Global Configuration box where you define configuration settings for all aspects of the workstation. Opens the Feature Selector, which lets you hide or display specific features based on your needs.
Feature Selector
Copyrights and Trademarks
536
TWS Menus Reference
Help Menu
The Help menu provides links to online customer service information including the User's Guide. Menu commands are described in the table below.
Menu Command Online Help Contract Lookup Customer Service IB Home Page Quick Start Guide Release Notes System Status Training Tutorial Users' Guide About Trader Workstation
Description Click to load the javahelp version of the TWS user's guide. Opens the Contract and Securities Search page on the IB website. Brings you to the IB Customer Service help page on the IB website. Opens the Interactive Brokers' home page. Opens the TWS Quickstart Reference guide, which Opens the index to the TWS production release notes. View the IB System Status and System Availability. Opens the TWS Basics tutorial. Opens the TWS Users' Guide. Shows the current TWS release number and Java version.
Copyrights and Trademarks
537
TWS Users' Guide
Right-click on a Market Data Line
To see a right-click menu, select a market data line and then click the right mouse button. Select an item from a right-click menu using your mouse. The right-click menu on a Market Data line contains the following menu commands: Menu Command Trade Description
• • • • • •
Buy - create a Buy order Sell - create a Sell order Order Ticket - opens the Order Ticket from which you define order parameters. Submit RFQ - request market data for instruments that are not showing data. Modify RFQ - Invokes a dialog box in which you can change the price/quantity of the last quote request made. Cancel RFQ - Cancels the last quote request made.
Request for Quote
Insert Ticker Insert Row Delete Row Clear Row Edit Tools
Adds a new market data line with the underlying symbol you request. Inserts blank row above the selected row. Deletes the selected row and its data. Deletes data from row and leaves a blank row. Elect to cut or copy the selected market data line.
• • •
Book Trader - Opens the Book Trader window. Option Trader - Opens the Option Trader window. Market Depth - Displays the market depth window for the selected security. Note that for selected Nasdaq and NYSE-listed securities, Level II and NYSE Open Book quotes are available in place of market depth. Set Alarm - Opens the Alarm Settings box where you can set a price movement-activated alarm for the selected asset. Real-time Charts - Opens the New Chart window where you define parameters to create a custom chart. Historical Charts - Create a chart for the selected underlying. Earnings Estimates - See earnings estimates including per share book value, prior year's earnings estimate and estimated earnings growth rate for the selected underlying.
•
Analysis
• • •
538
TWS Menus Reference
Menu Command
Description
• • • • • •
Contract Info
Analyst Information - Shows analyst recommendations for the selected contract. Company Profile - Profiles the selected underlying, including per share data, company at a glance, valuation ratios and profitability. Financials - Income statement and other financials for the selected underlying. Insider Trading - Shows the last ten insider trading actions for the selected underlying. News & Research - Industry-related news and commentary based on the selected underlying. SEC Filings - SEC filings associated with the selected underlying. Description - Displays the Ticker Description box which contains information about the selected underlying. Details - Shows details for the selected underlying.
• •
Copyrights and Trademarks
539
TWS Users' Guide
Right-click on an Order Management Line
To see a right-click menu, select an order management line and then click the right mouse button. Select an item from a right-click menu using your mouse. The right-click menu on an Order Management line contains the following menu commands: Menu Command Transmit Cancel Description Transmits the selected order to the order destination. For non-working orders, cancels the order and deletes it from the order management line. For working orders, sends a cancellation request to the order destination. A working order is not confirmed cancelled until the Status field turns red. Deactivate Check Margin Restore Cancels a transmitted order at the exchange, but leaves it on the trading page for later re-submission. Opens the What-if Scenario box which describes your margin requirements for the order. Lets you undo changes to a working order on an order management line BEFORE YOU RE-TRANSMIT THE ORDER.
Attach
• • •
Auto Stop - Attach a stop order to the limit order. Auto Trailing Stop - Attach a trailing stop order to the limit order. Bracket Orders - Attach a set of opposite-side orders that "bracket" the current order in an attempt to limit loss. Duplicate - Creates another order management line with the same order parameters directly below the selected line. Scale Orders - Create a series of orders at incrementally decreasing/increasing price intervals. Order Ticket - Opens the Order Ticket window where you can modify parameters before you transmit the order. Trigger Method - Select a stop trigger method for simulated stop, simulated stop limit, and trailing stop order types. This option lets you reset the trigger method for a single order. To change the trigger method for all orders, on the Configure menu select Order. then select Stop Trigger Method. To allow stop-limit and eligible simulated stop orders to trigger after hours, select the "Allow
Create
• •
Modify
• •
540
TWS Menus Reference
Menu Command
Description triggering outside of regular trading hours" checkbox. Note that the trigger method for cash contracts must always be the default double bid/ask method.
•
Condition - Opens the Conditional tab on the Order Ticket where you can create or modify a conditional order, which is an order that will automatically be submitted or cancelled ONLY IF specified criteria for one or more defined contracts are met. Convert to price-based - Converts the market data display from Volatility to price-based display. The values in the Bid Price and Ask Price fields change from volatility to price. Convert to volatility-based - Converts the market data display from price-based to Volatility display. The values in the Bid Price and Ask Price fields change from price to volatility.
Volatility
•
•
Copyrights and Trademarks
541
TWS Users' Guide
Right-click in a Blank Line
To see a right-click menu, select a line and then click the right mouse button. Select an item from a right-click menu using your mouse. The Right-click menu on in a blank line contains the following menu commands: Menu Command Order Ticker Generic Combo Request Quote Insert Row Delete Row Description Opens the Order Ticket window which you use to create and transmit orders. Opens the Request Ticker box where you enter contract information. This creates a new market data line. Opens the Combo Composition box to the Underlying field. Begin defining legs for a spread order. Enter contract information to request a quote. Inserts a blank line above the selected line. Deletes the selected row or rows. This command deletes both blank lines and market data lines without a warning.
Copyrights and Trademarks
542