This property requires the GetAccountUpdates method to be called first to populate the string list. The Account Values property maintains a String List of current account values from the TWS. Each string is a combination of the Key, Data, Currency values separated by one space between each element. New changes from the TWS are included as they arrive. Each change from TWS generates an OnAccountValue event. (read and write).
These values below are defined, and the zero based Index will refer to these in order.
- AccountDescription
- CashBalance
- Currency
- DayTradeEquity
- DayTradesRemaining
- EquityWithLoanValue
- FutureOptionValue
- FuturesPNL
- GrossPositionValue
- InitMarginReq
- Leverage
- LongOptionValue
- MaintMarginReq
- NetLiquidation
- OptionMarketValue
- PreviousDayEquityWithLoanValue
- RealizedPnL
- ShortOptionValue
- StockMarketValue
- UnalteredInitMarginReq
- UnalteredMaintMarginReq
- UnrealizedPnL
This property requires the GetAccountUpdates method to be called first to populate the list. The Portfolio property maintains a list of all TPortfolioItem updates or adjustments sent by the TWS. Any changes to the list will generate an OnPortfolioUpdate event. (read and write). Access each item in the same manner as Lines property in a TMemo. i.e. Portfolio[2].MarketPrice
The fields of a TPortfolioItem are:
- Symbol: string;
- Local: string;
- SecurityType: TIABSecurityType;
- Expiry: string;
- Strike: Double;
- Right: TIABRight;
- Currency: string;
- Position: Integer;
- MarketPrice: Double;
- MarketValue: Double;
- AverageCost: Double;
- UnrealizedPNL: Double;
- RealizedPNL: Double;
- AccountName: string;
Read the Connected property to determine if connected to the TWS. Write false / true to set the connection to the TWS. Monitor the OnConnectionState event for changes in connection status. Do not communicate with TWS until the OnConnectionState signals twsReady. (read and write).
Set a value for the TWS to identify this Client application. This value may be changed whilst disconnected. Each new ClientId distinguishes each running API process to the TWS. Each running client must have a unique ID. (read and write).
A value of 0 to cause this client to become part of the TWS. See BindTWSOrdersToClient.
This property provides access to the TIABScanner object. This controls the scans in the same manner as the TWS. See the TIABScanner for details.
These events are related to the TIABScanner; OnScannerParam and OnScannerData.
The DefOrder is the default order. Use the default order to set many of the basic values that will not change between separate orders. This order can be passed to the PlaceOrder method, changing only the values that are different from last order. (read and write).
See the TIABOrder object for details on the properties of DefOrder.
This property requires the GetInstrumentSpecs method to be called first. The InstrumentSpecs property maintains a list of TIABInstrumentSpecItem requested from the TWS. (read and write). Access each item in the same manner as Lines property in a TMemo. i.e. InstrumentSpecs[2].MinimumTick
The fields of a TIABInstrumentSpecItem are:
- MarketName: string;
- TradingClass: string;
- ContractId: Integer;
- Multiplier: string;
- MinimumTick: Double;
- OrderTypes: TIABOrderTypesSet;
- ValidExchanges: string;
- Symbol: string;
- SecurityType: TIABSecurityType;
- Expiry: string;
- Strike: Double;
- Right: TIABRight;
- Exchange: string;
- Currency: string;
- LocalSymbol: string;
- PriceMagnifier: Integer;
- DataID: Integer;
- UnderConId: Integer;
This property requires the GetInstrumentSpecs method to be called first, using a valid bond CUSIP or ISIN number in the Symbol field.. The BondSpecs property maintains a list of TIABBondSpecItem requested from the TWS. (read and write). Access each item in the same manner as Lines property in a TMemo. i.e. BondSpecs[2].Cusip
The fields of a TIABBondSpecItem are:
- MarketName: string
- TradingClass: string
- ContractId: Integer
- MinimumTick: Double
- OrderTypes: TIABOrderTypesSet
- ValidExchanges: string
- Symbol: string
- SecurityType: TIABSecurityType
- Cusip: string
- Ratings: string
- DescAppend: string
- BondType: string
- CouponType: string
- Callable: Boolean
- Putable: Boolean
- Coupon: Double
- Convertible: Boolean
- Maturity: string
- IssueDate: string
- Exchange: string
- Currency: string
- NextOptionDate: string
- NextOptionType: string
- NextOptionPartial: Boolean
- Notes: string
Set the required number of TempId's required. Advises the TWS to reserve a block of TempId's. (read and write).
Note: Not certain this really is required for successful orders.
Sets the IP Address that the TWS Server is located. The default is '127.0.0.1' (localhost). The TWS will now accept connections from any IP address.
This value is the port that the TWS server listens. The default TWS port is 7496. This value must correspond the value set in the TWS configuration. (read and write).
Read only. This property is set after a good connection. Read this value in the OnConnectionState event when a Ready state exists.
The format is The TWS connection time is provided as a string with the format "yyyymmdd{space}hh:nn:ss{space}" followed by the local time zone. Use the IABDateTimeStrToDateTime function to convert to a TDateTime value.
Orders property is an array component of all singular Orders. The array is populated automatically, each time a new order is placed, and when TWS sends notification of previous executions or OpenOrders. Each Order fill / price is amended automatically as changes occur.
Access this property in the same manner as a Lines property of a TMemo. i.e. Orders[2].FillPrice
See the TIABOrders object for details on its properties / methods / events.
This property operates in the same manner as Orders property - see above for descriptions.
The VerifiedOrders property contains only orders that have been sucessfully processed by the VerifyOrder method. See the VerifyOrder method for a description of verified Orders.
This method cancels a previous request for Account updates via GetAccountUpdates.
This method cancels an existing open order. The TempId is the value that was returned by the PlaceOrder method. Confirm that the cancel was processed correctly by the OnOrderStatus event and an Order.Completed property of true;
Cancels the flow of OnMarketDepth and OnMarketLevel2 events. The DataId value is the value supplied to the GetMarketDepth method used to identify and start the flow of data.
Cancels the flow of OnTickPrice and OnTickSize and TickSizeAndPrice events. The DataId value is the value supplied to the GetMarketData method used to identify and start the flow of data.
Starts the flow of account status and amendment updates. The AccountCode parameter applies to FA (financial adviser) accounts only. All other account types - pass an empty string. The TWS will send about 20 initial values. The TWS will continue to amend the account every minute, and when order executions occur. The OnAccountDetailsReady event will fire at the completion of the *initial only* call to this method. The flow of data is stopped with CancelAccountUpdates.
This method starts the OnAccountValue and OnAccountTime events.
Requests from the TWS executions based on the filter conditions. Setting a field to null or 0 will remove that condition. Time is based on exchange time. The function returns a sequential request number that will be in the OnExecutionDetailsReady event parameter. The return values of the execution are received through the OnExecution event. The Orders property will be populated for each new or old order received.
TIABExecutionFilter = record
ClientId: Integer;
AccountCode: string;
FromTime: TDateTime;
Symbol: string;
SecurityType: TIABSecurityType;
Exchange: string;
Action: TIABActionFilter;
end;
TIABActionFilter = (afNone,afBuy,afSell,afShort,afExercise,afLapse);
See also RebuildFromTWS.
Call this function to download all details for a particular underlying instrument, contract or Bond. The return values for instrument or contract are received through the OnInstrumentSpecDetails event. Bond details are returned via the OnBondSpecDetails event.
IncludeExpired parameter (default = false). If it is true, historical data queries can be done on expired contracts, those queries being limited to the last year of the contracts life.
The DataId value is a unique value used to identify this set of data, and is used for identifying the response later.
This method is the same as the API GetContractDetails.
GetMarketData is an overload method, and may be called three different ways. These methods start the flow of data to the OnTickPrice and OnTickSize and TickSizeAndPrice events. The DataId value is a unique value used to identify this set of data, and is used for canceling later via CancelMarketdata method.
In the first method, the Order parameter is an existing TIABOrder, and GetMarketData will use the symbol and Exchange information contained there. (Pass the DefOrder or create a new TIABOrder, and pass it). OR you may specify the individual details in the second GetMarketData method.
The ExMarketData parameter is to specify an Extended Market Data values. This is a parameter set. Normal (basic) market data requests do not need this parameter. This parameter is defaulted to an empty set [].
The values of TIABExMktDataSet comprise of:
TIABExMktData = (emdOptionVolume, emdOptionOpenInterest, emdHistoricalVolatility, emdOptionImpliedVolatility, emdIndexFuturePremium, emdMiscellaneous, emdMarkPricePnL, emdMarkPricePnLAuction);
Each of these values will generate additional OnTickPrice and OnTickSize events. Not all the requests apply to all instrument types. See the beta notes, or regular help for a table of events from each specific ExMktData value.
The third version of GetMarketData, is for passing special ID strings directly into the TWS. The ExMarketDataString parameter is a comma separated string of Integer ID's (eg. '234,123,'). Use this function to retrieve the Shortable state of an instrument - set the ExMktDataString to '236'. The result is delivered in the OnTickGeneric event.
To cancel the data flow, call CancelMarketData using the same DataId value.
See also GetMarketSnapShot method to retrieve a one time only set of data for an instrument.
GetMarketSnapShot is much like the GetMarketData method, except that a snapshot will give just a single set of data through the OnTick events only. See GetMarketData for parameter details.
GetMarketDepth is an overload method, and may be called two ways. These methods start the flow of data to the OnMarketLevel2 and OnMarketDepth events. The TWS will send data to one Event only, depending on the type of data available for the instrument requested. The DataId value is a unique value used to identify the data for this instrument.
In the first method, the Order parameter is an existing TIABOrder, and GetMarketDepth will use the symbol and Exchange information contained there. (Pass the DefOrder or create a new TIABOrder, and pass it). OR you may specify the individual details in the second GetMarketDepth method.
To cancel the data flow, call CancelMarketDepth using the same DataId value.
This method requests from the TWS all open orders - for this Client Id only. The results arrive via the OnOpenOrder and OnOrderStatus events. The TIABSocket will locate the matching Order and amend it, or generate a new TIABOrder in the Orders property, for each value returned. At the end of each data set for this method, the OnOpenOrderDetailsReady event fires.
See also RebuildFromTWS.
This method requests from the TWS all open orders - for the entire account. i.e via other Clients or Id's, including TWS generated orders. The results arrive via the OnOpenOrder and OnOrderStatus events. The TIABSocket will locate the matching Order and amend it, or generate a new TIABOrder in the Orders property, for each value returned. At the end of each data set for this method, the OnOpenOrderDetailsReady event fires.
Note: The TWS generated orders are currently excluded from the output, as these all have identical Id's (ClientId=0, OrderId=0), and they cannot be distinguished from each other. Awaiting a fix from IAB (PermId inclusion in OpenOrder event).
See also RebuildFromTWS.
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 OnOpenOrder and OnOrderStatus events. At the end of each data set for this method, the OnOpenOrderDetailsReady event fires.
AutoBind - If set to TRUE, newly created TWS orders will be implicitly associated with the client. If set to FALSE, no association will be made.
Note: This request can only be made from a client with ClientId of 0.
Modify an existing open order. A return value of true indicates only that the order was sent to TWS. It does not indicate a successful change to the order. The TWS will generate a new OnOrderStatus event if successful (usually a Submitted status).
TempId = existing order identity - must be open (not Completed). ClientID = associated with this order.
The TWS allows only these parameters to be changed in an existing order.This method may be called using only the parameters requiring change to be set, and the remaining parameters set to 0 to keep the existing values. i.e.
- Quantity = new quantity.
- OrderType = otMarket.
- Price = new Price
- AuxPrice = new AuxPrice
ModifyOrder(OrderId, ClientID, 0, otNoChange, 25.75, 0.0); will change only the Price field in the submitted order.
Change
up to API 7.3: This method re-adjusts the quantity downwards if a partial fill occurred.
API 7.6 onwards: TWS manages partial fills. This method allows TWS to adjust quantity as required. Pass a new total quantity to adjust total required quantity, or zero to leave order quantity unchanged.
For partial fills: do not adjust quantity - pass a 0 for quantity, and the component assumes the modify is to fill the remainder at the new price, or MKT if specified.
Places an order into the TWS. The Order parameter is a TIABOrder object. The return vale is the TempId of this order. The TempId is used to identify this order at all times.
Order parameter may be set to nil, and PlaceOrder will use the DefOrder values. OR Create a new TIABOrder object, set its values, and pass it as the Order parameter. In this case, you will free the TIABOrder just created.
Each PlaceOrder method call will add the order to the Orders property and maintained by the TIABOrders object. This new order may be found using method of the TIABOrders object through the Orders property.
Places an ExerciseOptions order into the TWS. The Order parameter is a TIABOrder object. The return vale is the TempId of this order. The TempId is used to identify this order at all times.
Order parameter may be set to nil, and PlaceOrder will use the DefOrder values. OR Create a new TIABOrder object, set its values, and pass it as the Order parameter. In this case, you will free the TIABOrder just created.
Each ExerciseOptions method call will add the order to the Orders property and maintained by the TIABOrders object. This new order may be found using method of the TIABOrders object through the Orders property.
The Order.Action poperty can have two values: iabExercise for exercise, and iabLapse for lapse. If no multiplier is specified, a default of 100 is assumed. If the OverridePos parameter is true, exercise instructions will be processed even if the option is out-of-the-money, and lapse instructions will be processed even if the option is in-the-money. Please note that SMART is not an allowed exchange in ExerciseOptions method, and that TWS does a moneyness request for the position in question whenever any API initiated exercise or lapse is attempted.
This method will initialize, or rebuild the Orders property, so it corresponds with the TWS. Use this method if you hold positions, or open orders, and have restarted your application or the TWS.
The OnRebuildFromTWS event will be called for each element update. Note that this method, once completed, should set the Orders property to reflect the TWS version of trades to this client.
This method will start the flow of Flash news Bulletins, and messages concerning Exchange avialability. News / bulletins arrive in the OnNewsBulletin Event. Changes in exchange avialability arrive in the OnExchangeStatus Event. The AllMessages parameter 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.
Cancel with CancelNewsBulletins.
Cancels the flow of Flash news Bulletins, and messages concerning Exchange avialability.
Start the flow with GetNewsBulletins.
This method controls the details the TWS will log (log.txt) when communicating with an API Client. This setting has no affect on this API's functionality or the component set. See the IAB help files for details.
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.
Call this method to request the list of managed accounts. The list will be returned by the OnManagedAccounts event. Note: This request can only be made when connected to a FA managed account.
Call this method to request the details of managed accounts. The list will be returned by the OnReceiveFADetail event. Note: This request can only be made when connected to a FA managed account.
Call this method to request the deatils of managed accounts. The list will be returned by the OnReceiveFADetail event. Note: This request can only be made when connected to a FA managed account.
Call this method to request the details of Historical Chart data. The data will be returned by the OnHistoricalData event. This method and event is cancelled with the CancelHistoricalData method;
A client can extract historical data of up to one year in duration, which can end at any date and time during the past six months for any valid contract or combo. Unlike market data requests, only one request for Historical data can be in process at any given time. The time span covered by the request is specified in the DataDuration parameter. Use the Constants IAB_TIME_UNIT_xx in the DurationTimeUnits parameter to specify the meaning of DataDuration. The DataEndDateTime parameter accepts a string in the form "yyyymmdd{space}hh:mm:ss", with a time zone optionally allowed after a space at the end of the string. At the time of this release, "20050701 18:26:44 GMT" is a legal value for this parameter (though it will not be six months later!).
The BarSize specifies the size of the bars that will be returned (within limits imposed by IB's servers and TWS). The values range from 1 second to 1 day. Use a TIABChartBarSize value here.
Data is returned in bars of a nature very similar to the bars in TWS charts, each bar containing the start time, open, high, low, close, volume, and weighted average price during the time slice in question.
The final time slice has a Date value of "finished," allowing an API application to know when its query has completed. API 882: This also has a time stamp appended showing the request start-finish times eg:
'finished-20060406 12:19:16-20060406 12:24:16'
The nature of the data extracted is governed by setting the value in DataBasis ("TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK" ). Bars of the first four types contain the start time, open, high, low, close, volume, and weighted average price during the time slice in question. The contents of bars returned in response to a BID_ASK query differ from those returned by the other query types, in that the open and close values are actually the time weighted average bid, and time weighted average offer, respectively. This makes these bars identical in nature to TWS's BID_ASK candlestick chart bars.
The ExtendedHours parameter exists to specify regular or extended trading sessions. All data available during the time span requested is returned, even data bars covering time intervals where the market in question was il-liquid. If ExtendedHours is set false, only data within the "Regular Trading Hours" of the product in question is returned, even if the time span requested falls partially or completely outside of them.
IncludeExpired parameter. If it is true, historical data queries can be done on expired contracts, those queries being limited to the last year of the contracts life.
DateFormat parameter: If formatDate = 1, dates applying to bars are returned in a format "yyyymmdd{space}hh:mm:dd," which is the same format already used in EXECUTION_DATA messages. If formatDate = 2, those dates are returned as a long integer specifying the number of seconds since 1/1/1970 GMT.
For details on time frames and allowable requests - see this thread discussion.
When TWS connects either to IB via the internet, or an API client application, it creates Java-based sockets of a predetermined size. If an API application intends to make historical data requests that return more than 1000 bars, it is recommended that TWS be configured to increase the sizes of the API socket buffer. This can be done in the "settings.xml" file in the user's Jts directory. It is important that TWS not be running when its settings.xml file is manually modified. In the <SystemSettings> XML element, the <apiSocketBufferSizes> elements can be used for this purpose. Adding this line to the <SystemSettings> element in settings.xml should suffice:
<apiSocketBufferSizes>500000</apiSocketBufferSizes>
Call this method to request the details of RealTime data. The data will be returned by the OnRealTimeData event. This method and event is cancelled with the CancelRealTimeData method;
NOTE: the current Barsize value is limited by the TWS to a 5 second period ONLY.
Data is returned in bars of a nature very similar to the bars in TWS charts, each bar containing the start time, open, high, low, close, volume, and weighted average price during the time slice in question.
The nature of the data extracted is governed by setting the value in DataBasis ("TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK" ).
The ExtendedHours parameter exists to specify regular or extended trading sessions. All data available during the time span requested is returned, even data bars covering time
Cancels a previous call to GetHistoricalData
For receiving Reuters global fundamental market data. Please note that you must set up a subscription to Reuters Fundamentals through the Market Data section of Account Management before you can receive data.
You can receive data via three reports: Estimates (estimates), Financial Statements (finstat) and Summary (snapshot). Reports are sent via XML.
You can also request fundamental ratios using the tickType ttFundamentRatios. Ratios will be sent as a form of TAG=VALUE;TAG2=VALUE2 ...." string in the the OnTickGeneric event. TAGs include: (long list - see the TWS help for specifics);
Data is returned in the OnFundamentalData event. The event is stopped with a call to CancelFundamentalData
Cancels a previous call to GetFundamentalData
Request the current time from the TWS. Result is returned in the OnCurrentTime event.
This method and associated events and properties include the functionality of the TWS API "What-If" features, and extend that capability to the testing of orders validity. VerifyOrder is a method that allows a test order to be placed and run through the TWS API, but it will not execute or affect the account. Verified orders do not form any part of the trading on the account - they are simply a test of the parameters, and a successful result will provide commission and margin requirements information.
A successful VerifyOrder will generate an OnVerifiedOrder event.
A Verified Order will be placed into the special VerifiedOrders property list (like the Orders property for Live orders).
A successful verification will set the read only TIABOrder.Verified property set to true, and the fields of the TIABOrder.GetQueryResult method record will contain valid data (commissions and margins information). A failed verification will generate regular API error messages, and the event will not fire.
An order on the VerifiedOrders list can be submitted for placement to regular live status as follows: PlaceOrder( VerifiedOrders[2] );
Verified Orders will remain on the VerifiedOrders List, and the VerifiedOrders list can be used as a place to store inactive Order type templates.
This event has the account time from the TWS. It updates each minute or so. To start this event, call the GetAccountUpdates method. To stop the flow of data, call CancelAccountUpdates.
This event has the Index of the value updated in the AccountValue property. Use the Index value in the AccountValues property like so;
AccountString := AccountValue[Index];
The value returned is in the format Key Data Currency string, separated by a single space between elements. See the AccountValue property for the defined Keys.
See the GetAccountUpdates and CancelAccountUpdates methods.
TIABConnection = (twsClosed,twsConnecting,twsReady,twsFailed);
This event updates as the state of the connection to TWS changes. States areNote: This reflects the connection state between your app and the TWS only. In most cases, this will be across the local host, and not likely to encounter many errors. But you may also run your app and the TWS remotely, and net errors will be more prevelant.
- twsClosed: When the connection is closed.
- twsConnecting: After the property SetConnected is set true, but a connection has not yet completed.
- twsReady: The connection is complete, and you may commence sending orders or methods to the TWS. Do not attempt to communicate with TWS until this State is reached.
- twsFailed: Connection lost, TWS forced you off, or other failure.
The connection from TWS to IAB's server is something completely different. We are not able to have direct knowledge of this connection, however its where the real failures will occur. The TWS does send us some error messages after a time out period though.
This event fires at the end of each successful stream read. Note that each stream chunk from the socket can be fragmented, or a truncation of several pieces of data. i.e. the stream may contain several changes to a market data's bid price and size, and the OnTickPrice & OnTickSize & OnTickPrceAndSize events will fire several times accordingly. Using this event, you can collect the changes to market data, and then process the final changes from here.
TempId will be the Order's TempId when known. See the TWS help for a description of codes and messages. Codes above 500 apply to the API.
This event fires after a call to GetInstrumentSpecs. The Index refers to the TIABInstrumentSpecItem in the InstrumentSpecs property.
This event fires after a call to GetInstrumentSpecs, using the bonds Cusip or ISIN in the symbol field. The Index refers to the TIABBondSpecItem in the BondSpecs property.
This event occurs in response to the GetMarketDepth method. The TWS decides if this event, or the OnMarketLevel2 gets the data, depending on the symbol requested.
These constants are defined for use in OnMarketDepth / OnMarketLevel2
OPERATION_INSERT = 0; OPERATION_UPDATE = 1; OPERATION_DELETE = 2; SIDE_ASK = 0; SIDE_BID = 1;
DataId is the value of DataId passed in the GetMarketDepth method.
Index is the row that is to altered. Index is 0 based.
Operation as per above.
Side as per above.
Size is the quantity.
Price is just that.
This event occurs in response to the GetMarketDepth method. The TWS decides if this event, or the OnMarketDepth gets the data, depending on the symbol requested.
These constants are defined for use in OnMarketDepth / OnMarketLevel2
OPERATION_INSERT = 0; OPERATION_UPDATE = 1; OPERATION_DELETE = 2; SIDE_ASK = 0; SIDE_BID = 1;
DataId is the value of DataId passed in the GetMarketDepth method.
Index is the row that is to altered. Index is 0 based.
Operation as per above.
Side as per above.
Size is the quantity.
Price is just that.
MMid is the string abbreviation for the Market Maker.
This event occurs in response to the GetOpenOrdersClient, GetOpenOrdersAccount, GetExecutions methods. Each order sent from the TWS is added to the Orders property automatically. See also the OnExecutionDetailsReady event.
Notify any change to an order's state. Values of State are
TIABOrderState = (osPendSubmit,osPendCancel,osPreSubmit,osSubmitted,osCancelled,osFilled);
Note: An orders state may change - without any change in the filled quantity. And an Order may fill in any state. Do not rely on the State as an indication of an orders fill progress. i.e. A partial fill can be pending, submitted or filled. The Cancelled and Filled states indicate that the Order is Completed.
The filled quantity on an order can be found by checking the properties of the Order parameter. These includeSee the TIABOrder object for a complete list and description.
- property Changed: Boolean;
- property Completed: Boolean;
- property TempId: Integer;
- property PermId: Integer;
- property Filled: Integer;
- property Remaining: Integer;
- property FillPrice: Double;
- property LatestFillQty: Integer;
- property LatestFillPrice: Double;
This event is fired for each change or addition the TWS makes to the Portfolio. The Index parameter is used in the Portfolio property. Check the fields of each TPortfolioItem to read the values. i.e. NewHoldings := Portfolio[Index].Quantity;
The fields of a TPortfolioItem are:
- Symbol: string;
- Local: string;
- SecurityType: TIABSecurityType;
- Expiry: string;
- Strike: Double;
- Right: TIABRight;
- Currency: string;
- Position: Integer;
- MarketPrice: Double;
- MarketValue: Double;
- AverageCost: Double;
- UnrealizedPNL: Double;
- RealizedPNL: Double;
This event will fire after a call to RebuildFromTWS. It will be called for each new element being updated, and may include several calls per order when a partial fill occurred. The OnExecution and OnOpenOrder events are disabled whilst the rebuild is happening.
Note that there is no end of rebuild marker or event, and this event may be called many times before a full rebuild is complete. After all data has been recieved, the TIABSocket.Orders property will reflect the TWS version of orders for this client.
This event is started by a call to GetMarketData method. DataId is the value used to identify this stream. TickType identifies the type of tick data to amend, and Price is the new value.
When running against TWS version 835.0 or higher, API version 8.2 and above (client version 17 and above) supports the reporting of whether a market data price tick is eligible for automatic execution. On occasion, a bid or offer price tick is not available for automatic execution, which means that the market maker may or may not fill an order against it. TWS displays such price ticks in a light purple color to distinguish them, and the AutoExecute field passes this detail into the API. When tick type is either a ttBid or ttAsk, a AutoExecute will be a 1 when this price is eligible for automatic execution and a value of 0 when is not eligible. ttClose and ttLast price ticks will always have a value of 0.
TIABTickType = (ttBidSize,ttBid,ttAsk,ttAskSize,ttLast,ttLastSize,ttHigh,ttLow,ttVolume,ttClose, ttBidOptionComp,ttAskOptionComp,ttLastOptionComp,ttModelOption, ttOpen,ttLow13Week,ttHigh13Week,ttLow26Week,ttHigh26Week,ttLow52Week,ttHigh52Week,ttAvgVolume, ttOpenInterest,ttOptionHistoricalVol,ttOptionImpliedVol, ttOptionBidExch,ttOptionAskExch,ttOptionCallOpenInterest,ttOptionPutOpenInterest, ttOptionCallVolume,ttOptionPutVolume,ttIndexFuturePremium,ttBidExch, ttAskExch,ttAuctionVolume,ttAuctionPrice,ttAuctionImbalance,ttMarkPrice, ttBidEFPComp,ttAskEFPComp,ttLastEFPComp,ttOpenEFPComp,ttHighEFPComp,ttLowEFPComp,ttCloseEFPComp, ttLastTimeStamp, ttShortable, ttFundamentalRatios, ttNotSet);
This event is started by a call to GetMarketData method. DataId is the value used to identify this stream. TickType identifies the type of tick data to amend, and Size is the new value.
The ttLastTimeStamp valu is delivered here also, and the Size value represents a ctime in seconds. To change a ctime to a TDateTime value with
TimeStamp := Size / 86400 + 25569;
TIABTickType = (ttBidSize,ttBid,ttAsk,ttAskSize,ttLast,ttLastSize,ttHigh,ttLow,ttVolume,ttClose, ttBidOptionComp,ttAskOptionComp,ttLastOptionComp,ttModelOption, ttOpen,ttLow13Week,ttHigh13Week,ttLow26Week,ttHigh26Week,ttLow52Week,ttHigh52Week,ttAvgVolume, ttOpenInterest,ttOptionHistoricalVol,ttOptionImpliedVol, ttOptionBidExch,ttOptionAskExch,ttOptionCallOpenInterest,ttOptionPutOpenInterest, ttOptionCallVolume,ttOptionPutVolume,ttIndexFuturePremium,ttBidExch, ttAskExch,ttAuctionVolume,ttAuctionPrice,ttAuctionImbalance,ttMarkPrice, ttBidEFPComp,ttAskEFPComp,ttLastEFPComp,ttOpenEFPComp,ttHighEFPComp,ttLowEFPComp,ttCloseEFPComp, ttLastTimeStamp, ttShortable, ttFundamentalRatios, ttNotSet);
This event is started by a call to GetMarketData method. DataId is the value used to identify this stream. TickType identifies the type of tick data to amend, and Size is the new value.
Note: This event fires in addition to the individual OnTickPrice & OnTickSize events. It is best to select either this combination event, or the two seperated events. Otherwise information will become duplicated.
Also experience shows that collecting the data from each of the seperate Price and Size events, and then acting on it in the OnEndOfStreamRead event will achieve the same result as this combination event.
TIABTickType = (ttBidSize,ttBid,ttAsk,ttAskSize,ttLast,ttLastSize,ttHigh,ttLow,ttVolume,ttClose, ttBidOptionComp,ttAskOptionComp,ttLastOptionComp,ttModelOption, ttOpen,ttLow13Week,ttHigh13Week,ttLow26Week,ttHigh26Week,ttLow52Week,ttHigh52Week,ttAvgVolume, ttOpenInterest,ttOptionHistoricalVol,ttOptionImpliedVol, ttOptionBidExch,ttOptionAskExch,ttOptionCallOpenInterest,ttOptionPutOpenInterest, ttOptionCallVolume,ttOptionPutVolume,ttIndexFuturePremium,ttBidExch, ttAskExch,ttAuctionVolume,ttAuctionPrice,ttAuctionImbalance,ttMarkPrice, ttBidEFPComp,ttAskEFPComp,ttLastEFPComp,ttOpenEFPComp,ttHighEFPComp,ttLowEFPComp,ttCloseEFPComp, ttLastTimeStamp, ttShortable, ttFundamentalRatios, ttNotSet);
This event is started by a call to GetMarketData method and applies to Option orders and the resulting computed values. DataId is the value used to identify this stream. The values of ImpliedVol or Delta may also return a null value (defined as UNSET_DOUBLE).
TIABTickType = (ttBidSize,ttBid,ttAsk,ttAskSize,ttLast,ttLastSize,ttHigh,ttLow,ttVolume,ttClose, ttBidOptionComp,ttAskOptionComp,ttLastOptionComp,ttModelOption, ttOpen,ttLow13Week,ttHigh13Week,ttLow26Week,ttHigh26Week,ttLow52Week,ttHigh52Week,ttAvgVolume, ttOpenInterest,ttOptionHistoricalVol,ttOptionImpliedVol, ttOptionBidExch,ttOptionAskExch,ttOptionCallOpenInterest,ttOptionPutOpenInterest, ttOptionCallVolume,ttOptionPutVolume,ttIndexFuturePremium,ttBidExch, ttAskExch,ttAuctionVolume,ttAuctionPrice,ttAuctionImbalance,ttMarkPrice, ttBidEFPComp,ttAskEFPComp,ttLastEFPComp,ttOpenEFPComp,ttHighEFPComp,ttLowEFPComp,ttCloseEFPComp, ttLastTimeStamp, ttShortable, ttFundamentalRatios, ttNotSet);
This is a multipurpose event, for a variety of special ticks and values. Some are related to optional extended Market Data parameters (see GetMarketData).
The Tick type ttShortable returns through here. See GetMarketData on details of calling this. This code will give details of a shortable item and the available shares for shorting.
if TickType = ttShortable then
begin
if Value > 2.5 then // 3.0
// There are at least 1000 shares available for a short sale
else if Value > 1.5 then // 2.0
// This contract will be available for short sale if shares can be located
else if Value > 0.5 then // 1.0
// Not available for short sale
else
// unknown value
end;
At this time, this event is undocumented, and the events purpose is not known. It appears in the TWS API, but IAB have not published details. Most likely related to optional extended Market Data parameters (see GetMarketData).
This event fires in response to a request for GetMarketData method, with a TIABTickType in this range:
ttBidEFPComp,ttAskEFPComp,ttLastEFPComp,ttOpenEFPComp,ttHighEFPComp,ttLowEFPComp,ttCloseEFPComp
This event is created by a call to GetCurrentTime method. The DateTime is the current TWS date and time.
This event is started by a call to GetNewsBulletins method. MsgId is used to identify the message. Bulletin is the actual message, and NewsSource will usually be an exchange name.
This event is started by a call to GetNewsBulletins method. MsgId is used to identify the message. Status is the condition of the particuliar exchange. Bulletin is the actual message, and NewsSource will usually be an exchange name.
TIABExchangeStatus = (esUnknown,esAvailable,esUnAvailable);
This event is fire for calls to GetExecutions, GetOpenOrdersAccount, GetOpenOrdersClient. The Order parameter is the affected order. The Executions property of the Order has this execution attached, and will be the highest of the ExecutionsCount.
Event for a call to GetManagedAccounts.
Event for a call in response to RequestFA and ReplaceFA methods.
Event for a call in response to GetHistoricalData methods. See the GetHistoricalData for details.
Event for a call in response to GetRealTimeData methods. See the GetRealTimeData for details.
Event for a call in response to GetFundamentalData methods. See the GetFundamentalData for details. Cancel this event with CancelFundamentalData
The report is in an XML format in the xmlStrData parameter.
The event will fire at the completion of a successful call of the following methods. GetOpenOrdersClient, GetOpenOrdersAccount, BindTWSOrdersToClient.
Event for a call in response to GetAccountUpdates method. Note that this event triggers just once per application run, only after the initial call to GetAccountUpdates.
Event at the completion of the GetExecutions method.
Event for a call to GetScannerParameters of the TIABScanner object.
The Parameters is a string of XML formatted text. You will need to parse this to get the data from it. The format is as follows
<?xmlVersion="1.0" encoding="UTF-8"?> <ScanParameterResponse> <InstrumentList> list of instruments, including STK </InstrumentList> <LocationTree> list of locations with their own trees, including STK.NYSE </LocationTree> <ScanTypeList> list of scan types with columns, including TOP_PERC_GAIN </ScanTypeList> </ScanParameterResponse>These are described in more detail at TIABScanner.
Event for a call to NewScan of the TIABScanner object.
This event fire each time the TWS ammends the results of a scan (every 30 seconds or so). Each Scan object holds an array of instruments. Access this like so:
procedure IABSocket1.OnScannerData(Sender: TObject; Scan: TIABScan); var i, j; Integer; s: string; begin for i := 0 to Scan.Count -1 do begin j := Scan.Items[i].Rank; s := Scan.Items[i].Symbol; ...
This event fires in response to a successful VerifyOrder method call. The Order will be stored on the VerifiedOrders property list. The Order's readonly Verified property will be true, and the GetQueryResult method will contain valid information.
See the VerifyOrder method for further details.
Identifies if the Filled value has just changed. Check this to indicate if the last OnOrderStatus notification from TWS actually amended the Filled quantity. This is more reliable than interpreting the various order status. (read and write).
The Changed property is reset to false when an order status changes, but the filled quantity does not.
Completed is true when an order is successfully cancelled, or an order is completely filled, otherwise false. Value is set automatically from notifications from TWS (read and write).
The TempId is the identity used by TWS to identify this order. See also ClientId. (read and write).
PermId is created by TWS, and is filled in by TIABSocket component when first discovered. (read and write).
Total volume of executed filled shares / contracts for this order. Updated automatically. (read and write).
Remaining of open volume of shares / contracts for this order. Updated automatically. (read and write).
Current fill price of executed shares. This value is the average price for all fills in this order so far. Updated automatically. (read and write).
The last number of filled shares / contracts when a partial fill occurs. Updated automatically. (read and write).
The price of the last filled shares / contracts when a partial fill occurs. This is the price of the portion of LatestFillQty shares / contracts. Updated automatically.
Note: API version 7.01 The TWS now sends this data. Prior versions the TWS does not send this data - it is a calculated value from the current accumulated Price. The TWS usually only goes to 4 decimal places, and often this isn't enough to calculate the actual price exactly of each partial fill portion. I recommend you use some rounding on this property. (read and write).
For institutional customers only. Account number / name. (read and write).
TIABAction = (iabIdle,iabBuy,iabSell,iabShort,iabExercise,iabLapse);
Sets the action (buy, sell, short) for this order when passed to the PlaceOrder method. For Options use the ExerciseOptions method and the action set to iabExercise or iabLapse. Changing this property does not send the order. (read and write).
This is the STOP price for stop-limit orders, and the offset amount for Relative orders and Trail orders. In all other cases, specify zero. (read and write).
Specifies the currency. This field is only required when the SecurityType = stCash. Otherwise it is ignored. (read and write).
The order destination such as 'SMART' or 'GLOBEX'. NOTE: When you connect to TWS using any of the API components, you must route all U.S. stock and option orders through Smart order routing. (read and write).
Note: see also PrimaryExchange property.
The expiration date of a Future or Option. The format is 'YYYYMM'. (read and write).
This is the local exchange symbol of the underlying asset. (read and write).
Identifies an OCA (one cancels all) group. Set this to any unique string, and all open orders with same value, will be tied together. (read and write).
For institutional customers only. Specifies whether the order is an open or close order. Valid values are 'O', 'C'. (read and write, default = 'O').
For institutional customers only. The order reference. (read and write).
TIABOrderOrigin = (orCustomer,orFirm,orUnknown); (read and write).
TIABOrderType = (otNoChange,otMarket,otLimit,otStop, otStopLimit,otRelative,otVWAP, otMarketClose,otLimitClose,otTrail, otLimitOpen,otMarketOpen, otOneCancelOther,otISEBlock,otPegMarket, otVolume,otTrailLimit, otScale,otNone,otUnknown);
Use otNoChange for a call to ModifyOrder only. Not all order types are supported in the API as yet.
See ScaledOrder for details on parametrs affecting these order types.
Order share / contract quantity. (read and write).
Order limit price. Maximum precision is 6 places. The TWS may limit this further depending on the asset. (read and write).
For options.
TIABRight = (rtNone,rtPut,rtCall); (read and write). Use rtNone for non Option orders.
TIABSecurityType = (stStock,stOption,stFuture,stIndex,stFutOpt,stCash,stBag,stBond); (read and write).
For options. (read and write).
This is the symbol of the asset. (read and write).
For Trailing stop limit orders.
Use the order type of otTrailLimit. When placing trailing stop limit orders, the AuxPrice property specifies the trailing amount, and the stop price is specified as this TrailStopPrice property.
For Combo type orders. (Read Only)
Information about the combo order returned by the TWS.
Delta-Neutral Combo Orders: Submit Delta-Neutral Combo Orders and RFQs, and request corresponding market data.
Such combos should be constructed as follows:
a) OPT or FOP goes into the leg (e.g. comboLegs list contain 1 leg only)
b) Underlying (STK or FUT), delta and underlying price goes into newly added "underComp" attribute of a Contract.
For use with EFP type orders. (Read Only) Default value = UNSET_DOUBLE
For use with EFP type orders. (Read Only) Default value = UNSET_INTEGER
TIABTimeInForce = (tifDay,tifGTC,tifIOC,tifOPG,tifGTD);
Values are Day, GoodTilCancelled, ImmediateOrCancel(FillOrKill), opg(?), Good Till Date (read and write).
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. (read and write).
The order ID of the parent order, used for bracket and auto trailing stop orders. (read and write).
If set to true, specifies that the order is an ISE Block order. (read and write).
If set to true, specifies that the order is a Sweep-to-Fill order. (read and write).
The desired futures or options contract multiplier in any API operation that involves describing a contract. These operations are: placing orders, requesting market data, requesting market depth, and requesting contract (instrument) specifications. An example of when this functionality is useful is when a corporate action has resulted in more than one options contract being traded on the same underlying, with the same right (put or call), strike, and expiration. If a contract only trades with a single multiplier (typically 100), specifying the multiplier is not necessary.
The publicly disclosed order size, used when placing Iceberg orders. (read and write).
Retail customers set to a value of 0.
Institutional (ie non-cleared) customer specify "Short Sale Slot" information when placing an order of side "SSHORT." This information concerns the location from which shares will be delivered, and has two parameters, "Short Sale Slot" and "Designated Location." If "Short Sale Slot" is 1, then shares will be delivered from the customer's clearing firm, and no "Designated Location" is specified. If "Short Sale Slot" is 2, then shares will be delivered from a "Designated Location" clearing firm, and the value of "Designated Location" is a comma-delimitted list of possible firms.
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.
3 - "double-last" method, where stop orders are triggered based on last two prices.
If set to true, allows triggering of orders outside of regular trading hours. (read and write).
Effective API 9.40 and TWS 878 onwards. This property now replaces the RegTradingHoursOnly property.
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. (read and write).
ClientId that generated this Order. This field is filled automatically on all orders placed from the TIABSocket. This value will normally be the TIABSocket.ClientId.
It becomes relevant when calling GetOpenOrdersAccount, to get details on orders generated by other clients, or within the TWS.
Specifies the number of order shares allocated to each FA managed account. The format of the allocation string is as follows:
<account_code1>/<number_shares1>,...
For example, to allocate 20 shares of a 100 share order to account 'U101' and the other 80 shares to account 'U203', enter the following share allocation string: U101/20,U203/80
This property is an index property to the array of TIABExecution records, that the TWS has sent for this order. The count of items in the array is avaiable in the ExecutionsCount property. The Liquidation field will have a value of 1 if this execution is a result of a liquidation, and a value of 0 otherwise.
Access this property like so; LastOrderExid := IABSocket.Orders[2].Executions[0].ExecutionId;
TIABExecution = record
ExecutionId: string;
Time: string;
AcctNumber: string;
Exchange: string;
Side: TIABAction;
Volume: Integer;
Price: Double;
PermId: Integer;
Liquidation: Integer;
CumulativeQty: Integer;
AveragePrice: Double;
end;
This property is the number of records in the array of the Executions property;
This property is an index property to the array of TIABComboLeg records, that you have added to create Combination Orders (BAG). The count of items in the array is avaiable in the ComboLegsCount property. Add new ComboLegs with the AddComboLeg method, and remove them with the DeleteComboLeg method.
Access this property like so; AComboLegContractId := IABSocket.Orders[2].ComboLegs[0].ContractId;
TIABComboLeg = record
ContractId: Integer;
Action: TIABAction;
Ratio: Integer;
Exchange: string;
OpenClose: TIABLegOpenClose;
ShortSaleSlot: Integer;
DesignatedLocation: string;
end;
The ShortSalelot and DesignatedLocation fields provide support for institutional customers to specify ShortSaleSlot / DesignatedLocation for an individual leg of a COMBO order. Valid values specified for ShortSaleSlot are as follows:
0 - unapplicable (e.g. retail customer or not SSHORT leg (not Action of iabShort)
1 - clearing broker
2 - third party
When ShortSaleSlot = 2, a DesignatedLocation value is to be specified. Non-empty DesignatedLocation values for all other cases will cause orders to be rejected.
TIABLegOpenClose = (locSamePos,locOpenPos,locClosePos,locUnknownPos);
This property is the number of records in the array of the ComboLegs property;
Field discretionaryAmt - unknown purpose?
For Finacial Adviser accounts, otherwise a blank string '';
For Finacial Adviser accounts, otherwise a blank string '';
For Finacial Adviser accounts, otherwise a blank string '';
For Finacial Adviser accounts, otherwise a blank string '';
The trade's "Good After Time," format "YYYYMMDD HH:MM:SS" -- use an empty String if not applicable.
The trade's "Good Till Date," format "YYYYMMDD HH:MM:SS" -- use an empty String if not applicable.
Specify the PrimaryExchange for Smart Routing.
You must specify the primary exchange when placing orders routed through SMART exchange, or when making SMART market data requests. Specifying the primary exchange allows the API to resolve routing ambiguities for example in instances when an asset trades in the same currency on multiple exchanges (i.e. QQQ trades in US dollars on both AMEX and NYSE). Note that the primary exchange for NASDAQ-traded products is SUPERSOES.
Unknown... see TWS help.
TIABOcaMethod = (ocaCancelWithBlock, ocaReduceWithBlock, ocaReduceNonBlock);
Regular trading hours only.
TIABRule80A = (r80na,r80aIndividual, r80aAgency, r80aAgentOtherMember, r80aIndividualPTIA, r80aAgencyPTIA, r80aAgentOtherMemberPTIA, r80aIndividualPT, r80aAgencyPT, r80aAgentOtherMemberPT);
Parameters for the entry of a "Scale" order. The OrderType must be set to otScale for a Scaled order.
Either ScaleNumComponents (split order into X buckets) or ScaleComponentSize (split order so each bucket is of the size X) AND ScalePriceIncrement (price increment per bucket).
The PriceIncrement is unconditionally required, and only one of either NumComponents/ComponentSize must be specified.
Update v9.50:
The scaleNumComponent order attribute was removed, and the scaleComponentSize attribute was split in two: scaleInitLevelSize and scaleSubsLevelSize to match the way TWS defines Scale Orders.
This property contains the comma-separated list of reasons for order to be held. For orders being held due to SLAL , the value will be 'locate'.
Overrides TWS's order price percentage constraints, which are applied to orders that TWS sees as deviating too much from the NBBO of the contract. This functionality was put into place to work in conjunction with the fact that TWS will no longer pop up a confirmation dialog when an API order violates the percentage constraints TWS imposes. If this is set to false, such orders going forward will be rejected. Keep in mind that orders with prices that severely depart from the contract's NBBO but would otherwise be filled will be rejected by IB's servers.
Pertains to institutional only.
Self explan.
Minimum quantity.
Pertains to relative orders only.
...
Trade with firm quotes..?
Maximum SMART order distance from the NBBO
TIABAuctionStrategy = (asUnset, asMatch, asImprovement, asTransparent);
Pertains to BOX exchange only.
Pertains to Dynamic Volatility Orders.
All volatility orders have these two parameters:Dynamic volatility orders have these five additional parameters:
- Volatility: What the price is computed from via TWS's options analytics. For VOL orders, the limit price sent to an exchange is not editable, as it is the output of a function. Volatility is expressed as a percentage.
- VolatilityPeriod: Set to vpUnSet, vpDaily or vpAnnual.
- DeltaNeutral: Specifies whether TWS is supposed to do the corresponding delta trade upon full or partial execution of the option order. If delta neutral is selected, market orders in the underlier will be placed in response to executions to maintain delta-neutrality.
- ContinuousUpdate: Whether TWS is supposed to update the order price as the underlier moves. If Continuous Update is selected, the limit price sent to an exchange is modified by TWS if the computed price of the option changes enough to warrant doing so. This is very helpful in keeping the limit price sent to the exchange up to date as the underlier price changes.
- LowWatermarkPrice: If the underlier's reference price crosses below this price, TWS will cancel the order. Merely touching the watermark does not cancel the order.
- HighWatermarkPrice: If the underlier's reference price crosses above this price, TWS will cancel the order. Merely touching the watermark does not cancel the order.
- ReferencePrice: rpUnSet, rpAverage or rpBidOrAsk. Set to rpAverage for Average of National Best Bid or Ask, or set to rpBidOrAsk for National Best Bid when buying a call or selling a put, and National Best Ask when selling a call or buying a put. The reference price is used to compute the limit price sent to an exchange (whether or not Continuous Update is selected), and for watermark price monitoring.
Read only property. An order that has been sent to the VerifyOrder method, and sucessfully processed, will have its Verified property set true, and the method GetQueryResult will contain valid data for commissions and margins.
See the VerifyOrder method for further details.
This property will contain the Id number of the trading instrument, after the order has been submitted.
For IBExecution Customers: Away and PTA Orders Supported (requires TWS 879)
ClearingIntent: Valid values include: IB, Away, PTA.
ClearingAccount: The true beneficiary of the order.This value is required to be sent on FUT/FOP orders for reporting to the exchange.
Assign the values of one TIABOrder to another. Use this to copy one TIABOrder to another.
Adds a TIABComboLeg to the Order.ComboLegs property. The return value is the Index of this ComboLeg. These are used in Combination orders, and require the Order Type set to otBag.
Deletes an existing TIABComboLeg from the Order.ComboLegs property. Calling this procedure with a value of -1 will delete all ComboLegs from this Order.
An order that has been sent to the VerifyOrder method, and sucessfully processed, will have its Verified property set true, and the method GetQueryResult will contain valid data for commissions and margins.
This method returns a record of type TIABOrderQueryResult.
TIABOrderQueryResult = record Status: string; InitMargin: string; MaintMargin: string; EquityWithLoan: string; Commission: Double; MinCommission: Double; MaxCommission: Double; CommissionCurrency: string; WarningText: string; end;
See the VerifyOrder method for further details.
Fires each time an order has a fill (partial or full). This event is not assigned in the TIABSocket component. Instead use the OnOrderStatus event and check the Order's Changed property.
Fires when the order has been cancelled or completely filled. This event is not assigned in the TIABSocket component. Instead use the OnOrderStatus event and check the Order's Completed property.
Number of TIABOrder objects in the TIABOrders object. Based on 1. (read only).
Each individual TIABOrder item. Index is zero based. This is the default property of TIABOrders. (read and write).
Adds an order to the array. Return value is the Index. This is normally done by TIABSocket. The Add method takes ownership of the IABOrder object.
Inserts an order into the array. Return value is the Index. This is normally done by TIABSocket. The Insert method takes ownership of the IABOrder object.
Deletes a TIABOrder object from the array. Index is zero based. The TIABSocket normally does this.
Locates duplicate orders based on the PermId value. Index1 and Index2 will show the locations in the array. This method does not make any changes - you will need to combine, or delete the duplicate orders.
Call this method after the GetExecutions, GetOpenOrdersClient, GetOpenOrdersAccount methods.
This function returns false when all duplicates are removed. Note that this function finds the first duplicates encountered - and does not change them.
Find an Order by its TempId / ClientId pair. Result is Index or -1;
Find an Order by its PermId. Result is Index or -1;
Finds the PermId of an order by its TempID and ClientId pair. Result is PermId or -1;
Sets the PermId of an order. The TIABSocket normally does this when it first discovers the PermId of the order.
Retrieves an order based on TempId and ClientId.
The scanner system allows API client to make TWS market scanning calls based on the criteria given. The API allows for 50 returned items and these are updated every 30 seconds. Multiple queries can run concurrently.
The TIABScanner object is a manager for the various TIABScan objects. A TIABScan object represents a single scanner Query, and it contains TIABScanResultItem records. This TIABScanner object is accessed as the Scanner property of TIABSocket component. The primary methods are:
1/ Find available parameters of scanner;IABSocket1.Scanner.GetScannerParameters;The return information is an XML string of parameters descibing the attributes of the Scanner - see OnScannerParam. You will need to parse this data string further. Use the data to construct a Query for a scan.
2/ Start a scan;IABSocket1.Scanner.InitializeScanCriteria(ScanCriteria); IABSocket1.Scanner.NewScan(ScanId, ScanCriteria);The call to InitializeScanCriteria is required to format the data in various fields for the TWS. Create your scan query by setting the fields of the ScanCriteria record as required. All unused fields should left with the default initialized values. The ScannerSettingPairs field has this special purpose: Scanner setting pairs are delimited by slashes, making this parameter open ended as further developments occur. The "Annual,true" pairing would cause the "Top Option Implied Vol % Gainers" scan to return annualized volatilites.
ScanId is a unique number used to ID this query.
The ScanCriteria used in the request above, has these fields;TIABScanCriteria = record NumberOfRows: Integer; Instrument: string; LocationCode: string; ScanCode: string; AbovePrice: Double; BelowPrice: Double; AboveVolume: Integer; MarketCapAbove: Double; MarketCapBelow: Double; MoodyRatingAbove: string; MoodyRatingBelow: string; SPRatingAbove: string; SPRatingBelow: string; MaturityDateAbove: string; MaturityDateBelow: string; CouponRateAbove: Double; CouponRateBelow: Double; ExcludeConvertible: Integer; AverageOptionVolumeAbove: Integer; ScannerSettingPairs: string; StockTypeFilter: string; end;The results will return via the OnScannerData event every 30 seconds or so.procedure IABSocket1.OnScannerData(Sender: TObject; Scan: TIABScan); var i, j; Integer; s: string; begin for i := 0 to Scan.Count -1 do begin j := Scan.Items[i].Rank; s := Scan.Items[i].Symbol; ...3/ Cancel a scan;IABSocket1.Scanner.CancelScan(ScanId);
The component set will intercept incomming ammendments to each TIABScan object and a new event will fire. All TIABScanResultItem data in this TIABScan object is overwritten with each update Do not rely on persistant data in these objects - they will change frequently as market conditions change.
// the scanner objects manager TIABScanner = class(TPersistent) public function Add(IABScan: TIABScan): Integer; procedure CancelScan(ScanId: Integer); procedure Delete(Index: Integer); procedure GetScannerParameters; procedure Insert(Index: Integer; IABScan: TIABScan); procedure InitializeScanCriteria(PDetails: PTIABScanCriteria); function IndexOfScanId(ScanId: Integer): Integer; function NewScan(ScanId: Integer; Details: TIABScanCriteria): Integer; property Count: Integer read GetCount; property Items[Index: Integer]: TIABScan read GetItems; default; property Parameters: string read FParameters; end; // An individual scan query // accessed as Items property of TIABScanner TIABScan = class(TPersistent) public function Add(IABScanResultItem: TIABScanResultItem): Integer; procedure Insert(Index: Integer; IABScanResultItem: TIABScanResultItem); procedure Delete(Index: Integer); function Find(IABScanResultItem: TIABScanResultItem): Integer; function QueryCriteria: TIABScanCriteria; property Count: Integer read GetCount; property Items[Index: Integer]: TIABScanResultItem read GetItems write SetItems; default; property ScanId: Integer read FScanId; end; // an instrument that meets the current criteria // accessed as Items property of TIABScan TIABScanResultItem = record Rank: Integer; Symbol: string; SecurityType: TIABSecurityType; Expiry: string; Strike: Double; Right: TIABRight; Exchange: string; Currency: string; LocalSymbol: string; MarketName: string; TradingClass: string; Distance: string; Benchmark: string; Projection: string; LegsString: string; end;