ib-underscore-async-api.md
Release 2.1.0.
Also see the official Python API documentation from IB.
High-level interface to Interactive Brokers.
class ib_async.ib.StartupFetch(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]POSITIONS = 1ORDERS_OPEN = 2ORDERS_COMPLETE = 4ACCOUNT_UPDATES = 8SUB_ACCOUNT_UPDATES = 16EXECUTIONS = 32class ib_async.ib.IB(defaults=IBDefaults(emptyPrice=-1, emptySize=0, unset=nan, timezone=datetime.timezone.utc))[source]
Provides both a blocking and an asynchronous interface to the IB API, using asyncio networking and event loop.
The IB class offers direct access to the current state, such as orders, executions, positions, tickers etc. This state is automatically kept in sync with the TWS/IBG application.
This class has most request methods of EClient, with the same names and parameters (except for the reqId parameter which is not needed anymore). Request methods that return a result come in two versions:
Blocking: Will block until complete and return the result. The current state will be kept updated while the request is ongoing;
Asynchronous: All methods that have the “Async” postfix. Implemented as coroutines or methods that return a Future and intended for advanced users.
The One Rule:
While some of the request methods are blocking from the perspective of the user, the framework will still keep spinning in the background and handle all messages received from TWS/IBG. It is important to not block the framework from doing its work. If, for example, the user code spends much time in a calculation, or uses time.sleep() with a long delay, the framework will stop spinning, messages accumulate and things may go awry.
The one rule when working with the IB class is therefore that
user code may not block for too long.
To be clear, the IB request methods are okay to use and do not count towards the user operation time, no matter how long the request takes to finish.
So what is “too long”? That depends on the situation. If, for example, the timestamp of tick data is to remain accurate within a millisecond, then the user code must not spend longer than a millisecond. If, on the other extreme, there is very little incoming data and there is no desire for accurate timestamps, then the user code can block for hours.
If a user operation takes a long time then it can be farmed out to a different process. Alternatively the operation can be made such that it periodically calls IB.sleep(0); This will let the framework handle any pending work and return when finished. The operation should be aware that the current state may have been updated during the sleep(0) call.
For introducing a delay, never use time.sleep() but use sleep() instead.
Parameters:
RequestTimeout (float) – Timeout (in seconds) to wait for a blocking request to finish before raising asyncio.TimeoutError. The default value of 0 will wait indefinitely. Note: This timeout is not used for the *Async methods.
RaiseRequestErrors (bool) –
MaxSyncedSubAccounts (int) – Do not use sub-account updates if the number of sub-accounts exceeds this number (50 by default).
TimezoneTWS (str) – Specifies what timezone TWS (or gateway) is using. The default is to assume local system timezone.
Events:
connectedEvent (): Is emitted after connecting and synchronzing with TWS/gateway.
disconnectedEvent (): Is emitted after disconnecting from TWS/gateway.
updateEvent (): Is emitted after a network packet has been handled.
pendingTickersEvent (tickers: Set[Ticker]): Emits the set of tickers that have been updated during the last update and for which there are new ticks, tickByTicks or domTicks.
barUpdateEvent (bars: BarDataList, hasNewBar: bool): Emits the bar list that has been updated in real time. If a new bar has been added then hasNewBar is True, when the last bar has changed it is False.
newOrderEvent (trade: Trade): Emits a newly placed trade.
orderModifyEvent (trade: Trade): Emits when order is modified.
cancelOrderEvent (trade: Trade): Emits a trade directly after requesting for it to be cancelled.
openOrderEvent (trade: Trade): Emits the trade with open order.
orderStatusEvent (trade: Trade): Emits the changed order status of the ongoing trade.
execDetailsEvent (trade: Trade, fill: Fill): Emits the fill together with the ongoing trade it belongs to.
commissionReportEvent (trade: Trade, fill: Fill, report: CommissionReport): The commission report is emitted after the fill that it belongs to.
updatePortfolioEvent (item: PortfolioItem): A portfolio item has changed.
positionEvent (position: Position): A position has changed.
accountValueEvent (value: AccountValue): An account value has changed.
accountSummaryEvent (value: AccountValue): An account value has changed.
pnlEvent (entry: PnL): A profit- and loss entry is updated.
pnlSingleEvent (entry: PnLSingle): A profit- and loss entry for a single position is updated.
tickNewsEvent (news: NewsTick): Emit a new news headline.
newsBulletinEvent (bulletin: NewsBulletin): Emit a new news bulletin.
scannerDataEvent (data: ScanDataList): Emit data from a scanner subscription.
wshMetaEvent (dataJson: str): Emit WSH metadata.
wshEvent (dataJson: str): Emit WSH event data (such as earnings dates, dividend dates, options expiration dates, splits, spinoffs and conferences).
errorEvent (reqId: int, errorCode: int, errorString: str, contract: Contract): Emits the reqId/orderId and TWS error code and string (see https://interactivebrokers.github.io/tws-api/message_codes.html) together with the contract the error applies to (or None if no contract applies).
timeoutEvent (idlePeriod: float): Is emitted if no data is received for longer than the timeout period specified with setTimeout(). The value emitted is the period in seconds since the last update.
Note that it is not advisable to place new requests inside an event handler as it may lead to too much recursion.
events = ('connectedEvent', 'disconnectedEvent', 'updateEvent', 'pendingTickersEvent', 'barUpdateEvent', 'newOrderEvent', 'orderModifyEvent', 'cancelOrderEvent', 'openOrderEvent', 'orderStatusEvent', 'execDetailsEvent', 'commissionReportEvent', 'updatePortfolioEvent', 'positionEvent', 'accountValueEvent', 'accountSummaryEvent', 'pnlEvent', 'pnlSingleEvent', 'scannerDataEvent', 'tickNewsEvent', 'newsBulletinEvent', 'wshMetaEvent', 'wshEvent', 'errorEvent', 'timeoutEvent')RequestTimeout_: float_ = 0RaiseRequestErrors_: bool_ = FalseMaxSyncedSubAccounts_: int_ = 50TimezoneTWS_: str_ = ''connect(host='127.0.0.1', port=7497, clientId=1, timeout=4, readonly=False, account='', raiseSyncErrors=False, fetchFields=<StartupFetch.POSITIONS|ORDERS_OPEN|ORDERS_COMPLETE|ACCOUNT_UPDATES|SUB_ACCOUNT_UPDATES|EXECUTIONS: 63>)[source]
Connect to a running TWS or IB gateway application. After the connection is made the client is fully synchronized and ready to serve requests.
This method is blocking.
Parameters:
host (str) – Host name or IP address.
port (int) – Port number.
clientId (int) – ID number to use for this client; must be unique per connection. Setting clientId=0 will automatically merge manual TWS trading with this client.
timeout (float) – If establishing the connection takes longer than timeout seconds then the asyncio.TimeoutError exception is raised. Set to 0 to disable timeout.
readonly (bool) – Set to True when API is in read-only mode.
account (str) – Main account to receive updates for.
raiseSyncErrors (bool) –
Disconnect from a TWS or IB gateway application. This will clear all session state.
Return type:
Is there an API connection to TWS or IB gateway?
Return type:
static run(*, timeout=None)
By default run the event loop forever.
When awaitables (like Tasks, Futures or coroutines) are given then run the event loop until each has completed and return their results.
An optional timeout (in seconds) can be given that will raise asyncio.TimeoutError if the awaitables are not ready within the timeout period.
static schedule(callback, *args)
Schedule the callback to be run at the given time with the given arguments. This will return the Event Handle.
Parameters:
time (time | datetime) – Time to run callback. If given as datetime.time then use today as date.
callback (Callable) – Callable scheduled to run.
args – Arguments for to call callback with.
static sleep()
Wait for the given amount of seconds while everything still keeps processing in the background. Never use time.sleep().
Parameters:
secs (float) – Time in seconds to wait.
Return type:
static timeRange(end, step)
Iterator that waits periodically until certain time points are reached while yielding those time points.
Parameters:
start (time | datetime) – Start time, can be specified as datetime.datetime, or as datetime.time in which case today is used as the date
end (time | datetime) – End time, can be specified as datetime.datetime, or as datetime.time in which case today is used as the date
step (float) – The number of seconds of each period
Return type:
static timeRangeAsync(end, step)
Async version of timeRange().
Return type:
static waitUntil()
Wait until the given time t is reached.
Parameters:
t (time | datetime) – The time t can be specified as datetime.datetime, or as datetime.time in which case today is used as the date.
Return type:
waitOnUpdate(timeout=0)[source]
Wait on any new update to arrive from the network.
Parameters:
timeout (float) – Maximum time in seconds to wait. If 0 then no timeout is used.
Note
A loop with waitOnUpdate should not be used to harvest tick data from tickers, since some ticks can go missing. This happens when multiple updates occur almost simultaneously; The ticks from the first update are then cleared. Use events instead to prevent this.
Return type:
Returns:
True if not timed-out, False otherwise.
loopUntil(condition=None, timeout=0)[source]
Iterate until condition is met, with optional timeout in seconds. The yielded value is that of the condition or False when timed out.
Parameters:
condition – Predicate function that is tested after every network
update.
timeout (float) – Maximum time in seconds to wait. If 0 then no timeout is used.
Return type:
setTimeout(timeout=60)[source]
Set a timeout for receiving messages from TWS/IBG, emitting timeoutEvent if there is no incoming data for too long.
The timeout fires once per connected session but can be set again after firing or after a reconnect.
Parameters:
timeout (float) – Timeout in seconds.
List of account names.
Return type:
accountValues(account='')[source]
List of account values for the given account, or of all accounts if account is left blank.
Parameters:
account (str) – If specified, filter for this account name.
Return type:
accountSummary(account='')[source]
List of account values for the given account, or of all accounts if account is left blank.
This method is blocking on first run, non-blocking after that.
Parameters:
account (str) – If specified, filter for this account name.
Return type:
portfolio(account='')[source]
List of portfolio items for the given account, or of all retrieved portfolio items if account is left blank.
Parameters:
account (str) – If specified, filter for this account name.
Return type:
positions(account='')[source]
List of positions for the given account, or of all accounts if account is left blank.
Parameters:
account (str) – If specified, filter for this account name.
Return type:
pnl(account='', modelCode='')[source]
List of subscribed PnL objects (profit and loss), optionally filtered by account and/or modelCode.
The PnL objects are kept live updated.
Parameters:
account – If specified, filter for this account name.
modelCode – If specified, filter for this account model.
Return type:
pnlSingle(account='', modelCode='', conId=0)[source]
List of subscribed PnLSingle objects (profit and loss for single positions).
The PnLSingle objects are kept live updated.
Parameters:
account (str) – If specified, filter for this account name.
modelCode (str) – If specified, filter for this account model.
conId (int) – If specified, filter for this contract ID.
Return type:
List of all order trades from this session.
Return type:
List of all open order trades.
Return type:
List of all orders from this session.
Return type:
List of all open orders.
Return type:
List of all fills from this session.
Return type:
List of all executions from this session.
Return type:
Get ticker of the given contract. It must have been requested before with reqMktData with the same contract object. The ticker may not be ready yet if called directly after reqMktData().
Parameters:
contract (Contract) – Contract to get ticker for.
Return type:
Get a list of all tickers.
Return type:
Get a list of all tickers that have pending ticks or domTicks.
Return type:
Get a list of all live updated bars. These can be 5 second realtime bars or live updated historical bars.
Return type:
list[BarDataList | RealTimeBarList]
List of ticks with headline news. The article itself can be retrieved with reqNewsArticle().
Return type:
List of IB news bulletins.
Return type:
reqTickers(*contracts, regulatorySnapshot=False)[source]
Request and return a list of snapshot tickers. The list is returned when all tickers are ready.
This method is blocking.
Parameters:
contracts (Contract) – Contracts to get tickers for.
regulatorySnapshot (bool) – Request NBBO snapshots (may incur a fee).
Return type:
qualifyContracts(*contracts)[source]
Fully qualify the given contracts in-place. This will fill in the missing fields in the contract, especially the conId.
Returns a list of contracts that have been successfully qualified.
This method is blocking.
Parameters:
contracts (Contract) – Contracts to qualify.
Return type:
bracketOrder(action, quantity, limitPrice, takeProfitPrice, stopLossPrice, **kwargs)[source]
Create a limit order that is bracketed by a take-profit order and a stop-loss order. Submit the bracket like:
foroinbracket:ib.placeOrder(contract,o)
https://interactivebrokers.github.io/tws-api/bracket_order.html
Parameters:
action (str) – ‘BUY’ or ‘SELL’.
quantity (float) – Size of order.
limitPrice (float) – Limit price of entry order.
takeProfitPrice (float) – Limit price of profit order.
stopLossPrice (float) – Stop price of loss order.
Return type:
static oneCancelsAll(orders, ocaGroup, ocaType)[source]
Place the trades in the same One Cancels All (OCA) group.
https://interactivebrokers.github.io/tws-api/oca.html
Parameters:
orders (list[Order]) – The orders that are to be placed together.
Return type:
whatIfOrder(contract, order)[source]
Retrieve commission and margin impact without actually placing the order. The given order will not be modified in any way.
This method is blocking.
Parameters:
Return type:
placeOrder(contract, order)[source]
Place a new order or modify an existing order. Returns a Trade that is kept live updated with status changes, fills, etc.
Parameters:
Return type:
cancelOrder(order, manualCancelOrderTime='')[source]
Cancel the order and return the Trade it belongs to.
Parameters:
Return type:
Cancel all active trades including those placed by other clients or TWS/IB gateway.
Request TWS current time.
This method is blocking.
Return type:
reqAccountUpdates(account='')[source]
This is called at startup - no need to call again.
Request account and portfolio values of the account and keep updated. Returns when both account values and portfolio are filled.
This method is blocking.
Parameters:
account (str) – If specified, filter for this account name.
reqAccountUpdatesMulti(account='', modelCode='')[source]
It is recommended to use accountValues() instead.
Request account values of multiple accounts and keep updated.
This method is blocking.
Parameters:
account (str) – If specified, filter for this account name.
modelCode (str) – If specified, filter for this account model.
It is recommended to use accountSummary() instead.
Request account values for all accounts and keep them updated. Returns when account summary is filled.
This method is blocking.
reqAutoOpenOrders(autoBind=True)[source]
Bind manual TWS orders so that they can be managed from this client. The clientId must be 0 and the TWS API setting “Use negative numbers to bind automatic orders” must be checked.
This request is automatically called when clientId=0.
https://interactivebrokers.github.io/tws-api/open_orders.htmlhttps://interactivebrokers.github.io/tws-api/modifying_orders.html
Parameters:
autoBind (bool) – Set binding on or off.
Request and return a list of open orders.
This method can give stale information where a new open order is not reported or an already filled or cancelled order is reported as open. It is recommended to use the more reliable and much faster openTrades() or openOrders() methods instead.
This method is blocking.
Return type:
Request and return a list of all open orders over all clients. Note that the orders of other clients will not be kept in sync, use the master clientId mechanism instead to see other client’s orders that are kept in sync.
Return type:
reqCompletedOrders(apiOnly)[source]
Request and return a list of completed trades.
Parameters:
apiOnly (bool) – Request only API orders (not manually placed TWS orders).
Return type:
reqExecutions(execFilter=None)[source]
It is recommended to use fills() or executions() instead.
Request and return a list of fills.
This method is blocking.
Parameters:
execFilter (ExecutionFilter | None) – If specified, return executions that match the filter.
Return type:
It is recommended to use positions() instead.
Request and return a list of positions for all accounts.
This method is blocking.
Return type:
reqPnL(account, modelCode='')[source]
Start a subscription for profit and loss events.
Returns a PnL object that is kept live updated. The result can also be queried from pnl().
https://interactivebrokers.github.io/tws-api/pnl.html
Parameters:
account (str) – Subscribe to this account.
modelCode (str) – If specified, filter for this account model.
Return type:
cancelPnL(account, modelCode='')[source]
Cancel PnL subscription.
Parameters:
account – Cancel for this account.
modelCode (str) – If specified, cancel for this account model.
reqPnLSingle(account, modelCode, conId)[source]
Start a subscription for profit and loss events for single positions.
Returns a PnLSingle object that is kept live updated. The result can also be queried from pnlSingle().
https://interactivebrokers.github.io/tws-api/pnl.html
Parameters:
account (str) – Subscribe to this account.
modelCode (str) – Filter for this account model.
conId (int) – Filter for this contract ID.
Return type:
cancelPnLSingle(account, modelCode, conId)[source]
Cancel PnLSingle subscription for the given account, modelCode and conId.
Parameters:
account (str) – Cancel for this account name.
modelCode (str) – Cancel for this account model.
conId (int) – Cancel for this contract ID.
reqContractDetails(contract)[source]
Get a list of contract details that match the given contract. If the returned list is empty then the contract is not known; If the list has multiple values then the contract is ambiguous.
The fully qualified contract is available in the the ContractDetails.contract attribute.
This method is blocking.
https://interactivebrokers.github.io/tws-api/contract_details.html
Parameters:
contract (Contract) – The contract to get details for.
Return type:
reqMatchingSymbols(pattern)[source]
Request contract descriptions of contracts that match a pattern.
This method is blocking.
https://interactivebrokers.github.io/tws-api/matching_symbols.html
Parameters:
pattern (str) – The first few letters of the ticker symbol, or for longer strings a character sequence matching a word in the security name.
Return type:
reqMarketRule(marketRuleId)[source]
Request price increments rule.
https://interactivebrokers.github.io/tws-api/minimum_increment.html
Parameters:
marketRuleId (int) – ID of market rule. The market rule IDs for a contract can be obtained via reqContractDetails() from ContractDetails.marketRuleIds, which contains a comma separated string of market rule IDs.
Return type:
reqRealTimeBars(contract, barSize, whatToShow, useRTH, realTimeBarsOptions=[])[source]
Request realtime 5 second bars.
https://interactivebrokers.github.io/tws-api/realtime_bars.html
Parameters:
contract (Contract) – Contract of interest.
barSize (int) – Must be 5.
whatToShow (str) – Specifies the source for constructing bars. Can be ‘TRADES’, ‘MIDPOINT’, ‘BID’ or ‘ASK’.
useRTH (bool) – If True then only show data from within Regular Trading Hours, if False then show all data.
Return type:
cancelRealTimeBars(bars)[source]
Cancel the realtime bars subscription.
Parameters:
bars (RealTimeBarList) – The bar list that was obtained from reqRealTimeBars.
reqHistoricalData(contract, endDateTime, durationStr, barSizeSetting, whatToShow, useRTH, formatDate=1, keepUpToDate=False, chartOptions=[], timeout=60)[source]
Request historical bar data.
This method is blocking.
https://interactivebrokers.github.io/tws-api/historical_bars.html
Parameters:
contract (Contract) – Contract of interest.
endDateTime (datetime | date | str | None) – Can be set to ‘’ to indicate the current time, or it can be given as a datetime.date or datetime.datetime, or it can be given as a string in ‘yyyyMMdd HH:mm:ss’ format. If no timezone is given then the TWS login timezone is used.
durationStr (str) – Time span of all the bars. Examples: ‘60 S’, ‘30 D’, ‘13 W’, ‘6 M’, ‘10 Y’.
barSizeSetting (str) – Time period of one bar. Must be one of: ‘1 secs’, ‘5 secs’, ‘10 secs’ 15 secs’, ‘30 secs’, ‘1 min’, ‘2 mins’, ‘3 mins’, ‘5 mins’, ‘10 mins’, ‘15 mins’, ‘20 mins’, ‘30 mins’, ‘1 hour’, ‘2 hours’, ‘3 hours’, ‘4 hours’, ‘8 hours’, ‘1 day’, ‘1 week’, ‘1 month’.
whatToShow (str) – Specifies the source for constructing bars. Must be one of: ‘TRADES’, ‘MIDPOINT’, ‘BID’, ‘ASK’, ‘BID_ASK’, ‘ADJUSTED_LAST’, ‘HISTORICAL_VOLATILITY’, ‘OPTION_IMPLIED_VOLATILITY’, ‘REBATE_RATE’, ‘FEE_RATE’, ‘YIELD_BID’, ‘YIELD_ASK’, ‘YIELD_BID_ASK’, ‘YIELD_LAST’. For ‘SCHEDULE’ use reqHistoricalSchedule().
useRTH (bool) – If True then only show data from within Regular Trading Hours, if False then show all data.
formatDate (int) – For an intraday request setting to 2 will cause the returned date fields to be timezone-aware datetime.datetime with UTC timezone, instead of local timezone as used by TWS.
keepUpToDate (bool) – If True then a realtime subscription is started to keep the bars updated; endDateTime must be set empty (‘’) then.
timeout (float) – Timeout in seconds after which to cancel the request and return an empty bar series. Set to 0 to wait indefinitely.
Return type:
cancelHistoricalData(bars)[source]
Cancel the update subscription for the historical bars.
Parameters:
bars (BarDataList) – The bar list that was obtained from reqHistoricalData with a keepUpToDate subscription.
reqHistoricalSchedule(contract, numDays, endDateTime='', useRTH=True)[source]
Request historical schedule.
This method is blocking.
Parameters:
contract (Contract) – Contract of interest.
numDays (int) – Number of days.
endDateTime (datetime | date | str | None) – Can be set to ‘’ to indicate the current time, or it can be given as a datetime.date or datetime.datetime, or it can be given as a string in ‘yyyyMMdd HH:mm:ss’ format. If no timezone is given then the TWS login timezone is used.
useRTH (bool) – If True then show schedule for Regular Trading Hours, if False then for extended hours.
Return type:
reqHistoricalTicks(contract, startDateTime, endDateTime, numberOfTicks, whatToShow, useRth, ignoreSize=False, miscOptions=[])[source]
Request historical ticks. The time resolution of the ticks is one second.
This method is blocking.
https://interactivebrokers.github.io/tws-api/historical_time_and_sales.html
Parameters:
contract (Contract) – Contract to query.
startDateTime (str | date) – Can be given as a datetime.date or datetime.datetime, or it can be given as a string in ‘yyyyMMdd HH:mm:ss’ format. If no timezone is given then the TWS login timezone is used.
endDateTime (str | date) – One of startDateTime or endDateTime can be given, the other must be blank.
numberOfTicks (int) – Number of ticks to request (1000 max). The actual result can contain a bit more to accommodate all ticks in the latest second.
whatToShow (str) – One of ‘Bid_Ask’, ‘Midpoint’ or ‘Trades’.
useRTH – If True then only show data from within Regular Trading Hours, if False then show all data.
ignoreSize (bool) – Ignore bid/ask ticks that only update the size.
Return type:
reqMarketDataType(marketDataType)[source]
Set the market data type used for reqMktData().
Parameters:
marketDataType (int) –
One of:
1 = Live
2 = Frozen
3 = Delayed
4 = Delayed frozen
https://interactivebrokers.github.io/tws-api/market_data_type.html
reqHeadTimeStamp(contract, whatToShow, useRTH, formatDate=1)[source]
Get the datetime of earliest available historical data for the contract.
Parameters:
contract (Contract) – Contract of interest.
useRTH (bool) – If True then only show data from within Regular Trading Hours, if False then show all data.
formatDate (int) – If set to 2 then the result is returned as a timezone-aware datetime.datetime with UTC timezone.
Return type:
reqMktData(contract, genericTickList='', snapshot=False, regulatorySnapshot=False, mktDataOptions=[])[source]
Subscribe to tick data or request a snapshot. Returns the Ticker that holds the market data. The ticker will initially be empty and gradually (after a couple of seconds) be filled.
https://interactivebrokers.github.io/tws-api/md_request.html
Parameters:
contract (Contract) – Contract of interest.
genericTickList (str) –
snapshot (bool) – If True then request a one-time snapshot, otherwise subscribe to a stream of realtime tick data.
regulatorySnapshot (bool) – Request NBBO snapshot (may incur a fee).
Return type:
cancelMktData(contract)[source]
Unsubscribe from realtime streaming tick data.
Parameters:
contract (Contract) – The contract of a previously subscribed ticker to unsubscribe.
Return type:
Returns:
Returns True if cancel was successful. Returns False if ‘contract’ was not found.
reqTickByTickData(contract, tickType, numberOfTicks=0, ignoreSize=False)[source]
Subscribe to tick-by-tick data and return the Ticker that holds the ticks in ticker.tickByTicks.
https://interactivebrokers.github.io/tws-api/tick_data.html
Parameters:
contract (Contract) – Contract of interest.
tickType (str) – One of ‘Last’, ‘AllLast’, ‘BidAsk’ or ‘MidPoint’.
numberOfTicks (int) – Number of ticks or 0 for unlimited.
ignoreSize (bool) – Ignore bid/ask ticks that only update the size.
Return type:
cancelTickByTickData(contract, tickType)[source]
Unsubscribe from tick-by-tick data
Parameters:
contract (Contract) – The contract of a previously subscribed ticker to unsubscribe.
Return type:
Returns:
Returns True if cancel was successful. Returns False if ‘contract’ was not found.
reqSmartComponents(bboExchange)[source]
Obtain mapping from single letter codes to exchange names.
Note: The exchanges must be open when using this request, otherwise an empty list is returned.
Return type:
reqMktDepthExchanges()[source]
Get those exchanges that have have multiple market makers (and have ticks returned with marketMaker info).
Return type:
reqMktDepth(contract, numRows=5, isSmartDepth=False, mktDepthOptions=None)[source]
Subscribe to market depth data (a.k.a. DOM, L2 or order book).
https://interactivebrokers.github.io/tws-api/market_depth.html
Parameters:
contract (Contract) – Contract of interest.
numRows (int) – Number of depth level on each side of the order book (5 max).
isSmartDepth (bool) – Consolidate the order book across exchanges.
mktDepthOptions – Unknown.
Return type:
Returns:
The Ticker that holds the market depth in ticker.domBids and ticker.domAsks and the list of MktDepthData in ticker.domTicks.
cancelMktDepth(contract, isSmartDepth=False)[source]
Unsubscribe from market depth data.
Parameters:
contract (Contract) – The exact contract object that was used to subscribe with.
reqHistogramData(contract, useRTH, period)[source]
Request histogram data.
This method is blocking.
https://interactivebrokers.github.io/tws-api/histograms.html
Parameters:
contract (Contract) – Contract to query.
useRTH (bool) – If True then only show data from within Regular Trading Hours, if False then show all data.
period (str) – Period of which data is being requested, for example ‘3 days’.
Return type:
reqFundamentalData(contract, reportType, fundamentalDataOptions=[])[source]
Get fundamental data of a contract in XML format.
This method is blocking.
https://interactivebrokers.github.io/tws-api/fundamentals.html
Parameters:
Return type:
reqScannerData(subscription, scannerSubscriptionOptions=[], scannerSubscriptionFilterOptions=[])[source]
Do a blocking market scan by starting a subscription and canceling it after the initial list of results are in.
This method is blocking.
https://interactivebrokers.github.io/tws-api/market_scanners.html
Parameters:
subscription (ScannerSubscription) – Basic filters.
scannerSubscriptionFilterOptions (list[TagValue]) – Advanced generic filters.
Return type:
reqScannerSubscription(subscription, scannerSubscriptionOptions=[], scannerSubscriptionFilterOptions=[])[source]
Subscribe to market scan data.
https://interactivebrokers.github.io/tws-api/market_scanners.html
Parameters:
subscription (ScannerSubscription) – What to scan for.
scannerSubscriptionFilterOptions (list[TagValue]) – Unknown.
Return type:
cancelScannerSubscription(dataList)[source]
Cancel market data subscription.
https://interactivebrokers.github.io/tws-api/market_scanners.html
Parameters:
dataList (ScanDataList) – The scan data list that was obtained from reqScannerSubscription().
reqScannerParameters()[source]
Requests an XML list of scanner parameters.
This method is blocking.
Return type:
calculateImpliedVolatility(contract, optionPrice, underPrice, implVolOptions=[])[source]
Calculate the volatility given the option price.
This method is blocking.
https://interactivebrokers.github.io/tws-api/option_computations.html
Parameters:
contract (Contract) – Option contract.
optionPrice (float) – Option price to use in calculation.
underPrice (float) – Price of the underlier to use in calculation
Return type:
calculateOptionPrice(contract, volatility, underPrice, optPrcOptions=[])[source]
Calculate the option price given the volatility.
This method is blocking.
https://interactivebrokers.github.io/tws-api/option_computations.html
Parameters:
contract (Contract) – Option contract.
volatility (float) – Option volatility to use in calculation.
underPrice (float) – Price of the underlier to use in calculation
implVolOptions – Unknown
Return type:
reqSecDefOptParams(underlyingSymbol, futFopExchange, underlyingSecType, underlyingConId)[source]
Get the option chain.
This method is blocking.
https://interactivebrokers.github.io/tws-api/options.html
Parameters:
underlyingSymbol (str) – Symbol of underlier contract.
futFopExchange (str) – Exchange (only for FuturesOption, otherwise leave blank).
underlyingSecType (str) – The type of the underlying security, like ‘STK’ or ‘FUT’.
underlyingConId (int) – conId of the underlying contract.
Return type:
exerciseOptions(contract, exerciseAction, exerciseQuantity, account, override)[source]
Exercise an options contract.
https://interactivebrokers.github.io/tws-api/options.html
Parameters:
contract (Contract) – The option contract to be exercised.
exerciseAction (int) –
exerciseQuantity (int) – Number of contracts to be exercised.
account (str) – Destination account.
override (int) –
Get a list of news providers.
This method is blocking.
Return type:
reqNewsArticle(providerCode, articleId, newsArticleOptions=[])[source]
Get the body of a news article.
This method is blocking.
https://interactivebrokers.github.io/tws-api/news.html
Parameters:
providerCode (str) – Code indicating news provider, like ‘BZ’ or ‘FLY’.
articleId (str) – ID of the specific article.
Return type:
reqHistoricalNews(conId, providerCodes, startDateTime, endDateTime, totalResults, historicalNewsOptions=[])[source]
Get historical news headline.
https://interactivebrokers.github.io/tws-api/news.html
This method is blocking.
Parameters:
conId (int) – Search news articles for contract with this conId.
providerCodes (str) – A ‘+’-separated list of provider codes, like ‘BZ+FLY’.
startDateTime (str | date) – The (exclusive) start of the date range. Can be given as a datetime.date or datetime.datetime, or it can be given as a string in ‘yyyyMMdd HH:mm:ss’ format. If no timezone is given then the TWS login timezone is used.
endDateTime (str | date) – The (inclusive) end of the date range. Can be given as a datetime.date or datetime.datetime, or it can be given as a string in ‘yyyyMMdd HH:mm:ss’ format. If no timezone is given then the TWS login timezone is used.
totalResults (int) – Maximum number of headlines to fetch (300 max).
Return type:
reqNewsBulletins(allMessages)[source]
Subscribe to IB news bulletins.
https://interactivebrokers.github.io/tws-api/news.html
Parameters:
allMessages (bool) – If True then fetch all messages for the day.
cancelNewsBulletins()[source]
Cancel subscription to IB news bulletins.
requestFA(faDataType)[source]
Requests to change the FA configuration.
This method is blocking.
Parameters:
faDataType (int) –
1 = Groups: Offer traders a way to create a group of accounts and apply a single allocation method to all accounts in the group.
2 = Profiles: Let you allocate shares on an account-by-account basis using a predefined calculation value.
3 = Account Aliases: Let you easily identify the accounts by meaningful names rather than account numbers.
replaceFA(faDataType, xml)[source]
Replaces Financial Advisor’s settings.
Parameters:
faDataType (int) – See requestFA().
xml (str) – The XML-formatted configuration string.
Request Wall Street Horizon metadata.
https://interactivebrokers.github.io/tws-api/fundamentals.html
Cancel WSH metadata.
reqWshEventData(data)[source]
Request Wall Street Horizon event data.
reqWshMetaData() must have been called first before using this method.
Parameters:
data (WshEventData) – Filters for selecting the corporate event data.
https://interactivebrokers.github.io/tws-api/wshe_filters.html
Cancel active WHS event data.
Blocking convenience method that returns the WSH metadata (that is the available filters and event types) as a JSON string.
Please note that a Wall Street Horizon subscription is required.
# Get the list of available filters and event types:meta=ib.getWshMetaData()print(meta)
Return type:
getWshEventData(data)[source]
Blocking convenience method that returns the WSH event data as a JSON string. getWshMetaData() must have been called first before using this method.
Please note that a Wall Street Horizon subscription is required.
# For IBM (with conId=8314) query the:# - Earnings Dates (wshe\_ed)# - Board of Directors meetings (wshe\_bod)data=WshEventData(filter='''{ "country": "All", "watchlist": ["8314"], "limit\_region": 10, "limit": 10, "wshe\_ed": "true", "wshe\_bod": "true" }''')events=ib.getWshEventData(data)print(events)
Return type:
Get the White Branding ID of the user.
Return type:
async connectAsync(host='127.0.0.1', port=7497, clientId=1, timeout=4, readonly=False, account='', raiseSyncErrors=False, fetchFields=<StartupFetch.POSITIONS|ORDERS_OPEN|ORDERS_COMPLETE|ACCOUNT_UPDATES|SUB_ACCOUNT_UPDATES|EXECUTIONS: 63>)[source]async qualifyContractsAsync(*contracts, returnAll=False)[source]
Looks up all contract details, but only returns matching Contract objects.
If ‘returnAll’ is True, instead of returning ‘None’ on an ambiguous contract request, the return slot will have a list of the matching contracts. Previously the conflicts were only sent to the log, which isn’t useful if you are logging to a file and not watching immediately.
Return type:
list[Contract | list[Contract | None] | None]
Note: return value has elements in same position as input request. If a contract
cannot be qualified (bad values, ambiguous), the return value for the contract position in the result is None.
async reqTickersAsync(*contracts, regulatorySnapshot=False)[source]Return type:
whatIfOrderAsync(contract, order)[source]Return type:
reqCurrentTimeAsync()[source]Return type:
reqAccountUpdatesAsync(account)[source]Return type:
reqAccountUpdatesMultiAsync(account, modelCode='')[source]Return type:
async accountSummaryAsync(account='')[source]Return type:
reqAccountSummaryAsync()[source]Return type:
reqOpenOrdersAsync()[source]Return type:
reqAllOpenOrdersAsync()[source]Return type:
reqCompletedOrdersAsync(apiOnly)[source]Return type:
reqExecutionsAsync(execFilter=None)[source]Return type:
reqPositionsAsync()[source]Return type:
reqContractDetailsAsync(contract)[source]Return type:
Awaitable[list[ContractDetails]]
async reqMatchingSymbolsAsync(pattern)[source]Return type:
list[ContractDescription] | None
async reqMarketRuleAsync(marketRuleId)[source]Return type:
async reqHistoricalDataAsync(contract, endDateTime, durationStr, barSizeSetting, whatToShow, useRTH, formatDate=1, keepUpToDate=False, chartOptions=[], timeout=60)[source]Return type:
reqHistoricalScheduleAsync(contract, numDays, endDateTime='', useRTH=True)[source]Return type:
reqHistoricalTicksAsync(contract, startDateTime, endDateTime, numberOfTicks, whatToShow, useRth, ignoreSize=False, miscOptions=[])[source]Return type:
async reqHeadTimeStampAsync(contract, whatToShow, useRTH, formatDate)[source]Return type:
reqSmartComponentsAsync(bboExchange)[source]reqMktDepthExchangesAsync()[source]Return type:
Awaitable[list[DepthMktDataDescription]]
reqHistogramDataAsync(contract, useRTH, period)[source]Return type:
Awaitable[list[HistogramData]]
reqFundamentalDataAsync(contract, reportType, fundamentalDataOptions=[])[source]Return type:
async reqScannerDataAsync(subscription, scannerSubscriptionOptions=[], scannerSubscriptionFilterOptions=[])[source]Return type:
reqScannerParametersAsync()[source]Return type:
async calculateImpliedVolatilityAsync(contract, optionPrice, underPrice, implVolOptions=[])[source]Return type:
async calculateOptionPriceAsync(contract, volatility, underPrice, optPrcOptions=[])[source]Return type:
reqSecDefOptParamsAsync(underlyingSymbol, futFopExchange, underlyingSecType, underlyingConId)[source]Return type:
reqNewsProvidersAsync()[source]Return type:
reqNewsArticleAsync(providerCode, articleId, newsArticleOptions=[])[source]Return type:
async reqHistoricalNewsAsync(conId, providerCodes, startDateTime, endDateTime, totalResults, historicalNewsOptions=[])[source]Return type:
async requestFAAsync(faDataType)[source]async getWshMetaDataAsync()[source]Return type:
async getWshEventDataAsync(data)[source]Return type:
Socket client for communicating with Interactive Brokers.
class ib_async.client.Client(wrapper)[source]
Replacement for ibapi.client.EClient that uses asyncio.
The client is fully asynchronous and has its own event-driven networking code that replaces the networking code of the standard EClient. It also replaces the infinite loop of EClient.run() with the asyncio event loop. It can be used as a drop-in replacement for the standard EClient as provided by IBAPI.
Compared to the standard EClient this client has the following additional features:
client.connect() will block until the client is ready to serve requests; It is not necessary to wait for nextValidId to start requests as the client has already done that. The reqId is directly available with getReqId().
client.connectAsync() is a coroutine for connecting asynchronously.
When blocking, client.connect() can be made to time out with the timeout parameter (default 2 seconds).
Optional wrapper.priceSizeTick(reqId, tickType, price, size) that combines price and size instead of the two wrapper methods priceTick and sizeTick.
Automatic request throttling.
Optional wrapper.tcpDataArrived() method; If the wrapper has this method it is invoked directly after a network packet has arrived. A possible use is to timestamp all data in the packet with the exact same time.
Optional wrapper.tcpDataProcessed() method; If the wrapper has this method it is invoked after the network packet’s data has been handled. A possible use is to write or evaluate the newly arrived data in one batch instead of item by item.
Parameters:
MaxRequests (int) – Throttle the number of requests to MaxRequests per RequestsInterval seconds. Set to 0 to disable throttling.
RequestsInterval (float) – Time interval (in seconds) for request throttling.
MinClientVersion (int) – Client protocol version.
MaxClientVersion (int) – Client protocol version.
Events:
apiStart ()
apiEnd ()
apiError (errorMsg: str)
throttleStart ()
throttleEnd ()
events = ('apiStart', 'apiEnd', 'apiError', 'throttleStart', 'throttleEnd')MaxRequests = 45RequestsInterval = 1MinClientVersion = 157MaxClientVersion = 178DISCONNECTED = 0CONNECTING = 1CONNECTED = 2reset()[source]serverVersion()[source]Return type:
run()[source]isConnected()[source]isReady()[source]
Is the API connection up and running?
Return type:
Get statistics about the connection.
Return type:
Get new request ID.
Return type:
updateReqId(minReqId)[source]
Update the next reqId to be at least minReqId.
Get the list of account names that are under management.
Return type:
setConnectOptions(connectOptions)[source]
Set additional connect options.
Parameters:
connectOptions (str) – Use “+PACEAPI” to use request-pacing built into TWS/gateway 974+ (obsolete).
connect(host, port, clientId, timeout=2.0)[source]
Connect to a running TWS or IB gateway application.
Parameters:
host (str) – Host name or IP address.
port (int) – Port number.
clientId (int) – ID number to use for this client; must be unique per connection.
timeout (float | None) – If establishing the connection takes longer than timeout seconds then the asyncio.TimeoutError exception is raised. Set to 0 to disable timeout.
async connectAsync(host, port, clientId, timeout=2.0)[source]disconnect()[source]
Disconnect from IB connection.
send(*fields, makeEmpty=True)[source]
Serialize and send the given fields using the IB socket protocol.
if ‘makeEmpty’ is True (default), then the IBKR values representing “no value” become the empty string.
sendMsg(msg)[source]reqMktData(reqId, contract, genericTickList, snapshot, regulatorySnapshot, mktDataOptions)[source]cancelMktData(reqId)[source]placeOrder(orderId, contract, order)[source]cancelOrder(orderId, manualCancelOrderTime='')[source]reqOpenOrders()[source]reqAccountUpdates(subscribe, acctCode)[source]reqExecutions(reqId, execFilter)[source]reqIds(numIds)[source]reqContractDetails(reqId, contract)[source]reqMktDepth(reqId, contract, numRows, isSmartDepth, mktDepthOptions)[source]cancelMktDepth(reqId, isSmartDepth)[source]reqNewsBulletins(allMsgs)[source]cancelNewsBulletins()[source]setServerLogLevel(logLevel)[source]reqAutoOpenOrders(bAutoBind)[source]reqAllOpenOrders()[source]reqManagedAccts()[source]requestFA(faData)[source]replaceFA(reqId, faData, cxml)[source]reqHistoricalData(reqId, contract, endDateTime, durationStr, barSizeSetting, whatToShow, useRTH, formatDate, keepUpToDate, chartOptions)[source]exerciseOptions(reqId, contract, exerciseAction, exerciseQuantity, account, override)[source]reqScannerSubscription(reqId, subscription, scannerSubscriptionOptions, scannerSubscriptionFilterOptions)[source]cancelScannerSubscription(reqId)[source]reqScannerParameters()[source]cancelHistoricalData(reqId)[source]reqCurrentTime()[source]reqRealTimeBars(reqId, contract, barSize, whatToShow, useRTH, realTimeBarsOptions)[source]cancelRealTimeBars(reqId)[source]reqFundamentalData(reqId, contract, reportType, fundamentalDataOptions)[source]cancelFundamentalData(reqId)[source]calculateImpliedVolatility(reqId, contract, optionPrice, underPrice, implVolOptions)[source]calculateOptionPrice(reqId, contract, volatility, underPrice, optPrcOptions)[source]cancelCalculateImpliedVolatility(reqId)[source]cancelCalculateOptionPrice(reqId)[source]reqGlobalCancel()[source]reqMarketDataType(marketDataType)[source]reqPositions()[source]reqAccountSummary(reqId, groupName, tags)[source]cancelAccountSummary(reqId)[source]cancelPositions()[source]verifyRequest(apiName, apiVersion)[source]verifyMessage(apiData)[source]queryDisplayGroups(reqId)[source]subscribeToGroupEvents(reqId, groupId)[source]updateDisplayGroup(reqId, contractInfo)[source]unsubscribeFromGroupEvents(reqId)[source]startApi()[source]verifyAndAuthRequest(apiName, apiVersion, opaqueIsvKey)[source]verifyAndAuthMessage(apiData, xyzResponse)[source]reqPositionsMulti(reqId, account, modelCode)[source]cancelPositionsMulti(reqId)[source]reqAccountUpdatesMulti(reqId, account, modelCode, ledgerAndNLV)[source]cancelAccountUpdatesMulti(reqId)[source]reqSecDefOptParams(reqId, underlyingSymbol, futFopExchange, underlyingSecType, underlyingConId)[source]reqSoftDollarTiers(reqId)[source]reqFamilyCodes()[source]reqMatchingSymbols(reqId, pattern)[source]reqMktDepthExchanges()[source]reqSmartComponents(reqId, bboExchange)[source]reqNewsArticle(reqId, providerCode, articleId, newsArticleOptions)[source]reqNewsProviders()[source]reqHistoricalNews(reqId, conId, providerCodes, startDateTime, endDateTime, totalResults, historicalNewsOptions)[source]reqHeadTimeStamp(reqId, contract, whatToShow, useRTH, formatDate)[source]reqHistogramData(tickerId, contract, useRTH, timePeriod)[source]cancelHistogramData(tickerId)[source]cancelHeadTimeStamp(reqId)[source]reqMarketRule(marketRuleId)[source]reqPnL(reqId, account, modelCode)[source]cancelPnL(reqId)[source]reqPnLSingle(reqId, account, modelCode, conid)[source]cancelPnLSingle(reqId)[source]reqHistoricalTicks(reqId, contract, startDateTime, endDateTime, numberOfTicks, whatToShow, useRth, ignoreSize, miscOptions)[source]reqTickByTickData(reqId, contract, tickType, numberOfTicks, ignoreSize)[source]cancelTickByTickData(reqId)[source]reqCompletedOrders(apiOnly)[source]reqWshMetaData(reqId)[source]cancelWshMetaData(reqId)[source]reqWshEventData(reqId, data)[source]cancelWshEventData(reqId)[source]reqUserInfo(reqId)[source]
Order types used by Interactive Brokers.
class ib_async.order.Order(orderId=0, clientId=0, permId=0, action='', totalQuantity=0.0, orderType='', lmtPrice=1.7976931348623157e+308, auxPrice=1.7976931348623157e+308, tif='', activeStartTime='', activeStopTime='', ocaGroup='', ocaType=0, orderRef='', transmit=True, parentId=0, blockOrder=False, sweepToFill=False, displaySize=0, triggerMethod=0, outsideRth=False, hidden=False, goodAfterTime='', goodTillDate='', rule80A='', allOrNone=False, minQty=2147483647, percentOffset=1.7976931348623157e+308, overridePercentageConstraints=False, trailStopPrice=1.7976931348623157e+308, trailingPercent=1.7976931348623157e+308, faGroup='', faProfile='', faMethod='', faPercentage='', designatedLocation='', openClose='O', origin=0, shortSaleSlot=0, exemptCode=-1, discretionaryAmt=0.0, eTradeOnly=False, firmQuoteOnly=False, nbboPriceCap=1.7976931348623157e+308, optOutSmartRouting=False, auctionStrategy=0, startingPrice=1.7976931348623157e+308, stockRefPrice=1.7976931348623157e+308, delta=1.7976931348623157e+308, stockRangeLower=1.7976931348623157e+308, stockRangeUpper=1.7976931348623157e+308, randomizePrice=False, randomizeSize=False, volatility=1.7976931348623157e+308, volatilityType=2147483647, deltaNeutralOrderType='', deltaNeutralAuxPrice=1.7976931348623157e+308, deltaNeutralConId=0, deltaNeutralSettlingFirm='', deltaNeutralClearingAccount='', deltaNeutralClearingIntent='', deltaNeutralOpenClose='', deltaNeutralShortSale=False, deltaNeutralShortSaleSlot=0, deltaNeutralDesignatedLocation='', continuousUpdate=False, referencePriceType=2147483647, basisPoints=1.7976931348623157e+308, basisPointsType=2147483647, scaleInitLevelSize=2147483647, scaleSubsLevelSize=2147483647, scalePriceIncrement=1.7976931348623157e+308, scalePriceAdjustValue=1.7976931348623157e+308, scalePriceAdjustInterval=2147483647, scaleProfitOffset=1.7976931348623157e+308, scaleAutoReset=False, scaleInitPosition=2147483647, scaleInitFillQty=2147483647, scaleRandomPercent=False, scaleTable='', hedgeType='', hedgeParam='', account='', settlingFirm='', clearingAccount='', clearingIntent='', algoStrategy='', algoParams=<factory>, smartComboRoutingParams=<factory>, algoId='', whatIf=False, notHeld=False, solicited=False, modelCode='', orderComboLegs=<factory>, orderMiscOptions=<factory>, referenceContractId=0, peggedChangeAmount=0.0, isPeggedChangeAmountDecrease=False, referenceChangeAmount=0.0, referenceExchangeId='', adjustedOrderType='', triggerPrice=1.7976931348623157e+308, adjustedStopPrice=1.7976931348623157e+308, adjustedStopLimitPrice=1.7976931348623157e+308, adjustedTrailingAmount=1.7976931348623157e+308, adjustableTrailingUnit=0, lmtPriceOffset=1.7976931348623157e+308, conditions=<factory>, conditionsCancelOrder=False, conditionsIgnoreRth=False, extOperator='', softDollarTier=<factory>, cashQty=1.7976931348623157e+308, mifid2DecisionMaker='', mifid2DecisionAlgo='', mifid2ExecutionTrader='', mifid2ExecutionAlgo='', dontUseAutoPriceForHedge=False, isOmsContainer=False, discretionaryUpToLimitPrice=False, autoCancelDate='', filledQuantity=1.7976931348623157e+308, refFuturesConId=0, autoCancelParent=False, shareholder='', imbalanceOnly=False, routeMarketableToBbo=False, parentPermId=0, usePriceMgmtAlgo=False, duration=2147483647, postToAts=2147483647, advancedErrorOverride='', manualOrderTime='', minTradeQty=2147483647, minCompeteSize=2147483647, competeAgainstBestOffset=1.7976931348623157e+308, midOffsetAtWhole=1.7976931348623157e+308, midOffsetAtHalf=1.7976931348623157e+308)[source]
Order for trading contracts.
https://interactivebrokers.github.io/tws-api/available_orders.html
orderId_: int_ = 0clientId_: int_ = 0permId_: int_ = 0action_: str_ = ''totalQuantity_: float_ = 0.0orderType_: str_ = ''lmtPrice_: float | Decimal | None_ = 1.7976931348623157e+308auxPrice_: float | Decimal | None_ = 1.7976931348623157e+308tif_: str_ = ''activeStartTime_: str_ = ''activeStopTime_: str_ = ''ocaGroup_: str_ = ''ocaType_: int_ = 0orderRef_: str_ = ''transmit_: bool_ = TrueparentId_: int_ = 0blockOrder_: bool_ = FalsesweepToFill_: bool_ = FalsedisplaySize_: int_ = 0triggerMethod_: int_ = 0outsideRth_: bool_ = Falsehidden_: bool_ = FalsegoodAfterTime_: str_ = ''goodTillDate_: str_ = ''rule80A_: str_ = ''allOrNone_: bool_ = FalseminQty_: int_ = 2147483647percentOffset_: float | Decimal_ = 1.7976931348623157e+308overridePercentageConstraints_: bool_ = FalsetrailStopPrice_: float | Decimal_ = 1.7976931348623157e+308trailingPercent_: float | Decimal_ = 1.7976931348623157e+308faGroup_: str_ = ''faProfile_: str_ = ''faMethod_: str_ = ''faPercentage_: str_ = ''designatedLocation_: str_ = ''openClose_: str_ = 'O'origin_: int_ = 0shortSaleSlot_: int_ = 0exemptCode_: int_ = -1discretionaryAmt_: float_ = 0.0eTradeOnly_: bool_ = FalsefirmQuoteOnly_: bool_ = FalsenbboPriceCap_: float | Decimal_ = 1.7976931348623157e+308optOutSmartRouting_: bool_ = FalseauctionStrategy_: int_ = 0startingPrice_: float | Decimal_ = 1.7976931348623157e+308stockRefPrice_: float | Decimal_ = 1.7976931348623157e+308delta_: float | Decimal_ = 1.7976931348623157e+308stockRangeLower_: float | Decimal_ = 1.7976931348623157e+308stockRangeUpper_: float | Decimal_ = 1.7976931348623157e+308randomizePrice_: bool_ = FalserandomizeSize_: bool_ = Falsevolatility_: float | Decimal_ = 1.7976931348623157e+308volatilityType_: int_ = 2147483647deltaNeutralOrderType_: str_ = ''deltaNeutralAuxPrice_: float | Decimal_ = 1.7976931348623157e+308deltaNeutralConId_: int_ = 0deltaNeutralSettlingFirm_: str_ = ''deltaNeutralClearingAccount_: str_ = ''deltaNeutralClearingIntent_: str_ = ''deltaNeutralOpenClose_: str_ = ''deltaNeutralShortSale_: bool_ = FalsedeltaNeutralShortSaleSlot_: int_ = 0deltaNeutralDesignatedLocation_: str_ = ''continuousUpdate_: bool_ = FalsereferencePriceType_: int_ = 2147483647basisPoints_: float | Decimal_ = 1.7976931348623157e+308basisPointsType_: int_ = 2147483647scaleInitLevelSize_: int_ = 2147483647scaleSubsLevelSize_: int_ = 2147483647scalePriceIncrement_: float | Decimal_ = 1.7976931348623157e+308scalePriceAdjustValue_: float | Decimal_ = 1.7976931348623157e+308scalePriceAdjustInterval_: int_ = 2147483647scaleProfitOffset_: float | Decimal_ = 1.7976931348623157e+308scaleAutoReset_: bool_ = FalsescaleInitPosition_: int_ = 2147483647scaleInitFillQty_: int_ = 2147483647scaleRandomPercent_: bool_ = FalsescaleTable_: str_ = ''hedgeType_: str_ = ''hedgeParam_: str_ = ''account_: str_ = ''settlingFirm_: str_ = ''clearingAccount_: str_ = ''clearingIntent_: str_ = ''algoStrategy_: str_ = ''algoParams_: list[TagValue]smartComboRoutingParams: list[TagValue]algoId: str_ = ''whatIf_: bool_ = FalsenotHeld_: bool_ = Falsesolicited_: bool_ = FalsemodelCode_: str_ = ''orderComboLegs_: list[OrderComboLeg]orderMiscOptions: list[TagValue]referenceContractId: int_ = 0peggedChangeAmount_: float_ = 0.0isPeggedChangeAmountDecrease_: bool_ = FalsereferenceChangeAmount_: float_ = 0.0referenceExchangeId_: str_ = ''adjustedOrderType_: str_ = ''triggerPrice_: float | Decimal | None_ = 1.7976931348623157e+308adjustedStopPrice_: float | Decimal_ = 1.7976931348623157e+308adjustedStopLimitPrice_: float | Decimal_ = 1.7976931348623157e+308adjustedTrailingAmount_: float | Decimal_ = 1.7976931348623157e+308adjustableTrailingUnit_: int_ = 0lmtPriceOffset_: float | Decimal_ = 1.7976931348623157e+308conditions_: list[OrderCondition]conditionsCancelOrder: bool_ = FalseconditionsIgnoreRth_: bool_ = FalseextOperator_: str_ = ''softDollarTier_: SoftDollarTiercashQty: float | Decimal_ = 1.7976931348623157e+308mifid2DecisionMaker_: str_ = ''mifid2DecisionAlgo_: str_ = ''mifid2ExecutionTrader_: str_ = ''mifid2ExecutionAlgo_: str_ = ''dontUseAutoPriceForHedge_: bool_ = FalseisOmsContainer_: bool_ = FalsediscretionaryUpToLimitPrice_: bool_ = FalseautoCancelDate_: str_ = ''filledQuantity_: float | Decimal_ = 1.7976931348623157e+308refFuturesConId_: int_ = 0autoCancelParent_: bool_ = Falseshareholder_: str_ = ''imbalanceOnly_: bool_ = FalserouteMarketableToBbo_: bool_ = FalseparentPermId_: int_ = 0usePriceMgmtAlgo_: bool_ = Falseduration_: int_ = 2147483647postToAts_: int_ = 2147483647advancedErrorOverride_: str_ = ''manualOrderTime_: str_ = ''minTradeQty_: int_ = 2147483647minCompeteSize_: int_ = 2147483647competeAgainstBestOffset_: float | Decimal_ = 1.7976931348623157e+308midOffsetAtWhole_: float | Decimal_ = 1.7976931348623157e+308midOffsetAtHalf_: float | Decimal_ = 1.7976931348623157e+308dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.order.LimitOrder(action, totalQuantity, lmtPrice, **kwargs)[source]dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.order.MarketOrder(action, totalQuantity, **kwargs)[source]dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.order.StopOrder(action, totalQuantity, stopPrice, **kwargs)[source]dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.order.StopLimitOrder(action, totalQuantity, lmtPrice, stopPrice, **kwargs)[source]dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.order.OrderStatus(orderId=0, status='', filled=0.0, remaining=0.0, avgFillPrice=0.0, permId=0, parentId=0, lastFillPrice=0.0, clientId=0, whyHeld='', mktCapPrice=0.0)[source]orderId_: int_ = 0status_: str_ = ''filled_: float_ = 0.0remaining_: float_ = 0.0avgFillPrice_: float_ = 0.0permId_: int_ = 0parentId_: int_ = 0lastFillPrice_: float_ = 0.0clientId_: int_ = 0whyHeld_: str_ = ''mktCapPrice_: float_ = 0.0property total_: float_
Helper property to return the total size of this requested order.
PendingSubmit_: ClassVar[str]_ = 'PendingSubmit'PendingCancel_: ClassVar[str]_ = 'PendingCancel'PreSubmitted_: ClassVar[str]_ = 'PreSubmitted'Submitted_: ClassVar[str]_ = 'Submitted'ApiPending_: ClassVar[str]_ = 'ApiPending'ApiCancelled_: ClassVar[str]_ = 'ApiCancelled'ApiUpdate_: ClassVar[str]_ = 'ApiUpdate'Cancelled_: ClassVar[str]_ = 'Cancelled'Filled_: ClassVar[str]_ = 'Filled'Inactive_: ClassVar[str]_ = 'Inactive'ValidationError_: ClassVar[str]_ = 'ValidationError'DoneStates_: ClassVar[frozenset[str]]_ = frozenset({'ApiCancelled', 'Cancelled', 'Filled', 'Inactive'})ActiveStates_: ClassVar[frozenset[str]]_ = frozenset({'ApiPending', 'ApiUpdate', 'PendingSubmit', 'PreSubmitted', 'Submitted', 'ValidationError'})WaitingStates_: ClassVar[frozenset[str]]_ = frozenset({'ApiPending', 'PendingSubmit', 'PreSubmitted'})WorkingStates_: ClassVar[frozenset[str]]_ = frozenset({'ApiUpdate', 'Submitted', 'ValidationError'})dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.order.OrderState(status='', initMarginBefore='', maintMarginBefore='', equityWithLoanBefore='', initMarginChange='', maintMarginChange='', equityWithLoanChange='', initMarginAfter='', maintMarginAfter='', equityWithLoanAfter='', commission=1.7976931348623157e+308, minCommission=1.7976931348623157e+308, maxCommission=1.7976931348623157e+308, commissionCurrency='', warningText='', completedTime='', completedStatus='')[source]status_: str_ = ''initMarginBefore_: str_ = ''maintMarginBefore_: str_ = ''equityWithLoanBefore_: str_ = ''initMarginChange_: str_ = ''maintMarginChange_: str_ = ''equityWithLoanChange_: str_ = ''initMarginAfter_: str_ = ''maintMarginAfter_: str_ = ''equityWithLoanAfter_: str_ = ''commission_: float_ = 1.7976931348623157e+308minCommission_: float_ = 1.7976931348623157e+308maxCommission_: float_ = 1.7976931348623157e+308commissionCurrency_: str_ = ''warningText_: str_ = ''completedTime_: str_ = ''completedStatus_: str_ = ''transform(transformer)[source]
Convert the numeric values of this OrderState into a new OrderState transformed by ‘using’
Return a new OrderState with the current values values to floats instead of strings as returned from IBKR directly.
Return type:
Return a new OrderState with the current values as formatted strings.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.order.OrderStateNumeric(status='', initMarginBefore=nan, maintMarginBefore=nan, equityWithLoanBefore=nan, initMarginChange=nan, maintMarginChange=nan, equityWithLoanChange=nan, initMarginAfter=nan, maintMarginAfter=nan, equityWithLoanAfter=nan, commission=1.7976931348623157e+308, minCommission=1.7976931348623157e+308, maxCommission=1.7976931348623157e+308, commissionCurrency='', warningText='', completedTime='', completedStatus='')[source]
Just a type helper for mypy to check against if you convert OrderState to .numeric().
Usage:
state_numeric: OrderStateNumeric = state.numeric(digits=2)
initMarginBefore_: float_ = nanmaintMarginBefore_: float_ = nanequityWithLoanBefore_: float_ = naninitMarginChange_: float_ = nanmaintMarginChange_: float_ = nanequityWithLoanChange_: float_ = naninitMarginAfter_: float_ = nanmaintMarginAfter_: float_ = nanequityWithLoanAfter_: float_ = nandict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.order.OrderComboLeg(price=1.7976931348623157e+308)[source]price_: float | Decimal_ = 1.7976931348623157e+308dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.order.Trade(contract=<factory>, order=<factory>, orderStatus=<factory>, fills=<factory>, log=<factory>, advancedError='')[source]
Trade keeps track of an order, its status and all its fills.
Events:
statusEvent (trade: Trade)
modifyEvent (trade: Trade)
commissionReportEvent (trade: Trade, fill: Fill, commissionReport: CommissionReport)
filledEvent (trade: Trade)
cancelEvent (trade: Trade)
cancelledEvent (trade: Trade)
contract_: Contractorder: OrderorderStatus: OrderStatusfills: list[Fill]log: list[TradeLogEntry]advancedError: str_ = ''events_: ClassVar_ = ('statusEvent', 'modifyEvent', 'fillEvent', 'commissionReportEvent', 'filledEvent', 'cancelEvent', 'cancelledEvent')isWaiting()[source]
True if sent to IBKR but not “Submitted” for live execution yet.
Return type:
True if sent to IBKR but not “Submitted” for live execution yet.
Return type:
True if eligible for execution, false otherwise.
Return type:
True if completely filled or cancelled, false otherwise.
Return type:
Number of shares filled.
Return type:
Number of shares remaining to be filled.
Return type:
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.order.BracketOrder(parent, takeProfit, stopLoss)[source]
Create new instance of BracketOrder(parent, takeProfit, stopLoss)
parent_: OrdertakeProfit: OrderstopLoss: Order_class ib_async.order.OrderCondition[source]static createClass(condType)[source]And()[source]Or()[source]dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.order.PriceCondition(condType=1, conjunction='a', isMore=True, price=0.0, conId=0, exch='', triggerMethod=0)[source]condType_: int_ = 1conjunction_: str_ = 'a'isMore_: bool_ = Trueprice_: float_ = 0.0conId_: int_ = 0exch_: str_ = ''triggerMethod_: int_ = 0dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.order.TimeCondition(condType=3, conjunction='a', isMore=True, time='')[source]condType_: int_ = 3conjunction_: str_ = 'a'isMore_: bool_ = Truetime_: str_ = ''dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.order.MarginCondition(condType=4, conjunction='a', isMore=True, percent=0)[source]condType_: int_ = 4conjunction_: str_ = 'a'isMore_: bool_ = Truepercent_: int_ = 0dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.order.ExecutionCondition(condType=5, conjunction='a', secType='', exch='', symbol='')[source]condType_: int_ = 5conjunction_: str_ = 'a'secType_: str_ = ''exch_: str_ = ''symbol_: str_ = ''dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.order.VolumeCondition(condType=6, conjunction='a', isMore=True, volume=0, conId=0, exch='')[source]condType_: int_ = 6conjunction_: str_ = 'a'isMore_: bool_ = Truevolume_: int_ = 0conId_: int_ = 0exch_: str_ = ''dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.order.PercentChangeCondition(condType=7, conjunction='a', isMore=True, changePercent=0.0, conId=0, exch='')[source]condType_: int_ = 7conjunction_: str_ = 'a'isMore_: bool_ = TruechangePercent_: float_ = 0.0conId_: int_ = 0exch_: str_ = ''dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
Financial instrument types used by Interactive Brokers.
class ib_async.contract.Contract(secType='', conId=0, symbol='', lastTradeDateOrContractMonth='', strike=0.0, right='', multiplier='', exchange='', primaryExchange='', currency='', localSymbol='', tradingClass='', includeExpired=False, secIdType='', secId='', description='', issuerId='', comboLegsDescrip='', comboLegs=<factory>, deltaNeutralContract=None)[source]
Contract(**kwargs) can create any contract using keyword arguments. To simplify working with contracts, there are also more specialized contracts that take optional positional arguments. Some examples:
Contract(conId=270639)Stock('AMD','SMART','USD')Stock('INTC','SMART','USD',primaryExchange='NASDAQ')Forex('EURUSD')CFD('IBUS30')Future('ES','20180921','GLOBEX')Option('SPY','20170721',240,'C','SMART')Bond(secIdType='ISIN',secId='US03076KAA60')Crypto('BTC','PAXOS','USD')
Parameters:
conId (int) – The unique IB contract identifier.
symbol (str) – The contract (or its underlying) symbol.
secType (str) –
lastTradeDateOrContractMonth (str) – The 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.
strike (float) – The option’s strike price.
right (str) – Put or Call. Valid values are ‘P’, ‘PUT’, ‘C’, ‘CALL’, or ‘’ for non-options.
multiplier (str) – The instrument’s multiplier (i.e. options, futures).
exchange (str) – The destination exchange.
currency (str) – The underlying’s currency.
localSymbol (str) – The contract’s symbol within its primary exchange. For options, this will be the OCC symbol.
primaryExchange (str) – The contract’s primary exchange. For smart routed contracts, used to define contract in case of ambiguity. Should be defined as native exchange of contract, e.g. ISLAND for MSFT. For exchanges which contain a period in name, will only be part of exchange name prior to period, i.e. ENEXT for ENEXT.BE.
tradingClass (str) – The 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”.
includeExpired (bool) – If 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.
secIdType (str) –
secId (str) – Security identifier.
comboLegsDescription (str) – Description of the combo legs.
comboLegs (List_[ComboLeg]_) – The legs of a combined contract definition.
deltaNeutralContract (DeltaNeutralContract) – Delta and underlying price for Delta-Neutral combo orders.
secType_: str_ = ''conId_: int_ = 0symbol_: str_ = ''lastTradeDateOrContractMonth_: str_ = ''strike_: float_ = 0.0right_: str_ = ''multiplier_: str_ = ''exchange_: str_ = ''primaryExchange_: str_ = ''currency_: str_ = ''localSymbol_: str_ = ''tradingClass_: str_ = ''includeExpired_: bool_ = FalsesecIdType_: str_ = ''secId_: str_ = ''description_: str_ = ''issuerId_: str_ = ''comboLegsDescrip_: str_ = ''comboLegs_: list[ComboLeg]deltaNeutralContract: Optional[DeltaNeutralContract]_ = Nonestatic create(**kwargs)[source]
Create and a return a specialized contract based on the given secType, or a general Contract if secType is not given.
Return type:
Comply an existing generic Contract into its most specific type.
Return type:
See if this contract can be hashed by conId.
Return type:
Note: Bag contracts always get conId=28812380, so they’re not hashable by conId,
but we generate a synthetic hash for them based on leg details instead.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.Stock(symbol='', exchange='', currency='', **kwargs)[source]
Stock contract.
Parameters:
symbol (str) – Symbol name.
exchange (str) – Destination exchange.
currency (str) – Underlying currency.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.Option(symbol='', lastTradeDateOrContractMonth='', strike=0.0, right='', exchange='', multiplier='', currency='', **kwargs)[source]
Option contract.
Parameters:
symbol (str) – Symbol name.
lastTradeDateOrContractMonth (str) –
strike (float) – The option’s strike price.
right (str) – Put or call option. Valid values are ‘P’, ‘PUT’, ‘C’ or ‘CALL’.
exchange (str) – Destination exchange.
multiplier (str) – The contract multiplier.
currency (str) – Underlying currency.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.Future(symbol='', lastTradeDateOrContractMonth='', exchange='', localSymbol='', multiplier='', currency='', **kwargs)[source]
Future contract.
Parameters:
symbol (str) – Symbol name.
lastTradeDateOrContractMonth (str) –
exchange (str) – Destination exchange.
localSymbol (str) – The contract’s symbol within its primary exchange.
multiplier (str) – The contract multiplier.
currency (str) – Underlying currency.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.ContFuture(symbol='', exchange='', localSymbol='', multiplier='', currency='', **kwargs)[source]
Continuous future contract.
Parameters:
symbol (str) – Symbol name.
exchange (str) – Destination exchange.
localSymbol (str) – The contract’s symbol within its primary exchange.
multiplier (str) – The contract multiplier.
currency (str) – Underlying currency.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.Forex(pair='', exchange='IDEALPRO', symbol='', currency='', **kwargs)[source]
Foreign exchange currency pair.
Parameters:
pair (str) – Shortcut for specifying symbol and currency, like ‘EURUSD’.
exchange (str) – Destination exchange.
symbol (str) – Base currency.
currency (str) – Quote currency.
Short name of pair.
Return type:
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.Index(symbol='', exchange='', currency='', **kwargs)[source]
Index.
Parameters:
symbol (str) – Symbol name.
exchange (str) – Destination exchange.
currency (str) – Underlying currency.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.CFD(symbol='', exchange='', currency='', **kwargs)[source]
Contract For Difference.
Parameters:
symbol (str) – Symbol name.
exchange (str) – Destination exchange.
currency (str) – Underlying currency.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.Commodity(symbol='', exchange='', currency='', **kwargs)[source]
Commodity.
Parameters:
symbol (str) – Symbol name.
exchange (str) – Destination exchange.
currency (str) – Underlying currency.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.Bond(**kwargs)[source]
Bond.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.FuturesOption(symbol='', lastTradeDateOrContractMonth='', strike=0.0, right='', exchange='', multiplier='', currency='', **kwargs)[source]
Option on a futures contract.
Parameters:
symbol (str) – Symbol name.
lastTradeDateOrContractMonth (str) –
strike (float) – The option’s strike price.
right (str) – Put or call option. Valid values are ‘P’, ‘PUT’, ‘C’ or ‘CALL’.
exchange (str) – Destination exchange.
multiplier (str) – The contract multiplier.
currency (str) – Underlying currency.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.MutualFund(**kwargs)[source]
Mutual fund.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.Warrant(**kwargs)[source]
Warrant option.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.Bag(**kwargs)[source]
Bag contract.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.Crypto(symbol='', exchange='', currency='', **kwargs)[source]
Crypto currency contract.
Parameters:
symbol (str) – Symbol name.
exchange (str) – Destination exchange.
currency (str) – Underlying currency.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.TagValue(tag, value)[source]
Create new instance of TagValue(tag, value)
tag_: strvalue: strclass ib_async.contract.ComboLeg(conId=0, ratio=0, action='', exchange='', openClose=0, shortSaleSlot=0, designatedLocation='', exemptCode=-1)[source]conId: int_ = 0ratio_: int_ = 0action_: str_ = ''exchange_: str_ = ''openClose_: int_ = 0shortSaleSlot_: int_ = 0designatedLocation_: str_ = ''exemptCode_: int_ = -1dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.DeltaNeutralContract(conId=0, delta=0.0, price=0.0)[source]conId_: int_ = 0delta_: float_ = 0.0price_: float_ = 0.0dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.TradingSession(start, end)[source]
Create new instance of TradingSession(start, end)
start_: datetimeend: datetimeclass ib_async.contract.ContractDetails(contract=None, marketName='', minTick=0.0, orderTypes='', validExchanges='', priceMagnifier=0, underConId=0, longName='', contractMonth='', industry='', category='', subcategory='', timeZoneId='', tradingHours='', liquidHours='', evRule='', evMultiplier=0, mdSizeMultiplier=1, aggGroup=0, underSymbol='', underSecType='', marketRuleIds='', secIdList=<factory>, realExpirationDate='', lastTradeTime='', stockType='', minSize=0.0, sizeIncrement=0.0, suggestedSizeIncrement=0.0, cusip='', ratings='', descAppend='', bondType='', couponType='', callable=False, putable=False, coupon=0, convertible=False, maturity='', issueDate='', nextOptionDate='', nextOptionType='', nextOptionPartial=False, notes='')[source]contract: Contract | None_ = NonemarketName_: str_ = ''minTick_: float_ = 0.0orderTypes_: str_ = ''validExchanges_: str_ = ''priceMagnifier_: int_ = 0underConId_: int_ = 0longName_: str_ = ''contractMonth_: str_ = ''industry_: str_ = ''category_: str_ = ''subcategory_: str_ = ''timeZoneId_: str_ = ''tradingHours_: str_ = ''liquidHours_: str_ = ''evRule_: str_ = ''evMultiplier_: int_ = 0mdSizeMultiplier_: int_ = 1aggGroup_: int_ = 0underSymbol_: str_ = ''underSecType_: str_ = ''marketRuleIds_: str_ = ''secIdList_: list[TagValue]realExpirationDate: str_ = ''lastTradeTime_: str_ = ''stockType_: str_ = ''minSize_: float_ = 0.0sizeIncrement_: float_ = 0.0suggestedSizeIncrement_: float_ = 0.0cusip_: str_ = ''ratings_: str_ = ''descAppend_: str_ = ''bondType_: str_ = ''couponType_: str_ = ''callable_: bool_ = Falseputable_: bool_ = Falsecoupon_: float_ = 0convertible_: bool_ = Falsematurity_: str_ = ''issueDate_: str_ = ''nextOptionDate_: str_ = ''nextOptionType_: str_ = ''nextOptionPartial_: bool_ = Falsenotes_: str_ = ''tradingSessions()[source]Return type:
liquidSessions()[source]Return type:
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.ContractDescription(contract=None, derivativeSecTypes=<factory>)[source]contract_: Contract | None_ = NonederivativeSecTypes_: list[str]_dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.contract.ScanData(rank, contractDetails, distance, benchmark, projection, legsStr)[source]rank_: intcontractDetails: ContractDetailsdistance: strbenchmark: strprojection: strlegsStr: str_dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
Access to realtime market information.
class ib_async.ticker.Ticker(contract=None, time=None, timestamp=None, marketDataType=1, minTick=nan, bid=nan, bidSize=nan, bidExchange='', ask=nan, askSize=nan, askExchange='', last=nan, lastSize=nan, lastExchange='', lastTimestamp=None, prevBid=nan, prevBidSize=nan, prevAsk=nan, prevAskSize=nan, prevLast=nan, prevLastSize=nan, volume=nan, open=nan, high=nan, low=nan, close=nan, vwap=nan, low13week=nan, high13week=nan, low26week=nan, high26week=nan, low52week=nan, high52week=nan, bidYield=nan, askYield=nan, lastYield=nan, markPrice=nan, halted=nan, rtHistVolatility=nan, rtVolume=nan, rtTradeVolume=nan, rtTime=None, avVolume=nan, tradeCount=nan, tradeRate=nan, volumeRate=nan, volumeRate3Min=nan, volumeRate5Min=nan, volumeRate10Min=nan, shortable=nan, shortableShares=nan, indexFuturePremium=nan, futuresOpenInterest=nan, putOpenInterest=nan, callOpenInterest=nan, putVolume=nan, callVolume=nan, avOptionVolume=nan, histVolatility=nan, impliedVolatility=nan, openInterest=nan, lastRthTrade=nan, lastRegTime='', optionBidExch='', optionAskExch='', bondFactorMultiplier=nan, creditmanMarkPrice=nan, creditmanSlowMarkPrice=nan, delayedLastTimestamp=None, delayedHalted=nan, reutersMutualFunds='', etfNavClose=nan, etfNavPriorClose=nan, etfNavBid=nan, etfNavAsk=nan, etfNavLast=nan, etfFrozenNavLast=nan, etfNavHigh=nan, etfNavLow=nan, socialMarketAnalytics='', estimatedIpoMidpoint=nan, finalIpoLast=nan, dividends=None, fundamentalRatios=None, ticks=<factory>, tickByTicks=<factory>, domBids=<factory>, domBidsDict=<factory>, domAsks=<factory>, domAsksDict=<factory>, domTicks=<factory>, bidGreeks=None, askGreeks=None, lastGreeks=None, modelGreeks=None, custGreeks=None, bidEfp=None, askEfp=None, lastEfp=None, openEfp=None, highEfp=None, lowEfp=None, closeEfp=None, auctionVolume=nan, auctionPrice=nan, auctionImbalance=nan, regulatoryImbalance=nan, bboExchange='', snapshotPermissions=0, defaults=<factory>, created=False)[source]
Current market data such as bid, ask, last price, etc. for a contract.
Streaming level-1 ticks of type TickData are stored in the ticks list.
Streaming level-2 ticks of type MktDepthData are stored in the domTicks list. The order book (DOM) is available as lists of DOMLevel in domBids and domAsks.
Streaming tick-by-tick ticks are stored in tickByTicks.
For options the OptionComputation values for the bid, ask, resp. last price are stored in the bidGreeks, askGreeks resp. lastGreeks attributes. There is also modelGreeks that conveys the greeks as calculated by Interactive Brokers’ option model.
Events:
updateEvent (ticker: Ticker)events_: ClassVar_ = ('updateEvent',)contract_: Contract | None_ = Nonetime_: datetime | None_ = Nonetimestamp_: float | None_ = NonemarketDataType_: int_ = 1minTick_: float_ = nanbid_: float_ = nanbidSize_: float_ = nanbidExchange_: str_ = ''ask_: float_ = nanaskSize_: float_ = nanaskExchange_: str_ = ''last_: float_ = nanlastSize_: float_ = nanlastExchange_: str_ = ''lastTimestamp_: datetime | None_ = NoneprevBid_: float_ = nanprevBidSize_: float_ = nanprevAsk_: float_ = nanprevAskSize_: float_ = nanprevLast_: float_ = nanprevLastSize_: float_ = nanvolume_: float_ = nanopen_: float_ = nanhigh_: float_ = nanlow_: float_ = nanclose_: float_ = nanvwap_: float_ = nanlow13week_: float_ = nanhigh13week_: float_ = nanlow26week_: float_ = nanhigh26week_: float_ = nanlow52week_: float_ = nanhigh52week_: float_ = nanbidYield_: float_ = nanaskYield_: float_ = nanlastYield_: float_ = nanmarkPrice_: float_ = nanhalted_: float_ = nanrtHistVolatility_: float_ = nanrtVolume_: float_ = nanrtTradeVolume_: float_ = nanrtTime_: datetime | None_ = NoneavVolume_: float_ = nantradeCount_: float_ = nantradeRate_: float_ = nanvolumeRate_: float_ = nanvolumeRate3Min_: float_ = nanvolumeRate5Min_: float_ = nanvolumeRate10Min_: float_ = nanshortable_: float_ = nanshortableShares_: float_ = nanindexFuturePremium_: float_ = nanfuturesOpenInterest_: float_ = nanputOpenInterest_: float_ = nancallOpenInterest_: float_ = nanputVolume_: float_ = nancallVolume_: float_ = nanavOptionVolume_: float_ = nanhistVolatility_: float_ = nanimpliedVolatility_: float_ = nanopenInterest_: float_ = nanlastRthTrade_: float_ = nanlastRegTime_: str_ = ''optionBidExch_: str_ = ''optionAskExch_: str_ = ''bondFactorMultiplier_: float_ = nancreditmanMarkPrice_: float_ = nancreditmanSlowMarkPrice_: float_ = nandelayedLastTimestamp_: datetime | None_ = NonedelayedHalted_: float_ = nanreutersMutualFunds_: str_ = ''etfNavClose_: float_ = nanetfNavPriorClose_: float_ = nanetfNavBid_: float_ = nanetfNavAsk_: float_ = nanetfNavLast_: float_ = nanetfFrozenNavLast_: float_ = nanetfNavHigh_: float_ = nanetfNavLow_: float_ = nansocialMarketAnalytics_: str_ = ''estimatedIpoMidpoint_: float_ = nanfinalIpoLast_: float_ = nandividends_: Dividends | None_ = NonefundamentalRatios_: FundamentalRatios | None_ = Noneticks_: list[TickData]tickByTicks: list[TickByTickAllLast | TickByTickBidAsk | TickByTickMidPoint]domBids: list[DOMLevel]domBidsDict: dict[int, DOMLevel]domAsks: list[DOMLevel]domAsksDict: dict[int, DOMLevel]domTicks: list[MktDepthData]bidGreeks: OptionComputation | None_ = NoneaskGreeks_: OptionComputation | None_ = NonelastGreeks_: OptionComputation | None_ = NonemodelGreeks_: OptionComputation | None_ = NonecustGreeks_: OptionComputation | None_ = NonebidEfp_: EfpData | None_ = NoneaskEfp_: EfpData | None_ = NonelastEfp_: EfpData | None_ = NoneopenEfp_: EfpData | None_ = NonehighEfp_: EfpData | None_ = NonelowEfp_: EfpData | None_ = NonecloseEfp_: EfpData | None_ = NoneauctionVolume_: float_ = nanauctionPrice_: float_ = nanauctionImbalance_: float_ = nanregulatoryImbalance_: float_ = nanbboExchange_: str_ = ''snapshotPermissions_: int_ = 0defaults_: IBDefaultscreated: bool_ = FalseisUnset(value)[source]Return type:
See if this ticker has a valid bid and ask.
Return type:
Return average of bid and ask, or defaults.unset if no valid bid and ask are available.
Return type:
Return the first available one of :rtype: float
last price if within current bid/ask or no bid/ask available;
average of bid and ask (midpoint).
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.ticker.TickerUpdateEvent(_name='', _with_error_done_events=True, error_event=None, done_event=None, _value=<NoValue>, _slots=<factory>, _done=False, _source=None, __weakref__=None, _task=None, NO_VALUE=<NoValue>)[source]trades()[source]
Emit trade ticks.
Return type:
Emit bid ticks.
Return type:
Emit ask ticks.
Return type:
Emit bid and ask ticks.
Return type:
Emit midpoint ticks.
Return type:
class ib_async.ticker.Tickfilter(tickTypes, source=None)[source]
Tick filtering event operators that emit(time, price, size).
Emit a new value to all connected listeners.
Parameters:
args – Argument values to emit to listeners.
Aggregate ticks into time bars, where the timing of new bars is derived from a timer event. Emits a completed Bar.
This event stores a BarList of all created bars in the bars property.
Parameters:
timer (Event) – Event for timing when a new bar starts.
Return type:
Aggregate ticks into bars that have the same number of ticks. Emits a completed Bar.
This event stores a BarList of all created bars in the bars property.
Parameters:
count (int) – Number of ticks to use to form one bar.
Return type:
Aggregate ticks into bars that have the same volume. Emits a completed Bar.
This event stores a BarList of all created bars in the bars property.
Parameters:
count – Number of ticks to use to form one bar.
Return type:
class ib_async.ticker.Midpoints(tickTypes, source=None)[source]on_source(ticker)[source]
Emit a new value to all connected listeners.
Parameters:
args – Argument values to emit to listeners.
class ib_async.ticker.Bar(time, open=nan, high=nan, low=nan, close=nan, volume=0, count=0)[source]time_: datetime | Noneopen: float_ = nanhigh_: float_ = nanlow_: float_ = nanclose_: float_ = nanvolume_: int_ = 0count_: int_ = 0class ib_async.ticker.BarList(*args)[source]class ib_async.ticker.TimeBars(timer, source=None)[source]
Aggregate ticks into time bars, where the timing of new bars is derived from a timer event. Emits a completed Bar.
This event stores a BarList of all created bars in the bars property.
Parameters:
timer – Event for timing when a new bar starts.
bars_: BarList_on_source(time, price, size)[source]
Emit a new value to all connected listeners.
Parameters:
args – Argument values to emit to listeners.
class ib_async.ticker.TickBars(count, source=None)[source]
Aggregate ticks into bars that have the same number of ticks. Emits a completed Bar.
This event stores a BarList of all created bars in the bars property.
Parameters:
count – Number of ticks to use to form one bar.
bars_: BarList_on_source(time, price, size)[source]
Emit a new value to all connected listeners.
Parameters:
args – Argument values to emit to listeners.
class ib_async.ticker.VolumeBars(volume, source=None)[source]
Aggregate ticks into bars that have the same volume. Emits a completed Bar.
This event stores a BarList of all created bars in the bars property.
Parameters:
count – Number of ticks to use to form one bar.
bars_: BarList_on_source(time, price, size)[source]
Emit a new value to all connected listeners.
Parameters:
args – Argument values to emit to listeners.
Object hierarchy.
class ib_async.objects.ScannerSubscription(numberOfRows=-1, instrument='', locationCode='', scanCode='', abovePrice=1.7976931348623157e+308, belowPrice=1.7976931348623157e+308, aboveVolume=2147483647, marketCapAbove=1.7976931348623157e+308, marketCapBelow=1.7976931348623157e+308, moodyRatingAbove='', moodyRatingBelow='', spRatingAbove='', spRatingBelow='', maturityDateAbove='', maturityDateBelow='', couponRateAbove=1.7976931348623157e+308, couponRateBelow=1.7976931348623157e+308, excludeConvertible=False, averageOptionVolumeAbove=2147483647, scannerSettingPairs='', stockTypeFilter='')[source]numberOfRows_: int_ = -1instrument_: str_ = ''locationCode_: str_ = ''scanCode_: str_ = ''abovePrice_: float_ = 1.7976931348623157e+308belowPrice_: float_ = 1.7976931348623157e+308aboveVolume_: int_ = 2147483647marketCapAbove_: float_ = 1.7976931348623157e+308marketCapBelow_: float_ = 1.7976931348623157e+308moodyRatingAbove_: str_ = ''moodyRatingBelow_: str_ = ''spRatingAbove_: str_ = ''spRatingBelow_: str_ = ''maturityDateAbove_: str_ = ''maturityDateBelow_: str_ = ''couponRateAbove_: float_ = 1.7976931348623157e+308couponRateBelow_: float_ = 1.7976931348623157e+308excludeConvertible_: bool_ = FalseaverageOptionVolumeAbove_: int_ = 2147483647scannerSettingPairs_: str_ = ''stockTypeFilter_: str_ = ''dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.SoftDollarTier(name='', val='', displayName='')[source]name_: str_ = ''val_: str_ = ''displayName_: str_ = ''dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.Execution(execId='', time=datetime.datetime(1970, 1, 1, 0, 0, tzinfo=datetime.timezone.utc), acctNumber='', exchange='', side='', shares=0.0, price=0.0, permId=0, clientId=0, orderId=0, liquidation=0, cumQty=0.0, avgPrice=0.0, orderRef='', evRule='', evMultiplier=0.0, modelCode='', lastLiquidity=0, pendingPriceRevision=False)[source]execId_: str_ = ''time_: datetime_ = datetime.datetime(1970, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)acctNumber_: str_ = ''exchange_: str_ = ''side_: str_ = ''shares_: float_ = 0.0price_: float_ = 0.0permId_: int_ = 0clientId_: int_ = 0orderId_: int_ = 0liquidation_: int_ = 0cumQty_: float_ = 0.0avgPrice_: float_ = 0.0orderRef_: str_ = ''evRule_: str_ = ''evMultiplier_: float_ = 0.0modelCode_: str_ = ''lastLiquidity_: int_ = 0pendingPriceRevision_: bool_ = Falsedict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.CommissionReport(execId='', commission=0.0, currency='', realizedPNL=0.0, yield_=0.0, yieldRedemptionDate=0)[source]execId_: str_ = ''commission_: float_ = 0.0currency_: str_ = ''realizedPNL_: float_ = 0.0yield_: float = 0.0yieldRedemptionDate_: int_ = 0dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.ExecutionFilter(clientId=0, acctCode='', time='', symbol='', secType='', exchange='', side='')[source]clientId_: int_ = 0acctCode_: str_ = ''time_: str_ = ''symbol_: str_ = ''secType_: str_ = ''exchange_: str_ = ''side_: str_ = ''dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.BarData(date=datetime.datetime(1970, 1, 1, 0, 0, tzinfo=datetime.timezone.utc), open=0.0, high=0.0, low=0.0, close=0.0, volume=0, average=0.0, barCount=0)[source]date_: date | datetime_ = datetime.datetime(1970, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)open_: float_ = 0.0high_: float_ = 0.0low_: float_ = 0.0close_: float_ = 0.0volume_: float_ = 0average_: float_ = 0.0barCount_: int_ = 0dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.RealTimeBar(time=datetime.datetime(1970, 1, 1, 0, 0, tzinfo=datetime.timezone.utc), endTime=-1, open_=0.0, high=0.0, low=0.0, close=0.0, volume=0.0, wap=0.0, count=0)[source]time_: datetime_ = datetime.datetime(1970, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)endTime_: int_ = -1open_: float = 0.0high_: float_ = 0.0low_: float_ = 0.0close_: float_ = 0.0volume_: float_ = 0.0wap_: float_ = 0.0count_: int_ = 0dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.TickAttrib(canAutoExecute=False, pastLimit=False, preOpen=False)[source]canAutoExecute_: bool_ = FalsepastLimit_: bool_ = FalsepreOpen_: bool_ = Falsedict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.TickAttribBidAsk(bidPastLow=False, askPastHigh=False)[source]bidPastLow_: bool_ = FalseaskPastHigh_: bool_ = Falsedict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.TickAttribLast(pastLimit=False, unreported=False)[source]pastLimit_: bool_ = Falseunreported_: bool_ = Falsedict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.HistogramData(price=0.0, count=0)[source]price_: float_ = 0.0count_: int_ = 0dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.NewsProvider(code='', name='')[source]code_: str_ = ''name_: str_ = ''dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.DepthMktDataDescription(exchange='', secType='', listingExch='', serviceDataType='', aggGroup=2147483647)[source]exchange_: str_ = ''secType_: str_ = ''listingExch_: str_ = ''serviceDataType_: str_ = ''aggGroup_: int_ = 2147483647dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.PnL(account='', modelCode='', dailyPnL=nan, unrealizedPnL=nan, realizedPnL=nan)[source]account_: str_ = ''modelCode_: str_ = ''dailyPnL_: float_ = nanunrealizedPnL_: float_ = nanrealizedPnL_: float_ = nandict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.TradeLogEntry(time, status='', message='', errorCode=0)[source]time_: datetimestatus: str_ = ''message_: str_ = ''errorCode_: int_ = 0dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.PnLSingle(account='', modelCode='', conId=0, dailyPnL=nan, unrealizedPnL=nan, realizedPnL=nan, position=0, value=nan)[source]account_: str_ = ''modelCode_: str_ = ''conId_: int_ = 0dailyPnL_: float_ = nanunrealizedPnL_: float_ = nanrealizedPnL_: float_ = nanposition_: int_ = 0value_: float_ = nandict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.HistoricalSession(startDateTime='', endDateTime='', refDate='')[source]startDateTime_: str_ = ''endDateTime_: str_ = ''refDate_: str_ = ''dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.HistoricalSchedule(startDateTime='', endDateTime='', timeZone='', sessions=<factory>)[source]startDateTime_: str_ = ''endDateTime_: str_ = ''timeZone_: str_ = ''sessions_: list[HistoricalSession]_dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.WshEventData(conId=2147483647, filter='', fillWatchlist=False, fillPortfolio=False, fillCompetitors=False, startDate='', endDate='', totalLimit=2147483647)[source]conId_: int_ = 2147483647filter_: str_ = ''fillWatchlist_: bool_ = FalsefillPortfolio_: bool_ = FalsefillCompetitors_: bool_ = FalsestartDate_: str_ = ''endDate_: str_ = ''totalLimit_: int_ = 2147483647dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.AccountValue(account, tag, value, currency, modelCode)[source]
Create new instance of AccountValue(account, tag, value, currency, modelCode)
account_: strtag: strvalue: strcurrency: strmodelCode: str_class ib_async.objects.TickData(time, tickType, price, size)[source]
Create new instance of TickData(time, tickType, price, size)
time_: datetimetickType: intprice: floatsize: float_class ib_async.objects.HistoricalTick(time, price, size)[source]
Create new instance of HistoricalTick(time, price, size)
time_: datetimeprice: floatsize: float_class ib_async.objects.HistoricalTickBidAsk(time, tickAttribBidAsk, priceBid, priceAsk, sizeBid, sizeAsk)[source]
Create new instance of HistoricalTickBidAsk(time, tickAttribBidAsk, priceBid, priceAsk, sizeBid, sizeAsk)
time_: datetimetickAttribBidAsk: TickAttribBidAskpriceBid: floatpriceAsk: floatsizeBid: floatsizeAsk: float_class ib_async.objects.HistoricalTickLast(time, tickAttribLast, price, size, exchange, specialConditions)[source]
Create new instance of HistoricalTickLast(time, tickAttribLast, price, size, exchange, specialConditions)
time_: datetimetickAttribLast: TickAttribLastprice: floatsize: floatexchange: strspecialConditions: str_class ib_async.objects.TickByTickAllLast(tickType, time, price, size, tickAttribLast, exchange, specialConditions)[source]
Create new instance of TickByTickAllLast(tickType, time, price, size, tickAttribLast, exchange, specialConditions)
tickType_: inttime: datetimeprice: floatsize: floattickAttribLast: TickAttribLastexchange: strspecialConditions: str_class ib_async.objects.TickByTickBidAsk(time, bidPrice, askPrice, bidSize, askSize, tickAttribBidAsk)[source]
Create new instance of TickByTickBidAsk(time, bidPrice, askPrice, bidSize, askSize, tickAttribBidAsk)
time_: datetimebidPrice: floataskPrice: floatbidSize: floataskSize: floattickAttribBidAsk: TickAttribBidAsk_class ib_async.objects.TickByTickMidPoint(time, midPoint)[source]
Create new instance of TickByTickMidPoint(time, midPoint)
time_: datetimemidPoint: float_class ib_async.objects.MktDepthData(time, position, marketMaker, operation, side, price, size)[source]
Create new instance of MktDepthData(time, position, marketMaker, operation, side, price, size)
time_: datetimeposition: intmarketMaker: stroperation: intside: intprice: floatsize: float_class ib_async.objects.DOMLevel(price, size, marketMaker)[source]
Create new instance of DOMLevel(price, size, marketMaker)
price_: floatsize: floatmarketMaker: str_class ib_async.objects.PriceIncrement(lowEdge, increment)[source]
Create new instance of PriceIncrement(lowEdge, increment)
lowEdge_: floatincrement: float_class ib_async.objects.PortfolioItem(contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, account)[source]
Create new instance of PortfolioItem(contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, account)
contract_: Contractposition: floatmarketPrice: floatmarketValue: floataverageCost: floatunrealizedPNL: floatrealizedPNL: floataccount: str_class ib_async.objects.Position(account, contract, position, avgCost)[source]
Create new instance of Position(account, contract, position, avgCost)
account_: strcontract: Contractposition: floatavgCost: float_class ib_async.objects.Fill(contract, execution, commissionReport, time)[source]
Create new instance of Fill(contract, execution, commissionReport, time)
contract_: Contractexecution: ExecutioncommissionReport: CommissionReporttime: datetime_class ib_async.objects.EfpData(basisPoints, formattedBasisPoints, impliedFuture, holdDays, futureLastTradeDate, dividendImpact, dividendsToLastTradeDate)[source]
Exchange for Physical (EFP) futures data.
EFP allows trading a position in a single stock for a position in the corresponding single stock future.
basisPoints_: floatformattedBasisPoints: strimpliedFuture: floatholdDays: intfutureLastTradeDate: strdividendImpact: floatdividendsToLastTradeDate: floatclass ib_async.objects.OptionComputation(tickAttrib, impliedVol=None, delta=None, optPrice=None, pvDividend=None, gamma=None, vega=None, theta=None, undPrice=None)[source]tickAttrib: intimpliedVol: float | Nonedelta: float | NoneoptPrice: float | NonepvDividend: float | Nonegamma: float | Nonevega: float | Nonetheta: float | NoneundPrice: float | None_dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.OptionChain(exchange, underlyingConId, tradingClass, multiplier, expirations, strikes)[source]exchange_: strunderlyingConId: inttradingClass: strmultiplier: strexpirations: list[str]strikes: list[float]_dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.Dividends(past12Months, next12Months, nextDate, nextAmount)[source]past12Months_: float | Nonenext12Months: float | NonenextDate: date | NonenextAmount: float | None_dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.NewsArticle(articleType, articleText)[source]articleType_: intarticleText: str_dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.HistoricalNews(time, providerCode, articleId, headline)[source]time_: datetimeproviderCode: strarticleId: strheadline: str_dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.NewsTick(timeStamp, providerCode, articleId, headline, extraData)[source]timeStamp_: intproviderCode: strarticleId: strheadline: strextraData: str_dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.NewsBulletin(msgId, msgType, message, origExchange)[source]msgId_: intmsgType: intmessage: strorigExchange: str_dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.FamilyCode(accountID, familyCodeStr)[source]accountID_: strfamilyCodeStr: str_dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.SmartComponent(bitNumber, exchange, exchangeLetter)[source]bitNumber_: intexchange: strexchangeLetter: str_dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.ConnectionStats(startTime, duration, numBytesRecv, numBytesSent, numMsgRecv, numMsgSent)[source]startTime_: floatduration: floatnumBytesRecv: intnumBytesSent: intnumMsgRecv: intnumMsgSent: int_dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.objects.BarDataList(*args)[source]
List of BarData that also stores all request parameters.
Events:
updateEvent(bars:BarDataList, hasNewBar: bool)
reqId_: intcontract: ContractendDateTime: datetime | date | str | NonedurationStr: strbarSizeSetting: strwhatToShow: struseRTH: boolformatDate: intkeepUpToDate: boolchartOptions: list[TagValue]class ib_async.objects.RealTimeBarList(*args_)[source]
List of RealTimeBar that also stores all request parameters.
Events:
updateEvent(bars:RealTimeBarList, hasNewBar: bool)
reqId_: intcontract: ContractbarSize: intwhatToShow: struseRTH: boolrealTimeBarsOptions: list[TagValue]class ib_async.objects.ScanDataList(*args_)[source]
List of ScanData that also stores all request parameters.
Events:
updateEvent (ScanDataList)reqId_: intsubscription: ScannerSubscriptionscannerSubscriptionOptions: list[TagValue]scannerSubscriptionFilterOptions: list[TagValue]class ib_async.objects.DynamicObject(**kwargs_)[source]class ib_async.objects.FundamentalRatios(**kwargs)[source]
class ib_async.objects.IBDefaults(emptyPrice=-1, emptySize=0, unset=nan, timezone=datetime.timezone.utc)[source]
A simple way to provide default values when populating API data.
emptyPrice_: Any_ = -1emptySize_: Any_ = 0unset_: Any_ = nantimezone_: tzinfo_ = datetime.timezone.utcdict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.wrapper.RequestError(reqId, code, message)[source]
Exception to raise when the API reports an error that can be tied to a single request.
Parameters:
reqId (int) – Original request ID.
code (int) – Original error code.
message (str) – Original error message.
Utilities.
ib_async.util.globalErrorEvent(*args) = Event<Event, Slots(slots=[])>
Event to emit global exceptions.
ib_async.util.df(objs, labels=None)[source]
Create pandas DataFrame from the sequence of same-type objects.
Parameters:
labels (list[str] | None) – If supplied, retain only the given labels and drop the rest.
ib_async.util.dataclassAsDict(obj)[source]
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
ib_async.util.dataclassAsTuple(obj)[source]
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
ib_async.util.dataclassNonDefaults(obj)[source]
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
ib_async.util.dataclassUpdate(obj, *srcObjs, **kwargs)[source]
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
ib_async.util.dataclassRepr(obj)[source]
Provide a culled representation of the given dataclass instance, showing only the fields with a non-default value.
Return type:
ib_async.util.isnamedtupleinstance(x)[source]
From https://stackoverflow.com/a/2166841/6067848
ib_async.util.tree(obj)[source]
Convert object to a tree of lists, dicts and simple values. The result can be serialized to JSON.
ib_async.util.barplot(bars, title='', upColor='blue', downColor='red')[source]
Create candlestick plot for the given bars. The bars can be given as a DataFrame or as a list of bar objects.
ib_async.util.allowCtrlC()[source]
Allow Control-C to end program.
ib_async.util.logToFile(path, level=20)[source]
Create a log handler that logs to the given file.
ib_async.util.logToConsole(level=20)[source]
Create a log handler that logs to the console.
ib_async.util.isNan(x)[source]
Not a number test.
Return type:
ib_async.util.formatSI(n)[source]
Format the integer or float n to 3 significant digits + SI prefix.
Return type:
class ib_async.util.timeit(title='Run')[source]
Context manager for timing.
ib_async.util.run(*awaitables, timeout=None)[source]
By default run the event loop forever.
When awaitables (like Tasks, Futures or coroutines) are given then run the event loop until each has completed and return their results.
An optional timeout (in seconds) can be given that will raise asyncio.TimeoutError if the awaitables are not ready within the timeout period.
ib_async.util.schedule(time, callback, *args)[source]
Schedule the callback to be run at the given time with the given arguments. This will return the Event Handle.
Parameters:
time (time | datetime) – Time to run callback. If given as datetime.time then use today as date.
callback (Callable) – Callable scheduled to run.
args – Arguments for to call callback with.
ib_async.util.sleep(secs=0.02)[source]
Wait for the given amount of seconds while everything still keeps processing in the background. Never use time.sleep().
Parameters:
secs (float) – Time in seconds to wait.
Return type:
ib_async.util.timeRange(start, end, step)[source]
Iterator that waits periodically until certain time points are reached while yielding those time points.
Parameters:
start (time | datetime) – Start time, can be specified as datetime.datetime, or as datetime.time in which case today is used as the date
end (time | datetime) – End time, can be specified as datetime.datetime, or as datetime.time in which case today is used as the date
step (float) – The number of seconds of each period
Return type:
ib_async.util.waitUntil(t)[source]
Wait until the given time t is reached.
Parameters:
t (time | datetime) – The time t can be specified as datetime.datetime, or as datetime.time in which case today is used as the date.
Return type:
async ib_async.util.timeRangeAsync(start, end, step)[source]
Async version of timeRange().
Return type:
async ib_async.util.waitUntilAsync(t)[source]
Async version of waitUntil().
Return type:
ib_async.util.patchAsyncio()[source]
Patch asyncio to allow nested event loops.
ib_async.util.getLoop()[source]
Get asyncio event loop with smart fallback handling.
This function is designed for use in synchronous contexts or when the execution context is unknown. It will: 1. Try to get the currently running event loop (if in async context) 2. Fall back to getting the current thread’s event loop via policy 3. Create a new event loop if none exists or if the existing one is closed
For performance-critical async code paths, prefer using asyncio.get_running_loop() directly instead of this function.
Note: This function does NOT cache the loop to avoid stale loop bugs when loops are closed and recreated (e.g., in testing, Jupyter notebooks).
ib_async.util.startLoop()[source]
Use nested asyncio event loop for Jupyter notebooks.
ib_async.util.useQt(qtLib='PyQt5', period=0.01)[source]
Run combined Qt5/asyncio event loop.
Parameters:
ib_async.util.formatIBDatetime(t)[source]
Format date or datetime to string that IB uses.
Return type:
ib_async.util.parseIBDatetime(s)[source]
Parse string in IB date or datetime format to datetime.
Return type:
Access to account statement webservice.
ib_async.flexreport.FLEXREPORT_URL_: Final_ _= 'https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService/SendRequest?'_[](#ib_async.flexreport.FLEXREPORT_URL "Link to this definition")
//www.interactivebrokers.com/campus/ibkr-api-page/flex-web-service/#flex-generate-report
Type:
https
exception ib_async.flexreport.FlexError[source]class ib_async.flexreport.FlexReport(token=None, queryId=None, path=None)[source]
To obtain a token:
Login to web portal
Go to Settings
Click on “Configure Flex Web Service”
Generate token
Download a report by giving a valid token and queryId, or load from file by giving a valid path.
To overwrite default URL, set env variable IB_FLEXREPORT_URL.
data_: bytesroot: Element_topics()[source]
Get the set of topics that can be extracted from this report.
extract(topic, parseNumbers=True)[source]
Extract items of given topic and return as list of objects.
The topic is a string like TradeConfirm, ChangeInDividendAccrual, Order, etc.
Return type:
df(topic, parseNumbers=True)[source]
Same as extract but return the result as a pandas DataFrame.
Generate flexreport URL.
download(token, queryId)[source]
Download report for the given token and queryId.
Load report from XML file.
Save report to XML file.
class ib_async.ibcontroller.IBC(twsVersion=0, gateway=False, tradingMode='', twsPath='', twsSettingsPath='', ibcPath='', ibcIni='', javaPath='', userid='', password='', fixuserid='', fixpassword='', on2fatimeout='')[source]
Programmatic control over starting and stopping TWS/Gateway using IBC (https://github.com/IbcAlpha/IBC).
Parameters:
twsVersion (int) – (required) The major version number for TWS or gateway.
gateway (bool) –
tradingMode (str) – ‘live’ or ‘paper’.
userid (str) – IB account username. It is recommended to set the real username/password in a secured IBC config file.
password (str) – IB account password.
twsPath (str) –
twsSettingsPath (str) –
ibcPath (str) –
ibcIni (str) –
javaPath (str) – Path to Java executable. Default is to use the Java VM included with TWS/gateway.
fixuserid (str) – FIX account user id (gateway only).
fixpassword (str) – FIX account password (gateway only).
on2fatimeout (str) – What to do if 2-factor authentication times out; Can be ‘restart’ or ‘exit’.
This is not intended to be run in a notebook.
To use IBC on Windows, the proactor (or quamash) event loop must have been set:
import asyncioasyncio.set\_event\_loop(asyncio.ProactorEventLoop())
Example usage:
ibc=IBC(976,gateway=True,tradingMode='live',userid='edemo',password='demouser')ibc.start()IB.run()
IbcLogLevel_: ClassVar_ = 10twsVersion_: int_ = 0gateway_: bool_ = FalsetradingMode_: str_ = ''twsPath_: str_ = ''twsSettingsPath_: str_ = ''ibcPath_: str_ = ''ibcIni_: str_ = ''javaPath_: str_ = ''userid_: str_ = ''password_: str_ = ''fixuserid_: str_ = ''fixpassword_: str_ = ''on2fatimeout_: str_ = ''start()[source]
Launch TWS/IBG.
Terminate TWS/IBG.
async startAsync()[source]async terminateAsync()[source]async monitorAsync()[source]dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type:
class ib_async.ibcontroller.Watchdog(controller, ib, host='127.0.0.1', port=7497, clientId=1, connectTimeout=2, appStartupTime=30, appTimeout=20, retryDelay=2, readonly=False, account='', raiseSyncErrors=False, probeContract=Forex('EURUSD', exchange='IDEALPRO'), probeTimeout=4)[source]
Start, connect and watch over the TWS or gateway app and try to keep it up and running. It is intended to be used in an event-driven application that properly initializes itself upon (re-)connect.
It is not intended to be used in a notebook or in imperative-style code. Do not expect Watchdog to magically shield you from reality. Do not use Watchdog unless you understand what it does and doesn’t do.
Parameters:
controller (IBC) – (required) IBC instance.
ib (IB) – (required) IB instance to be used. Do not connect this instance as Watchdog takes care of that.
host (str) – Used for connecting IB instance.
port (int) – Used for connecting IB instance.
clientId (int) – Used for connecting IB instance.
connectTimeout (float) – Used for connecting IB instance.
readonly (bool) – Used for connecting IB instance.
appStartupTime (float) – Time (in seconds) that the app is given to start up. Make sure that it is given ample time.
appTimeout (float) – Timeout (in seconds) for network traffic idle time.
retryDelay (float) – Time (in seconds) to restart app after a previous failure.
probeContract (Contract) – Contract to use for historical data probe requests (default is EURUSD).
probeTimeout (float)__; Timeout _(_in seconds)
The idea is to wait until there is no traffic coming from the app for a certain amount of time (the appTimeout parameter). This triggers a historical request to be placed just to see if the app is still alive and well. If yes, then continue, if no then restart the whole app and reconnect. Restarting will also occur directly on errors 1100 and 100.
Example usage:
def onConnected():print(ib.accountValues())ibc=IBC(974,gateway=True,tradingMode='paper')ib=IB()ib.connectedEvent+=onConnectedwatchdog=Watchdog(ibc,ib,port=4002)watchdog.start()ib.run()
Events:
startingEvent (watchdog: Watchdog)
startedEvent (watchdog: Watchdog)
stoppingEvent (watchdog: Watchdog)
stoppedEvent (watchdog: Watchdog)
softTimeoutEvent (watchdog: Watchdog)
hardTimeoutEvent (watchdog: Watchdog)
events = ['startingEvent', 'startedEvent', 'stoppingEvent', 'stoppedEvent', 'softTimeoutEvent', 'hardTimeoutEvent']controller_: IBCib: IBhost: str_ = '127.0.0.1'port_: int_ = 7497clientId_: int_ = 1connectTimeout_: float_ = 2appStartupTime_: float_ = 30appTimeout_: float_ = 20retryDelay_: float_ = 2readonly_: bool_ = Falseaccount_: str_ = ''raiseSyncErrors_: bool_ = FalseprobeContract_: Contract_ = Forex('EURUSD', exchange='IDEALPRO')probeTimeout_: float_ = 4start()[source]stop()[source]async runAsync()[source]dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type:
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type:
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type:
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword arguments.
Return type: