Skip to main content

ib_async.ib

Generated from the installed ib_async 2.1.0 package. Signatures and defaults are version-specific.

High-level interface to Interactive Brokers.

IB

IB(defaults: ib_async.objects.IBDefaults = IBDefaults(emptyPrice=-1, emptySize=0, unset=nan, timezone=datetime.timezone.utc))

Completeness: signature-only · Canonical ID: ib_async.ib.IB

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

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): Specifies the behaviour when certain API requests fail:

  • False: Silently return an empty result;
  • True: Raise a .RequestError. 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

IB.accountSummaryEvent

accountSummaryEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.accountSummaryEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.accountValueEvent

accountValueEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.accountValueEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.barUpdateEvent

barUpdateEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.barUpdateEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.cancelOrderEvent

cancelOrderEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.cancelOrderEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.commissionReportEvent

commissionReportEvent

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.commissionReportEvent

Explicit policy override after evidence-backed documentation review.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.connectedEvent

connectedEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.connectedEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

IB.disconnectedEvent

disconnectedEvent

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.disconnectedEvent

Explicit policy override after evidence-backed documentation review.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.errorEvent

errorEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.errorEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.execDetailsEvent

execDetailsEvent

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.execDetailsEvent

Explicit policy override after evidence-backed documentation review.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.newOrderEvent

newOrderEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.newOrderEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.newsBulletinEvent

newsBulletinEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.newsBulletinEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.openOrderEvent

openOrderEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.openOrderEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.orderModifyEvent

orderModifyEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.orderModifyEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.orderStatusEvent

orderStatusEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.orderStatusEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.pendingTickersEvent

pendingTickersEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.pendingTickersEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.pnlEvent

pnlEvent

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.pnlEvent

Explicit policy override after evidence-backed documentation review.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.pnlSingleEvent

pnlSingleEvent

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.pnlSingleEvent

Explicit policy override after evidence-backed documentation review.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.positionEvent

positionEvent

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.positionEvent

Explicit policy override after evidence-backed documentation review.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.scannerDataEvent

scannerDataEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.scannerDataEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.tickNewsEvent

tickNewsEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.tickNewsEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.timeoutEvent

timeoutEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.timeoutEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.updateEvent

updateEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.updateEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.updatePortfolioEvent

updatePortfolioEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.updatePortfolioEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.wshEvent

wshEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.wshEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

IB.wshMetaEvent

wshMetaEvent

Completeness: signature-only · Canonical ID: ib_async.ib.IB.wshMetaEvent

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

  • Emitted by: IB

Sources and provenance

enter

__enter__(self)

Completeness: signature-only · Canonical ID: ib_async.ib.IB.__enter__

Runtime signature is published; semantic enrichment remains outstanding.

No library docstring is provided; consult the signature, type fields, and operational guides.

exit

__exit__(self, *_exc)

Completeness: signature-only · Canonical ID: ib_async.ib.IB.__exit__

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

No library docstring is provided; consult the signature, type fields, and operational guides.

accountSummary

accountSummary(self, account: str = '') -> list[ib_async.objects.AccountValue]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.accountSummary

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

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.

Args: account: If specified, filter for this account name.

accountSummaryAsync

accountSummaryAsync(self, account: str = '') -> list[ib_async.objects.AccountValue]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.accountSummaryAsync

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

No library docstring is provided; consult the signature, type fields, and operational guides.

accountValues

accountValues(self, account: str = '') -> list[ib_async.objects.AccountValue]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.accountValues

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

List of account values for the given account, or of all accounts if account is left blank.

Args: account: If specified, filter for this account name.

bracketOrder

bracketOrder(self, action: str, quantity: float, limitPrice: float, takeProfitPrice: float, stopLossPrice: float, **kwargs) -> ib_async.order.BracketOrder

Completeness: signature-only · Canonical ID: ib_async.ib.IB.bracketOrder

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Create a limit order that is bracketed by a take-profit order and a stop-loss order. Submit the bracket like:

for o in bracket: ib.placeOrder(contract, o)

https://interactivebrokers.github.io/tws-api/bracket_order.html

Args: action: 'BUY' or 'SELL'. quantity: Size of order. limitPrice: Limit price of entry order. takeProfitPrice: Limit price of profit order. stopLossPrice: Stop price of loss order.

calculateImpliedVolatility

calculateImpliedVolatility(self, contract: ib_async.contract.Contract, optionPrice: float, underPrice: float, implVolOptions: list[ib_async.contract.TagValue] = []) -> ib_async.objects.OptionComputation

Completeness: signature-only · Canonical ID: ib_async.ib.IB.calculateImpliedVolatility

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Calculate the volatility given the option price.

This method is blocking.

https://interactivebrokers.github.io/tws-api/option_computations.html

Args: contract: Option contract. optionPrice: Option price to use in calculation. underPrice: Price of the underlier to use in calculation implVolOptions: Unknown

calculateOptionPrice

calculateOptionPrice(self, contract: ib_async.contract.Contract, volatility: float, underPrice: float, optPrcOptions: list[ib_async.contract.TagValue] = []) -> ib_async.objects.OptionComputation

Completeness: signature-only · Canonical ID: ib_async.ib.IB.calculateOptionPrice

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Calculate the option price given the volatility.

This method is blocking.

https://interactivebrokers.github.io/tws-api/option_computations.html

Args: contract: Option contract. volatility: Option volatility to use in calculation. underPrice: Price of the underlier to use in calculation implVolOptions: Unknown

connect

connect(self, host: str = '127.0.0.1', port: int = 7497, clientId: int = 1, timeout: float = 4, readonly: bool = False, account: str = '', raiseSyncErrors: bool = False, fetchFields: ib_async.ib.StartupFetch = <StartupFetch.POSITIONS|ORDERS_OPEN|ORDERS_COMPLETE|ACCOUNT_UPDATES|SUB_ACCOUNT_UPDATES|EXECUTIONS: 63>)

Completeness: signature-only · Canonical ID: ib_async.ib.IB.connect

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

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.

Args: host: Host name or IP address. port: Port number. clientId: 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: If establishing the connection takes longer than timeout seconds then the asyncio.TimeoutError exception is raised. Set to 0 to disable timeout. readonly: Set to True when API is in read-only mode. account: Main account to receive updates for. raiseSyncErrors: When True this will cause an initial sync request error to raise a ConnectionError. When False the error will only be logged at error level. fetchFields: By default, all account data is loaded and cached when a new connection is made. You can optionally disable all or some of the account attribute fetching during a connection using the StartupFetch field flags. See StartupFetch in ib.py for member details. There is also StartupFetchNONE and StartupFetchALL as shorthand. Individual flag field members can be added or removed to the fetchFields parameter as needed.

disconnect

disconnect(self) -> str | None

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.disconnect

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

Disconnect from a TWS or IB gateway application. This will clear all session state.

executions

executions(self) -> list[ib_async.objects.Execution]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.executions

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

List of all executions from this session.

fills

fills(self) -> list[ib_async.objects.Fill]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.fills

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

List of all fills from this session.

getWshEventData

getWshEventData(self, data: ib_async.objects.WshEventData) -> str

Completeness: signature-only · Canonical ID: ib_async.ib.IB.getWshEventData

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

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 &lt;https://www.wallstreethorizon.com/interactive-brokers&gt;_ 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)

getWshMetaData

getWshMetaData(self) -> str

Completeness: signature-only · Canonical ID: ib_async.ib.IB.getWshMetaData

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

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 &lt;https://www.wallstreethorizon.com/interactive-brokers&gt;_ is required.

Get the list of available filters and event types:

meta = ib.getWshMetaData() print(meta)

isConnected

isConnected(self) -> bool

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.isConnected

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

Is there an API connection to TWS or IB gateway?

loopUntil

loopUntil(self, condition=None, timeout: float = 0) -> collections.abc.Iterator[object]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.loopUntil

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Iterate until condition is met, with optional timeout in seconds. The yielded value is that of the condition or False when timed out.

Args: condition: Predicate function that is tested after every network update. timeout: Maximum time in seconds to wait. If 0 then no timeout is used.

managedAccounts

managedAccounts(self) -> list[str]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.managedAccounts

Explicit policy override after evidence-backed documentation review.

Sources and provenance

List of account names.

newsBulletins

newsBulletins(self) -> list[ib_async.objects.NewsBulletin]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.newsBulletins

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

List of IB news bulletins.

