Close Navigation
Learn more about IBKR accounts

TWS API Reference

Introduction

This section provides an approximate class reference for all of the TWS API classes referenced throughout the primary documentation pages.
Please be aware this content is currently in Beta and we are moving to further elaborate on all of these data points in the near future.

AccountSummaryTags Class

Class containing all existing values being reported by EClientSocket::reqAccountSummary.

Public Attributes

NameTypeDescription
AccountType = “AccountType” string
NetLiquidation = “NetLiquidation” string
TotalCashValue = “TotalCashValue” string
Total cash including futures pnl
SettledCash = “SettledCash” string
For cash accounts, this is the same as TotalCashValue
AccruedCash = “AccruedCash” string
Net accrued interest
BuyingPower = “BuyingPower” string
The maximum amount of marginable US stocks the account can buy
EquityWithLoanValue = “EquityWithLoanValue” string
Cash + stocks + bonds + mutual funds
PreviousDayEquityWithLoanValue = “PreviousDayEquityWithLoanValue” string
GrossPositionValue = “GrossPositionValue” string
The sum of the absolute value of all stock and equity option positions
ReqTEquity = “ReqTEquity” string
ReqTMargin = “ReqTMargin” string
SMA = “SMA” string
Special Memorandum Account
InitMarginReq = “InitMarginReq” string
MaintMarginReq = “MaintMarginReq” string
AvailableFunds = “AvailableFunds” string
ExcessLiquidity = “ExcessLiquidity” string
Cushion = “Cushion” string
Excess liquidity as a percentage of net liquidation value
FullInitMarginReq = “FullInitMarginReq” string
FullMaintMarginReq = “FullMaintMarginReq” string
FullAvailableFunds = “FullAvailableFunds” string
FullExcessLiquidity = “FullExcessLiquidity” string
LookAheadNextChange = “LookAheadNextChange” string
Time when look-ahead values take effect
LookAheadInitMarginReq = “LookAheadInitMarginReq” string
LookAheadMaintMarginReq = “LookAheadMaintMarginReq” string
LookAheadAvailableFunds = “LookAheadAvailableFunds” string
LookAheadExcessLiquidity = “LookAheadExcessLiquidity” string
HighestSeverity = “HighestSeverity” string
A measure of how close the account is to liquidation
DayTradesRemaining = “DayTradesRemaining” string
The Number of Open/Close trades one could do before Pattern Day Trading is detected; a value of “-1” means user can do unlimited day trades.
Leverage = “Leverage” string
GrossPositionValue / NetLiquidation

Static Public Member Functions

NameTypeDescription
GetAllTags ()static stringReturns All Tags

Bar Class Reference

The historical data bar’s description.

NameTypeDescription
TimestringThe bar’s date and time (either as a yyyymmss hh:mm:ss formatted string or as system time according to the request). Time zone is the TWS time zone chosen on login.
OpendoubleThe bar’s open price.
HighdoubleThe bar’s high price.
LowdoubleThe bar’s low price.
ClosedoubleThe bar’s close price.
VolumedecimalThe bar’s traded volume if available (only available for TRADES)
CountintThe number of trades during the bar’s timespan (only available for TRADES)
WAPdecimalThe bar’s Weighted Average Price (only available for TRADES)

ComboLeg Class Reference

Class representing a leg within combo orders.

NameTypeDescription
ConIdintThe Contract’s IB’s unique id.
RatiointSelect the relative number of contracts for the leg you are constructing. To help determine the ratio for a specific combination order
ActionstringThe side (buy or sell) of the leg:
For individual accounts, only BUY and SELL are available. SSHORT is for institutions.
ExchangestringThe destination exchange to which the order will be routed.
OpenCloseintSpecifies whether an order is an open or closing order. For institutional customers to determine if this order is to open or close a position. 0 – Same as the parent security. This is the only option for retail customers.
1 – Open. This value is only valid for institutional customers.
2 – Close. This value is only valid for institutional customers.
3 – Unknown.
ShortSaleSlotintFor stock legs when doing short selling.

Set to 1 = clearing broker, 2 = third party
DesignatedLocationstring
When ShortSaleSlot is 2, this field shall contain the designated location.
ExemptCodeintMark order as exempt from short sale uptick rule.
Possible values:
0 – Does not apply the rule.
-1 – Applies the short sale uptick rule.

Public Member Functions

NameTypeDescription
SAME = 0static int
Same as the parent security. This is the only option for retail customers.
OPEN = 1static int
Open. This value is only valid for institutional customers.
CLOSE = 2static int
Close. This value is only valid for institutional customers.
UNKNOWN = 3static int
Unknown

CommissionAndFeesReport Class Reference

Class representing the commissions and fees generated by an execution.

NameTypeDescription
ExecIdstringthe execution’s id this commission belongs to.
CommissionAndFeesdoublethe combined cost of commissions and fees.
CurrencystringThe currency denoting the value of the commissionAndFees.
RealizedPNLdoublethe realized profit and loss
YielddoubleThe income return.
YieldRedemptionDateintdate expressed in yyyymmdd format.

Public Member Functions

NameTypeDescription
Equals (object obj)override bool
GetHashCode ()override int

Contract Class Reference

Class describing an instrument’s definition.

NameTypeDescription
ConIdintThe unique IB contract identifier.
SymbolstringThe underlying’s asset symbol.
SecTypestringThe security’s type: STK – stock (or ETF) OPT – option FUT – future IND – index FOP – futures option CASH – forex pair BAG – combo WAR – warrant BOND- bond CMDTY- commodity NEWS- news FUND- mutual fund.
LastTradeDateOrContractMonthstringThe contract’s last trading day or contract month (for Options and Futures). Strings with format YYYYMM will be interpreted as the Contract Month whereas YYYYMMDD will be interpreted as Last Trading Day.
LastTradeDatestringThe contract’s last trading day.
StrikedoubleThe option’s strike price.
Rightstring
Either Put or Call (i.e. Options). Valid values are P, PUT, C, CALL.
Multiplierstring
The instrument’s multiplier (i.e. options, futures).
ExchangestringThe destination exchange.
CurrencystringThe underlying’s currency.
LocalSymbolstringThe contract’s symbol within its primary exchange. For options, this will be the OCC symbol
PrimaryExchstringThe contract’s primary exchange. For smart routed contracts, used to define contract in case of ambiguity.Should be defined as native exchange of contract. For exchanges which contain a period in name, will only be part of exchange name prior to period, i.e. ENEXT for ENEXT.BE
TradingClassstringThe trading class name for this contract. Available in TWS contract description window as well. For example, GBL Dec ’13 future’s trading class is “FGBL”
IncludeExpiredboolIf set to true, contract details requests and historical data queries can be performed pertaining to expired futures contracts. Expired options or other instrument types are not available.
SecIdTypestringSecurity’s identifier when querying contract’s details or placing orders ISIN – Example: Apple: US0378331005 CUSIP – Example: Apple: 037833100.
SecIdstringIdentifier of the security type. More…
DescriptionstringDescription of the contract.
IssuerIdstringIssuerId of the contract.
ComboLegsDescriptionstringDescription of the combo legs.
ComboLegsListThe legs of a combined contract definition. More…
DeltaNeutralContractDeltaNeutralContractDelta and underlying price for Delta-Neutral combo orders. Underlying (STK or FUT)

Public Member Functions

NameTypeDescription
ToString()override string

ContractDetails Class Reference

Extended contract details.

