Ib Insync Readthedocs Io en Latest
Ib Insync Readthedocs Io en Latest
Release 0.9.70
Ewald de Wit
1 Introduction 3
1.1 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Consultancy & Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2 API docs 7
2.1 IB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.3 Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.4 Contract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
2.5 Ticker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
2.6 Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
2.7 Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
2.8 FlexReport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
2.9 IBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
2.10 IBController . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
2.11 Watchdog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
3 Notebooks 91
4 Code recipes 93
4.1 Fetching consecutive historical data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
4.2 Scanner data (blocking) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
4.3 Scanner data (streaming) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
4.4 Option calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
4.5 Order book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
4.6 Minimum price increments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
4.7 News articles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
4.8 News bulletins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
4.9 Dividends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
4.10 Fundemental ratios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
4.11 Async streaming ticks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
4.12 Integration with PyQt5 or PySide2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
4.13 Integration with Tkinter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
5 Source code 99
6 Changelog 101
i
6.1 0.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
6.2 0.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
6.3 0.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
6.4 0.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
7 Links 117
8 Introduction 119
8.1 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
8.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
8.3 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
8.4 Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
8.5 Consultancy & Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
8.6 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Index 125
ii
ib_insync, Release 0.9.70
CONTENTS 1
ib_insync, Release 0.9.70
2 CONTENTS
CHAPTER
ONE
INTRODUCTION
The goal of the IB-insync library is to make working with the Trader Workstation API from Interactive Brokers as easy
as possible.
The main features are:
• An easy to use linear style of programming;
• An IB component that automatically keeps in sync with the TWS or IB Gateway application;
• A fully asynchonous framework based on asyncio and eventkit for advanced users;
• Interactive operation with live data in Jupyter notebooks.
Be sure to take a look at the notebooks, the recipes and the API docs.
1.1 Installation
For Python 3.6 install the dataclasses package as well (newer Python versions already have it):
pip install dataclasses
Requirements:
• Python 3.6 or higher;
• A running TWS or IB Gateway application (version 972 or higher). Make sure the API port is enabled and
‘Download open orders on connection’ is checked.
The ibapi package from IB is not needed.
1.2 Example
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)
3
ib_insync, Release 0.9.70
Output:
1.3 Documentation
1.4 Discussion
The insync user group is the place to discuss IB-insync and anything related to it.
IB-insync offers an easy entry into building automated trading systems for both individual traders and fintech compa-
nies. However, to get the most out of it is not a trivial matter and is beyond the reach of most developers.
If you need expert help, you can contact me. This can be for a small project, such as fixing something in your own
code, or it can be creating an entire new trading infrastructure. Please provide enough details so that I can assess both
the feasibility and the scope. Many folks worry about having to provide their ‘secret sauce’, but that is never necessary
(although you’re perfectly welcome to send that as well!)
4 Chapter 1. Introduction
ib_insync, Release 0.9.70
1.6 Disclaimer
1.6. Disclaimer 5
ib_insync, Release 0.9.70
6 Chapter 1. Introduction
CHAPTER
TWO
API DOCS
Release 0.9.70.
Also see the official Python API documentation from IB.
2.1 IB
7
ib_insync, Release 0.9.70
For introducing a delay, never use time.sleep() but use sleep() instead.
RequestTimeout
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.
Type float
RaiseRequestErrors
Specifies the behaviour when certain API requests fail:
• False: Silently return an empty result;
• True: Raise a RequestError.
Type bool
MaxSyncedSubAccounts
Do not use sub-account updates if the number of sub-accounts exceeds this number (50 by default).
Type int
TimezoneTWS
Specifies what timezone TWS (or gateway) is using. The default is to assume local system timezone.
Type pytz.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[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 be-
longs 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.
2.1. IB 9
ib_insync, Release 0.9.70
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.
loopUntil(condition=None, timeout=0)
Iterate until condition is met, with optional timeout in seconds. The yielded value is that of the condition
or False when timed out.
Parameters
• condition – Predicate function that is tested after every network
• update. –
• timeout (float) – Maximum time in seconds to wait. If 0 then no timeout is used.
Return type Iterator[object]
setTimeout(timeout=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.
Parameters timeout (float) – Timeout in seconds.
managedAccounts()
List of account names.
Return type List[str]
accountValues(account='')
List of account values for the given account, or of all accounts if account is left blank.
Parameters account (str) – If specified, filter for this account name.
Return type List[AccountValue]
accountSummary(account='')
List of account values for the given account, or of all accounts if account is left blank.
This method is blocking on first run, non-blocking after that.
Parameters account (str) – If specified, filter for this account name.
Return type List[AccountValue]
portfolio()
List of portfolio items of the default account.
Return type List[PortfolioItem]
positions(account='')
List of positions for the given account, or of all accounts if account is left blank.
Parameters account (str) – If specified, filter for this account name.
Return type List[Position]
2.1. IB 11
ib_insync, Release 0.9.70
pnl(account='', modelCode='')
List of subscribed PnL objects (profit and loss), optionally filtered by account and/or modelCode.
The PnL objects are kept live updated.
Parameters
• account – If specified, filter for this account name.
• modelCode – If specified, filter for this account model.
Return type List[PnL]
pnlSingle(account='', modelCode='', conId=0)
List of subscribed PnLSingle objects (profit and loss for single positions).
The PnLSingle objects are kept live updated.
Parameters
• account (str) – If specified, filter for this account name.
• modelCode (str) – If specified, filter for this account model.
• conId (int) – If specified, filter for this contract ID.
Return type List[PnLSingle]
trades()
List of all order trades from this session.
Return type List[Trade]
openTrades()
List of all open order trades.
Return type List[Trade]
orders()
List of all orders from this session.
Return type List[Order]
openOrders()
List of all open orders.
Return type List[Order]
fills()
List of all fills from this session.
Return type List[Fill]
executions()
List of all executions from this session.
Return type List[Execution]
ticker(contract)
Get ticker of the given contract. It must have been requested before with reqMktData with the same contract
object. The ticker may not be ready yet if called directly after reqMktData().
Parameters contract (Contract) – Contract to get ticker for.
Return type Ticker
tickers()
Get a list of all tickers.
for o in bracket:
ib.placeOrder(contract, o)
https://interactivebrokers.github.io/tws-api/bracket_order.html
Parameters
• action (str) – ‘BUY’ or ‘SELL’.
• quantity (float) – Size of order.
• limitPrice (float) – Limit price of entry order.
• takeProfitPrice (float) – Limit price of profit order.
• stopLossPrice (float) – Stop price of loss order.
Return type BracketOrder
2.1. IB 13
ib_insync, Release 0.9.70
Parameters
• account (str) – If specified, filter for this account name.
• modelCode (str) – If specified, filter for this account model.
reqAccountSummary()
It is recommended to use accountSummary() instead.
Request account values for all accounts and keep them updated. Returns when account summary is filled.
This method is blocking.
reqAutoOpenOrders(autoBind=True)
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
Parameters autoBind (bool) – Set binding on or off.
reqOpenOrders()
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 can-
celled order is reported as open. It is recommended to use the more reliable and much faster openTrades()
or openOrders() methods instead.
This method is blocking.
Return type List[Order]
reqAllOpenOrders()
Request and return a list of all open orders over all clients. Note that the orders of other clients will not be
kept in sync, use the master clientId mechanism instead to see other client’s orders that are kept in sync.
Return type List[Order]
reqCompletedOrders(apiOnly)
Request and return a list of completed trades.
Parameters apiOnly (bool) – Request only API orders (not manually placed TWS orders).
Return type List[Trade]
reqExecutions(execFilter=None)
It is recommended to use fills() or executions() instead.
Request and return a list of fills.
This method is blocking.
Parameters execFilter (Optional[ExecutionFilter]) – If specified, return executions that
match the filter.
Return type List[Fill]
reqPositions()
It is recommended to use positions() instead.
Request and return a list of positions for all accounts.
This method is blocking.
2.1. IB 15
ib_insync, Release 0.9.70
reqMatchingSymbols(pattern)
Request contract descriptions of contracts that match a pattern.
This method is blocking.
https://interactivebrokers.github.io/tws-api/matching_symbols.html
Parameters pattern (str) – The first few letters of the ticker symbol, or for longer strings a
character sequence matching a word in the security name.
Return type List[ContractDescription]
reqMarketRule(marketRuleId)
Request price increments rule.
https://interactivebrokers.github.io/tws-api/minimum_increment.html
Parameters marketRuleId (int) – ID of market rule. The market rule IDs for a contract can
be obtained via reqContractDetails() from ContractDetails.marketRuleIds, which
contains a comma separated string of market rule IDs.
Return type PriceIncrement
reqRealTimeBars(contract, barSize, whatToShow, useRTH, realTimeBarsOptions=[])
Request realtime 5 second bars.
https://interactivebrokers.github.io/tws-api/realtime_bars.html
Parameters
• contract (Contract) – Contract of interest.
• barSize (int) – Must be 5.
• whatToShow (str) – Specifies the source for constructing bars. Can be ‘TRADES’, ‘MID-
POINT’, ‘BID’ or ‘ASK’.
• useRTH (bool) – If True then only show data from within Regular Trading Hours, if False
then show all data.
• realTimeBarsOptions (List[TagValue]) – Unknown.
Return type RealTimeBarList
cancelRealTimeBars(bars)
Cancel the realtime bars subscription.
Parameters bars (RealTimeBarList) – The bar list that was obtained from
reqRealTimeBars.
reqHistoricalData(contract, endDateTime, durationStr, barSizeSetting, whatToShow, useRTH,
formatDate=1, keepUpToDate=False, chartOptions=[], timeout=60)
Request historical bar data.
This method is blocking.
https://interactivebrokers.github.io/tws-api/historical_bars.html
Parameters
• contract (Contract) – Contract of interest.
• endDateTime (Union[datetime, date, str, None]) – Can be set to ‘’ to indicate the
current time, or it can be given as a datetime.date or datetime.datetime, or it can be given
as a string in ‘yyyyMMdd HH:mm:ss’ format. If no timezone is given then the TWS login
timezone is used.
2.1. IB 17
ib_insync, Release 0.9.70
• durationStr (str) – Time span of all the bars. Examples: ‘60 S’, ‘30 D’, ‘13 W’, ‘6 M’,
‘10 Y’.
• barSizeSetting (str) – Time period of one bar. Must be one of: ‘1 secs’, ‘5 secs’, ‘10
secs’ 15 secs’, ‘30 secs’, ‘1 min’, ‘2 mins’, ‘3 mins’, ‘5 mins’, ‘10 mins’, ‘15 mins’, ‘20
mins’, ‘30 mins’, ‘1 hour’, ‘2 hours’, ‘3 hours’, ‘4 hours’, ‘8 hours’, ‘1 day’, ‘1 week’, ‘1
month’.
• whatToShow (str) – Specifies the source for constructing bars. Must be one
of: ‘TRADES’, ‘MIDPOINT’, ‘BID’, ‘ASK’, ‘BID_ASK’, ‘ADJUSTED_LAST’, ‘HIS-
TORICAL_VOLATILITY’, ‘OPTION_IMPLIED_VOLATILITY’, ‘REBATE_RATE’,
‘FEE_RATE’, ‘YIELD_BID’, ‘YIELD_ASK’, ‘YIELD_BID_ASK’, ‘YIELD_LAST’. For
‘SCHEDULE’ use:meth:.reqHistoricalSchedule.
• useRTH (bool) – If True then only show data from within Regular Trading Hours, if False
then show all data.
• formatDate (int) – For an intraday request setting to 2 will cause the returned date fields
to be timezone-aware datetime.datetime with UTC timezone, instead of local timezone as
used by TWS.
• keepUpToDate (bool) – If True then a realtime subscription is started to keep the bars
updated; endDateTime must be set empty (‘’) then.
• chartOptions (List[TagValue]) – Unknown.
• timeout (float) – Timeout in seconds after which to cancel the request and return an
empty bar series. Set to 0 to wait indefinitely.
Return type BarDataList
cancelHistoricalData(bars)
Cancel the update subscription for the historical bars.
Parameters bars (BarDataList) – The bar list that was obtained from reqHistoricalData
with a keepUpToDate subscription.
reqHistoricalSchedule(contract, numDays, endDateTime='', useRTH=True)
Request historical schedule.
This method is blocking.
Parameters
• contract (Contract) – Contract of interest.
• numDays (int) – Number of days.
• endDateTime (Union[datetime, date, str, None]) – Can be set to ‘’ to indicate the
current time, or it can be given as a datetime.date or datetime.datetime, or it can be given
as a string in ‘yyyyMMdd HH:mm:ss’ format. If no timezone is given then the TWS login
timezone is used.
• useRTH (bool) – If True then show schedule for Regular Trading Hours, if False then for
extended hours.
Return type HistoricalSchedule
reqHistoricalTicks(contract, startDateTime, endDateTime, numberOfTicks, whatToShow, useRth,
ignoreSize=False, miscOptions=[])
Request historical ticks. The time resolution of the ticks is one second.
This method is blocking.
https://interactivebrokers.github.io/tws-api/historical_time_and_sales.html
Parameters
• contract (Contract) – Contract to query.
• startDateTime (Union[str, date]) – Can be given as a datetime.date or date-
time.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 (Union[str, date]) – One of startDateTime or endDateTime can be
given, the other must be blank.
• numberOfTicks (int) – Number of ticks to request (1000 max). The actual result can
contain a bit more to accommodate all ticks in the latest second.
• whatToShow (str) – One of ‘Bid_Ask’, ‘Midpoint’ or ‘Trades’.
• useRTH – If True then only show data from within Regular Trading Hours, if False then
show all data.
• ignoreSize (bool) – Ignore bid/ask ticks that only update the size.
• miscOptions (List[TagValue]) – Unknown.
Return type List
reqMarketDataType(marketDataType)
Set the market data type used for reqMktData().
Parameters marketDataType (int) – One of:
• 1 = Live
• 2 = Frozen
• 3 = Delayed
• 4 = Delayed frozen
https://interactivebrokers.github.io/tws-api/market_data_type.html
reqHeadTimeStamp(contract, whatToShow, useRTH, formatDate=1)
Get the datetime of earliest available historical data for the contract.
Parameters
• contract (Contract) – Contract of interest.
• useRTH (bool) – If True then only show data from within Regular Trading Hours, if False
then show all data.
• formatDate (int) – If set to 2 then the result is returned as a timezone-aware date-
time.datetime with UTC timezone.
Return type datetime
reqMktData(contract, genericTickList='', snapshot=False, regulatorySnapshot=False,
mktDataOptions=None)
Subscribe to tick data or request a snapshot. Returns the Ticker that holds the market data. The ticker will
initially be empty and gradually (after a couple of seconds) be filled.
https://interactivebrokers.github.io/tws-api/md_request.html
Parameters
• contract (Contract) – Contract of interest.
2.1. IB 19
ib_insync, Release 0.9.70
• genericTickList (str) – 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_insync.objects.FundamentalRatios)
293 tradeCount
294 tradeRate
295 volumeRate
375 rtTradeVolume
411 rtHistVolatility
456 dividends (of type ib_insync.objects.Dividends)
588 futuresOpenInterest
reqMktDepthExchanges()
Get those exchanges that have have multiple market makers (and have ticks returned with marketMaker
info).
Return type List[DepthMktDataDescription]
reqMktDepth(contract, numRows=5, isSmartDepth=False, mktDepthOptions=None)
Subscribe to market depth data (a.k.a. DOM, L2 or order book).
https://interactivebrokers.github.io/tws-api/market_depth.html
Parameters
• contract (Contract) – Contract of interest.
• numRows (int) – Number of depth level on each side of the order book (5 max).
• isSmartDepth (bool) – Consolidate the order book across exchanges.
• mktDepthOptions – Unknown.
Return type Ticker
Returns The Ticker that holds the market depth in ticker.domBids and ticker.domAsks and
the list of MktDepthData in ticker.domTicks.
cancelMktDepth(contract, isSmartDepth=False)
Unsubscribe from market depth data.
Parameters contract (Contract) – The exact contract object that was used to subscribe with.
reqHistogramData(contract, useRTH, period)
Request histogram data.
This method is blocking.
https://interactivebrokers.github.io/tws-api/histograms.html
Parameters
• contract (Contract) – Contract to query.
• useRTH (bool) – If True then only show data from within Regular Trading Hours, if False
then show all data.
• period (str) – Period of which data is being requested, for example ‘3 days’.
Return type List[HistogramData]
reqFundamentalData(contract, reportType, fundamentalDataOptions=[])
Get fundamental data of a contract in XML format.
This method is blocking.
https://interactivebrokers.github.io/tws-api/fundamentals.html
Parameters
• contract (Contract) – Contract to query.
• reportType (str) –
– ‘ReportsFinSummary’: Financial summary
– ’ReportsOwnership’: Company’s ownership
– ’ReportSnapshot’: Company’s financial overview
– ’ReportsFinStatements’: Financial Statements
2.1. IB 21
ib_insync, Release 0.9.70
2.1. IB 23
ib_insync, Release 0.9.70
reqNewsProviders()
Get a list of news providers.
This method is blocking.
Return type List[NewsProvider]
reqNewsArticle(providerCode, articleId, newsArticleOptions=None)
Get the body of a news article.
This method is blocking.
https://interactivebrokers.github.io/tws-api/news.html
Parameters
• providerCode (str) – Code indicating news provider, like ‘BZ’ or ‘FLY’.
• articleId (str) – ID of the specific article.
• newsArticleOptions (Optional[List[TagValue]]) – Unknown.
Return type NewsArticle
reqHistoricalNews(conId, providerCodes, startDateTime, endDateTime, totalResults,
historicalNewsOptions=None)
Get historical news headline.
https://interactivebrokers.github.io/tws-api/news.html
This method is blocking.
Parameters
• conId (int) – Search news articles for contract with this conId.
• providerCodes (str) – A ‘+’-separated list of provider codes, like ‘BZ+FLY’.
• startDateTime (Union[str, date]) – The (exclusive) start of the date range. Can be
given as a datetime.date or datetime.datetime, or it can be given as a string in ‘yyyyMMdd
HH:mm:ss’ format. If no timezone is given then the TWS login timezone is used.
• endDateTime (Union[str, date]) – The (inclusive) end of the date range. Can be given
as a datetime.date or datetime.datetime, or it can be given as a string in ‘yyyyMMdd
HH:mm:ss’ format. If no timezone is given then the TWS login timezone is used.
• totalResults (int) – Maximum number of headlines to fetch (300 max).
• historicalNewsOptions (Optional[List[TagValue]]) – Unknown.
Return type HistoricalNews
reqNewsBulletins(allMessages)
Subscribe to IB news bulletins.
https://interactivebrokers.github.io/tws-api/news.html
Parameters allMessages (bool) – If True then fetch all messages for the day.
cancelNewsBulletins()
Cancel subscription to IB news bulletins.
requestFA(faDataType)
Requests to change the FA configuration.
This method is blocking.
Parameters faDataType (int) –
• 1 = Groups: Offer traders a way to create a group of accounts and apply a single allocation
method to all accounts in the group.
• 2 = Profiles: Let you allocate shares on an account-by-account basis using a predefined
calculation value.
• 3 = Account Aliases: Let you easily identify the accounts by meaningful names rather than
account numbers.
replaceFA(faDataType, xml)
Replaces Financial Advisor’s settings.
Parameters
• faDataType (int) – See requestFA().
• xml (str) – The XML-formatted configuration string.
async connectAsync(host='127.0.0.1', port=7497, clientId=1, timeout=4, readonly=False, account='')
async qualifyContractsAsync(*contracts)
whatIfOrderAsync(contract, order)
reqCurrentTimeAsync()
reqAccountUpdatesAsync(account)
reqAccountUpdatesMultiAsync(account, modelCode='')
async accountSummaryAsync(account='')
reqAccountSummaryAsync()
reqOpenOrdersAsync()
reqAllOpenOrdersAsync()
2.1. IB 25
ib_insync, Release 0.9.70
reqCompletedOrdersAsync(apiOnly)
reqExecutionsAsync(execFilter=None)
reqPositionsAsync()
reqContractDetailsAsync(contract)
async reqMatchingSymbolsAsync(pattern)
async reqMarketRuleAsync(marketRuleId)
reqMktDepthExchangesAsync()
reqScannerParametersAsync()
reqNewsProvidersAsync()
async requestFAAsync(faDataType)
2.2 Client
2.2. Client 27
ib_insync, Release 0.9.70
Events:
• apiStart ()
• apiEnd ()
• apiError (errorMsg: str)
• throttleStart ()
• throttleEnd ()
serverVersion()
run()
isConnected()
isReady()
Is the API connection up and running?
Return type bool
connectionStats()
Get statistics about the connection.
Return type ConnectionStats
getReqId()
Get new request ID.
Return type int
updateReqId(minReqId)
Update the next reqId to be at least minReqId.
getAccounts()
Get the list of account names that are under management.
Return type List[str]
setConnectOptions(connectOptions)
Set additional connect options.
Parameters connectOptions (str) – Use “+PACEAPI” to use request-pacing built into
TWS/gateway 974+.
connect(host, port, clientId, timeout=2.0)
Connect to a running TWS or IB gateway application.
Parameters
• host (str) – Host name or IP address.
• port (int) – Port number.
• clientId (int) – ID number to use for this client; must be unique per connection.
• timeout (Optional[float]) – If establishing the connection takes longer than timeout
seconds then the asyncio.TimeoutError exception is raised. Set to 0 to disable timeout.
async connectAsync(host, port, clientId, timeout=2.0)
disconnect()
Disconnect from IB connection.
send(*fields)
Serialize and send the given fields using the IB socket protocol.
sendMsg(msg)
reqMktData(reqId, contract, genericTickList, snapshot, regulatorySnapshot, mktDataOptions)
cancelMktData(reqId)
placeOrder(orderId, contract, order)
cancelOrder(orderId)
reqOpenOrders()
2.2. Client 29
ib_insync, Release 0.9.70
reqAccountUpdates(subscribe, acctCode)
reqExecutions(reqId, execFilter)
reqIds(numIds)
reqContractDetails(reqId, contract)
reqMktDepth(reqId, contract, numRows, isSmartDepth, mktDepthOptions)
cancelMktDepth(reqId, isSmartDepth)
reqNewsBulletins(allMsgs)
cancelNewsBulletins()
setServerLogLevel(logLevel)
reqAutoOpenOrders(bAutoBind)
reqAllOpenOrders()
reqManagedAccts()
requestFA(faData)
replaceFA(reqId, faData, cxml)
reqHistoricalData(reqId, contract, endDateTime, durationStr, barSizeSetting, whatToShow, useRTH,
formatDate, keepUpToDate, chartOptions)
exerciseOptions(reqId, contract, exerciseAction, exerciseQuantity, account, override)
reqScannerSubscription(reqId, subscription, scannerSubscriptionOptions,
scannerSubscriptionFilterOptions)
cancelScannerSubscription(reqId)
reqScannerParameters()
cancelHistoricalData(reqId)
reqCurrentTime()
reqRealTimeBars(reqId, contract, barSize, whatToShow, useRTH, realTimeBarsOptions)
cancelRealTimeBars(reqId)
reqFundamentalData(reqId, contract, reportType, fundamentalDataOptions)
cancelFundamentalData(reqId)
calculateImpliedVolatility(reqId, contract, optionPrice, underPrice, implVolOptions)
calculateOptionPrice(reqId, contract, volatility, underPrice, optPrcOptions)
cancelCalculateImpliedVolatility(reqId)
cancelCalculateOptionPrice(reqId)
reqGlobalCancel()
reqMarketDataType(marketDataType)
reqPositions()
reqAccountSummary(reqId, groupName, tags)
cancelAccountSummary(reqId)
cancelPositions()
verifyRequest(apiName, apiVersion)
verifyMessage(apiData)
queryDisplayGroups(reqId)
subscribeToGroupEvents(reqId, groupId)
updateDisplayGroup(reqId, contractInfo)
unsubscribeFromGroupEvents(reqId)
startApi()
verifyAndAuthRequest(apiName, apiVersion, opaqueIsvKey)
verifyAndAuthMessage(apiData, xyzResponse)
reqPositionsMulti(reqId, account, modelCode)
cancelPositionsMulti(reqId)
reqAccountUpdatesMulti(reqId, account, modelCode, ledgerAndNLV )
cancelAccountUpdatesMulti(reqId)
reqSecDefOptParams(reqId, underlyingSymbol, futFopExchange, underlyingSecType, underlyingConId)
reqSoftDollarTiers(reqId)
reqFamilyCodes()
reqMatchingSymbols(reqId, pattern)
reqMktDepthExchanges()
reqSmartComponents(reqId, bboExchange)
reqNewsArticle(reqId, providerCode, articleId, newsArticleOptions)
reqNewsProviders()
reqHistoricalNews(reqId, conId, providerCodes, startDateTime, endDateTime, totalResults,
historicalNewsOptions)
reqHeadTimeStamp(reqId, contract, whatToShow, useRTH, formatDate)
reqHistogramData(tickerId, contract, useRTH, timePeriod)
cancelHistogramData(tickerId)
cancelHeadTimeStamp(reqId)
reqMarketRule(marketRuleId)
reqPnL(reqId, account, modelCode)
cancelPnL(reqId)
reqPnLSingle(reqId, account, modelCode, conid)
cancelPnLSingle(reqId)
reqHistoricalTicks(reqId, contract, startDateTime, endDateTime, numberOfTicks, whatToShow, useRth,
ignoreSize, miscOptions)
reqTickByTickData(reqId, contract, tickType, numberOfTicks, ignoreSize)
cancelTickByTickData(reqId)
reqCompletedOrders(apiOnly)
2.2. Client 31
ib_insync, Release 0.9.70
reqWshMetaData(reqId)
cancelWshMetaData(reqId)
reqWshEventData(reqId, conId)
cancelWshEventData(reqId)
reqUserInfo(reqId)
2.3 Order
class ib_insync.order.Order(orderId: int = 0, clientId: int = 0, permId: int = 0, action: str = '',
totalQuantity: float = 0.0, orderType: str = '', lmtPrice: float =
1.7976931348623157e+308, auxPrice: float = 1.7976931348623157e+308, tif:
str = '', activeStartTime: str = '', activeStopTime: str = '', ocaGroup: str = '',
ocaType: int = 0, orderRef: str = '', transmit: bool = True, parentId: int = 0,
blockOrder: bool = False, sweepToFill: bool = False, displaySize: int = 0,
triggerMethod: int = 0, outsideRth: bool = False, hidden: bool = False,
goodAfterTime: str = '', goodTillDate: str = '', rule80A: str = '', allOrNone:
bool = False, minQty: int = 2147483647, percentOffset: float =
1.7976931348623157e+308, overridePercentageConstraints: bool = False,
trailStopPrice: float = 1.7976931348623157e+308, trailingPercent: float =
1.7976931348623157e+308, faGroup: str = '', faProfile: str = '', faMethod: str
= '', faPercentage: str = '', designatedLocation: str = '', openClose: str = 'O',
origin: int = 0, shortSaleSlot: int = 0, exemptCode: int = -1, discretionaryAmt:
float = 0.0, eTradeOnly: bool = False, firmQuoteOnly: bool = False,
nbboPriceCap: float = 1.7976931348623157e+308, optOutSmartRouting: bool
= False, auctionStrategy: int = 0, startingPrice: float =
1.7976931348623157e+308, stockRefPrice: float =
1.7976931348623157e+308, delta: float = 1.7976931348623157e+308,
stockRangeLower: float = 1.7976931348623157e+308, stockRangeUpper: float
= 1.7976931348623157e+308, randomizePrice: bool = False, randomizeSize:
bool = False, volatility: float = 1.7976931348623157e+308, volatilityType: int
= 2147483647, deltaNeutralOrderType: str = '', deltaNeutralAuxPrice: float =
1.7976931348623157e+308, deltaNeutralConId: int = 0,
deltaNeutralSettlingFirm: str = '', deltaNeutralClearingAccount: str = '',
deltaNeutralClearingIntent: str = '', deltaNeutralOpenClose: str = '',
deltaNeutralShortSale: bool = False, deltaNeutralShortSaleSlot: int = 0,
deltaNeutralDesignatedLocation: str = '', continuousUpdate: bool = False,
referencePriceType: int = 2147483647, basisPoints: float =
1.7976931348623157e+308, basisPointsType: int = 2147483647,
scaleInitLevelSize: int = 2147483647, scaleSubsLevelSize: int = 2147483647,
scalePriceIncrement: float = 1.7976931348623157e+308,
scalePriceAdjustValue: float = 1.7976931348623157e+308,
scalePriceAdjustInterval: int = 2147483647, scaleProfitOffset: float =
1.7976931348623157e+308, scaleAutoReset: bool = False, scaleInitPosition:
int = 2147483647, scaleInitFillQty: int = 2147483647, scaleRandomPercent:
bool = False, scaleTable: str = '', hedgeType: str = '', hedgeParam: str = '',
account: str = '', settlingFirm: str = '', clearingAccount: str = '', clearingIntent:
str = '', algoStrategy: str = '', algoParams:
typing.List[ib_insync.contract.TagValue] = <factory>,
smartComboRoutingParams: typing.List[ib_insync.contract.TagValue] =
<factory>, algoId: str = '', whatIf: bool = False, notHeld: bool = False,
solicited: bool = False, modelCode: str = '', orderComboLegs:
typing.List[ib_insync.order.OrderComboLeg] = <factory>, orderMiscOptions:
typing.List[ib_insync.contract.TagValue] = <factory>, referenceContractId: int
= 0, peggedChangeAmount: float = 0.0, isPeggedChangeAmountDecrease: bool
= False, referenceChangeAmount: float = 0.0, referenceExchangeId: str = '',
adjustedOrderType: str = '', triggerPrice: float = 1.7976931348623157e+308,
adjustedStopPrice: float = 1.7976931348623157e+308,
adjustedStopLimitPrice: float = 1.7976931348623157e+308,
adjustedTrailingAmount: float = 1.7976931348623157e+308,
adjustableTrailingUnit: int = 0, lmtPriceOffset: float =
1.7976931348623157e+308, conditions:
typing.List[ib_insync.order.OrderCondition] = <factory>,
conditionsCancelOrder: bool = False, conditionsIgnoreRth: bool = False,
extOperator: str = '', softDollarTier: ib_insync.objects.SoftDollarTier =
2.3. Order <factory>, cashQty: float = 1.7976931348623157e+308, mifid2DecisionMaker: 33
str = '', mifid2DecisionAlgo: str = '', mifid2ExecutionTrader: str = '',
mifid2ExecutionAlgo: str = '', dontUseAutoPriceForHedge: bool = False,
isOmsContainer: bool = False, discretionaryUpToLimitPrice: bool = False,
ib_insync, Release 0.9.70
https://interactivebrokers.github.io/tws-api/available_orders.html
orderId: int = 0
clientId: int = 0
permId: int = 0
action: str = ''
totalQuantity: float = 0.0
orderType: str = ''
lmtPrice: float = 1.7976931348623157e+308
auxPrice: float = 1.7976931348623157e+308
tif: str = ''
activeStartTime: str = ''
activeStopTime: str = ''
ocaGroup: str = ''
ocaType: int = 0
orderRef: str = ''
transmit: bool = True
parentId: int = 0
blockOrder: bool = False
sweepToFill: bool = False
displaySize: int = 0
triggerMethod: int = 0
outsideRth: bool = False
hidden: bool = False
goodAfterTime: str = ''
goodTillDate: str = ''
rule80A: str = ''
allOrNone: bool = False
minQty: int = 2147483647
percentOffset: float = 1.7976931348623157e+308
overridePercentageConstraints: bool = False
trailStopPrice: float = 1.7976931348623157e+308
trailingPercent: float = 1.7976931348623157e+308
faGroup: str = ''
faProfile: str = ''
faMethod: str = ''
faPercentage: str = ''
2.3. Order 35
ib_insync, Release 0.9.70
2.3. Order 37
ib_insync, Release 0.9.70
softDollarTier: ib_insync.objects.SoftDollarTier
class ib_insync.order.StopOrder(action, totalQuantity, stopPrice, **kwargs)
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
algoParams: List[ib_insync.contract.TagValue]
smartComboRoutingParams: List[ib_insync.contract.TagValue]
orderComboLegs: List[ib_insync.order.OrderComboLeg]
orderMiscOptions: List[ib_insync.contract.TagValue]
conditions: List[ib_insync.order.OrderCondition]
softDollarTier: ib_insync.objects.SoftDollarTier
class ib_insync.order.StopLimitOrder(action, totalQuantity, lmtPrice, stopPrice, **kwargs)
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
algoParams: List[ib_insync.contract.TagValue]
smartComboRoutingParams: List[ib_insync.contract.TagValue]
orderComboLegs: List[ib_insync.order.OrderComboLeg]
orderMiscOptions: List[ib_insync.contract.TagValue]
conditions: List[ib_insync.order.OrderCondition]
2.3. Order 39
ib_insync, Release 0.9.70
softDollarTier: ib_insync.objects.SoftDollarTier
class ib_insync.order.OrderStatus(orderId: int = 0, status: str = '', filled: float = 0.0, remaining: float =
0.0, avgFillPrice: float = 0.0, permId: int = 0, parentId: int = 0,
lastFillPrice: float = 0.0, clientId: int = 0, whyHeld: str = '',
mktCapPrice: float = 0.0)
orderId: int = 0
status: str = ''
filled: float = 0.0
remaining: float = 0.0
avgFillPrice: float = 0.0
permId: int = 0
parentId: int = 0
lastFillPrice: float = 0.0
clientId: int = 0
whyHeld: str = ''
mktCapPrice: float = 0.0
PendingSubmit: ClassVar[str] = 'PendingSubmit'
PendingCancel: ClassVar[str] = 'PendingCancel'
PreSubmitted: ClassVar[str] = 'PreSubmitted'
Submitted: ClassVar[str] = 'Submitted'
ApiPending: ClassVar[str] = 'ApiPending'
ApiCancelled: ClassVar[str] = 'ApiCancelled'
Cancelled: ClassVar[str] = 'Cancelled'
Filled: ClassVar[str] = 'Filled'
Inactive: ClassVar[str] = 'Inactive'
DoneStates: ClassVar[Set[str]] = {'ApiCancelled', 'Cancelled', 'Filled'}
ActiveStates: ClassVar[Set[str]] = {'ApiPending', 'PendingSubmit', 'PreSubmitted',
'Submitted'}
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.order.OrderState(status: str = '', initMarginBefore: str = '', maintMarginBefore: str = '',
equityWithLoanBefore: str = '', initMarginChange: str = '',
maintMarginChange: str = '', equityWithLoanChange: str = '',
initMarginAfter: str = '', maintMarginAfter: str = '', equityWithLoanAfter:
str = '', commission: float = 1.7976931348623157e+308,
minCommission: float = 1.7976931348623157e+308, maxCommission:
float = 1.7976931348623157e+308, commissionCurrency: str = '',
warningText: str = '', completedTime: str = '', completedStatus: str = '')
status: str = ''
initMarginBefore: str = ''
maintMarginBefore: str = ''
equityWithLoanBefore: str = ''
initMarginChange: str = ''
maintMarginChange: str = ''
equityWithLoanChange: str = ''
initMarginAfter: str = ''
maintMarginAfter: str = ''
equityWithLoanAfter: str = ''
commission: float = 1.7976931348623157e+308
minCommission: float = 1.7976931348623157e+308
maxCommission: float = 1.7976931348623157e+308
commissionCurrency: str = ''
warningText: str = ''
completedTime: str = ''
completedStatus: str = ''
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
2.3. Order 41
ib_insync, Release 0.9.70
isDone()
True if completely filled or cancelled, false otherwise.
filled()
Number of shares filled.
remaining()
Number of shares remaining to be filled.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.order.BracketOrder(parent, takeProfit, stopLoss)
Create new instance of BracketOrder(parent, takeProfit, stopLoss)
property parent
property takeProfit
property stopLoss
class ib_insync.order.OrderCondition
static createClass(condType)
And()
Or()
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
2.3. Order 43
ib_insync, Release 0.9.70
2.3. Order 45
ib_insync, Release 0.9.70
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
2.4 Contract
Contract(conId=270639)
Stock('AMD', 'SMART', 'USD')
Stock('INTC', 'SMART', 'USD', primaryExchange='NASDAQ')
Forex('EURUSD')
CFD('IBUS30')
Future('ES', '20180921', 'GLOBEX')
Option('SPY', '20170721', 240, 'C', 'SMART')
Bond(secIdType='ISIN', secId='US03076KAA60')
Crypto('BTC', 'PAXOS', 'USD')
Parameters
• conId (int) – The unique IB contract identifier.
• symbol (str) – The contract (or its underlying) symbol.
• secType (str) – The security type:
– ’STK’ = Stock (or ETF)
– ’OPT’ = Option
– ’FUT’ = Future
– ’IND’ = Index
– ’FOP’ = Futures option
– ’CASH’ = Forex pair
– ’CFD’ = CFD
– ’BAG’ = Combo
– ’WAR’ = Warrant
– ’BOND’ = Bond
2.4. Contract 47
ib_insync, Release 0.9.70
– ’CMDTY’ = Commodity
– ’NEWS’ = News
– ’FUND’ = Mutual fund
– ’CRYPTO’ = Crypto currency
• lastTradeDateOrContractMonth (str) – The contract’s last trading day or contract
month (for Options and Futures). Strings with format YYYYMM will be interpreted as
the Contract Month whereas YYYYMMDD will be interpreted as Last Trading Day.
• strike (float) – The option’s strike price.
• right (str) – Put or Call. Valid values are ‘P’, ‘PUT’, ‘C’, ‘CALL’, or ‘’ for non-options.
• multiplier (str) – he instrument’s multiplier (i.e. options, futures).
• exchange (str) – The destination exchange.
• currency (str) – The underlying’s currency.
• localSymbol (str) – The contract’s symbol within its primary exchange. For options, this
will be the OCC symbol.
• primaryExchange (str) – The contract’s primary exchange. For smart routed contracts,
used to define contract in case of ambiguity. Should be defined as native exchange of contract,
e.g. ISLAND for MSFT. For exchanges which contain a period in name, will only be part of
exchange name prior to period, i.e. ENEXT for ENEXT.BE.
• tradingClass (str) – The trading class name for this contract. Available in TWS contract
description window as well. For example, GBL Dec ‘13 future’s trading class is “FGBL”.
• includeExpired (bool) – If set to true, contract details requests and historical data queries
can be performed pertaining to expired futures contracts. Expired options or other instrument
types are not available.
• secIdType (str) – Security identifier type. Examples for Apple:
– secIdType=’ISIN’, secId=’US0378331005’
– secIdType=’CUSIP’, secId=’037833100’
• secId (str) – Security identifier.
• comboLegsDescription (str) – Description of the combo legs.
• comboLegs (List[ComboLeg]) – The legs of a combined contract definition.
• deltaNeutralContract (DeltaNeutralContract) – Delta and underlying price for
Delta-Neutral combo orders.
2.4. Contract 49
ib_insync, Release 0.9.70
2.4. Contract 51
ib_insync, Release 0.9.70
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
comboLegs: List[ib_insync.contract.ComboLeg]
class ib_insync.contract.CFD(symbol='', exchange='', currency='', **kwargs)
Contract For Difference.
Parameters
• symbol (str) – Symbol name.
• exchange (str) – Destination exchange.
• currency (str) – Underlying currency.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
comboLegs: List[ib_insync.contract.ComboLeg]
class ib_insync.contract.Commodity(symbol='', exchange='', currency='', **kwargs)
Commodity.
Parameters
• symbol (str) – Symbol name.
• exchange (str) – Destination exchange.
• currency (str) – Underlying currency.
2.4. Contract 53
ib_insync, Release 0.9.70
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
comboLegs: List[ib_insync.contract.ComboLeg]
class ib_insync.contract.Bond(**kwargs)
Bond.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
comboLegs: List[ib_insync.contract.ComboLeg]
class ib_insync.contract.FuturesOption(symbol='', lastTradeDateOrContractMonth='', strike=0.0,
right='', exchange='', multiplier='', currency='', **kwargs)
Option on a futures contract.
Parameters
• symbol (str) – Symbol name.
• lastTradeDateOrContractMonth (str) – The option’s last trading day or contract month.
– YYYYMM format: To specify last month
– YYYYMMDD format: To specify last trading day
• strike (float) – The option’s strike price.
• right (str) – Put or call option. Valid values are ‘P’, ‘PUT’, ‘C’ or ‘CALL’.
2.4. Contract 55
ib_insync, Release 0.9.70
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
comboLegs: List[ib_insync.contract.ComboLeg]
class ib_insync.contract.Bag(**kwargs)
Bag contract.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
comboLegs: List[ib_insync.contract.ComboLeg]
class ib_insync.contract.Crypto(symbol='', exchange='', currency='', **kwargs)
Crypto currency contract.
Parameters
• symbol (str) – Symbol name.
• exchange (str) – Destination exchange.
• currency (str) – Underlying currency.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
comboLegs: List[ib_insync.contract.ComboLeg]
class ib_insync.contract.TagValue(tag, value)
Create new instance of TagValue(tag, value)
property tag
property value
class ib_insync.contract.ComboLeg(conId: int = 0, ratio: int = 0, action: str = '', exchange: str = '',
openClose: int = 0, shortSaleSlot: int = 0, designatedLocation: str = '',
exemptCode: int = - 1)
conId: int = 0
ratio: int = 0
action: str = ''
exchange: str = ''
openClose: int = 0
shortSaleSlot: int = 0
designatedLocation: str = ''
exemptCode: int = -1
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.contract.DeltaNeutralContract(conId: int = 0, delta: float = 0.0, price: float = 0.0)
conId: int = 0
delta: float = 0.0
price: float = 0.0
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
2.4. Contract 57
ib_insync, Release 0.9.70
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.contract.ContractDetails(contract: Union[ib_insync.contract.Contract, NoneType] =
None, marketName: str = '', minTick: float = 0.0, orderTypes:
str = '', validExchanges: str = '', priceMagnifier: int = 0,
underConId: int = 0, longName: str = '', contractMonth: str =
'', industry: str = '', category: str = '', subcategory: str = '',
timeZoneId: str = '', tradingHours: str = '', liquidHours: str =
'', evRule: str = '', evMultiplier: int = 0, mdSizeMultiplier: int
= 1, aggGroup: int = 0, underSymbol: str = '', underSecType:
str = '', marketRuleIds: str = '', secIdList:
List[ib_insync.contract.TagValue] = <factory>,
realExpirationDate: str = '', lastTradeTime: str = '', stockType:
str = '', minSize: float = 0.0, sizeIncrement: float = 0.0,
suggestedSizeIncrement: float = 0.0, cusip: str = '', ratings: str
= '', descAppend: str = '', bondType: str = '', couponType: str
= '', callable: bool = False, putable: bool = False, coupon: int
= 0, convertible: bool = False, maturity: str = '', issueDate: str
= '', nextOptionDate: str = '', nextOptionType: str = '',
nextOptionPartial: bool = False, notes: str = '')
contract: Optional[ib_insync.contract.Contract] = None
marketName: str = ''
minTick: float = 0.0
orderTypes: str = ''
validExchanges: str = ''
priceMagnifier: int = 0
underConId: int = 0
longName: str = ''
contractMonth: str = ''
industry: str = ''
category: str = ''
subcategory: str = ''
timeZoneId: str = ''
tradingHours: str = ''
liquidHours: str = ''
2.4. Contract 59
ib_insync, Release 0.9.70
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
2.5 Ticker
2.5. Ticker 61
ib_insync, Release 0.9.70
2.5. Ticker 63
ib_insync, Release 0.9.70
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.ticker.TickerUpdateEvent(name='', _with_error_done_events=True)
trades()
Emit trade ticks.
Return type Tickfilter
bids()
Emit bid ticks.
Return type Tickfilter
asks()
Emit ask ticks.
Return type Tickfilter
bidasks()
Emit bid and ask ticks.
Return type Tickfilter
midpoints()
Emit midpoint ticks.
Return type Tickfilter
class ib_insync.ticker.Tickfilter(tickTypes, source=None)
Tick filtering event operators that emit(time, price, size).
on_source(ticker)
Emit a new value to all connected listeners.
2.5. Ticker 65
ib_insync, Release 0.9.70
2.6 Objects
Object hierarchy.
class ib_insync.objects.ScannerSubscription(numberOfRows: int = - 1, instrument: str = '',
locationCode: str = '', scanCode: str = '', abovePrice: float
= 1.7976931348623157e+308, belowPrice: float =
1.7976931348623157e+308, aboveVolume: int =
2147483647, marketCapAbove: float =
1.7976931348623157e+308, marketCapBelow: float =
1.7976931348623157e+308, moodyRatingAbove: str = '',
moodyRatingBelow: str = '', spRatingAbove: str = '',
spRatingBelow: str = '', maturityDateAbove: str = '',
maturityDateBelow: str = '', couponRateAbove: float =
1.7976931348623157e+308, couponRateBelow: float =
1.7976931348623157e+308, excludeConvertible: bool =
False, averageOptionVolumeAbove: int = 2147483647,
scannerSettingPairs: str = '', stockTypeFilter: str = '')
numberOfRows: int = -1
instrument: str = ''
locationCode: str = ''
scanCode: str = ''
abovePrice: float = 1.7976931348623157e+308
belowPrice: float = 1.7976931348623157e+308
aboveVolume: int = 2147483647
marketCapAbove: float = 1.7976931348623157e+308
marketCapBelow: float = 1.7976931348623157e+308
moodyRatingAbove: str = ''
moodyRatingBelow: str = ''
spRatingAbove: str = ''
spRatingBelow: str = ''
maturityDateAbove: str = ''
maturityDateBelow: str = ''
couponRateAbove: float = 1.7976931348623157e+308
couponRateBelow: float = 1.7976931348623157e+308
excludeConvertible: bool = False
averageOptionVolumeAbove: int = 2147483647
scannerSettingPairs: str = ''
2.6. Objects 67
ib_insync, Release 0.9.70
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.objects.ExecutionFilter(clientId: int = 0, acctCode: str = '', time: str = '', symbol: str =
'', secType: str = '', exchange: str = '', side: str = '')
clientId: int = 0
acctCode: str = ''
time: str = ''
symbol: str = ''
secType: str = ''
exchange: str = ''
side: str = ''
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.objects.BarData(date: Union[datetime.date, datetime.datetime] = datetime.datetime(1970,
1, 1, 0, 0, tzinfo=datetime.timezone.utc), open: float = 0.0, high: float =
0.0, low: float = 0.0, close: float = 0.0, volume: float = 0, average: float =
0.0, barCount: int = 0)
date: Union[datetime.date, datetime.datetime] = datetime.datetime(1970, 1, 1, 0, 0,
tzinfo=datetime.timezone.utc)
open: float = 0.0
high: float = 0.0
low: float = 0.0
2.6. Objects 69
ib_insync, Release 0.9.70
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.objects.TickAttrib(canAutoExecute: bool = False, pastLimit: bool = False, preOpen: bool
= False)
canAutoExecute: bool = False
pastLimit: bool = False
preOpen: bool = False
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.objects.TickAttribBidAsk(bidPastLow: bool = False, askPastHigh: bool = False)
bidPastLow: bool = False
askPastHigh: bool = False
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.objects.TickAttribLast(pastLimit: bool = False, unreported: bool = False)
pastLimit: bool = False
unreported: bool = False
2.6. Objects 71
ib_insync, Release 0.9.70
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.objects.HistogramData(price: float = 0.0, count: int = 0)
price: float = 0.0
count: int = 0
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.objects.NewsProvider(code: str = '', name: str = '')
code: str = ''
name: str = ''
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.objects.DepthMktDataDescription(exchange: str = '', secType: str = '', listingExch: str =
'', serviceDataType: str = '', aggGroup: int =
2147483647)
exchange: str = ''
secType: str = ''
listingExch: str = ''
serviceDataType: str = ''
aggGroup: int = 2147483647
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.objects.PnL(account: str = '', modelCode: str = '', dailyPnL: float = nan, unrealizedPnL:
float = nan, realizedPnL: float = nan)
account: str = ''
modelCode: str = ''
dailyPnL: float = nan
unrealizedPnL: float = nan
realizedPnL: float = nan
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
2.6. Objects 73
ib_insync, Release 0.9.70
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.objects.TradeLogEntry(time: datetime.datetime, status: str = '', message: str = '',
errorCode: int = 0)
time: datetime.datetime
status: str = ''
message: str = ''
errorCode: int = 0
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.objects.PnLSingle(account: str = '', modelCode: str = '', conId: int = 0, dailyPnL: float =
nan, unrealizedPnL: float = nan, realizedPnL: float = nan, position: int
= 0, value: float = nan)
account: str = ''
modelCode: str = ''
conId: int = 0
dailyPnL: float = nan
unrealizedPnL: float = nan
realizedPnL: float = nan
position: int = 0
value: float = nan
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.objects.HistoricalSession(startDateTime: str = '', endDateTime: str = '', refDate: str =
'')
startDateTime: str = ''
endDateTime: str = ''
refDate: str = ''
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.objects.HistoricalSchedule(startDateTime: str = '', endDateTime: str = '', timeZone: str
= '', sessions: List[ib_insync.objects.HistoricalSession] =
<factory>)
startDateTime: str = ''
endDateTime: str = ''
timeZone: str = ''
sessions: List[ib_insync.objects.HistoricalSession]
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
2.6. Objects 75
ib_insync, Release 0.9.70
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
class ib_insync.objects.AccountValue(account, tag, value, currency, modelCode)
Create new instance of AccountValue(account, tag, value, currency, modelCode)
property account
property tag
property value
property currency
property modelCode
class ib_insync.objects.TickData(time, tickType, price, size)
Create new instance of TickData(time, tickType, price, size)
property time
property tickType
property price
property size
class ib_insync.objects.HistoricalTick(time, price, size)
Create new instance of HistoricalTick(time, price, size)
property time
property price
property size
class ib_insync.objects.HistoricalTickBidAsk(time, tickAttribBidAsk, priceBid, priceAsk, sizeBid,
sizeAsk)
Create new instance of HistoricalTickBidAsk(time, tickAttribBidAsk, priceBid, priceAsk, sizeBid, sizeAsk)
property time
property tickAttribBidAsk
property priceBid
property priceAsk
property sizeBid
property sizeAsk
class ib_insync.objects.HistoricalTickLast(time, tickAttribLast, price, size, exchange,
specialConditions)
Create new instance of HistoricalTickLast(time, tickAttribLast, price, size, exchange, specialConditions)
property time
property tickAttribLast
property price
property size
property exchange
property specialConditions
class ib_insync.objects.TickByTickAllLast(tickType, time, price, size, tickAttribLast, exchange,
specialConditions)
Create new instance of TickByTickAllLast(tickType, time, price, size, tickAttribLast, exchange, specialCondi-
tions)
property tickType
property time
property price
property size
property tickAttribLast
property exchange
property specialConditions
class ib_insync.objects.TickByTickBidAsk(time, bidPrice, askPrice, bidSize, askSize, tickAttribBidAsk)
Create new instance of TickByTickBidAsk(time, bidPrice, askPrice, bidSize, askSize, tickAttribBidAsk)
property time
property bidPrice
property askPrice
property bidSize
property askSize
property tickAttribBidAsk
class ib_insync.objects.TickByTickMidPoint(time, midPoint)
Create new instance of TickByTickMidPoint(time, midPoint)
property time
property midPoint
class ib_insync.objects.MktDepthData(time, position, marketMaker, operation, side, price, size)
Create new instance of MktDepthData(time, position, marketMaker, operation, side, price, size)
property time
property position
property marketMaker
property operation
property side
property price
property size
class ib_insync.objects.DOMLevel(price, size, marketMaker)
Create new instance of DOMLevel(price, size, marketMaker)
property price
property size
property marketMaker
2.6. Objects 77
ib_insync, Release 0.9.70
property theta
property undPrice
class ib_insync.objects.OptionChain(exchange, underlyingConId, tradingClass, multiplier, expirations,
strikes)
Create new instance of OptionChain(exchange, underlyingConId, tradingClass, multiplier, expirations, strikes)
property exchange
property underlyingConId
property tradingClass
property multiplier
property expirations
property strikes
class ib_insync.objects.Dividends(past12Months, next12Months, nextDate, nextAmount)
Create new instance of Dividends(past12Months, next12Months, nextDate, nextAmount)
property past12Months
property next12Months
property nextDate
property nextAmount
class ib_insync.objects.NewsArticle(articleType, articleText)
Create new instance of NewsArticle(articleType, articleText)
property articleType
property articleText
class ib_insync.objects.HistoricalNews(time, providerCode, articleId, headline)
Create new instance of HistoricalNews(time, providerCode, articleId, headline)
property time
property providerCode
property articleId
property headline
class ib_insync.objects.NewsTick(timeStamp, providerCode, articleId, headline, extraData)
Create new instance of NewsTick(timeStamp, providerCode, articleId, headline, extraData)
property timeStamp
property providerCode
property articleId
property headline
property extraData
class ib_insync.objects.NewsBulletin(msgId, msgType, message, origExchange)
Create new instance of NewsBulletin(msgId, msgType, message, origExchange)
property msgId
property msgType
2.6. Objects 79
ib_insync, Release 0.9.70
property message
property origExchange
class ib_insync.objects.FamilyCode(accountID, familyCodeStr)
Create new instance of FamilyCode(accountID, familyCodeStr)
property accountID
property familyCodeStr
class ib_insync.objects.SmartComponent(bitNumber, exchange, exchangeLetter)
Create new instance of SmartComponent(bitNumber, exchange, exchangeLetter)
property bitNumber
property exchange
property exchangeLetter
class ib_insync.objects.ConnectionStats(startTime, duration, numBytesRecv, numBytesSent,
numMsgRecv, numMsgSent)
Create new instance of ConnectionStats(startTime, duration, numBytesRecv, numBytesSent, numMsgRecv,
numMsgSent)
property startTime
property duration
property numBytesRecv
property numBytesSent
property numMsgRecv
property numMsgSent
class ib_insync.objects.BarDataList(*args)
List of BarData that also stores all request parameters.
Events:
• updateEvent (bars: BarDataList, hasNewBar: bool)
reqId: int
contract: ib_insync.contract.Contract
endDateTime: Optional[Union[datetime.datetime, datetime.date, str]]
durationStr: str
barSizeSetting: str
whatToShow: str
useRTH: bool
formatDate: int
keepUpToDate: bool
chartOptions: List[ib_insync.contract.TagValue]
class ib_insync.objects.RealTimeBarList(*args)
List of RealTimeBar that also stores all request parameters.
Events:
2.7 Utilities
Utilities.
ib_insync.util.globalErrorEvent = Event<Event, []>
Event to emit global exceptions.
ib_insync.util.df(objs, labels=None)
Create pandas DataFrame from the sequence of same-type objects.
Parameters labels (Optional[List[str]]) – If supplied, retain only the given labels and drop the
rest.
ib_insync.util.dataclassAsDict(obj)
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
ib_insync.util.dataclassAsTuple(obj)
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
2.7. Utilities 81
ib_insync, Release 0.9.70
2.7. Utilities 83
ib_insync, Release 0.9.70
– PySide6
• period (float) – Period in seconds to poll Qt.
ib_insync.util.formatIBDatetime(dt)
Format date or datetime to string that IB uses.
Return type str
ib_insync.util.parseIBDatetime(s)
Parse string in IB date or datetime format to datetime.
Return type Union[date, datetime]
2.8 FlexReport
2.9 IBC
2.9. IBC 85
ib_insync, Release 0.9.70
import asyncio
asyncio.set_event_loop(asyncio.ProactorEventLoop())
Example usage:
IbcLogLevel: ClassVar = 10
twsVersion: int = 0
gateway: bool = False
tradingMode: str = ''
twsPath: str = ''
twsSettingsPath: str = ''
ibcPath: str = ''
ibcIni: str = ''
javaPath: str = ''
userid: str = ''
password: str = ''
fixuserid: str = ''
fixpassword: str = ''
start()
Launch TWS/IBG.
terminate()
Terminate TWS/IBG.
async startAsync()
async terminateAsync()
async monitorAsync()
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
2.10 IBController
import asyncio
asyncio.set_event_loop(asyncio.ProactorEventLoop())
2.10. IBController 87
ib_insync, Release 0.9.70
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
2.11 Watchdog
def onConnected():
print(ib.accountValues())
Events:
• startingEvent (watchdog: Watchdog)
• startedEvent (watchdog: Watchdog)
• stoppingEvent (watchdog: Watchdog)
• stoppedEvent (watchdog: Watchdog)
• softTimeoutEvent (watchdog: Watchdog)
• hardTimeoutEvent (watchdog: Watchdog)
2.11. Watchdog 89
ib_insync, Release 0.9.70
async runAsync()
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
tuple()
Return dataclass values as tuple. This is a non-recursive variant of dataclasses.astuple.
Return type tuple
update(*srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from
keyword arguments.
Return type object
THREE
NOTEBOOKS
IB-insync can be used in a fully interactive, exploratory way with live data from within a Jupyter notebook. Here are
some recipe notebooks:
91
ib_insync, Release 0.9.70
92 Chapter 3. Notebooks
CHAPTER
FOUR
CODE RECIPES
Suppose we want to get the 1 min bar data of Tesla since the very beginning up until now. The best way is to start with
now and keep requesting further and further back in time until there is no more data returned.
import datetime
from ib_insync import *
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)
dt = ''
barsList = []
while True:
bars = ib.reqHistoricalData(
contract,
endDateTime=dt,
durationStr='10 D',
barSizeSetting='1 min',
whatToShow='MIDPOINT',
useRTH=True,
formatDate=1)
if not bars:
break
barsList.append(bars)
dt = bars[0].date
print(dt)
93
ib_insync, Release 0.9.70
allParams = ib.reqScannerParameters())
print(allParams)
sub = ScannerSubscription(
instrument='FUT.US',
locationCode='FUT.GLOBEX',
scanCode='TOP_PERC_GAIN')
scanData = ib.reqScannerData(sub)
print(scanData)
def onScanData(scanData):
print(scanData[0])
print(len(scanData))
sub = ScannerSubscription(
instrument='FUT.US',
locationCode='FUT.GLOBEX',
scanCode='TOP_PERC_GAIN')
scanData = ib.reqScannerSubscription(sub)
scanData.updateEvent += onScanData
ib.sleep(60)
ib.cancelScannerSubscription(scanData)
calc = ib.calculateImpliedVolatility(
option, optionPrice=6.1, underPrice=525))
print(calc)
calc = ib.calculateOptionPrice(
option, volatility=0.14, underPrice=525))
print(calc)
eurusd = Forex('EURUSD')
ticker = ib.reqMktDepth(eurusd)
while ib.sleep(5):
print(
[d.price for d in ticker.domBids],
[d.price for d in ticker.domAsks])
usdjpy = Forex('USDJPY')
cd = ib.reqContractDetails(usdjpy)[0]
print(cd.marketRuleIds)
rules = [
ib.reqMarketRule(ruleId)
for ruleId in cd.marketRuleIds.split(',')]
print(rules)
newsProviders = ib.reqNewsProviders()
print(newsProviders)
codes = '+'.join(np.code for np in newsProviders)
ib.reqNewsBulletins(True)
ib.sleep(5)
print(ib.newsBulletins())
4.9 Dividends
Output:
import asyncio
class App:
def stop(self):
self.ib.disconnect()
app = App()
try:
asyncio.run(app.run())
(continues on next page)
This example of a ticker table shows how to integrate both realtime streaming and synchronous API requests in a single-
threaded Qt application. The API requests in this example are connect and ib.qualifyContracts(); The latter is
used to get the conId of a contract and use that as a unique key.
The Qt interface will not freeze when a request is ongoing and it is even possible to have multiple outstanding requests
at the same time.
This example depends on PyQt5:
pip3 install -U PyQt5.
It’s also possible to use PySide2 instead; To do so uncomment the PySide2 import and util.useQt lines in the example
and comment out their PyQt5 counterparts.
To integrate with the Tkinter event loop, take a look at this example app.
FIVE
SOURCE CODE
99
ib_insync, Release 0.9.70
SIX
CHANGELOG
6.1 0.9
• Crypto security class added. To accommodate fractional crypto currency sizes, all the various size and volume
fields that were of type int are now of type float.
• pull 385: Get day trades remaining for next four days in IB.accountSummary.
• Fixed: issue 361: Prevent util.logToConsole and util.logToFile from messing with the root logger.
• Fixed: issue 370: Catch asyncio.CancelledError during connect.
• Fixed: issue 371: Fix type annotation for reqMarketRuleAsync.
• Fixed: issue 380: Reject bogus whatIf order response.
• Fixed: issue 389: Add TradeLogEntry.errorCode field.
101
ib_insync, Release 0.9.70
• Fixed: issue 309: Aggregate past fills into the Trade they belong to upon connect.
• ContFut objects are now hashable (issue 310).
• Added Watchdog.probeTimeout parameter (issue 307).
• Fixed issue 282: util.Qt() also works with the ProactorEventLoop (default on Windows) now.
• Fixed issue 303: A regression in TWS 480.4l+ is bypassed now to avoid IB.connect() timeouts. Request
timeouts during syncing are logged as errors but will let the connect proceed.
• IB.TimezoneTWS field added, for when the TWS timezone differs from the local system timezone (issue 287).
• IB.RaiseRequestErrors field added, can be set to True to raise RequestError when certain requests fail,
instead of returning empty data (pull 296).
• IB.accountSummaryAsync() method added (issue 267).
• Watchdog.probeContract field added, to use a contract other then EURUSD for probing the data connection
(issue 298).
• Ticker.rtTime added (issue 274, pull 275). Please note that this timestamp appears to be mostly bogus.
• Fixed issue 270: Clear ticker depth data when canceling market depth subscription.
• Fixed issue with duplicate order IDs.
• IB.reqHistoricalData() has a new timeout parameter that automatically cancels the request after timing
out.
• BracketOrder is iterable again.
• IB.waitOnUpdate() returns False on timeout now.
• pull 210: Fix decoding of execDetails time.
• pull 215: New scanner notebook added, courtesy of C. Valcarcel.
• pull 220: Added readonly option for Watchdog.
• Fixed issue 221: Delayed close ticks handling by Ticker.
• Fixed issue 224: Added timeout for completedOrders request during connect.
• Fixed issue 227: IB.MaxSyncedSubAccounts added.
• Fixed issue 230: Fixed IB.reqHistogramData method.
• Fixed issue 235: Order.discretionaryAmt is now of type float (was int).
• Fixed issue 236: ticker.updateEvent is now fired for any change made to the ticker.
• Fixed issue 245: Emit trade.statusEvent when order is implicitly canceled by a problem.
• You can now sponsor the development of IB-insync!
• PR #196 treats error 492 as a warning so that scanner results can still be used.
• PR #184, #185 and #186 add the new Ticker fields rtTradeVolume, auctionVolume, auctionPrice and
auctionImbalance.
• PR #191 lets util.schedule return a handle that can be canceled.
• PR #192 adds throttleStart and throttleEnd events to the Client.
• PR #194 adds better JSON support for namedtuple objects.
• ContractDetails.stockType added.
• Fixed Trade.filled() for combo (BAG) contracts.
• Server version check added to make sure TWS/gateway version is at least 972.
• ib.reqCompletedOrders() request added (requires TWS/gateway >= 976). Completed orders are automati-
cally synced on connect and are available from ib.trades(), complete with fills and commission info.
• Fixed bug #144.
• ibapi package from IB is no longer needed, ib_insync handles its own socket protocol encoding and decoding
now.
• Documentation moved to readthedocs as rawgit will cease operation later this year.
• Blocking requests will now raise ConnectionError on a connection failure. This also goes for util.run,
util.timeRange, etc.
• Event class has been replaced with the one from eventkit.
• Event-driven bar construction from ticks added (via Ticker.updateEvent)
• Fixed bug #136.
• Default request throttling is now 45 requests/s for compatibility with TWS/gateway 974 and higher.
• Event.merge() added.
• TagValue serialization fixed.
• Ticker.hasBidAsk() added.
• IB.newsBulletinEvent added.
• Various small fixes.
• Autocompletion with Jedi plugin as used in Spyder and VS Code working again.
• Request results will return specialized contract types (like Stock) instead of generic Contract.
• IB.scannerDataEvent added.
• ContractDetails field summary renamed to contract.
• isSmartDepth parameter added for reqMktDepth.
• Event loop nesting is now handled by the nest_asyncio project.
• util.useQt is rewritten so that it can be used with any asyncio event loop, with support for both PyQt5 and
PySide2. It does not use quamash anymore.
• Various fixes, extensive documentation overhaul and flake8-compliant code formatting.
• IB.RequestTimeout added.
• util.schedule() accepts tz-aware datetimes now.
• Let client.disconnect() complete when no event loop is running.
• ticker.futuresOpenInterest added.
• execution.time was string, is now parsed to UTC datetime.
• ib.reqMarketRule() request added.
• IBC added.
• PR #53 (delayed greeks) merged.
• Ticker.futuresOpenInterest field removed.
• IBController added.
• openOrder callback added.
• default arguments for ib.connect() and ib.reqMktData().
6.2 0.8
• FlexReport added.
• BarDataList now used with reqHistoricalData; it also stores the request parameters.
• updated the typing annotations.
• added barUpdate event to IB.
• bar- and tick-data notebooks updated to use callbacks for realtime data.
6.3 0.7
• IB.whatIfOrder() added.
• Added detection and warning about common setup problems.
6.4 0.6
• Initial release.
SEVEN
LINKS
• Interactive Brokers
• Interactive Brokers Python API
• TWSAPI documentation
• TWSAPI user goup
• IB-insync user goup
• Dmitry’s TWS API FAQ
• IBC for hands-free operation of TWS or gateway
117
ib_insync, Release 0.9.70
EIGHT
INTRODUCTION
The goal of the IB-insync library is to make working with the Trader Workstation API from Interactive Brokers as easy
as possible.
The main features are:
• An easy to use linear style of programming;
• An IB component that automatically keeps in sync with the TWS or IB Gateway application;
• A fully asynchonous framework based on asyncio and eventkit for advanced users;
• Interactive operation with live data in Jupyter notebooks.
Be sure to take a look at the notebooks, the recipes and the API docs.
8.1 Installation
For Python 3.6 install the dataclasses package as well (newer Python versions already have it):
pip install dataclasses
Requirements:
• Python 3.6 or higher;
• A running TWS or IB Gateway application (version 972 or higher). Make sure the API port is enabled and
‘Download open orders on connection’ is checked.
The ibapi package from IB is not needed.
8.2 Example
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)
119
ib_insync, Release 0.9.70
Output:
8.3 Documentation
8.4 Discussion
The insync user group is the place to discuss IB-insync and anything related to it.
IB-insync offers an easy entry into building automated trading systems for both individual traders and fintech compa-
nies. However, to get the most out of it is not a trivial matter and is beyond the reach of most developers.
If you need expert help, you can contact me. This can be for a small project, such as fixing something in your own
code, or it can be creating an entire new trading infrastructure. Please provide enough details so that I can assess both
the feasibility and the scope. Many folks worry about having to provide their ‘secret sauce’, but that is never necessary
(although you’re perfectly welcome to send that as well!)
8.6 Disclaimer
i
ib_insync.client, 27
ib_insync.contract, 47
ib_insync.flexreport, 84
ib_insync.ib, 7
ib_insync.objects, 66
ib_insync.order, 32
ib_insync.ticker, 61
ib_insync.util, 81
123
ib_insync, Release 0.9.70
A attribute), 73
abovePrice (ib_insync.objects.ScannerSubscription at- algoId (ib_insync.order.Order attribute), 36
tribute), 66 algoParams (ib_insync.order.LimitOrder attribute), 38
aboveVolume (ib_insync.objects.ScannerSubscription algoParams (ib_insync.order.MarketOrder attribute), 38
attribute), 66 algoParams (ib_insync.order.Order attribute), 36
account (ib_insync.ibcontroller.Watchdog attribute), 89 algoParams (ib_insync.order.StopLimitOrder attribute),
account (ib_insync.objects.AccountValue property), 76 39
account (ib_insync.objects.PnL attribute), 73 algoParams (ib_insync.order.StopOrder attribute), 39
account (ib_insync.objects.PnLSingle attribute), 74 algoStrategy (ib_insync.order.Order attribute), 36
account (ib_insync.objects.PortfolioItem property), 78 allOrNone (ib_insync.order.Order attribute), 34
account (ib_insync.objects.Position property), 78 allowCtrlC() (in module ib_insync.util), 82
account (ib_insync.order.Order attribute), 36 And() (ib_insync.order.OrderCondition method), 43
accountID (ib_insync.objects.FamilyCode property), 80 ApiCancelled (ib_insync.order.OrderStatus attribute),
accountSummary() (ib_insync.ib.IB method), 11 40
accountSummaryAsync() (ib_insync.ib.IB method), 25 ApiPending (ib_insync.order.OrderStatus attribute), 40
AccountValue (class in ib_insync.objects), 76 APP (ib_insync.ibcontroller.IBController attribute), 87
accountValues() (ib_insync.ib.IB method), 11 appStartupTime (ib_insync.ibcontroller.Watchdog at-
acctCode (ib_insync.objects.ExecutionFilter attribute), tribute), 89
69 appTimeout (ib_insync.ibcontroller.Watchdog attribute),
acctNumber (ib_insync.objects.Execution attribute), 67 89
action (ib_insync.contract.ComboLeg attribute), 57 articleId (ib_insync.objects.HistoricalNews property),
action (ib_insync.order.Order attribute), 34 79
activeStartTime (ib_insync.order.Order attribute), 34 articleId (ib_insync.objects.NewsTick property), 79
ActiveStates (ib_insync.order.OrderStatus attribute), articleText (ib_insync.objects.NewsArticle property),
40 79
activeStopTime (ib_insync.order.Order attribute), 34 articleType (ib_insync.objects.NewsArticle property),
adjustableTrailingUnit (ib_insync.order.Order at- 79
tribute), 36 ask (ib_insync.ticker.Ticker attribute), 62
adjustedOrderType (ib_insync.order.Order attribute), askGreeks (ib_insync.ticker.Ticker attribute), 63
36 askPastHigh (ib_insync.objects.TickAttribBidAsk
adjustedStopLimitPrice (ib_insync.order.Order at- attribute), 71
tribute), 36 askPrice (ib_insync.objects.TickByTickBidAsk prop-
adjustedStopPrice (ib_insync.order.Order attribute), erty), 77
36 asks() (ib_insync.ticker.TickerUpdateEvent method), 64
adjustedTrailingAmount (ib_insync.order.Order at- askSize (ib_insync.objects.TickByTickBidAsk property),
tribute), 36 77
advancedError (ib_insync.order.Trade attribute), 42 askSize (ib_insync.ticker.Ticker attribute), 62
advancedErrorOverride (ib_insync.order.Order askYield (ib_insync.ticker.Ticker attribute), 62
attribute), 37 auctionImbalance (ib_insync.ticker.Ticker attribute),
aggGroup (ib_insync.contract.ContractDetails attribute), 63
59 auctionPrice (ib_insync.ticker.Ticker attribute), 63
aggGroup (ib_insync.objects.DepthMktDataDescription auctionStrategy (ib_insync.order.Order attribute), 35
125
ib_insync, Release 0.9.70
126 Index
ib_insync, Release 0.9.70
Index 127
ib_insync, Release 0.9.70
128 Index
ib_insync, Release 0.9.70
Index 129
ib_insync, Release 0.9.70
130 Index
ib_insync, Release 0.9.70
G ib_insync.util
gamma (ib_insync.objects.OptionComputation property), module, 81
78 IBC (class in ib_insync.ibcontroller), 85
gateway (ib_insync.ibcontroller.IBC attribute), 86 IBC_INI (ib_insync.ibcontroller.IBController attribute),
getAccounts() (ib_insync.client.Client method), 29 87
getReqId() (ib_insync.client.Client method), 29 IBC_PATH (ib_insync.ibcontroller.IBController at-
globalErrorEvent (in module ib_insync.util), 81 tribute), 87
goodAfterTime (ib_insync.order.Order attribute), 34 ibcIni (ib_insync.ibcontroller.IBC attribute), 86
goodTillDate (ib_insync.order.Order attribute), 34 IbcLogLevel (ib_insync.ibcontroller.IBC attribute), 86
IBController (class in ib_insync.ibcontroller), 87
H ibcPath (ib_insync.ibcontroller.IBC attribute), 86
imbalanceOnly (ib_insync.order.Order attribute), 37
halted (ib_insync.ticker.Ticker attribute), 62
impliedVol (ib_insync.objects.OptionComputation
hasBidAsk() (ib_insync.ticker.Ticker method), 63
property), 78
headline (ib_insync.objects.HistoricalNews property),
impliedVolatility (ib_insync.ticker.Ticker attribute),
79
63
headline (ib_insync.objects.NewsTick property), 79
Inactive (ib_insync.order.OrderStatus attribute), 40
hedgeParam (ib_insync.order.Order attribute), 36
includeExpired (ib_insync.contract.Contract at-
hedgeType (ib_insync.order.Order attribute), 36
tribute), 49
hidden (ib_insync.order.Order attribute), 34
increment (ib_insync.objects.PriceIncrement property),
high (ib_insync.objects.BarData attribute), 69
78
high (ib_insync.objects.RealTimeBar attribute), 70
Index (class in ib_insync.contract), 52
high (ib_insync.ticker.Bar attribute), 65
indexFuturePremium (ib_insync.ticker.Ticker at-
high (ib_insync.ticker.Ticker attribute), 62
tribute), 63
high13week (ib_insync.ticker.Ticker attribute), 62
industry (ib_insync.contract.ContractDetails attribute),
high26week (ib_insync.ticker.Ticker attribute), 62
58
high52week (ib_insync.ticker.Ticker attribute), 62
initMarginAfter (ib_insync.order.OrderState at-
HistogramData (class in ib_insync.objects), 72
tribute), 41
HistoricalNews (class in ib_insync.objects), 79
initMarginBefore (ib_insync.order.OrderState at-
HistoricalSchedule (class in ib_insync.objects), 75
tribute), 41
HistoricalSession (class in ib_insync.objects), 75
initMarginChange (ib_insync.order.OrderState at-
HistoricalTick (class in ib_insync.objects), 76
tribute), 41
HistoricalTickBidAsk (class in ib_insync.objects), 76
instrument (ib_insync.objects.ScannerSubscription at-
HistoricalTickLast (class in ib_insync.objects), 76
tribute), 66
histVolatility (ib_insync.ticker.Ticker attribute), 63
isActive() (ib_insync.order.Trade method), 42
host (ib_insync.ibcontroller.Watchdog attribute), 89
isConnected() (ib_insync.client.Client method), 29
isConnected() (ib_insync.ib.IB method), 9
I isDone() (ib_insync.order.Trade method), 42
IB (class in ib_insync.ib), 7 isHashable() (ib_insync.contract.Contract method), 49
ib (ib_insync.ibcontroller.Watchdog attribute), 89 isMore (ib_insync.order.MarginCondition attribute), 45
ib_insync.client isMore (ib_insync.order.PercentChangeCondition
module, 27 attribute), 46
ib_insync.contract isMore (ib_insync.order.PriceCondition attribute), 44
module, 47 isMore (ib_insync.order.TimeCondition attribute), 44
ib_insync.flexreport isMore (ib_insync.order.VolumeCondition attribute), 46
module, 84 isnamedtupleinstance() (in module ib_insync.util),
ib_insync.ib 82
module, 7 isNan() (in module ib_insync.util), 82
ib_insync.objects isOmsContainer (ib_insync.order.Order attribute), 37
module, 66 isPeggedChangeAmountDecrease
ib_insync.order (ib_insync.order.Order attribute), 36
module, 32 isReady() (ib_insync.client.Client method), 29
ib_insync.ticker issueDate (ib_insync.contract.ContractDetails at-
module, 61 tribute), 59
Index 131
ib_insync, Release 0.9.70
J M
JAVA_PATH (ib_insync.ibcontroller.IBController at- maintMarginAfter (ib_insync.order.OrderState at-
tribute), 87 tribute), 41
javaPath (ib_insync.ibcontroller.IBC attribute), 86 maintMarginBefore (ib_insync.order.OrderState
attribute), 41
K maintMarginChange (ib_insync.order.OrderState
keepUpToDate (ib_insync.objects.BarDataList at- attribute), 41
tribute), 80 managedAccounts() (ib_insync.ib.IB method), 11
MarginCondition (class in ib_insync.order), 45
L marketCapAbove (ib_insync.objects.ScannerSubscription
last (ib_insync.ticker.Ticker attribute), 62 attribute), 66
lastFillPrice (ib_insync.order.OrderStatus attribute), marketCapBelow (ib_insync.objects.ScannerSubscription
40 attribute), 66
lastGreeks (ib_insync.ticker.Ticker attribute), 63 marketDataType (ib_insync.ticker.Ticker attribute), 62
lastLiquidity (ib_insync.objects.Execution attribute), marketMaker (ib_insync.objects.DOMLevel property),
68 77
lastSize (ib_insync.ticker.Ticker attribute), 62 marketMaker (ib_insync.objects.MktDepthData prop-
lastTradeDateOrContractMonth erty), 77
(ib_insync.contract.Contract attribute), 48 marketName (ib_insync.contract.ContractDetails at-
lastTradeTime (ib_insync.contract.ContractDetails at- tribute), 58
tribute), 59 MarketOrder (class in ib_insync.order), 38
lastYield (ib_insync.ticker.Ticker attribute), 62 marketPrice (ib_insync.objects.PortfolioItem property),
legsStr (ib_insync.contract.ScanData attribute), 60 78
LimitOrder (class in ib_insync.order), 38 marketPrice() (ib_insync.ticker.Ticker method), 64
liquidation (ib_insync.objects.Execution attribute), 68 marketRuleIds (ib_insync.contract.ContractDetails at-
liquidHours (ib_insync.contract.ContractDetails tribute), 59
attribute), 58 marketValue (ib_insync.objects.PortfolioItem property),
listingExch (ib_insync.objects.DepthMktDataDescription 78
attribute), 73 markPrice (ib_insync.ticker.Ticker attribute), 62
lmtPrice (ib_insync.order.Order attribute), 34 maturity (ib_insync.contract.ContractDetails attribute),
lmtPriceOffset (ib_insync.order.Order attribute), 36 59
load() (ib_insync.flexreport.FlexReport method), 84 maturityDateAbove (ib_insync.objects.ScannerSubscription
localSymbol (ib_insync.contract.Contract attribute), 49 attribute), 66
locationCode (ib_insync.objects.ScannerSubscription maturityDateBelow (ib_insync.objects.ScannerSubscription
attribute), 66 attribute), 66
log (ib_insync.order.Trade attribute), 42 MaxClientVersion (ib_insync.client.Client attribute),
LOG_PATH (ib_insync.ibcontroller.IBController at- 28
tribute), 87 maxCommission (ib_insync.order.OrderState attribute),
logToConsole() (in module ib_insync.util), 82 41
logToFile() (in module ib_insync.util), 82 MaxRequests (ib_insync.client.Client attribute), 28
longName (ib_insync.contract.ContractDetails attribute), MaxSyncedSubAccounts (ib_insync.ib.IB attribute), 8, 9
58 mdSizeMultiplier (ib_insync.contract.ContractDetails
loopUntil() (ib_insync.ib.IB method), 11 attribute), 59
low (ib_insync.objects.BarData attribute), 69 message (ib_insync.objects.NewsBulletin property), 79
low (ib_insync.objects.RealTimeBar attribute), 70 message (ib_insync.objects.TradeLogEntry attribute), 74
low (ib_insync.ticker.Bar attribute), 65 midPoint (ib_insync.objects.TickByTickMidPoint prop-
low (ib_insync.ticker.Ticker attribute), 62 erty), 77
low13week (ib_insync.ticker.Ticker attribute), 62 midpoint() (ib_insync.ticker.Ticker method), 63
low26week (ib_insync.ticker.Ticker attribute), 62 Midpoints (class in ib_insync.ticker), 65
low52week (ib_insync.ticker.Ticker attribute), 62 midpoints() (ib_insync.ticker.TickerUpdateEvent
lowEdge (ib_insync.objects.PriceIncrement property), 78 method), 64
mifid2DecisionAlgo (ib_insync.order.Order at-
tribute), 37
132 Index
ib_insync, Release 0.9.70
Index 133
ib_insync, Release 0.9.70
134 Index
ib_insync, Release 0.9.70
Index 135
ib_insync, Release 0.9.70
136 Index
ib_insync, Release 0.9.70
Index 137
ib_insync, Release 0.9.70
138 Index
ib_insync, Release 0.9.70
Index 139
ib_insync, Release 0.9.70
140 Index
ib_insync, Release 0.9.70
Index 141
ib_insync, Release 0.9.70
142 Index
ib_insync, Release 0.9.70
Y
yield_ (ib_insync.objects.CommissionReport attribute),
68
yieldRedemptionDate
(ib_insync.objects.CommissionReport at-
tribute), 68
Index 143