newsTicks

newsTicks(self) -> list[ib_async.objects.NewsTick]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.newsTicks

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

List of ticks with headline news. The article itself can be retrieved with .reqNewsArticle.

oneCancelsAll

oneCancelsAll(orders: list[ib_async.order.Order], ocaGroup: str, ocaType: int) -> list[ib_async.order.Order]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.oneCancelsAll

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Place the trades in the same One Cancels All (OCA) group.

https://interactivebrokers.github.io/tws-api/oca.html

Args: orders: The orders that are to be placed together.

openOrders

openOrders(self) -> list[ib_async.order.Order]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.openOrders

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

List of all open orders.

openTrades

openTrades(self) -> list[ib_async.order.Trade]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.openTrades

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

List of all open order trades.

orders

orders(self) -> list[ib_async.order.Order]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.orders

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

List of all orders from this session.

pendingTickers

pendingTickers(self) -> list[ib_async.ticker.Ticker]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.pendingTickers

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Get a list of all tickers that have pending ticks or domTicks.

pnl

pnl(self, account='', modelCode='') -> list[ib_async.objects.PnL]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.pnl

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

List of subscribed .PnL objects (profit and loss), optionally filtered by account and/or modelCode.

The .PnL objects are kept live updated.

Args: account: If specified, filter for this account name. modelCode: If specified, filter for this account model.

pnlSingle

pnlSingle(self, account: str = '', modelCode: str = '', conId: int = 0) -> list[ib_async.objects.PnLSingle]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.pnlSingle

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

List of subscribed .PnLSingle objects (profit and loss for single positions).

The .PnLSingle objects are kept live updated.

Args: account: If specified, filter for this account name. modelCode: If specified, filter for this account model. conId: If specified, filter for this contract ID.

portfolio

portfolio(self, account: str = '') -> list[ib_async.objects.PortfolioItem]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.portfolio

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

List of portfolio items for the given account, or of all retrieved portfolio items if account is left blank.

Args: account: If specified, filter for this account name.

positions

positions(self, account: str = '') -> list[ib_async.objects.Position]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.positions

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

List of positions for the given account, or of all accounts if account is left blank.

Args: account: If specified, filter for this account name.

qualifyContracts

qualifyContracts(self, *contracts: ib_async.contract.Contract) -> list[ib_async.contract.Contract]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.qualifyContracts

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

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.

Args: contracts: Contracts to qualify.

qualifyContractsAsync

qualifyContractsAsync(self, *contracts: ib_async.contract.Contract, returnAll: bool = False) -> list[ib_async.contract.Contract | list[ib_async.contract.Contract | None] | None]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.qualifyContractsAsync

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

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.

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.

realtimeBars

realtimeBars(self) -> list[ib_async.objects.BarDataList | ib_async.objects.RealTimeBarList]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.realtimeBars

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Get a list of all live updated bars. These can be 5 second realtime bars or live updated historical bars.

reqAccountSummary

reqAccountSummary(self)

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.reqAccountSummary

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

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.

reqAccountUpdates

reqAccountUpdates(self, account: str = '')

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqAccountUpdates

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

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.

Args: account: If specified, filter for this account name.

reqAccountUpdatesMulti

reqAccountUpdatesMulti(self, account: str = '', modelCode: str = '')

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.reqAccountUpdatesMulti

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

It is recommended to use .accountValues instead.

Request account values of multiple accounts and keep updated.

This method is blocking.

Args: account: If specified, filter for this account name. modelCode: If specified, filter for this account model.

reqAllOpenOrders

reqAllOpenOrders(self) -> list[ib_async.order.Trade]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.reqAllOpenOrders

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

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.

reqCompletedOrders

reqCompletedOrders(self, apiOnly: bool) -> list[ib_async.order.Trade]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.reqCompletedOrders

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

Request and return a list of completed trades.

Args: apiOnly: Request only API orders (not manually placed TWS orders).

reqContractDetails

reqContractDetails(self, contract: ib_async.contract.Contract) -> list[ib_async.contract.ContractDetails]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.reqContractDetails

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

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

Args: contract: The contract to get details for.

reqCurrentTime

reqCurrentTime(self) -> datetime.datetime

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqCurrentTime

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Request TWS current time.

This method is blocking.