NameTypeDescription
ContractContractA fully-defined Contract object.
MarketNamestringThe market name for this product.
MinTickdoubleThe minimum allowed price variation. Note that many securities vary their minimum tick size according to their price. This value will only show the smallest of the different minimum tick sizes regardless of the product’s price. Full information about the minimum increment price structure can be obtained with the reqMarketRule function or the IB Contract and Security Search site.
PriceMagnifierintAllows execution and strike prices to be reported consistently with market data
OrderTypesstringSupported order types for this product.
ValidExchangesstringValid exchange fields when placing an order for this contract.
NoneThe list of exchanges will is provided in the same order as the corresponding MarketRuleIds list.None
UnderConIdintFor derivatives
LongNamestringDescriptive name of the product.
ContractMonthstringTypically the contract month of the underlying for a Future contract.
IndustrystringThe industry classification of the underlying/product. For example
CategorystringThe industry category of the underlying. For example
SubcategorystringThe industry subcategory of the underlying. For example
TimeZoneIdstringThe time zone for the trading hours of the product. For example
TradingHoursstringThe trading hours of the product. This value will contain the trading hours of the current day as well as the next’s. For example
LiquidHoursstringThe liquid hours of the product. This value will contain the liquid hours (regular trading hours) of the contract on the specified exchange. Format for TWS versions until 969: 20090507:0700-1830
EvRulestringContains the Economic Value Rule name and the respective optional argument. The two values should be separated by a colon. For example
EvMultiplierdoubleTells you approximately how much the market value of a contract would change if the price were to change by 1. It cannot be used to get market value by multiplying the price by the approximate multiplier.
AggGroupintAggregated group Indicates the smart-routing group to which a contract belongs. contracts which cannot be smart-routed have aggGroup = -1.
SecIdListListA list of contract identifiers that the customer is allowed to view. CUSIP/ISIN/etc. For US stocks
UnderSymbolstringFor derivatives
UnderSecTypestringFor derivatives
MarketRuleIdsstringThe list of market rule IDs separated by comma Market rule IDs can be used to determine the minimum price increment at a given price.
RealExpirationDatestringReal expiration date. Requires TWS 968+ and API v973.04+. Python API specifically requires API v973.06+.
LastTradeTimestringLast trade time.
StockTypestringStock type.
CusipstringThe nine-character bond CUSIP. For Bonds only. Receiving CUSIPs requires a CUSIP market data subscription.
RatingsstringIdentifies the credit rating of the issuer. This field is not currently available from the TWS API. For Bonds only. A higher credit rating generally indicates a less risky investment. Bond ratings are from Moody’s and S&P respectively. Not currently implemented due to bond market data restrictions.
DescAppendstringA description string containing further descriptive information about the bond. For Bonds only.
BondTypestringThe type of bond
CouponTypestringThe type of bond coupon. This field is currently not available from the TWS API. For Bonds only.
CallableboolIf true
PutableboolValues are True or False. If true
CoupondoubleThe interest rate used to calculate the amount you will receive in interest payments over the course of the year. This field is currently not available from the TWS API. For Bonds only.
ConvertibleboolValues are True or False. If true
Maturitystringhe date on which the issuer must repay the face value of the bond. This field is currently not available from the TWS API. For Bonds only. Not currently implemented due to bond market data restrictions.
IssueDatestringThe date the bond was issued. This field is currently not available from the TWS API. For Bonds only. Not currently implemented due to bond market data restrictions.
NextOptionDatestringOnly if bond has embedded options. This field is currently not available from the TWS API. Refers to callable bonds and puttable bonds. Available in TWS description window for bonds.
NextOptionTypestringType of embedded option. This field is currently not available from the TWS API. Only if bond has embedded options.
NextOptionPartialboolOnly if bond has embedded options. This field is currently not available from the TWS API. For Bonds only.
NotesstringIf populated for the bond in IB’s database. For Bonds only.
MinSizedecimalOrder’s minimal size.
SizeIncrementdecimalOrder’s size increment.
SuggestedSizeIncrementdecimalOrder’s suggested size increment.
FundNamestringFund’s name.
FundFamilystringFund’s family.
FundTypestringFund’s type.
FundFrontLoadstringFund’s front load.
FundBackLoadstringFund’s back load.
FundBackLoadTimeIntervalstringFund’s back load time interval.
FundManagementFeestringFund’s management fee.
FundClosedboolFund closed flag.
FundClosedForNewInvestorsboolFund closed for new investors flag.
FundClosedForNewMoneyboolFund closed for new money flag.
FundNotifyAmountstringFund’s notify amount.
FundMinimumInitialPurchasestringFund’s minimum initial purchase.
FundSubsequentMinimumPurchasestringFund’s subsequent minimum purchase.
FundBlueSkyStatesstringFund’s blue sky states.
FundBlueSkyTerritoriesstringFund’s blue sky territories.
FundDistributionPolicyIndicatorFundDistributionPolicyIndicatorFund’s distribution policy indicator.
FundAssetTypeFundAssetTypeFund’s asset type.

CodeMsgPair Class Reference

Associates error code and error message as a pair.

NameTypeDescription
CodeintNone
MessagestringNone

DeltaNeutralContract Class Reference

Delta-Neutral Contract.

NameTypeDescription
ConIdintThe unique contract identifier specifying the security. Used for Delta-Neutral Combo contracts.
DeltadoubleThe underlying stock or future delta. Used for Delta-Neutral Combo contracts.
PricedoubleThe price of the underlying. Used for Delta-Neutral Combo contracts.

EClient Class Reference

TWS/Gateway client class This client class contains all the available methods to communicate with IB. Up to thirty-two clients can be connected to a single instance of the TWS/Gateway simultaneously. From herein, the TWS/Gateway will be referred to as the Host.

NameTypeDescription
AllowRedirectbool
ServerTimestring
optionalCapabilitiesstring
AsyncEConnectbool

Public Member Functions

