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))
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.
__enter__
__enter__(self)
No library docstring is provided; consult the signature, type fields, and operational guides.
__exit__
__exit__(self, *_exc)
No library docstring is provided; consult the signature, type fields, and operational guides.
accountSummary
accountSummary(self, account: str = '') -> list[ib_async.objects.AccountValue]
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]
No library docstring is provided; consult the signature, type fields, and operational guides.
accountValues
accountValues(self, account: str = '') -> list[ib_async.objects.AccountValue]
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
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
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
calculateImpliedVolatilityAsync
calculateImpliedVolatilityAsync(self, contract: ib_async.contract.Contract, optionPrice: float, underPrice: float, implVolOptions: list[ib_async.contract.TagValue] = []) -> ib_async.objects.OptionComputation | None
No library docstring is provided; consult the signature, type fields, and operational guides.
calculateOptionPrice
calculateOptionPrice(self, contract: ib_async.contract.Contract, volatility: float, underPrice: float, optPrcOptions: list[ib_async.contract.TagValue] = []) -> ib_async.objects.OptionComputation
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
calculateOptionPriceAsync
calculateOptionPriceAsync(self, contract: ib_async.contract.Contract, volatility: float, underPrice: float, optPrcOptions: list[ib_async.contract.TagValue] = []) -> ib_async.objects.OptionComputation | None
No library docstring is provided; consult the signature, type fields, and operational guides.
cancelHistoricalData
cancelHistoricalData(self, bars: ib_async.objects.BarDataList)
Cancel the update subscription for the historical bars.
Args:
bars: The bar list that was obtained from reqHistoricalData
with a keepUpToDate subscription.
cancelMktData
cancelMktData(self, contract: ib_async.contract.Contract) -> bool
Unsubscribe from realtime streaming tick data.
Args: contract: The contract of a previously subscribed ticker to unsubscribe.
Returns: Returns True if cancel was successful. Returns False if 'contract' was not found.
cancelMktDepth
cancelMktDepth(self, contract: ib_async.contract.Contract, isSmartDepth=False)
Unsubscribe from market depth data.
Args: contract: The exact contract object that was used to subscribe with.
cancelNewsBulletins
cancelNewsBulletins(self)
Cancel subscription to IB news bulletins.
cancelOrder
cancelOrder(self, order: ib_async.order.Order, manualCancelOrderTime: str = '') -> ib_async.order.Trade | None
Cancel the order and return the Trade it belongs to.
Args: order: The order to be canceled. manualCancelOrderTime: For audit trail.
cancelPnL
cancelPnL(self, account, modelCode: str = '')
Cancel PnL subscription.
Args: account: Cancel for this account. modelCode: If specified, cancel for this account model.
cancelPnLSingle
cancelPnLSingle(self, account: str, modelCode: str, conId: int)
Cancel PnLSingle subscription for the given account, modelCode and conId.
Args: account: Cancel for this account name. modelCode: Cancel for this account model. conId: Cancel for this contract ID.
cancelRealTimeBars
cancelRealTimeBars(self, bars: ib_async.objects.RealTimeBarList)
Cancel the realtime bars subscription.
Args:
bars: The bar list that was obtained from reqRealTimeBars.
cancelScannerSubscription
cancelScannerSubscription(self, dataList: ib_async.objects.ScanDataList)
Cancel market data subscription.
https://interactivebrokers.github.io/tws-api/market_scanners.html
Args:
dataList: The scan data list that was obtained from
.reqScannerSubscription.
cancelTickByTickData
cancelTickByTickData(self, contract: ib_async.contract.Contract, tickType: str) -> bool
Unsubscribe from tick-by-tick data
Args: contract: The contract of a previously subscribed ticker to unsubscribe.
Returns: Returns True if cancel was successful. Returns False if 'contract' was not found.
cancelWshEventData
cancelWshEventData(self)
Cancel active WHS event data.
cancelWshMetaData
cancelWshMetaData(self)
Cancel WSH metadata.
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>)
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.
connectAsync
connectAsync(self, host: str = '127.0.0.1', port: int = 7497, clientId: int = 1, timeout: float | None = 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>)
No library docstring is provided; consult the signature, type fields, and operational guides.
disconnect
disconnect(self) -> str | None
Disconnect from a TWS or IB gateway application. This will clear all session state.
executions
executions(self) -> list[ib_async.objects.Execution]
List of all executions from this session.
exerciseOptions
exerciseOptions(self, contract: ib_async.contract.Contract, exerciseAction: int, exerciseQuantity: int, account: str, override: int)
Exercise an options contract.
https://interactivebrokers.github.io/tws-api/options.html
Args: contract: The option contract to be exercised. exerciseAction:
- 1 = exercise the option
- 2 = let the option lapse exerciseQuantity: Number of contracts to be exercised. account: Destination account. override:
- 0 = no override
- 1 = override the system's natural action
fills
fills(self) -> list[ib_async.objects.Fill]
List of all fills from this session.
getWshEventData
getWshEventData(self, data: ib_async.objects.WshEventData) -> str
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 <https://www.wallstreethorizon.com/interactive-brokers>_
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)
getWshEventDataAsync
getWshEventDataAsync(self, data: ib_async.objects.WshEventData) -> str
No library docstring is provided; consult the signature, type fields, and operational guides.
getWshMetaData
getWshMetaData(self) -> str
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 <https://www.wallstreethorizon.com/interactive-brokers>_
is required.
Get the list of available filters and event types:
meta = ib.getWshMetaData() print(meta)
getWshMetaDataAsync
getWshMetaDataAsync(self) -> str
No library docstring is provided; consult the signature, type fields, and operational guides.
isConnected
isConnected(self) -> bool
Is there an API connection to TWS or IB gateway?
loopUntil
loopUntil(self, condition=None, timeout: float = 0) -> collections.abc.Iterator[object]
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]
List of account names.
newsBulletins
newsBulletins(self) -> list[ib_async.objects.NewsBulletin]
List of IB news bulletins.
newsTicks
newsTicks(self) -> list[ib_async.objects.NewsTick]
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]
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]
List of all open orders.
openTrades
openTrades(self) -> list[ib_async.order.Trade]
List of all open order trades.
orders
orders(self) -> list[ib_async.order.Order]
List of all orders from this session.
pendingTickers
pendingTickers(self) -> list[ib_async.ticker.Ticker]
Get a list of all tickers that have pending ticks or domTicks.
placeOrder
placeOrder(self, contract: ib_async.contract.Contract, order: ib_async.order.Order) -> ib_async.order.Trade
Place a new order or modify an existing order. Returns a Trade that is kept live updated with status changes, fills, etc.
Args: contract: Contract to use for order. order: The order to be placed.
pnl
pnl(self, account='', modelCode='') -> list[ib_async.objects.PnL]
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]
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]
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]
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]
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]
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]
Get a list of all live updated bars. These can be 5 second realtime bars or live updated historical bars.
replaceFA
replaceFA(self, faDataType: int, xml: str)
Replaces Financial Advisor's settings.
Args:
faDataType: See .requestFA.
xml: The XML-formatted configuration string.
reqAccountSummary
reqAccountSummary(self)
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.
reqAccountSummaryAsync
reqAccountSummaryAsync(self) -> collections.abc.Awaitable[None]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqAccountUpdates
reqAccountUpdates(self, account: str = '')
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.
reqAccountUpdatesAsync
reqAccountUpdatesAsync(self, account: str) -> collections.abc.Awaitable[None]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqAccountUpdatesMulti
reqAccountUpdatesMulti(self, account: str = '', modelCode: str = '')
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.
reqAccountUpdatesMultiAsync
reqAccountUpdatesMultiAsync(self, account: str, modelCode: str = '') -> collections.abc.Awaitable[None]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqAllOpenOrders
reqAllOpenOrders(self) -> list[ib_async.order.Trade]
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.
reqAllOpenOrdersAsync
reqAllOpenOrdersAsync(self) -> collections.abc.Awaitable[list[ib_async.order.Trade]]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqAutoOpenOrders
reqAutoOpenOrders(self, autoBind: bool = True)
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.html https://interactivebrokers.github.io/tws-api/modifying_orders.html
Args: autoBind: Set binding on or off.
reqCompletedOrders
reqCompletedOrders(self, apiOnly: bool) -> list[ib_async.order.Trade]
Request and return a list of completed trades.
Args: apiOnly: Request only API orders (not manually placed TWS orders).
reqCompletedOrdersAsync
reqCompletedOrdersAsync(self, apiOnly: bool) -> collections.abc.Awaitable[list[ib_async.order.Trade]]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqContractDetails
reqContractDetails(self, contract: ib_async.contract.Contract) -> list[ib_async.contract.ContractDetails]
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.
reqContractDetailsAsync
reqContractDetailsAsync(self, contract: ib_async.contract.Contract) -> collections.abc.Awaitable[list[ib_async.contract.ContractDetails]]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqCurrentTime
reqCurrentTime(self) -> datetime.datetime
Request TWS current time.
This method is blocking.
reqCurrentTimeAsync
reqCurrentTimeAsync(self) -> collections.abc.Awaitable[datetime.datetime]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqExecutions
reqExecutions(self, execFilter: ib_async.objects.ExecutionFilter | None = None) -> list[ib_async.objects.Fill]
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.
reqExecutionsAsync
reqExecutionsAsync(self, execFilter: ib_async.objects.ExecutionFilter | None = None) -> collections.abc.Awaitable[list[ib_async.objects.Fill]]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqFundamentalData
reqFundamentalData(self, contract: ib_async.contract.Contract, reportType: str, fundamentalDataOptions: list[ib_async.contract.TagValue] = []) -> str
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
reqFundamentalDataAsync
reqFundamentalDataAsync(self, contract: ib_async.contract.Contract, reportType: str, fundamentalDataOptions: list[ib_async.contract.TagValue] = []) -> collections.abc.Awaitable[str]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqGlobalCancel
reqGlobalCancel(self)
Cancel all active trades including those placed by other clients or TWS/IB gateway.
reqHeadTimeStamp
reqHeadTimeStamp(self, contract: ib_async.contract.Contract, whatToShow: str, useRTH: bool, formatDate: int = 1) -> datetime.datetime
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.
reqHeadTimeStampAsync
reqHeadTimeStampAsync(self, contract: ib_async.contract.Contract, whatToShow: str, useRTH: bool, formatDate: int) -> datetime.datetime
No library docstring is provided; consult the signature, type fields, and operational guides.
reqHistogramData
reqHistogramData(self, contract: ib_async.contract.Contract, useRTH: bool, period: str) -> list[ib_async.objects.HistogramData]
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'.
reqHistogramDataAsync
reqHistogramDataAsync(self, contract: ib_async.contract.Contract, useRTH: bool, period: str) -> collections.abc.Awaitable[list[ib_async.objects.HistogramData]]
No library docstring is provided; consult the signature, type fields, and operational guides.
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
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.
reqHistoricalDataAsync
reqHistoricalDataAsync(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
No library docstring is provided; consult the signature, type fields, and operational guides.
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
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.
reqHistoricalNewsAsync
reqHistoricalNewsAsync(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 | None
No library docstring is provided; consult the signature, type fields, and operational guides.
reqHistoricalSchedule
reqHistoricalSchedule(self, contract: ib_async.contract.Contract, numDays: int, endDateTime: datetime.datetime | datetime.date | str | None = '', useRTH: bool = True) -> ib_async.objects.HistoricalSchedule
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.
reqHistoricalScheduleAsync
reqHistoricalScheduleAsync(self, contract: ib_async.contract.Contract, numDays: int, endDateTime: datetime.datetime | datetime.date | str | None = '', useRTH: bool = True) -> collections.abc.Awaitable[ib_async.objects.HistoricalSchedule]
No library docstring is provided; consult the signature, type fields, and operational guides.
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
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.
reqHistoricalTicksAsync
reqHistoricalTicksAsync(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] = []) -> collections.abc.Awaitable[list]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqMarketDataType
reqMarketDataType(self, marketDataType: int)
Set the market data type used for .reqMktData.
Args: marketDataType: One of:
- 1 = Live
- 2 = Frozen
- 3 = Delayed
- 4 = Delayed frozen
https://interactivebrokers.github.io/tws-api/market_data_type.html
reqMarketRule
reqMarketRule(self, marketRuleId: int) -> ib_async.objects.PriceIncrement
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.
reqMarketRuleAsync
reqMarketRuleAsync(self, marketRuleId: int) -> list[ib_async.objects.PriceIncrement] | None
No library docstring is provided; consult the signature, type fields, and operational guides.
reqMatchingSymbols
reqMatchingSymbols(self, pattern: str) -> list[ib_async.contract.ContractDescription]
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.
reqMatchingSymbolsAsync
reqMatchingSymbolsAsync(self, pattern: str) -> list[ib_async.contract.ContractDescription] | None
No library docstring is provided; consult the signature, type fields, and operational guides.
reqMktData
reqMktData(self, contract: ib_async.contract.Contract, genericTickList: str = '', snapshot: bool = False, regulatorySnapshot: bool = False, mktDataOptions: list[ib_async.contract.TagValue] = []) -> ib_async.ticker.Ticker
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
Args: contract: Contract of interest. genericTickList: Comma separated IDs of desired generic ticks that will cause corresponding Ticker fields to be filled:
===== ================================================
ID Ticker fields
===== ================================================
100 putVolume, callVolume (for options)
101 putOpenInterest, callOpenInterest (for options)
104 histVolatility (for options)
105 avOptionVolume (for options)
106 impliedVolatility (for options)
162 indexFuturePremium
165 low13week, high13week, low26week,
high26week, low52week, high52week,
avVolume
221 markPrice
225 auctionVolume, auctionPrice,
auctionImbalance
233 last, lastSize, rtVolume, rtTime,
vwap (Time & Sales)
236 shortableShares
258 fundamentalRatios (of type
ib_async.objects.FundamentalRatios)
293 tradeCount
294 tradeRate
295 volumeRate
375 rtTradeVolume
411 rtHistVolatility
456 dividends (of type
ib_async.objects.Dividends)
588 futuresOpenInterest
===== ================================================
snapshot: If True then request a one-time snapshot, otherwise subscribe to a stream of realtime tick data. regulatorySnapshot: Request NBBO snapshot (may incur a fee). mktDataOptions: Unknown
reqMktDepth
reqMktDepth(self, contract: ib_async.contract.Contract, numRows: int = 5, isSmartDepth: bool = False, mktDepthOptions=None) -> ib_async.ticker.Ticker
Subscribe to market depth data (a.k.a. DOM, L2 or order book).
https://interactivebrokers.github.io/tws-api/market_depth.html
Args: contract: Contract of interest. numRows: Number of depth level on each side of the order book (5 max). isSmartDepth: Consolidate the order book across exchanges. mktDepthOptions: Unknown.
Returns:
The Ticker that holds the market depth in ticker.domBids
and ticker.domAsks and the list of MktDepthData in
ticker.domTicks.
reqMktDepthExchanges
reqMktDepthExchanges(self) -> list[ib_async.objects.DepthMktDataDescription]
Get those exchanges that have have multiple market makers (and have ticks returned with marketMaker info).
reqMktDepthExchangesAsync
reqMktDepthExchangesAsync(self) -> collections.abc.Awaitable[list[ib_async.objects.DepthMktDataDescription]]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqNewsArticle
reqNewsArticle(self, providerCode: str, articleId: str, newsArticleOptions: list[ib_async.contract.TagValue] = []) -> ib_async.objects.NewsArticle
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.
reqNewsArticleAsync
reqNewsArticleAsync(self, providerCode: str, articleId: str, newsArticleOptions: list[ib_async.contract.TagValue] = []) -> collections.abc.Awaitable[ib_async.objects.NewsArticle]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqNewsBulletins
reqNewsBulletins(self, allMessages: bool)
Subscribe to IB news bulletins.
https://interactivebrokers.github.io/tws-api/news.html
Args: allMessages: If True then fetch all messages for the day.
reqNewsProviders
reqNewsProviders(self) -> list[ib_async.objects.NewsProvider]
Get a list of news providers.
This method is blocking.
reqNewsProvidersAsync
reqNewsProvidersAsync(self) -> collections.abc.Awaitable[list[ib_async.objects.NewsProvider]]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqOpenOrders
reqOpenOrders(self) -> list[ib_async.order.Trade]
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.
reqOpenOrdersAsync
reqOpenOrdersAsync(self) -> collections.abc.Awaitable[list[ib_async.order.Trade]]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqPnL
reqPnL(self, account: str, modelCode: str = '') -> ib_async.objects.PnL
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
Args: account: Subscribe to this account. modelCode: If specified, filter for this account model.
reqPnLSingle
reqPnLSingle(self, account: str, modelCode: str, conId: int) -> ib_async.objects.PnLSingle
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
Args: account: Subscribe to this account. modelCode: Filter for this account model. conId: Filter for this contract ID.
reqPositions
reqPositions(self) -> list[ib_async.objects.Position]
It is recommended to use .positions instead.
Request and return a list of positions for all accounts.
This method is blocking.
reqPositionsAsync
reqPositionsAsync(self) -> collections.abc.Awaitable[list[ib_async.objects.Position]]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqRealTimeBars
reqRealTimeBars(self, contract: ib_async.contract.Contract, barSize: int, whatToShow: str, useRTH: bool, realTimeBarsOptions: list[ib_async.contract.TagValue] = []) -> ib_async.objects.RealTimeBarList
Request realtime 5 second bars.
https://interactivebrokers.github.io/tws-api/realtime_bars.html
Args: contract: Contract of interest. barSize: Must be 5. whatToShow: Specifies the source for constructing bars. Can be 'TRADES', 'MIDPOINT', 'BID' or 'ASK'. useRTH: If True then only show data from within Regular Trading Hours, if False then show all data. realTimeBarsOptions: Unknown.
reqScannerData
reqScannerData(self, subscription: ib_async.objects.ScannerSubscription, scannerSubscriptionOptions: list[ib_async.contract.TagValue] = [], scannerSubscriptionFilterOptions: list[ib_async.contract.TagValue] = []) -> ib_async.objects.ScanDataList
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.
reqScannerDataAsync
reqScannerDataAsync(self, subscription: ib_async.objects.ScannerSubscription, scannerSubscriptionOptions: list[ib_async.contract.TagValue] = [], scannerSubscriptionFilterOptions: list[ib_async.contract.TagValue] = []) -> ib_async.objects.ScanDataList
No library docstring is provided; consult the signature, type fields, and operational guides.
reqScannerParameters
reqScannerParameters(self) -> str
Requests an XML list of scanner parameters.
This method is blocking.
reqScannerParametersAsync
reqScannerParametersAsync(self) -> collections.abc.Awaitable[str]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqScannerSubscription
reqScannerSubscription(self, subscription: ib_async.objects.ScannerSubscription, scannerSubscriptionOptions: list[ib_async.contract.TagValue] = [], scannerSubscriptionFilterOptions: list[ib_async.contract.TagValue] = []) -> ib_async.objects.ScanDataList
Subscribe to market scan data.
https://interactivebrokers.github.io/tws-api/market_scanners.html
Args: subscription: What to scan for. scannerSubscriptionOptions: Unknown. scannerSubscriptionFilterOptions: Unknown.
reqSecDefOptParams
reqSecDefOptParams(self, underlyingSymbol: str, futFopExchange: str, underlyingSecType: str, underlyingConId: int) -> list[ib_async.objects.OptionChain]
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.
reqSecDefOptParamsAsync
reqSecDefOptParamsAsync(self, underlyingSymbol: str, futFopExchange: str, underlyingSecType: str, underlyingConId: int) -> collections.abc.Awaitable[list[ib_async.objects.OptionChain]]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqSmartComponents
reqSmartComponents(self, bboExchange: str) -> list[ib_async.objects.SmartComponent]
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.
reqSmartComponentsAsync
reqSmartComponentsAsync(self, bboExchange)
No library docstring is provided; consult the signature, type fields, and operational guides.
reqTickByTickData
reqTickByTickData(self, contract: ib_async.contract.Contract, tickType: str, numberOfTicks: int = 0, ignoreSize: bool = False) -> ib_async.ticker.Ticker
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
Args: contract: Contract of interest. tickType: One of 'Last', 'AllLast', 'BidAsk' or 'MidPoint'. numberOfTicks: Number of ticks or 0 for unlimited. ignoreSize: Ignore bid/ask ticks that only update the size.
reqTickers
reqTickers(self, *contracts: ib_async.contract.Contract, regulatorySnapshot: bool = False) -> list[ib_async.ticker.Ticker]
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).
reqTickersAsync
reqTickersAsync(self, *contracts: ib_async.contract.Contract, regulatorySnapshot: bool = False) -> list[ib_async.ticker.Ticker]
No library docstring is provided; consult the signature, type fields, and operational guides.
reqUserInfo
reqUserInfo(self) -> str
Get the White Branding ID of the user.
reqUserInfoAsync
reqUserInfoAsync(self)
No library docstring is provided; consult the signature, type fields, and operational guides.
reqWshEventData
reqWshEventData(self, data: ib_async.objects.WshEventData)
Request Wall Street Horizon event data.
.reqWshMetaData must have been called first before using this
method.
Args: data: Filters for selecting the corporate event data.
https://interactivebrokers.github.io/tws-api/wshe_filters.html
reqWshMetaData
reqWshMetaData(self)
Request Wall Street Horizon metadata.
https://interactivebrokers.github.io/tws-api/fundamentals.html
requestFA
requestFA(self, faDataType: int)
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.
requestFAAsync
requestFAAsync(self, faDataType: int)
No library docstring is provided; consult the signature, type fields, and operational guides.
run
run(*awaitables: collections.abc.Awaitable, timeout: float | None = 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.
schedule
schedule(time: datetime.time | datetime.datetime, callback: collections.abc.Callable, *args)
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)
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
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
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]
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]
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]
Async version of timeRange.
trades
trades(self) -> list[ib_async.order.Trade]
List of all order trades from this session.
waitOnUpdate
waitOnUpdate(self, timeout: float = 0) -> bool
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
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
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.
whatIfOrderAsync
whatIfOrderAsync(self, contract: ib_async.contract.Contract, order: ib_async.order.Order) -> collections.abc.Awaitable[ib_async.order.OrderState]
No library docstring is provided; consult the signature, type fields, and operational guides.
StartupFetch
StartupFetch(*values)
Support for flags