reqExecutions

reqExecutions(self, execFilter: ib_async.objects.ExecutionFilter | None = None) -> list[ib_async.objects.Fill]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.reqExecutions

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

It is recommended to use .fills or .executions instead.

Request and return a list of fills.

This method is blocking.

Args: execFilter: If specified, return executions that match the filter.

reqFundamentalData

reqFundamentalData(self, contract: ib_async.contract.Contract, reportType: str, fundamentalDataOptions: list[ib_async.contract.TagValue] = []) -> str

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqFundamentalData

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Get fundamental data of a contract in XML format.

This method is blocking.

https://interactivebrokers.github.io/tws-api/fundamentals.html

Args: contract: Contract to query. reportType:

  • 'ReportsFinSummary': Financial summary
  • 'ReportsOwnership': Company's ownership
  • 'ReportSnapshot': Company's financial overview
  • 'ReportsFinStatements': Financial Statements
  • 'RESC': Analyst Estimates
  • 'CalendarReport': Company's calendar fundamentalDataOptions: Unknown

reqHeadTimeStamp

reqHeadTimeStamp(self, contract: ib_async.contract.Contract, whatToShow: str, useRTH: bool, formatDate: int = 1) -> datetime.datetime

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqHeadTimeStamp

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Get the datetime of earliest available historical data for the contract.

Args: contract: Contract of interest. useRTH: If True then only show data from within Regular Trading Hours, if False then show all data. formatDate: If set to 2 then the result is returned as a timezone-aware datetime.datetime with UTC timezone.

reqHistogramData

reqHistogramData(self, contract: ib_async.contract.Contract, useRTH: bool, period: str) -> list[ib_async.objects.HistogramData]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqHistogramData

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Request histogram data.

This method is blocking.

https://interactivebrokers.github.io/tws-api/histograms.html

Args: contract: Contract to query. useRTH: If True then only show data from within Regular Trading Hours, if False then show all data. period: Period of which data is being requested, for example '3 days'.

reqHistoricalData

reqHistoricalData(self, contract: ib_async.contract.Contract, endDateTime: datetime.datetime | datetime.date | str | None, durationStr: str, barSizeSetting: str, whatToShow: str, useRTH: bool, formatDate: int = 1, keepUpToDate: bool = False, chartOptions: list[ib_async.contract.TagValue] = [], timeout: float = 60) -> ib_async.objects.BarDataList

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.reqHistoricalData

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

Request historical bar data.

This method is blocking.

https://interactivebrokers.github.io/tws-api/historical_bars.html

Args: contract: Contract of interest. endDateTime: 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: Time span of all the bars. Examples: '60 S', '30 D', '13 W', '6 M', '10 Y'. barSizeSetting: 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: 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: If True then only show data from within Regular Trading Hours, if False then show all data. formatDate: 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: If True then a realtime subscription is started to keep the bars updated; endDateTime must be set empty ('') then. chartOptions: Unknown. timeout: Timeout in seconds after which to cancel the request and return an empty bar series. Set to 0 to wait indefinitely.

reqHistoricalNews

reqHistoricalNews(self, conId: int, providerCodes: str, startDateTime: str | datetime.date, endDateTime: str | datetime.date, totalResults: int, historicalNewsOptions: list[ib_async.contract.TagValue] = []) -> ib_async.objects.HistoricalNews

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqHistoricalNews

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Get historical news headline.

https://interactivebrokers.github.io/tws-api/news.html

This method is blocking.

Args: conId: Search news articles for contract with this conId. providerCodes: A '+'-separated list of provider codes, like 'BZ+FLY'. startDateTime: 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: 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: Maximum number of headlines to fetch (300 max). historicalNewsOptions: Unknown.

reqHistoricalSchedule

reqHistoricalSchedule(self, contract: ib_async.contract.Contract, numDays: int, endDateTime: datetime.datetime | datetime.date | str | None = '', useRTH: bool = True) -> ib_async.objects.HistoricalSchedule

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqHistoricalSchedule

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Request historical schedule.

This method is blocking.

Args: contract: Contract of interest. numDays: Number of days. endDateTime: 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: If True then show schedule for Regular Trading Hours, if False then for extended hours.

reqHistoricalTicks