NameTypeDescription
SetConnectOptions (string connectOptions)voidIgnore. Used for IB’s internal purposes.
DisableUseV100Plus ()voidAllows to switch between different current (V100+) and previous connection mechanisms.
IsConnected ()boolIndicates whether the API-TWS connection has been closed. Note: This function is not automatically invoked and must be by the API client. More…
startApi ()voidInitiates the message exchange between the client application and the TWS/IB Gateway.
Close ()voidTerminates the connection and notifies the EWrapper implementing class. More…
eDisconnect (bool resetState=true)virtual voidCloses the socket connection and terminates its thread.
reqCompletedOrders (bool apiOnly)voidRequests completed orders.
None. More…None
cancelTickByTickData (int requestId)voidCancels tick-by-tick data.
None. More…None
reqTickByTickData (int requestIdvoid Contract contract
None. More…None
cancelHistoricalData (int reqId)voidCancels a historical data request. More…
calculateImpliedVolatility (int reqIdvoid Contract contract
NoneRequest the calculation of the implied volatility based on hypothetical option and its underlying prices.None
NoneThe calculation will be return in EWrapper’s tickOptionComputation callback.None
None. More…None
calculateOptionPrice (int reqIdvoid Contract contract
NoneThe calculation will be return in EWrapper’s tickOptionComputation callback.None
None. More…None
cancelAccountSummary (int reqId)voidCancels the account’s summary request. After requesting an account’s summary
cancelCalculateImpliedVolatility (int reqId)voidCancels an option’s implied volatility calculation request. More…
cancelCalculateOptionPrice (int reqId)voidCancels an option’s price calculation request. More…
cancelFundamentalData (int reqId)voidCancels Fundamental data request. More…
cancelMktData (int tickerId)voidCancels a RT Market Data request. More…
cancelMktDepth (int tickerIdvoid bool isSmartDepth)
cancelNewsBulletin ()voidCancels IB’s news bulletin subscription. More…
cancelOrder (int orderIdvoid string manualOrderCancelTime)
NoneNote: API clients cannot cancel individual orders placed by other clients. Only reqGlobalCancel is available.None
None. More…None
cancelPositions ()voidCancels a previous position subscription request made with reqPositions. More…
cancelRealTimeBars (int tickerId)voidCancels Real Time Bars’ subscription. More…
cancelScannerSubscription (int tickerId)voidCancels Scanner Subscription. More…
exerciseOptions (int tickerIdvoid Contract contract
NoneNote: this function is affected by a TWS setting which specifies if an exercise request must be finalized. More…None
placeOrder (int idvoid Contract contract
replaceFA (int reqIdvoid int faDataType
requestFA (int faDataType)voidRequests the FA configuration A Financial Advisor can define three different configurations: More…
reqAccountSummary (int reqIdvoid string group
NoneThis method will subscribe to the account summary as presented in the TWS’ Account Summary tab. The data is returned at EWrapper::accountSummaryNone
Nonehttps://www.interactivebrokers.com/en/software/tws/accountwindowtop.htm. More…None
reqAccountUpdates (bool subscribevoid string acctCode)
reqAllOpenOrders ()voidRequests all current open orders in associated accounts at the current moment. The existing orders will be received via the openOrder and orderStatus events. Open orders are returned once; this function does not initiate a subscription. More…
reqAutoOpenOrders (bool autoBind)voidRequests status updates about future orders placed from TWS. Can only be used with client ID 0. More…
reqContractDetails (int reqIdvoid Contract contract)
NoneThis method will provide all the contracts matching the contract provided. It can also be used to retrieve complete options and futures chains. This information will be returned at EWrapper:contractDetails. Though it is now (in API version > 9.72.12) advised to use reqSecDefOptParams for that purpose.None
None. More…None
reqCurrentTime ()voidRequests TWS’s current time. More…
reqExecutions (int reqIdvoid ExecutionFilter filter)
reqFundamentalData (int reqIdvoid Contract contract
reqGlobalCancel ()voidCancels all active orders.
NoneThis method will cancel ALL open orders including those placed directly from TWS. More…None
reqHistoricalData (int tickerIdvoid Contract contract
reqIds (int numIds)voidRequests the next valid order ID at the current moment. More…
reqManagedAccts ()voidRequests the accounts to which the logged user has access to. More…
reqMktData (int tickerIdvoid Contract contract
reqMarketDataType (int marketDataType)voidSwitches data type returned from reqMktData request to “frozen”
NoneThe API can receive frozen market data from Trader Workstation. Frozen market data is the last data recorded in our system.None
the API receives real-time market data. Invoking this function with argument 2 requests a switch to frozen data immediately or after the close.During normal trading hoursNone
the market data type will automatically switch back to real time if available. More…When the market reopensNone
reqMarketDepth (int tickerIdvoid Contract contract
commissionsThis request must be direct-routed to an exchange and not smart-routed. The number of simultaneous market depth requests allowed in an account is calculated based on a formula that looks at an accounts equity and quote booster packs. More…
reqNewsBulletins (bool allMessages)voidSubscribes to IB’s News Bulletins. More…
reqOpenOrders ()voidRequests all open orders places by this specific API client (identified by the API client id). For client ID 0
reqPositions ()voidSubscribes to position updates for all accessible accounts. All positions sent initially
reqRealTimeBars (int tickerIdvoid Contract contract
only 5 seconds bars are provided. This request is subject to the same pacing as any historical data request: no more than 60 API queries in more than 600 seconds.CurrentlyNone
NoneReal time bars subscriptions are also included in the calculation of the number of Level 1 market data subscriptions allowed in an account. More…None
reqScannerParameters ()voidRequests an XML list of scanner parameters valid in TWS.
NoneNot all parameters are valid from API scanner. More…None
reqScannerSubscription (int reqIdvoid ScannerSubscription subscription
reqScannerSubscription (int reqIdvoid ScannerSubscription subscription
setServerLogLevel (int logLevel)voidChanges the TWS/GW log level. The default is 2 = ERROR
None5 = DETAIL is required for capturing all API messages and troubleshooting API programsNone
NoneValid values are:None
None1 = SYSTEMNone
None2 = ERRORNone
None3 = WARNINGNone
None4 = INFORMATIONNone
None5 = DETAILNone
None.None
verifyRequest (string apiNamevoid string apiVersion)
verifyMessage (string apiData)voidFor IB’s internal purpose. Allows to provide means of verification between the TWS and third party programs.
verifyAndAuthRequest (string apiNamevoid string apiVersion
verifyAndAuthMessage (string apiDatavoid string xyzResponse)
queryDisplayGroups (int requestId)voidRequests all available Display Groups in TWS. More…
subscribeToGroupEvents (int requestIdvoid int groupId)
updateDisplayGroup (int requestIdvoid string contractInfo)
unsubscribeFromGroupEvents (int requestId)voidCancels a TWS Window Group subscription.
reqPositionsMulti (int requestIdvoid string account
cancelPositionsMulti (int requestId)voidCancels positions request for account and/or model. More…
reqAccountUpdatesMulti (int requestIdvoid string account
cancelAccountUpdatesMulti (int requestId)voidCancels account updates request for account and/or model. More…
reqSecDefOptParams (int reqIdvoid string underlyingSymbol
reqSoftDollarTiers (int reqId)voidRequests pre-defined Soft Dollar Tiers. This is only supported for registered professional advisors and hedge and mutual funds who have configured Soft Dollar Tiers in Account Management. Refer to: https://www.interactivebrokers.com/en/software/am/am/manageaccount/requestsoftdollars.htm?Highlight=soft%20dollar%20tier. More…
reqFamilyCodes ()voidRequests family codes for an account
reqMatchingSymbols (int reqIdvoid string pattern)
reqMktDepthExchanges ()voidRequests venues for which market data is returned to updateMktDepthL2 (those with market makers) More…
reqSmartComponents (int reqIdvoid string bboExchange)
reqNewsProviders ()voidRequests news providers which the user has subscribed to. More…
reqNewsArticle (int requestIdvoid string providerCode
reqHistoricalNews (int requestIdvoid int conId
reqHeadTimestamp (int tickerIdvoid Contract contract
cancelHeadTimestamp (int tickerId)voidCancels a pending reqHeadTimeStamp request
None. More…None
reqHistogramData (int tickerIdvoid Contract contract
None. More…None
cancelHistogramData (int tickerId)voidCancels an active data histogram request. More…
reqMarketRule (int marketRuleId)voidRequests details about a given market rule
NoneThe market rule for an instrument on a particular exchange provides details about how the minimum price increment changes with priceNone
NoneA list of market rule ids can be obtained by invoking reqContractDetails on a particular contract. The returned market rule ID list will provide the market rule ID for the instrument in the correspond valid exchange list in contractDetails.None
None. More…None
reqPnL (int reqIdvoid string account
cancelPnL (int reqId)voidcancels subscription for real time updated daily PnL params reqId
reqPnLSingle (int reqIdvoid string account
cancelPnLSingle (int reqId)voidCancels real time subscription for a positions daily PnL information. More…
reqHistoricalTicks (int reqIdvoid Contract contract
reqWshMetaData (int reqId)voidRequests metadata from the WSH calendar. More…
cancelWshMetaData (int reqId)voidCancels pending request for WSH metadata. More…
reqWshEventData (int reqIdvoid WshEventData wshEventData)
cancelWshEventData (int reqId)voidCancels pending WSH event data request. More…
reqUserInfo (int reqId)voidRequests user info. More…
IsDataAvailable ()boolNone
ReadInt ()intNone
ReadAtLeastNBytes (int msgSize)byte[]None
ReadByteArray (int msgSize)byte[]None

Public Attributes

NameTypeDescription
ServerVersion => serverVersionintreturns the Host’s version. Some of the API functionality might not be available in older Hosts and therefore it is essential to keep the TWS/Gateway as up to date as possible.

Protected Member Functions

NameTypeDescription
prepareBuffer (BinaryWriter paramsList)abstract uintNone
sendConnectRequest ()voidNone
CheckServerVersion (int requiredVersion)boolNone
CheckServerVersion (int requestIdbool int requiredVersion)
CheckServerVersion (int requiredVersionbool string updatetail)
CheckServerVersion (int tickerIdbool int requiredVersion
CloseAndSend (BinaryWriter paramsListvoid uint lengthPos
CloseAndSend (int reqIdvoid BinaryWriter paramsList
CloseAndSend (BinaryWriter requestabstract void uint lengthPos)
CheckConnection ()boolNone
ReportError (int reqIdvoid CodeMsgPair error
ReportUpdateTWS (int reqIdvoid string tail)
ReportUpdateTWS (string tail)voidNone
ReportError (int reqIdvoid int code
SendCancelRequest (OutgoingMessages msgTypevoid int version
SendCancelRequest (OutgoingMessages msgTypevoid int version
VerifyOrderContract (Contract contractbool int id)
VerifyOrder (Order orderbool int id

Protected Attributes

NameTypeDescription
serverVersionintNone
socketTransportETransportNone
wrapperEWrapperNone
isConnectedvolatile boolNone
clientIdintNone
extraAuthboolNone
useV100Plus = trueboolNone
allowRedirectboolNone
tcpStreamStreamNone

EClientSocket Class Reference

TWS/Gateway client class This client class contains all the available methods to communicate with IB. Up to 32 clients can be connected to a single instance of the TWS/Gateway simultaneously. From herein, the TWS/Gateway will be referred to as the Host.

Inheritance diagram for EClient:

Public Member Functions

NameTypeDescription
serverVersion (int versionvoid EClientMsgSink. string time)
eConnect (string hostvoid int port
eConnect (string hostvoid int port
redirect (string host)voidRedirects connection to different host.
eDisconnect (bool resetState=true)override voidCloses the socket connection and terminates its thread.

Protected Member Functions

NameTypeDescription
createClientStream (string hostvirtual Stream int port)
prepareBuffer (BinaryWriter paramsList)override uintNone
CloseAndSend (BinaryWriter requestoverride void uint lengthPos)

EReader Class Reference

Captures incoming messages to the API client and places them into a queue.

Public Member Functions

NameTypeDescription
Start ()voidNone
processMsgs ()voidNone
putMessageToQueue ()boolNone

EReaderSignal Interface Reference

Notifies the thread reading information from the TWS whenever there are messages ready to be consumed. Not currently used in Python API.

Public Member Functions

NameTypeDescription
issueSignal ()voidIssues a signal to the consuming thread when there are things to be consumed.
waitForSignal ()voidMakes the consuming thread waiting until a signal is issued.

EWrapper Interface Reference

This interface’s methods are used by the TWS/Gateway to communicate with the API client. Every API client application needs to implement this interface in order to handle all the events generated by the TWS/Gateway. Almost every EClientSocket method call will result in at least one event delivered here.

Public Member Functions

NameTypeDescription
error (Exception e)voidHandles errors generated within the API itself. If an exception is thrown within the API code it will be notified here. Possible cases include errors while reading the information from the socket or even mishandling at EWrapper’s implementing class. More…
error (string str)voidNone
error (int idvoid int errorCode
currentTime (long time)voidTWS’s current time. TWS is synchronized with the server (not local computer) using NTP and this function will receive the current time in TWS. More…
tickPrice (int tickerIdvoid int field
tickSize (int tickerIdvoid int field
tickString (int tickerIdvoid int field
tickGeneric (int tickerIdvoid int field
tickEFP (int tickerIdvoid int tickType
deltaNeutralValidation (int reqIdvoid DeltaNeutralContract deltaNeutralContract)
the server sends a deltaNeutralValidation() message with the DeltaNeutralContract structure. If the delta and price fields are empty in the original requestUpon accepting a Delta-Neutral DN RFQ(request for quote) the confirmation will contain the current values from the server. These values are locked when RFQ is processed and remain locked until the RFQ is cancelled.
NoneMore…None
tickOptionComputation (int tickerIdvoid int field
tickSnapshotEnd (int tickerId)voidWhen requesting market data snapshots
nextValidId (int orderId)voidReceives next valid order id. Will be invoked automatically upon successfull API client connection
managedAccounts (string accountsList)voidReceives a comma-separated string with the managed account ids. Occurs automatically on initial API client connection. More…
connectionClosed ()voidCallback to indicate the API connection has closed. Following a API TWS broken socket connection
accountSummary (int reqIdvoid string account
accountSummaryEnd (int reqId)voidnotifies when all the accounts’ information has ben received. Requires TWS 967+ to receive accountSummaryEnd in linked account structures. More…
bondContractDetails (int reqIdvoid ContractDetails contract)
updateAccountValue (string keyvoid string value
updatePortfolio (Contract contractvoid decimal position
updateAccountTime (string timestamp)voidReceives the last time on which the account was updated. More…
accountDownloadEnd (string account)voidNotifies when all the account’s information has finished. More…
orderStatus (int orderIdvoid string status
openOrder (int orderIdvoid Contract contract
openOrderEnd ()voidNotifies the end of the open orders’ reception. More…
contractDetails (int reqIdvoid ContractDetails contractDetails)
contractDetailsEnd (int reqId)voidAfter all contracts matching the request were returned
execDetails (int reqIdvoid Contract contract
execDetailsEnd (int reqId)voidindicates the end of the Execution reception. More…
commissionReport (CommissionReport commissionReport)voidprovides the CommissionReport of an Execution More…
fundamentalData (int reqIdvoid string data)
historicalData (int reqIdvoid Bar bar)
historicalDataUpdate (int reqIdvoid Bar bar)
historicalDataEnd (int reqIdvoid string start
marketDataType (int reqIdvoid int marketDataType)
updateMktDepth (int tickerIdvoid int position
updateMktDepthL2 (int tickerIdvoid int position
updateNewsBulletin (int msgIdvoid int msgType
position (string accountvoid Contract contract
positionEnd ()voidIndicates all the positions have been transmitted. More…
realtimeBar (int reqIdvoid long date
scannerParameters (string xml)voidprovides the xml-formatted parameters available from TWS market scanners (not all available in API). More…
scannerData (int reqIdvoid int rank
scannerDataEnd (int reqId)voidIndicates the scanner data reception has terminated. More…
receiveFA (int faDataTypevoid string faXmlData)
verifyMessageAPI (string apiData)voidNot generally available.
verifyCompleted (bool isSuccessfulvoid string errorText)
verifyAndAuthMessageAPI (string apiDatavoid string xyzChallenge)
verifyAndAuthCompleted (bool isSuccessfulvoid string errorText)
displayGroupList (int reqIdvoid string groups)
displayGroupUpdated (int reqIdvoid string contractInfo)
connectAck ()voidcallback initially acknowledging connection attempt connection handshake not complete until nextValidID is received
positionMulti (int requestIdvoid string account
positionMultiEnd (int requestId)voidIndicates all the positions have been transmitted. More…
accountUpdateMulti (int requestIdvoid string account
accountUpdateMultiEnd (int requestId)voidIndicates all the account updates have been transmitted. More…
securityDefinitionOptionParameter (int reqIdvoid string exchange
securityDefinitionOptionParameterEnd (int reqId)voidcalled when all callbacks to securityDefinitionOptionParameter are complete More…
softDollarTiers (int reqIdvoid SoftDollarTier[] tiers)
familyCodes (FamilyCode[] familyCodes)voidreturns array of family codes More…
symbolSamples (int reqIdvoid ContractDescription[] contractDescriptions)
mktDepthExchanges (DepthMktDataDescription[] depthMktDataDescriptions)voidcalled when receives Depth Market Data Descriptions More…
tickNews (int tickerIdvoid long timeStamp
smartComponents (int reqIdvoid Dictionary< int
tickReqParams (int tickerIdvoid double minTick
newsProviders (NewsProvider[] newsProviders)voidreturns array of subscribed API news providers for this user More…
newsArticle (int requestIdvoid int articleType
historicalNews (int requestIdvoid string time
historicalNewsEnd (int requestIdvoid bool hasMore)
headTimestamp (int reqIdvoid string headTimestamp)
Nonereturns beginning of data for contract for specified data typeNone
NoneMore…None
histogramData (int reqIdvoid HistogramEntry[] data)
rerouteMktDataReq (int reqIdvoid int conId
Nonereturns conId and exchange for CFD market data request re-routeNone
NoneMore…None
rerouteMktDepthReq (int reqIdvoid int conId
marketRule (int marketRuleIdvoid PriceIncrement[] priceIncrements)
pnl (int reqIdvoid double dailyPnL
pnlSingle (int reqIdvoid decimal pos
historicalTicks (int reqIdvoid HistoricalTick[] ticks
historicalTicksBidAsk (int reqIdvoid HistoricalTickBidAsk[] ticks
historicalTicksLast (int reqIdvoid HistoricalTickLast[] ticks
tickByTickAllLast (int reqIdvoid int tickType
tickByTickBidAsk (int reqIdvoid long time
tickByTickMidPoint (int reqIdvoid long time
orderBound (long orderIdvoid int apiClientId
completedOrder (Contract contractvoid Order order
completedOrdersEnd ()voidNotifies the end of the completed orders’ reception. More…
replaceFAEnd (int reqIdvoid string text)
wshMetaData (int reqIdvoid string dataJson)
wshEventData (int reqIdvoid string dataJson)
historicalSchedule (int reqIdvoid string startDateTime
userInfo (int reqIdvoid string whiteBrandingId)

Execution Class Reference

Class describing an order’s execution.

NameTypeDescription
OrderIdintThe API client’s order Id. May not be unique to an account.
ClientIdintThe API client identifier which placed the order which originated this execution.
ExecIdstringThe execution’s identifier. Each partial fill has a separate ExecId. A correction is indicated by an ExecId which differs from a previous ExecId in only the digits after the final period
TimestringThe execution’s server time.
AcctNumberstringThe account to which the order was allocated.
ExchangestringThe exchange where the execution took place.
SidestringSpecifies if the transaction was buy or sale BOT for bought
SharesdecimalThe number of shares filled.
PricedoubleThe order’s execution price excluding commissions.
PermIdintThe TWS order identifier. The PermId can be 0 for trades originating outside IB.
LiquidationintIdentifies whether an execution occurred because of an IB-initiated liquidation.
CumQtydecimalCumulative quantity. Used in regular trades
AvgPricedoubleAverage price. Used in regular trades
OrderRefstringThe OrderRef is a user-customizable string that can be set from the API or TWS and will be associated with an order for its lifetime.
EvRulestringThe Economic Value Rule name and the respective optional argument. The two values should be separated by a colon. For example
EvMultiplierdoubleTells you approximately how much the market value of a contract would change if the price were to change by 1. It cannot be used to get market value by multiplying the price by the approximate multiplier.
ModelCodestringmodel code
LastLiquidityLiquidityThe liquidity type of the execution. Requires TWS 968+ and API v973.05+. Python API specifically requires API v973.06+.
PendingPriceRevisionboolpending price revision

Public Member Functions

NameTypeDescription
Equals (object obj)override bool
GetHashCode ()override int

ExecutionCondition Class Reference

This class represents a condition requiring a specific execution event to be fulfilled. Orders can be activated or canceled if a set of given conditions is met. An ExecutionCondition is met whenever a trade occurs on a certain product at the given exchange.

NameTypeDescription
ExchangestringExchange where the symbol needs to be traded.
SecTypestringKind of instrument being monitored.
SymbolstringInstrument’s symbol.

Inheritance diagram for ExecutionCondition:

Public Member Functions

NameTypeDescription
ToString()override stringReturns string to display.
Equals (object obj)override bool
GetHashCode ()override int
Deserialize (IDecoder inStream)override void
Serialize (BinaryWriter outStream)override void

Protected Member Functions

NameTypeDescription
TryParse(string cond)override boolValidates the price condition format is valid.

ExecutionFilter Class Reference

When requesting executions, a filter can be specified to receive only a subset of them

NameTypeDescription
ClientIdintThe API client which placed the order.
AcctCodestringThe account to which the order was allocated to.
TimestringTime from which the executions will be returned yyyymmdd hh:mm:ss Only those executions reported after the specified time will be returned.
SymbolstringThe instrument’s symbol.
SecTypestringThe Contract’s security’s type (i.e. STK
ExchangestringThe exchange at which the execution was produced.
SidestringThe Contract’s side (BUY or SELL)

Public Member Functions

NameTypeDescription
Equals (object obj)override bool
GetHashCode ()override int

HistoricalTick Class Reference

Used when requesting historical tick data with whatToShow = MIDPOINT.

NameTypeDescription
Timelong
Pricedouble
Sizedecimal

HistoricalTickBidAsk Class Reference

Used when requesting historical tick data with whatToShow = BID_ASK.

NameTypeDescription
TimelongThe UNIX timestamp of the historical tick.
TickAttribLastTickAttribLastTick attribs of historical last tick.
PricedoubleThe last price of the historical tick.
SizedecimalThe last size of the historical tick.
ExchangestringThe source exchange of the historical tick.
SpecialConditionsstringThe conditions of the historical tick. Refer to Trade Conditions page for more details

HistoricalTickLast Class Reference

Used when requesting historical tick data with whatToShow = TRADES.

NameTypeDescription
TimelongThe UNIX timestamp of the historical tick.
TickAttribLastTickAttribLastTick attribs of historical last tick.
PricedoubleThe last price of the historical tick.
SizedecimalThe last size of the historical tick.
ExchangestringThe source exchange of the historical tick.
SpecialConditionsstringThe conditions of the historical tick. Refer to Trade Conditions page for more details.

Liquidity Class Reference

Class describing the liquidity type of an execution.

NameTypeDescription
ValueintThe value of the liquidity type.

Public Member Functions

NameTypeDescription
ToString()override stringReturns string to display.

MarginCondition Class Reference

Used with conditional orders to cancel or submit order based on price of an instrument.

NameTypeDescription
Percentoverride integerThe margin cushion percentage available.
IsMoreBooleantd>

Determine if the MarginCondition should trigger while more or less than the percent value.

Order Class Reference

NameTypeDescription
AccountstringThe account the trade will be allocated to.
ActionstringIdentifies the side. Generally available values are BUY and SELL. Additionally, <b>SSHORT</b> and <b>SLONG</b> are available in some institutional-accounts only.
ActiveStartTime = new List()stringDefines the start time of GTC orders.
ActiveStopTimestringDefines the stop time of GTC orders.
AdjustableTrailingUnitintAdjusted Stop orders: specifies where the trailing unit is an amount (set to 0) or a percentage (set to 1)
AdjustedOrderTypestringAdjusted Stop orders: the parent order will be adjusted to the given type when the adjusted trigger price is penetrated.
AdjustedStopLimitPricedoubleAdjusted Stop orders: specifies the stop limit price of the adjusted (STPL LMT) parent.
AdjustedStopPricedoubleAdjusted Stop orders: specifies the stop price of the adjusted (STP) parent.
AdjustedTrailingAmountdoubleAdjusted Stop orders: specifies the trailing amount of the adjusted (TRAIL) parent.
AdvancedErrorOverridestringAccepts a string with parameters obtained from advancedOrderRejectJson.
AlgoIdstringIdentifies orders generated by algorithmic trading.
AlgoParamsListThe list of parameters for the IB algorithm. For more information about IB’s API algorithms
AlgoStrategystringThe algorithm strategy. ArrivalPx – Arrival Price DarkIce – Dark Ice PctVol – Percentage of Volume Twap – TWAP (Time Weighted Average Price) Vwap – VWAP (Volume Weighted Average Price) For more information about IB’s API algorithms
AllOrNoneboolIndicates whether or not all the order has to be filled on a single execution.
AuctionStrategyintFor BOX orders only. Values include: 1 – Match 2 – Improvement 3 – Transparent.
AutoCancelDatestringSpecifies the date to auto cancel the order.
AutoCancelParentboolCancels the parent order if child order was cancelled.
BasisPointsdoubleSpecifies Basis Points for EFP order. The values increment in 0.01% = 1 basis point. For EFP orders only.
BasisPointsTypeintSpecifies the increment of the Basis Points. For EFP orders only.
BlockOrderboolIf set to true
CashQtydoubleThe native cash quantity.
ClearingAccountstringSpecifies the true beneficiary of the order. For IBExecution customers. This value is required for FUT/FOP orders for reporting to the exchange.
ClearingIntentstringFor execution-only clients to know where do they want their shares to be cleared at. Valid values are: IB
ClientIdintThe API client id which placed the order.
CompeteAgainstBestOffsetdoubleDpecifies the offset Off The Midpoint that will be applied to the order. For IBKRATS orders.
ConditionsListConditions determining when the order will be activated or canceled.
ConditionsCancelOrderboolConditions can determine if an order should become active or canceled.
ConditionsIgnoreRthboolIndicates whether or not conditions will also be valid outside Regular Trading Hours.
ContinuousUpdateintSpecifies whether TWS will automatically update the limit price of the order as the underlying price moves. VOL orders only.
DeltadoubleThe stock’s Delta. For orders on BOX only.
DeltaNeutralAuxPricedoubleUse this field to enter a value if the value in the deltaNeutralOrderType field is an order type that requires an Aux price
DeltaNeutralClearingAccountstringSpecifies the beneficiary of the Delta Neutral order.
DeltaNeutralClearingIntentstringSpecifies where the clients want their shares to be cleared at. Must be specified by execution-only clients. Valid values are: IB
DeltaNeutralConIdintThe unique contract identifier specifying the security in Delta Neutral order.
DeltaNeutralDesignatedLocationstringIdentifies third party order origin. Used only when deltaNeutralShortSaleSlot = 2.
DeltaNeutralOpenClosestringSpecifies whether the order is an Open or a Close order and is used when the hedge involves a CFD and and the order is clearing away.
DeltaNeutralOrderTypestringEnter an order type to instruct TWS to submit a delta neutral trade on full or partial execution of the VOL order. VOL orders only. For no hedge delta order to be sent
DeltaNeutralSettlingFirmstringIndicates the firm which will settle the Delta Neutral trade. Institutions only.
DeltaNeutralShortSaleboolUsed when the hedge involves a stock and indicates whether or not it is sold short.
DeltaNeutralShortSaleSlotintIndicates a short sale Delta Neutral order. Has a value of 1 (the clearing broker holds shares) or 2 (delivered from a third party). If you use 2
DesignatedLocationstringFor institutions only. Indicates the location where the shares to short come from. Used only when short sale slot is set to 2 (which means that the shares to short are held elsewhere and not with IB).
DiscretionaryAmtdoubleThe amount off the limit price allowed for discretionary orders.
DiscretionaryUpToLimitPriceboolSet to true to convert order of type ‘Primary Peg’ to ‘D-Peg’.
DisplaySizeintThe publicly disclosed order size
DontUseAutoPriceForHedgeboolDon’t use auto price for hedge.
DurationintSpecifies the duration of the order. Format: yyyymmdd hh:mm:ss TZ. For GTD orders.
ExemptCodeintOnly available with IB Execution-Only accounts with applicable securities. Mark order as exempt from short sale uptick rule.
ExtOperatorStringFollowing CME Rule 576, the ExtOperator field will signify if the unique API operator at the time of trading for order management.
FaGroupstringThe Financial Advisor group the trade will be allocated to. Use an empty string if not applicable.
FaMethodstringThe Financial Advisor allocation method the trade will be allocated to. Use an empty string if not applicable.
FaPercentagestringThe Financial Advisor percentage concerning the trade’s allocation. Use an empty string if not applicable.
FilledQuantitydecimalSpecifies the initial order quantity to be filled.
GoodAfterTimestringSpecifies the date and time after which the order will be active. Format: yyyymmdd hh:mm:ss {optional Timezone}.
GoodTillDatestringThe date and time until the order will be active. You must enter GTD as the time in force to use this string. The trade’s “Good Till Date
HedgeParamstringFor hedge orders. Beta = x for Beta hedge orders
HedgeTypestringFor hedge orders. Possible values include: D – Delta B – Beta F – FX P – Pair
HiddenboolIf set to true, the order will not be visible when viewing the market depth. This option only applies to orders routed to the NASDAQ exchange.
ImbalanceOnlyboolUsed to specify “imbalance only open orders” or “imbalance only closing orders”.
IsOmsContainerboolSet to true to create tickets from API orders when TWS is used as an OMS.
IsPeggedChangeAmountDecreaseboolPegged-to-benchmark orders: indicates whether the order’s pegged price should increase or decreases.
LmtPricedoubleThe LIMIT price. Used for limit
LmtPriceOffsetdoubleAdjusted Stop orders: specifies the price offset for the stop to move in increments.
ManualOrderIndicatorintFollowing CME Rule 576, the ManualOrderIndicator field will signify if an order is manual (1) or automated (0).
ManualOrderTimestringUsed by brokers and advisors when manually entering an order request. Format should be “YYYYMMDD-HH:mm:ss” using UTC as the timezone value.
MidOffsetAtHalfdoubleThis offset is applied when the spread is an odd number of cents wide. This offset must be in half-penny increments. For IBKRATS orders.
MidOffsetAtWholedoubleThis offset is applied when the spread is an even number of cents wide. This offset must be in whole-penny increments or zero. For IBKRATS orders.
Mifid2DecisionAlgostringIdentifies the algorithm responsible for investment decisions within the firm. Orders covered under MiFID 2 must include either Mifid2DecisionMaker or Mifid2DecisionAlgo
Mifid2DecisionMakerstringIdentifies a person as the responsible party for investment decisions within the firm. Orders covered by MiFID 2 (Markets in Financial Instruments Directive 2) must include either Mifid2DecisionMaker or Mifid2DecisionAlgo field (but not both). Requires TWS 969+.
Mifid2ExecutionAlgostringFor MiFID 2 reporting; identifies the algorithm responsible for the execution of a transaction within the firm. Requires TWS 969+.
Mifid2ExecutionTraderstringFor MiFID 2 reporting; identifies a person as the responsible party for the execution of a transaction within the firm. Requires TWS 969+.
MinCompeteSizeintDefines the minimum size to compete. For IBKRATS orders.
MinQtyintIdentifies a minimum quantity order type.
MinTradeQtyintDefines the minimum trade quantity to fill. For IBKRATS orders.
ModelCodestringIs used to place an order to a model. For example
NotHeldboolOrders routed to IBDARK are tagged as “post only” and are held in IB’s order book
OcaGroupstringOne-Cancels-All group identifier.
OcaTypeintTells how to handle remaining orders in an OCA group when one order or part of an order executes. Valid values are: 1 – Cancel all remaining orders with block. 2 – Remaining orders are proportionately reduced in size with block. 3 – Remaining orders are proportionately reduced in size with no block. If you use a value “with block” it gives the order overfill protection. This means that only one order in the group will be routed at a time to remove the possibility of an overfill.
OpenClosestringFor institutional customers only. Valid values are O (open) and C (close). Available for institutional clients to determine if this order is to open or close a position. When Action = “BUY” and OpenClose = “O” this will open a new position. When Action = “BUY” and OpenClose = “C” this will close and existing short position.
OptOutSmartRoutingboolUse to opt out of default SmartRouting for orders routed directly to ASX. This attribute defaults to false unless explicitly set to true. When set to false
OrderComboLegsListList of Per-leg price following the same sequence combo legs are added. The combo price must be left unspecified when using per-leg prices.
OrderIdintThe API client’s order id.
OrderMiscOptions = new List()ListFor internal use only. Use the default value XYZ.
OrderRefstringThe order reference. Intended for institutional customers only
OrderTypestringThe order’s type.
OriginintThe order’s origin. Same as TWS “Origin” column. Identifies the type of customer from which the order originated. Valid values are:0 – Customer 1 – Firm.
OutsideRthboolIf set to true, allows orders to also trigger or fill outside of regular trading hours.
OverridePercentageConstraintsboolOverrides TWS constraints. Precautionary constraints are defined on the TWS Presets page
ParentIdintThe order ID of the parent order, used for bracket and auto trailing stop orders.
ParentPermIdlongParent order Id.
PeggedChangeAmountdoublePegged-to-benchmark orders: amount by which the order’s pegged price should move.
PercentOffsetdoubleThe percent offset amount for relative orders.
PermIdintThe Host order identifier.
PostToAtsintValue must be positive
RandomizePriceboolRandomizes the order’s price. Only for Volatility and Pegged to Volatility orders.
RandomizeSizeboolRandomizes the order’s size. Only for Volatility and Pegged to Volatility orders.
RefFuturesConIdintIdentifies the reference future conId.
ReferenceChangeAmountdoublePegged-to-benchmark orders: the amount the reference contract needs to move to adjust the pegged order.
ReferenceContractIdintPegged-to-benchmark orders: this attribute will contain the conId of the contract against which the order will be pegged.
ReferenceExchangestringPegged-to-benchmark orders: the exchange against which we want to observe the reference contract.
ReferencePriceTypeintSpecifies how you want TWS to calculate the limit price for options
RouteMarketableToBboboolRoutes market order to Best Bid Offer.
Rule80AstringIndividual = ‘I’ Agency = ‘A’ AgentOtherMember = ‘W’ IndividualPTIA = ‘J’ AgencyPTIA = ‘U’ AgentOtherMemberPTIA = ‘M’ IndividualPT = ‘K’ AgencyPT = ‘Y’ AgentOtherMemberPT = ‘N’.
ScaleAutoResetboolRestarts the Scale series if the order is cancelled. For extended scale orders.
ScaleInitFillQtyintSpecifies the initial quantity to be filled. For extended scale orders.
ScaleInitLevelSizeintDefines the size of the first
ScaleInitPositionintThe initial position of the Scale order. For extended scale orders.
ScalePriceAdjustIntervalintSpecifies the interval when the price is adjusted. For extended Scale orders.
ScalePriceAdjustValuedoubleModifies the value of the Scale order. For extended Scale orders.
ScalePriceIncrementdoubleDefines the price increment between scale components. For Scale orders only. This value is compulsory.
ScaleProfitOffsetdoubleSpecifies the offset when to adjust profit. For extended scale orders.
ScaleRandomPercentboolDefines the random percent by which to adjust the position. For extended scale orders.
ScaleSubsLevelSizeintDefines the order size of the subsequent scale order components. For Scale orders only. Used in conjunction with scaleInitLevelSize().
ScaleTablestringThe list of scale orders. Used for scale orders.
SettlingFirmstringIndicates the firm which will settle the trade. Institutions only.
ShareholderstringIdentifies the Shareholder.
ShortSaleSlotintFor institutions only. Valid values are: 1 – Broker holds shares 2 – Shares come from elsewhere.
SmartComboRoutingParamsListAdvanced parameters for Smart combo routing. These features are for both guaranteed and nonguaranteed combination orders routed to Smart
SolicitedboolThe Solicited field should be used for orders initiated or recommended by the broker or adviser that were approved by the client (by phone, email, chat, verbally, etc.) prior to entry. Please note that orders that the adviser or broker placed without specifically discussing with the client are discretionary orders, not solicited.
StartingPricedoubleThe auction’s starting price. For BOX orders only.
StockRangeLowerdoubleThe lower value for the acceptable underlying stock price range. For price improvement option orders on BOX and VOL orders with dynamic management.
StockRangeUpperdoubleThe upper value for the acceptable underlying stock price range. For price improvement option orders on BOX and VOL orders with dynamic management.
StockRefPricedoubleThe stock’s reference price. The reference price is used for VOL orders to compute the limit price sent to an exchange (whether or not Continuous Update is selected)
SweepToFillboolIf set to true
TierSoftDollarTierDefine the Soft Dollar Tier used for the order. Only provided for registered professional advisors and hedge and mutual funds.
TifstringThe time in force. Valid values are: DAY – Valid for the day only. GTC – Good until canceled. The order will continue to work within the system and in the marketplace until it executes or is canceled. GTC orders will be automatically be cancelled under the following conditions: If a corporate action on a security results in a stock split (forward or reverse)
TotalQuantitydecimalThe number of positions being bought/sold.
TrailStopPricedoubleTrail stop price for TRAIL LIMIT orders.
TrailingPercentdoubleSpecifies the trailing amount of a trailing stop order as a percentage. Observe the following guidelines when using the trailingPercent field:
TransmitboolSpecifies whether the order will be transmitted by TWS. If set to false, the order will be created at TWS but will not be sent.
TriggerMethodintSpecifies how Simulated Stop
TriggerPricedoubleAdjusted Stop orders: specifies the trigger price to execute.
UsePriceMgmtAlgoboolSpecifies wether to use Price Management Algo. CTCI users only.
VolatilitydoubleThe option price in volatility
VolatilityTypeintValues include: 1 – Daily Volatility 2 – Annual Volatility.
WhatIfboolAllows to retrieve the commissions and margin information. When placing an order with this attribute set to true
customerAccountStringRequired for Nondisclosed Omnibus Accounts. A unique identifier for each account within the Omnibus structure to signify the account holder being traded. Best practice (Not Required): clients should look to hash this value, using something along the lines of 5 digits of SHA1 of the account number. This should not be implemented for non-omnibus accounts.
isProCustomerBooleanRequired for Nondisclosed Omnibus Accounts Signify whether or not the subaccount is classified as Professional or Non-Professional. This should not be implemented for non-omnibus accounts.

Public Member Functions

NameTypeDescription
Equals (object obj)override bool
GetHashCode ()override int

Static Public Member Functions

NameTypeDescription
CUSTOMER = 0static int
FIRM = 1static int
OPT_UNKNOWN = ‘?’static char
OPT_BROKER_DEALER = ‘b’static char
OPT_CUSTOMER = ‘c’static char
OPT_FIRM = ‘f’static char
OPT_ISEMM = ‘m’static char
OPT_FARMM = ‘n’static char
OPT_SPECIALIST = ‘y’static char
AUCTION_MATCH = 1static int
AUCTION_IMPROVEMENT = 2static int
AUCTION_TRANSPARENT = 3static int
EMPTY_STR = “”static string
COMPETE_AGAINST_BEST_OFFSET_UP_TO_MID = double.PositiveInfinitystatic doublestatic int
FIRM = 1static int
OPT_UNKNOWN = ‘?’static char
OPT_BROKER_DEALER = ‘b’static char
OPT_CUSTOMER = ‘c’static char
OPT_FIRM = ‘f’static char
OPT_ISEMM = ‘m’static char
OPT_FARMM = ‘n’static char
OPT_SPECIALIST = ‘y’static char
AUCTION_MATCH = 1static int
AUCTION_IMPROVEMENT = 2static int
AUCTION_TRANSPARENT = 3static int
EMPTY_STR = “”static string
COMPETE_AGAINST_BEST_OFFSET_UP_TO_MID = double.PositiveInfinitystatic doubleNone

OrderAllocation Class Reference

The OrderAllocation class to denote an advisor’s allocations while trading subaccounts.

NameTypeDescription
AccountStringReferences the Account ID, i.e. U1234567, being allocated to.
PositionDecimalReferences the current position of the account being allocated to.
PositionDesiredDecimalStates the full position increase intended by the current trade.
PosiionAfterDecimalReferences the increase to position from the current trade. Unless the order is partially filled, this should reflect the PositionDesired value.
DesiredAllocQtyDecimalReference the quantity to increase by based on allocation.
AllowedAllocQtyDecimalReferences the maximum allowed quantity increase.
IsMonetaryBooleanDenotes whether the order is a monetary allocation (true) or whole share allocation (false).

OrderCancel Class Reference

The Order cancellation parameters when cancelling an order.

NameTypeDescription
extOperatorstringFollowing CME Rule 576, the ExtOperator field will signify if the unique API operator at the time of trading for order management.
manualOrderIndicatorintFollowing CME Rule 576, the ManualOrderIndicator field will signify if an order is manual (1) or automated (0).
manualOrderCancelTimestringUsed by brokers and advisors when manually entering an order cancellation request. Format should be “YYYYMMDD-HH:mm:ss” using UTC as the timezone value.

OrderComboLeg Class Reference

Allows to specify a price on an order’s leg.

NameTypeDescription
PricedoubleThe order leg’s price.

Public Member Functions

NameTypeDescription
OrderComboLeg (double p_price)override bool
GetHashCode ()override int

OrderState Class Reference

Provides an active order’s current state.

NameTypeDescription
StatusstringThe order’s current status.
InitMarginBeforestringThe account’s current initial margin.
MaintMarginBeforestringThe account’s current maintenance margin.
EquityWithLoanBeforestringThe account’s current equity with loan.
InitMarginChangestringThe change of the account’s initial margin.
MaintMarginChangestringThe change of the account’s maintenance margin.
EquityWithLoanChangestringThe change of the account’s equity with loan.
InitMarginAfterstringThe order’s impact on the account’s initial margin.
MaintMarginAfterstringThe order’s impact on the account’s maintenance margin.
EquityWithLoanAfterstringShows the impact the order would have on the account’s equity with loan.
InitMarginBeforeOutsideRTHfloatThe account’s expected initial margin outside of regular trading hours.
MaintMarginBeforeOutsideRTHfloatThe account’s expected maintenance margin outside of regular trading hours.
EquityWithLoanBeforeOutsideRTHfloatThe account’s expected equity with loan outside of regular trading hours.
InitMarginChangeOutsideRTHfloatThe expected change of the account’s initial margin outside of regular trading hours.
MaintMarginChangeOutsideRTHfloatThe expected change of the account’s maintenance margin outside of regular trading hours.
EquityWithLoanChangeOutsideRTHfloatThe expected change of the account’s equity with loan outside of regular trading hours.
InitMarginAfterOutsideRTHfloatThe order’s expected impact on the account’s initial margin outside of regular trading hours.
MaintMarginAfterOutsideRTHfloatThe order’s expected impact on the account’s maintenance margin outside of regular trading hours.
EquityWithLoanAfterOutsideRTHfloatShows the expected impact the order would have on the account’s equity with loan outside of regular trading hours.
CommissiondoubleThe order’s generated commission.
MinCommissiondoubleThe execution’s minimum commission.
MaxCommissiondoubleThe executions maximum commission.
CommissionCurrencystringThe generated commission currency.
WarningTextstringIf the order is warranted, a descriptive message will be provided.
CompletedTimestring
CompletedStatusstring

Public Member Functions

NameTypeDescription
OrderState (string status, string initMarginBefore, string maintMarginBefore, string equityWithLoanBefore, string initMarginChange, string maintMarginChange, string equityWithLoanChange, string initMarginAfter, string maintMarginAfter, string equityWithLoanAfter, double commission, double minCommission, double maxCommission, string commissionCurrency, string warningText, string completedTime, string completedStatus)override bool
Equals (object obj)override bool
GetHashCode ()override int

PercentChangeCondition Class Reference

Used with conditional orders to place or submit an order based on a percentage change of an instrument to the last close price.

NameTypeDescription
Valueoverride string
ChangePercentdoublePercentage Change field used in conditional order logic.

Inheritance diagram for PercentChangeCondition:

PriceCondition Class Reference

Used with conditional orders to cancel or submit order based on price of an instrument.

NameTypeDescription
Valueoverride string
PricestringPrice field used in conditional order logic.
TriggerMethodTriggerMethod

Public Member Functions

NameTypeDescription
ToString()override stringReturns string to display.
Equals (object obj)override bool
GetHashCode ()override int
Deserialize (IDecoder inStream)override void
Serialize (BinaryWriter outStream)override void

Protected Member Functions

NameTypeDescription
TryParse(string cond)override boolValidates the price condition format is valid.

ScannerSubscription Class Reference

Defines a market scanner request.

NameTypeDescription
NumberOfRowsint
Instrument = -1string
LocationCodestring
ScanCodestring
AbovePricedouble
BelowPrice = double.MaxValuedouble
AboveVolume = double.MaxValueint
AverageOptionVolumeAbove = int.MaxValueint
MarketCapAbove = int.MaxValuedouble
MarketCapBelow = double.MaxValuedouble
MoodyRatingAbove = double.MaxValuestring
MoodyRatingBelowstring
SpRatingAbovestring
SpRatingBelowstring
MaturityDateAbovestring
MaturityDateBelowstring
CouponRateAbovedouble
CouponRateBelow = double.MaxValuedouble
ExcludeConvertible = double.MaxValuebool
ScannerSettingPairsstring
StockTypeFilterstring

SoftDollarTier Class Reference

A container for storing Soft Dollar Tier information.

NameTypeDescription
NamestringThe name of the Soft Dollar Tier.
ValuestringThe value of the Soft Dollar Tier.
DisplayNamestringThe display name of the Soft Dollar Tier.

Public Member Functions

NameTypeDescription
Equals (object obj)override bool
GetHashCode ()override int
ToString()override stringReturns string to display.

Static Public Member Functions

NameTypeDescription
operator== (SoftDollarTier leftstatic bool, SoftDollarTier right)
operator!= (SoftDollarTier leftstatic bool, SoftDollarTier right)

TagValue Class Reference

Convenience class to define key-value pairs.

NameTypeDescription
Tagstring
Valuestring

Public Member Functions

NameTypeDescription
Equals (object other)override bool
GetHashCode ()override int

TickAttrib Class Reference

Tick attributes that describes additional information for price ticks

NameTypeDescription
CanAutoExecuteboolUsed with tickPrice callback from reqMktData. Specifies whether the price tick is available for automatic execution (1) or not (0).
PastLimitboolUsed with tickPrice to indicate if the bid price is lower than the day’s lowest value or the ask price is higher than the highest ask.
PreOpenboolIndicates whether the bid/ask price tick is from pre-open session.
UnreportedboolUsed with tick-by-tick data to indicate if a trade is classified as ‘unreportable’ (odd lots
BidPastLowboolUsed with real time tick-by-tick. Indicates if bid is lower than day’s lowest low.
AskPastHighboolUsed with real time tick-by-tick. Indicates if ask is higher than day’s highest ask.

Public Member Functions

NameTypeDescription
ToString()override stringReturns string to display.

TimeCondition Class Reference

Time condition used in conditional orders to submit or cancel orders at specified time.

NameTypeDescription
Valueoverride string
TimestringTime field used in conditional order logic. Valid format: YYYYMMDD HH:MM:SS.

Inheritance diagram for TimeCondition:

Public Member Functions

NameTypeDescription
ToString()override stringReturns string to display.

VolumeCondition Class Reference

Used with conditional orders to submit or cancel an order based on a specified volume change in a security.

NameTypeDescription
Valueoverride string
Volumeint

Inheritance diagram for VolumeCOndition:

WshEventData Class Reference

Class used to define the parameters for the EClient::reqWshEventData query to filter results.

The beginning of your request formatting. Values should be represented like “YYYYMMDD”.

NameTypeDescription
ConIdintContract identifier used to specify an unique contract
FilterstringA JSON formatted string containing a minimum of string Country, and array watchlist tags. In addition, a unique filter may be specified as “true” in order to receive a specific filter. Filter values are returned from the wshMetaData function.
FillWatchlistbooleanDefines
FillPortfolioboolean
FillCompetitorsboolean
StartDatestring
EndDatestringThe end of your request formatting. Values should be represented like “YYYYMMDD”.
TotalLimitintSpecify the maximum number of results that can be returned. A maximum of

IBKR Campus Newsletters

This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.