IB
ib_interface.api.ib
High-level interface to Interactive Brokers.
IB
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
:meth:.sleep instead.
Attributes:
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:
- :data:
False: Silently return an empty result; - :data:
True: Raise a :class:.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 handeled. -
pendingTickersEvent(tickers: Set[:class:.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: :class:.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: :class:.Trade): Emits a newly placed trade. -
orderModifyEvent(trade: :class:.Trade): Emits when order is modified. -
cancelOrderEvent(trade: :class:.Trade): Emits a trade directly after requesting for it to be cancelled. -
openOrderEvent(trade: :class:.Trade): Emits the trade with open order. -
orderStatusEvent(trade: :class:.Trade): Emits the changed order status of the ongoing trade. -
execDetailsEvent(trade: :class:.Trade, fill: :class:.Fill): Emits the fill together with the ongoing trade it belongs to. -
commissionReportEvent(trade: :class:.Trade, fill: :class:.Fill, report: :class:.CommissionReport): The commission report is emitted after the fill that it belongs to. -
updatePortfolioEvent(item: :class:.PortfolioItem): A portfolio item has changed. -
positionEvent(position: :class:.Position): A position has changed. -
accountValueEvent(value: :class:.AccountValue): An account value has changed. -
accountSummaryEvent(value: :class:.AccountValue): An account value has changed. -
pnlEvent(entry: :class:.PnL): A profit- and loss entry is updated. -
pnlSingleEvent(entry: :class:.PnLSingle): A profit- and loss entry for a single position is updated. -
tickNewsEvent(news: :class:.NewsTick): Emit a new news headline. -
newsBulletinEvent(bulletin: :class:.NewsBulletin): Emit a new news bulletin. -
scannerDataEvent(data: :class:.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: :class:.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 :meth:.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.
connect
def connect(host: str = '127.0.0.1', port: int = 7497, clientId: int = 1, timeout: float = 4, readonly: bool = False, account: str = '', raiseSyncErrors: bool = False)
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.
disconnect
def disconnect()
Disconnect from a TWS or IB gateway application. This will clear all session state.
isConnected
def isConnected() -> bool
Is there an API connection to TWS or IB gateway?
waitOnUpdate
def waitOnUpdate(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.
.. note::
A loop with waitOnUpdate should not be used to harvest
tick data from tickers, since some ticks can go missing.
This happens when multiple updates occur almost simultaneously;
The ticks from the first update are then cleared.
Use events instead to prevent this.
Returns:
True if not timed-out, False otherwise.
loopUntil
def loopUntil(condition = None, timeout: float = 0) -> 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 (callable): Predicate function that is tested after every network update. timeout (float): Maximum time in seconds to wait. If 0 then no timeout is used.
setTimeout
def setTimeout(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.
managedAccounts
def managedAccounts() -> List[str]
List of account names.
accountValues
def accountValues(account: str = '') -> List[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.
accountSummary
def accountSummary(account: str = '') -> List[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.
portfolio
def portfolio(account: str = '') -> List[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
def positions(account: str = '') -> List[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.
pnl
def pnl(account = '', modelCode = '') -> List[PnL]
List of subscribed :class:.PnL objects (profit and loss),
optionally filtered by account and/or modelCode.
The :class:.PnL objects are kept live updated.
Args: account (str): If specified, filter for this account name. modelCode (str): If specified, filter for this account model.
pnlSingle
def pnlSingle(account: str = '', modelCode: str = '', conId: int = 0) -> List[PnLSingle]
List of subscribed :class:.PnLSingle objects (profit and loss for
single positions).
The :class:.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.
trades
def trades() -> List[Trade]
List of all order trades from this session.
openTrades
def openTrades() -> List[Trade]
List of all open order trades.
orders
def orders() -> List[Order]
List of all orders from this session.
openOrders
def openOrders() -> List[Order]
List of all open orders.
fills
def fills() -> List[Fill]
List of all fills from this session.
executions
def executions() -> List[Execution]
List of all executions from this session.
ticker
def ticker(contract: Contract) -> Optional[Ticker]
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 :meth:.reqMktData.
Args: contract: Contract to get ticker for.
tickers
def tickers() -> List[Ticker]
Get a list of all tickers.
pendingTickers
def pendingTickers() -> List[Ticker]
Get a list of all tickers that have pending ticks or domTicks.
realtimeBars
def realtimeBars() -> List[Union[BarDataList, RealTimeBarList]]
Get a list of all live updated bars. These can be 5 second realtime bars or live updated historical bars.
newsTicks
def newsTicks() -> List[NewsTick]
List of ticks with headline news.
The article itself can be retrieved with :meth:.reqNewsArticle.
newsBulletins
def newsBulletins() -> List[NewsBulletin]
List of IB news bulletins.
reqTickers
def reqTickers(contracts: Contract = (), regulatorySnapshot: bool = False) -> List[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).
qualifyContracts
def qualifyContracts(contracts: Contract = ()) -> List[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.
bracketOrder
def bracketOrder(action: str, quantity: float, limitPrice: float, takeProfitPrice: float, stopLossPrice: float, kwargs = {}) -> BracketOrder
Create a limit order that is bracketed by a take-profit order and a stop-loss order. Submit the bracket like:
.. code-block:: python
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.
oneCancelsAll
def oneCancelsAll(orders: List[Order], ocaGroup: str, ocaType: int) -> List[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.
whatIfOrder
def whatIfOrder(contract: Contract, order: 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.
placeOrder
def placeOrder(contract: Contract, order: 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.
cancelOrder
def cancelOrder(order: Order, manualCancelOrderTime: str = '') -> Optional[Trade]
Cancel the order and return the Trade it belongs to.
Args: order: The order to be canceled. manualCancelOrderTime: For audit trail.
reqGlobalCancel
def reqGlobalCancel()
Cancel all active trades including those placed by other clients or TWS/IB gateway.
reqCurrentTime
def reqCurrentTime() -> datetime.datetime
Request TWS current time.
This method is blocking.
reqAccountUpdates
def reqAccountUpdates(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.
reqAccountUpdatesMulti
def reqAccountUpdatesMulti(account: str = '', modelCode: str = '')
It is recommended to use :meth:.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.
reqAccountSummary
def reqAccountSummary()
It is recommended to use :meth:.accountSummary instead.
Request account values for all accounts and keep them updated. Returns when account summary is filled.
This method is blocking.
getConfig
def getConfig() -> dict
Request API configuration from TWS/Gateway.
Returns the current API configuration as a dictionary. Requires Protobuf support (server version 219+).
This method is blocking.
Returns: Dictionary of configuration key-value pairs
Raises: ConnectionError: If server doesn't support Protobuf asyncio.TimeoutError: If request times out
Example: >>> config = ib.getConfig() >>> print(config.get('useProtobuf'))
updateConfig
def updateConfig(config_params: dict) -> tuple[bool, str]
Update API configuration settings.
Send configuration updates to TWS/Gateway and wait for response. Requires Protobuf support (server version 219+).
This method is blocking.
Args: config_params: Dictionary of config key-value pairs to update
Returns: Tuple of (success: bool, message: str)
- success: True if update succeeded
- message: Status message or error description
Raises: ConnectionError: If server doesn't support Protobuf asyncio.TimeoutError: If request times out
Example: >>> success, msg = ib.updateConfig({'useProtobuf': 'true'}) >>> if not success: >>> print(f"Update failed: {msg}")
reqAutoOpenOrders
def reqAutoOpenOrders(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.
reqOpenOrders
def reqOpenOrders() -> List[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
:meth:.openTrades or :meth:.openOrders methods instead.
This method is blocking.
reqAllOpenOrders
def reqAllOpenOrders() -> List[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.
reqCompletedOrders
def reqCompletedOrders(apiOnly: bool) -> List[Trade]
Request and return a list of completed trades.
Args: apiOnly: Request only API orders (not manually placed TWS orders).
reqExecutions
def reqExecutions(execFilter: Optional[ExecutionFilter] = None) -> List[Fill]
It is recommended to use :meth:.fills or
:meth:.executions instead.
Request and return a list of fills.
This method is blocking.
Args: execFilter: If specified, return executions that match the filter.
reqPositions
def reqPositions() -> List[Position]
It is recommended to use :meth:.positions instead.
Request and return a list of positions for all accounts.
This method is blocking.
reqPnL
def reqPnL(account: str, modelCode: str = '') -> PnL
Start a subscription for profit and loss events.
Returns a :class:.PnL object that is kept live updated.
The result can also be queried from :meth:.pnl.
https://interactivebrokers.github.io/tws-api/pnl.html
Args: account: Subscribe to this account. modelCode: If specified, filter for this account model.
cancelPnL
def cancelPnL(account, modelCode: str = '')
Cancel PnL subscription.
Args: account (str): Cancel for this account. modelCode (str): If specified, cancel for this account model.
reqPnLSingle
def reqPnLSingle(account: str, modelCode: str, conId: int) -> PnLSingle
Start a subscription for profit and loss events for single positions.
Returns a :class:.PnLSingle object that is kept live updated.
The result can also be queried from :meth:.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.
cancelPnLSingle
def cancelPnLSingle(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.
reqContractDetails
def reqContractDetails(contract: Contract) -> List[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.
reqMatchingSymbols
def reqMatchingSymbols(pattern: str) -> List[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.
reqMarketRule
def reqMarketRule(marketRuleId: int) -> 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 :meth:.reqContractDetails from
:class:.ContractDetails.marketRuleIds,
which contains a comma separated string of market rule IDs.
reqRealTimeBars
def reqRealTimeBars(contract: Contract, barSize: int, whatToShow: str, useRTH: bool, realTimeBarsOptions: List[TagValue] = []) -> 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.
cancelRealTimeBars
def cancelRealTimeBars(bars: RealTimeBarList)
Cancel the realtime bars subscription.
Args:
bars: The bar list that was obtained from reqRealTimeBars.
reqHistoricalData
def reqHistoricalData(contract: Contract, endDateTime: Union[datetime.datetime, datetime.date, str, None], durationStr: str, barSizeSetting: str, whatToShow: str, useRTH: bool, formatDate: int = 1, keepUpToDate: bool = False, chartOptions: List[TagValue] = [], timeout: float = 60) -> 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 :meth:.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.
cancelHistoricalData
def cancelHistoricalData(bars: BarDataList)
Cancel the update subscription for the historical bars.
Args:
bars: The bar list that was obtained from reqHistoricalData
with a keepUpToDate subscription.
reqHistoricalSchedule
def reqHistoricalSchedule(contract: Contract, numDays: int, endDateTime: Union[datetime.datetime, datetime.date, str, None] = '', useRTH: bool = True) -> 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.
reqHistoricalTicks
def reqHistoricalTicks(contract: Contract, startDateTime: Union[str, datetime.date], endDateTime: Union[str, datetime.date], numberOfTicks: int, whatToShow: str, useRth: bool, ignoreSize: bool = False, miscOptions: List[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 (str): One of 'Bid_Ask', 'Midpoint' or 'Trades'.
useRth (bool): 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.
reqMarketDataType
def reqMarketDataType(marketDataType: int)
Set the market data type used for :meth:.reqMktData.
Args: marketDataType: One of:
- 1 = Live
- 2 = Frozen
- 3 = Delayed
- 4 = Delayed frozen
https://interactivebrokers.github.io/tws-api/market_data_type.html
reqHeadTimeStamp
def reqHeadTimeStamp(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.
reqMktData
def reqMktData(contract: Contract, genericTickList: str = '', snapshot: bool = False, regulatorySnapshot: bool = False, mktDataOptions: List[TagValue] = []) -> 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
:class:ib_insync.objects.FundamentalRatios)
293 tradeCount
294 tradeRate
295 volumeRate
375 rtTradeVolume
411 rtHistVolatility
456 dividends (of type
:class:ib_insync.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
cancelMktData
def cancelMktData(contract: Contract)
Unsubscribe from realtime streaming tick data.
Args: contract: The exact contract object that was used to subscribe with.
reqTickByTickData
def reqTickByTickData(contract: Contract, tickType: str, numberOfTicks: int = 0, ignoreSize: bool = False) -> 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.
cancelTickByTickData
def cancelTickByTickData(contract: Contract, tickType: str)
Unsubscribe from tick-by-tick data
Args: contract: The exact contract object that was used to subscribe with.
reqSmartComponents
def reqSmartComponents(bboExchange: str) -> List[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.
reqMktDepthExchanges
def reqMktDepthExchanges() -> List[DepthMktDataDescription]
Get those exchanges that have have multiple market makers (and have ticks returned with marketMaker info).
reqMktDepth
def reqMktDepth(contract: Contract, numRows: int = 5, isSmartDepth: bool = False, mktDepthOptions = None) -> 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 (bool): Consolidate the order book across exchanges. mktDepthOptions (list): Unknown.
Returns:
The Ticker that holds the market depth in ticker.domBids
and ticker.domAsks and the list of MktDepthData in
ticker.domTicks.
cancelMktDepth
def cancelMktDepth(contract: Contract, isSmartDepth = False)
Unsubscribe from market depth data.
Args: contract: The exact contract object that was used to subscribe with.
reqHistogramData
def reqHistogramData(contract: Contract, useRTH: bool, period: str) -> List[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'.
reqFundamentalData
def reqFundamentalData(contract: Contract, reportType: str, fundamentalDataOptions: List[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
reqScannerData
def reqScannerData(subscription: ScannerSubscription, scannerSubscriptionOptions: List[TagValue] = [], scannerSubscriptionFilterOptions: List[TagValue] = []) -> 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.
reqScannerSubscription
def reqScannerSubscription(subscription: ScannerSubscription, scannerSubscriptionOptions: List[TagValue] = [], scannerSubscriptionFilterOptions: List[TagValue] = []) -> 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.
cancelScannerSubscription
def cancelScannerSubscription(dataList: ScanDataList)
Cancel market data subscription.
https://interactivebrokers.github.io/tws-api/market_scanners.html
Args:
dataList: The scan data list that was obtained from
:meth:.reqScannerSubscription.
reqScannerParameters
def reqScannerParameters() -> str
Requests an XML list of scanner parameters.
This method is blocking.
calculateImpliedVolatility
def calculateImpliedVolatility(contract: Contract, optionPrice: float, underPrice: float, implVolOptions: List[TagValue] = []) -> 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
calculateOptionPrice
def calculateOptionPrice(contract: Contract, volatility: float, underPrice: float, optPrcOptions: List[TagValue] = []) -> OptionComputation
Calculate the option price given the volatility.
This method is blocking.
https://interactivebrokers.github.io/tws-api/option_computations.html
Args: contract (Contract): Option contract. volatility (float): Option volatility to use in calculation. underPrice (float): Price of the underlier to use in calculation. optPrcOptions (list): Unknown.
reqSecDefOptParams
def reqSecDefOptParams(underlyingSymbol: str, futFopExchange: str, underlyingSecType: str, underlyingConId: int) -> List[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.
exerciseOptions
def exerciseOptions(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
reqNewsProviders
def reqNewsProviders() -> List[NewsProvider]
Get a list of news providers.
This method is blocking.
reqNewsArticle
def reqNewsArticle(providerCode: str, articleId: str, newsArticleOptions: List[TagValue] = []) -> 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.
reqHistoricalNews
def reqHistoricalNews(conId: int, providerCodes: str, startDateTime: Union[str, datetime.date], endDateTime: Union[str, datetime.date], totalResults: int, historicalNewsOptions: List[TagValue] = []) -> 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.
reqNewsBulletins
def reqNewsBulletins(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.
cancelNewsBulletins
def cancelNewsBulletins()
Cancel subscription to IB news bulletins.
requestFA
def requestFA(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.
replaceFA
def replaceFA(faDataType: int, xml: str)
Replaces Financial Advisor's settings.
Args:
faDataType: See :meth:.requestFA.
xml: The XML-formatted configuration string.
reqWshMetaData
def reqWshMetaData()
Request Wall Street Horizon metadata.
https://interactivebrokers.github.io/tws-api/fundamentals.html
cancelWshMetaData
def cancelWshMetaData()
Cancel WSH metadata.
reqWshEventData
def reqWshEventData(data: WshEventData)
Request Wall Street Horizon event data.
:meth:.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
cancelWshEventData
def cancelWshEventData()
Cancel active WHS event data.
getWshMetaData
def getWshMetaData() -> 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.
.. code-block:: python
Get the list of available filters and event types:
meta = ib.getWshMetaData() print(meta)
getWshEventData
def getWshEventData(data: WshEventData) -> str
Blocking convenience method that returns the WSH event data as
a JSON string.
:meth:.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.
.. code-block:: python
For IBM (with conId=8314) query the:
- Earnings Dates (wshe_ed)
- Board of Directors meetings (wshe_bod)
data = WshEventData( filter=json.dumps( { "country": "All", "watchlist": ["8314"], "limit_region": 10, "limit": 10, "wshe_ed": "true", "wshe_bod": "true", } ) ) events = ib.getWshEventData(data) print(events)
reqUserInfo
def reqUserInfo() -> str
Get the White Branding ID of the user.
connectAsync
def connectAsync(host: str = '127.0.0.1', port: int = 7497, clientId: int = 1, timeout: Optional[float] = 4, readonly: bool = False, account: str = '', raiseSyncErrors: bool = False)
qualifyContractsAsync
def qualifyContractsAsync(contracts: Contract = ()) -> List[Contract]
reqTickersAsync
def reqTickersAsync(contracts: Contract = (), regulatorySnapshot: bool = False) -> List[Ticker]
whatIfOrderAsync
def whatIfOrderAsync(contract: Contract, order: Order) -> Awaitable[OrderState]
reqCurrentTimeAsync
def reqCurrentTimeAsync() -> Awaitable[datetime.datetime]
reqAccountUpdatesAsync
def reqAccountUpdatesAsync(account: str) -> Awaitable[None]
reqAccountUpdatesMultiAsync
def reqAccountUpdatesMultiAsync(account: str, modelCode: str = '') -> Awaitable[None]
accountSummaryAsync
def accountSummaryAsync(account: str = '') -> List[AccountValue]
reqAccountSummaryAsync
def reqAccountSummaryAsync() -> Awaitable[None]
reqOpenOrdersAsync
def reqOpenOrdersAsync() -> Awaitable[List[Trade]]
reqAllOpenOrdersAsync
def reqAllOpenOrdersAsync() -> Awaitable[List[Trade]]
reqCompletedOrdersAsync
def reqCompletedOrdersAsync(apiOnly: bool) -> Awaitable[List[Trade]]
reqExecutionsAsync
def reqExecutionsAsync(execFilter: Optional[ExecutionFilter] = None) -> Awaitable[List[Fill]]
reqPositionsAsync
def reqPositionsAsync() -> Awaitable[List[Position]]
reqContractDetailsAsync
def reqContractDetailsAsync(contract: Contract) -> Awaitable[List[ContractDetails]]
reqMatchingSymbolsAsync
def reqMatchingSymbolsAsync(pattern: str) -> Optional[List[ContractDescription]]
reqMarketRuleAsync
def reqMarketRuleAsync(marketRuleId: int) -> Optional[List[PriceIncrement]]
getConfigAsync
def getConfigAsync() -> dict
Request API configuration from TWS/Gateway (async).
Returns the current API configuration as a dictionary. Requires Protobuf support (server version 219+).
Returns: Dictionary of configuration key-value pairs
Raises: ConnectionError: If server doesn't support Protobuf asyncio.TimeoutError: If request times out
updateConfigAsync
def updateConfigAsync(config_params: dict) -> tuple[bool, str]
Update API configuration settings (async).
Send configuration updates to TWS/Gateway and wait for response. Requires Protobuf support (server version 219+).
Args: config_params: Dictionary of config key-value pairs to update
Returns: Tuple of (success: bool, message: str)
- success: True if update succeeded
- message: Status message or error description
Raises: ConnectionError: If server doesn't support Protobuf asyncio.TimeoutError: If request times out
Example: >>> success, msg = await ib.updateConfigAsync({'useProtobuf': 'true'}) >>> if success: >>> print("Config updated successfully")
reqHistoricalDataAsync
def reqHistoricalDataAsync(contract: Contract, endDateTime: Union[datetime.datetime, datetime.date, str, None], durationStr: str, barSizeSetting: str, whatToShow: str, useRTH: bool, formatDate: int = 1, keepUpToDate: bool = False, chartOptions: List[TagValue] = [], timeout: float = 60) -> BarDataList
reqHistoricalScheduleAsync
def reqHistoricalScheduleAsync(contract: Contract, numDays: int, endDateTime: Union[datetime.datetime, datetime.date, str, None] = '', useRTH: bool = True) -> Awaitable[HistoricalSchedule]
reqHistoricalTicksAsync
def reqHistoricalTicksAsync(contract: Contract, startDateTime: Union[str, datetime.date], endDateTime: Union[str, datetime.date], numberOfTicks: int, whatToShow: str, useRth: bool, ignoreSize: bool = False, miscOptions: List[TagValue] = []) -> Awaitable[List]
reqHeadTimeStampAsync
def reqHeadTimeStampAsync(contract: Contract, whatToShow: str, useRTH: bool, formatDate: int) -> datetime.datetime
reqSmartComponentsAsync
def reqSmartComponentsAsync(bboExchange)
reqMktDepthExchangesAsync
def reqMktDepthExchangesAsync() -> Awaitable[List[DepthMktDataDescription]]
reqHistogramDataAsync
def reqHistogramDataAsync(contract: Contract, useRTH: bool, period: str) -> Awaitable[List[HistogramData]]
reqFundamentalDataAsync
def reqFundamentalDataAsync(contract: Contract, reportType: str, fundamentalDataOptions: List[TagValue] = []) -> Awaitable[str]
reqScannerDataAsync
def reqScannerDataAsync(subscription: ScannerSubscription, scannerSubscriptionOptions: List[TagValue] = [], scannerSubscriptionFilterOptions: List[TagValue] = []) -> ScanDataList
reqScannerParametersAsync
def reqScannerParametersAsync() -> Awaitable[str]
calculateImpliedVolatilityAsync
def calculateImpliedVolatilityAsync(contract: Contract, optionPrice: float, underPrice: float, implVolOptions: List[TagValue] = []) -> Optional[OptionComputation]
calculateOptionPriceAsync
def calculateOptionPriceAsync(contract: Contract, volatility: float, underPrice: float, optPrcOptions: List[TagValue] = []) -> Optional[OptionComputation]
reqSecDefOptParamsAsync
def reqSecDefOptParamsAsync(underlyingSymbol: str, futFopExchange: str, underlyingSecType: str, underlyingConId: int) -> Awaitable[List[OptionChain]]
reqNewsProvidersAsync
def reqNewsProvidersAsync() -> Awaitable[List[NewsProvider]]
reqNewsArticleAsync
def reqNewsArticleAsync(providerCode: str, articleId: str, newsArticleOptions: List[TagValue] = []) -> Awaitable[NewsArticle]
reqHistoricalNewsAsync
def reqHistoricalNewsAsync(conId: int, providerCodes: str, startDateTime: Union[str, datetime.date], endDateTime: Union[str, datetime.date], totalResults: int, historicalNewsOptions: List[TagValue] = []) -> Optional[HistoricalNews]
requestFAAsync
def requestFAAsync(faDataType: int)
getWshMetaDataAsync
def getWshMetaDataAsync() -> str
getWshEventDataAsync
def getWshEventDataAsync(data: WshEventData) -> str
reqUserInfoAsync
def reqUserInfoAsync()