reqHistoricalTicks(self, contract: ib_async.contract.Contract, startDateTime: str | datetime.date, endDateTime: str | datetime.date, numberOfTicks: int, whatToShow: str, useRth: bool, ignoreSize: bool = False, miscOptions: list[ib_async.contract.TagValue] = []) -> list

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqHistoricalTicks

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

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

Args: contract: Contract to query. startDateTime: 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: One of startDateTime or endDateTime can be given, the other must be blank. numberOfTicks: Number of ticks to request (1000 max). The actual result can contain a bit more to accommodate all ticks in the latest second. whatToShow: 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: Ignore bid/ask ticks that only update the size. miscOptions: Unknown.

reqMarketRule

reqMarketRule(self, marketRuleId: int) -> ib_async.objects.PriceIncrement

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqMarketRule

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Request price increments rule.

https://interactivebrokers.github.io/tws-api/minimum_increment.html

Args: marketRuleId: 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.

reqMatchingSymbols

reqMatchingSymbols(self, pattern: str) -> list[ib_async.contract.ContractDescription]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqMatchingSymbols

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Request contract descriptions of contracts that match a pattern.

This method is blocking.

https://interactivebrokers.github.io/tws-api/matching_symbols.html

Args: pattern: The first few letters of the ticker symbol, or for longer strings a character sequence matching a word in the security name.

reqMktDepthExchanges

reqMktDepthExchanges(self) -> list[ib_async.objects.DepthMktDataDescription]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqMktDepthExchanges

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Get those exchanges that have have multiple market makers (and have ticks returned with marketMaker info).

reqNewsArticle

reqNewsArticle(self, providerCode: str, articleId: str, newsArticleOptions: list[ib_async.contract.TagValue] = []) -> ib_async.objects.NewsArticle

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqNewsArticle

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Get the body of a news article.

This method is blocking.

https://interactivebrokers.github.io/tws-api/news.html

Args: providerCode: Code indicating news provider, like 'BZ' or 'FLY'. articleId: ID of the specific article. newsArticleOptions: Unknown.

reqNewsProviders

reqNewsProviders(self) -> list[ib_async.objects.NewsProvider]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqNewsProviders

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Get a list of news providers.

This method is blocking.

reqOpenOrders

reqOpenOrders(self) -> list[ib_async.order.Trade]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.reqOpenOrders

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

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.

reqPositions

reqPositions(self) -> list[ib_async.objects.Position]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.reqPositions

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

It is recommended to use .positions instead.

Request and return a list of positions for all accounts.

This method is blocking.

reqScannerData

reqScannerData(self, subscription: ib_async.objects.ScannerSubscription, scannerSubscriptionOptions: list[ib_async.contract.TagValue] = [], scannerSubscriptionFilterOptions: list[ib_async.contract.TagValue] = []) -> ib_async.objects.ScanDataList

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqScannerData

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

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

Args: subscription: Basic filters. scannerSubscriptionOptions: Unknown. scannerSubscriptionFilterOptions: Advanced generic filters.

reqScannerParameters

reqScannerParameters(self) -> str

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqScannerParameters

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Requests an XML list of scanner parameters.

This method is blocking.

reqSecDefOptParams

reqSecDefOptParams(self, underlyingSymbol: str, futFopExchange: str, underlyingSecType: str, underlyingConId: int) -> list[ib_async.objects.OptionChain]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqSecDefOptParams

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Get the option chain.

This method is blocking.

https://interactivebrokers.github.io/tws-api/options.html

Args: underlyingSymbol: Symbol of underlier contract. futFopExchange: Exchange (only for FuturesOption, otherwise leave blank). underlyingSecType: The type of the underlying security, like 'STK' or 'FUT'. underlyingConId: conId of the underlying contract.

reqSmartComponents

reqSmartComponents(self, bboExchange: str) -> list[ib_async.objects.SmartComponent]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqSmartComponents

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

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.

reqTickers

reqTickers(self, *contracts: ib_async.contract.Contract, regulatorySnapshot: bool = False) -> list[ib_async.ticker.Ticker]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqTickers

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Request and return a list of snapshot tickers. The list is returned when all tickers are ready.

This method is blocking.

Args: contracts: Contracts to get tickers for. regulatorySnapshot: Request NBBO snapshots (may incur a fee).

reqUserInfo

reqUserInfo(self) -> str

Completeness: signature-only · Canonical ID: ib_async.ib.IB.reqUserInfo

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Get the White Branding ID of the user.

requestFA

requestFA(self, faDataType: int)

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.requestFA

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

Requests to change the FA configuration.

This method is blocking.

Args: faDataType:

  • 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.

run

run(*awaitables: collections.abc.Awaitable, timeout: float | None = None)

Completeness: signature-only · Canonical ID: ib_async.ib.IB.run

Runtime signature is published; semantic enrichment remains outstanding.

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.

schedule

schedule(time: datetime.time | datetime.datetime, callback: collections.abc.Callable, *args)

Completeness: signature-only · Canonical ID: ib_async.ib.IB.schedule

Runtime signature is published; semantic enrichment remains outstanding.

Schedule the callback to be run at the given time with the given arguments. This will return the Event Handle.

Args: time: Time to run callback. If given as :pydatetime.time then use today as date. callback: Callable scheduled to run. args: Arguments for to call callback with.

setTimeout

setTimeout(self, timeout: float = 60)

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.setTimeout

Explicit policy override after evidence-backed documentation review.

Sources and provenance

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.

Args: timeout: Timeout in seconds.

sleep

sleep(secs: float = 0.02) -> bool

Completeness: signature-only · Canonical ID: ib_async.ib.IB.sleep

Runtime signature is published; semantic enrichment remains outstanding.

Wait for the given amount of seconds while everything still keeps processing in the background. Never use time.sleep().

Args: secs (float): Time in seconds to wait.

ticker

ticker(self, contract: ib_async.contract.Contract) -> ib_async.ticker.Ticker | None

Completeness: signature-only · Canonical ID: ib_async.ib.IB.ticker

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

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.

Args: contract: Contract to get ticker for.

tickers

tickers(self) -> list[ib_async.ticker.Ticker]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.tickers

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Get a list of all tickers.

timeRange

timeRange(start: datetime.time | datetime.datetime, end: datetime.time | datetime.datetime, step: float) -> collections.abc.Iterator[datetime.datetime]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.timeRange

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Iterator that waits periodically until certain time points are reached while yielding those time points.

Args: start: Start time, can be specified as datetime.datetime, or as datetime.time in which case today is used as the date end: 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

timeRangeAsync

timeRangeAsync(start: datetime.time | datetime.datetime, end: datetime.time | datetime.datetime, step: float) -> collections.abc.AsyncIterator[datetime.datetime]

Completeness: signature-only · Canonical ID: ib_async.ib.IB.timeRangeAsync

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Async version of timeRange.

trades

trades(self) -> list[ib_async.order.Trade]

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.trades

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

List of all order trades from this session.

waitOnUpdate

waitOnUpdate(self, timeout: float = 0) -> bool

Completeness: signature-only · Canonical ID: ib_async.ib.IB.waitOnUpdate

Runtime signature is published; semantic enrichment remains outstanding.

Related API navigation

Sources and provenance

Wait on any new update to arrive from the network.

Args: timeout: Maximum time in seconds to wait. If 0 then no timeout is used.

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.

Returns: True if not timed-out, False otherwise.

waitUntil

waitUntil(t: datetime.time | datetime.datetime) -> bool

Completeness: signature-only · Canonical ID: ib_async.ib.IB.waitUntil

Runtime signature is published; semantic enrichment remains outstanding.

Wait until the given time t is reached.

Args: t: The time t can be specified as datetime.datetime, or as datetime.time in which case today is used as the date.

whatIfOrder

whatIfOrder(self, contract: ib_async.contract.Contract, order: ib_async.order.Order) -> ib_async.order.OrderState

Completeness: fully-documented · Canonical ID: ib_async.ib.IB.whatIfOrder

Explicit policy override after evidence-backed documentation review.

Related API navigation

Sources and provenance

Retrieve commission and margin impact without actually placing the order. The given order will not be modified in any way.

This method is blocking.

Args: contract: Contract to test. order: Order to test.

Dedicated method references

StartupFetch

StartupFetch(*values)

Completeness: signature-only · Canonical ID: ib_async.ib.StartupFetch

Runtime signature is published; semantic enrichment remains outstanding.

Support for flags