0% found this document useful (0 votes)
14 views147 pages

Ib Insync Readthedocs Io en Latest

The document is the release notes for ib_insync version 0.9.70, authored by Ewald de Wit on February 11, 2022. It includes sections on installation, examples, API documentation, code recipes, and a changelog. The document serves as a comprehensive guide for users to understand and utilize the features of the ib_insync library.

Uploaded by

Konny Her
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views147 pages

Ib Insync Readthedocs Io en Latest

The document is the release notes for ib_insync version 0.9.70, authored by Ewald de Wit on February 11, 2022. It includes sections on installation, examples, API documentation, code recipes, and a changelog. The document serves as a comprehensive guide for users to understand and utilize the features of the ib_insync library.

Uploaded by

Konny Her
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 147

ib_insync

Release 0.9.70

Ewald de Wit

Feb 11, 2022


CONTENTS

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

Python Module Index 123

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

pip install ib_insync

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

This is a complete script to download historical data:


from ib_insync import *
# util.startLoop() # uncomment this line when in a notebook

ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)

(continues on next page)

3
ib_insync, Release 0.9.70

(continued from previous page)


contract = Forex('EURUSD')
bars = ib.reqHistoricalData(
contract, endDateTime='', durationStr='30 D',
barSizeSetting='1 hour', whatToShow='MIDPOINT', useRTH=True)

# convert to pandas dataframe:


df = util.df(bars)
print(df)

Output:

date open high low close volume \


0 2019-11-19 23:15:00 1.107875 1.108050 1.107725 1.107825 -1
1 2019-11-20 00:00:00 1.107825 1.107925 1.107675 1.107825 -1
2 2019-11-20 01:00:00 1.107825 1.107975 1.107675 1.107875 -1
3 2019-11-20 02:00:00 1.107875 1.107975 1.107025 1.107225 -1
4 2019-11-20 03:00:00 1.107225 1.107725 1.107025 1.107525 -1
.. ... ... ... ... ... ...
705 2020-01-02 14:00:00 1.119325 1.119675 1.119075 1.119225 -1

1.3 Documentation

The complete API documentation.


Changelog.

1.4 Discussion

The insync user group is the place to discuss IB-insync and anything related to it.

1.5 Consultancy & Development

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

The software is provided on the conditions of the simplified BSD license.


This project is not affiliated with Interactive Brokers Group, Inc.’s.
Good luck and enjoy,
author Ewald de Wit <[email protected]>

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

High-level interface to Interactive Brokers.


class ib_insync.ib.IB
Provides both a blocking and an asynchronous interface to the IB API, using asyncio networking and event loop.
The IB class offers direct access to the current state, such as orders, executions, positions, tickers etc. This state
is automatically kept in sync with the TWS/IBG application.
This class has most request methods of EClient, with the same names and parameters (except for the reqId
parameter which is not needed anymore). Request methods that return a result come in two versions:
• Blocking: Will block until complete and return the result. The current state will be kept updated while the
request is ongoing;
• Asynchronous: All methods that have the “Async” postfix. Implemented as coroutines or methods that
return a Future and intended for advanced users.
The One Rule:
While some of the request methods are blocking from the perspective of the user, the framework will still keep
spinning in the background and handle all messages received from TWS/IBG. It is important to not block the
framework from doing its work. If, for example, the user code spends much time in a calculation, or uses
time.sleep() with a long delay, the framework will stop spinning, messages accumulate and things may go awry.
The one rule when working with the IB class is therefore that
user code may not block for too long.
To be clear, the IB request methods are okay to use and do not count towards the user operation time, no matter
how long the request takes to finish.
So what is “too long”? That depends on the situation. If, for example, the timestamp of tick data is to remain
accurate within a millisecond, then the user code must not spend longer than a millisecond. If, on the other
extreme, there is very little incoming data and there is no desire for accurate timestamps, then the user code can
block for hours.
If a user operation takes a long time then it can be farmed out to a different process. Alternatively the operation
can be made such that it periodically calls IB.sleep(0); This will let the framework handle any pending work and
return when finished. The operation should be aware that the current state may have been updated during the
sleep(0) call.

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.

8 Chapter 2. API docs


ib_insync, Release 0.9.70

• pnlEvent (entry: PnL): A profit- and loss entry is updated.


• pnlSingleEvent (entry: PnLSingle): A profit- and loss entry for a single position is updated.
• tickNewsEvent (news: NewsTick): Emit a new news headline.
• newsBulletinEvent (bulletin: NewsBulletin): Emit a new news bulletin.
• scannerDataEvent (data: ScanDataList): Emit data from a scanner subscription.
• errorEvent (reqId: int, errorCode: int, errorString: str, contract: Contract): Emits the re-
qId/orderId and TWS error code and string (see https://interactivebrokers.github.io/tws-api/message_
codes.html) together with the contract the error applies to (or None if no contract applies).
• timeoutEvent (idlePeriod: float): Is emitted if no data is received for longer than the timeout period
specified with setTimeout(). The value emitted is the period in seconds since the last update.
Note that it is not advisable to place new requests inside an event handler as it may lead to too much
recursion.

events = ('connectedEvent', 'disconnectedEvent', 'updateEvent',


'pendingTickersEvent', 'barUpdateEvent', 'newOrderEvent', 'orderModifyEvent',
'cancelOrderEvent', 'openOrderEvent', 'orderStatusEvent', 'execDetailsEvent',
'commissionReportEvent', 'updatePortfolioEvent', 'positionEvent',
'accountValueEvent', 'accountSummaryEvent', 'pnlEvent', 'pnlSingleEvent',
'scannerDataEvent', 'tickNewsEvent', 'newsBulletinEvent', 'errorEvent',
'timeoutEvent')
RequestTimeout: float = 0
RaiseRequestErrors: bool = False
MaxSyncedSubAccounts: int = 50
TimezoneTWS = None
connect(host='127.0.0.1', port=7497, clientId=1, timeout=4, readonly=False, account='')
Connect to a running TWS or IB gateway application. After the connection is made the client is fully
synchronized and ready to serve requests.
This method is blocking.
Parameters
• host (str) – Host name or IP address.
• port (int) – Port number.
• clientId (int) – ID number to use for this client; must be unique per connection. Setting
clientId=0 will automatically merge manual TWS trading with this client.
• timeout (float) – If establishing the connection takes longer than timeout seconds then
the asyncio.TimeoutError exception is raised. Set to 0 to disable timeout.
• readonly (bool) – Set to True when API is in read-only mode.
• account (str) – Main account to receive updates for.
disconnect()
Disconnect from a TWS or IB gateway application. This will clear all session state.
isConnected()
Is there an API connection to TWS or IB gateway?
Return type bool

2.1. IB 9
ib_insync, Release 0.9.70

static run(*, timeout=None)


By default run the event loop forever.
When awaitables (like Tasks, Futures or coroutines) are given then run the event loop until each has com-
pleted and return their results.
An optional timeout (in seconds) can be given that will raise asyncio.TimeoutError if the awaitables are
not ready within the timeout period.
static schedule(callback, *args)
Schedule the callback to be run at the given time with the given arguments. This will return the Event
Handle.
Parameters
• time (Union[time, datetime]) – Time to run callback. If given as datetime.time then
use today as date.
• callback (Callable) – Callable scheduled to run.
• args – Arguments for to call callback with.
static sleep()
Wait for the given amount of seconds while everything still keeps processing in the background. Never use
time.sleep().
Parameters secs (float) – Time in seconds to wait.
Return type bool
static timeRange(end, step)
Iterator that waits periodically until certain time points are reached while yielding those time points.
Parameters
• start (Union[time, datetime]) – Start time, can be specified as datetime.datetime, or
as datetime.time in which case today is used as the date
• end (Union[time, datetime]) – End time, can be specified as datetime.datetime, or as
datetime.time in which case today is used as the date
• step (float) – The number of seconds of each period
Return type Iterator[datetime]
static timeRangeAsync(end, step)
Async version of timeRange().
Return type AsyncIterator[datetime]
static waitUntil()
Wait until the given time t is reached.
Parameters t (Union[time, datetime]) – The time t can be specified as datetime.datetime, or
as datetime.time in which case today is used as the date.
Return type bool
waitOnUpdate(timeout=0)
Wait on any new update to arrive from the network.
Parameters timeout (float) – Maximum time in seconds to wait. If 0 then no timeout is used.

10 Chapter 2. API docs


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.

Return type bool


Returns True if not timed-out, False otherwise.

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.

12 Chapter 2. API docs


ib_insync, Release 0.9.70

Return type List[Ticker]


pendingTickers()
Get a list of all tickers that have pending ticks or domTicks.
Return type List[Ticker]
realtimeBars()
Get a list of all live updated bars. These can be 5 second realtime bars or live updated historical bars.
Return type List[Union[BarDataList, RealTimeBarList]]
newsTicks()
List of ticks with headline news. The article itself can be retrieved with reqNewsArticle().
Return type List[NewsTick]
newsBulletins()
List of IB news bulletins.
Return type List[NewsBulletin]
reqTickers(*contracts, regulatorySnapshot=False)
Request and return a list of snapshot tickers. The list is returned when all tickers are ready.
This method is blocking.
Parameters
• contracts (Contract) – Contracts to get tickers for.
• regulatorySnapshot (bool) – Request NBBO snapshots (may incur a fee).
Return type List[Ticker]
qualifyContracts(*contracts)
Fully qualify the given contracts in-place. This will fill in the missing fields in the contract, especially the
conId.
Returns a list of contracts that have been successfully qualified.
This method is blocking.
Parameters contracts (Contract) – Contracts to qualify.
Return type List[Contract]
bracketOrder(action, quantity, limitPrice, takeProfitPrice, stopLossPrice, **kwargs)
Create a limit order that is bracketed by a take-profit order and a stop-loss order. Submit the bracket like:

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

https://interactivebrokers.github.io/tws-api/bracket_order.html
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

static oneCancelsAll(orders, ocaGroup, ocaType)


Place the trades in the same One Cancels All (OCA) group.
https://interactivebrokers.github.io/tws-api/oca.html
Parameters orders (List[Order]) – The orders that are to be placed together.
Return type List[Order]
whatIfOrder(contract, order)
Retrieve commission and margin impact without actually placing the order. The given order will not be
modified in any way.
This method is blocking.
Parameters
• contract (Contract) – Contract to test.
• order (Order) – Order to test.
Return type OrderState
placeOrder(contract, order)
Place a new order or modify an existing order. Returns a Trade that is kept live updated with status changes,
fills, etc.
Parameters
• contract (Contract) – Contract to use for order.
• order (Order) – The order to be placed.
Return type Trade
cancelOrder(order)
Cancel the order and return the Trade it belongs to.
Parameters order (Order) – The order to be canceled.
Return type Trade
reqGlobalCancel()
Cancel all active trades including those placed by other clients or TWS/IB gateway.
reqCurrentTime()
Request TWS current time.
This method is blocking.
Return type datetime
reqAccountUpdates(account='')
This is called at startup - no need to call again.
Request account and portfolio values of the account and keep updated. Returns when both account values
and portfolio are filled.
This method is blocking.
Parameters account (str) – If specified, filter for this account name.
reqAccountUpdatesMulti(account='', modelCode='')
It is recommended to use accountValues() instead.
Request account values of multiple accounts and keep updated.
This method is blocking.

14 Chapter 2. API docs


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

Return type List[Position]


reqPnL(account, modelCode='')
Start a subscription for profit and loss events.
Returns a PnL object that is kept live updated. The result can also be queried from pnl().
https://interactivebrokers.github.io/tws-api/pnl.html
Parameters
• account (str) – Subscribe to this account.
• modelCode (str) – If specified, filter for this account model.
Return type PnL
cancelPnL(account, modelCode='')
Cancel PnL subscription.
Parameters
• account – Cancel for this account.
• modelCode (str) – If specified, cancel for this account model.
reqPnLSingle(account, modelCode, conId)
Start a subscription for profit and loss events for single positions.
Returns a PnLSingle object that is kept live updated. The result can also be queried from pnlSingle().
https://interactivebrokers.github.io/tws-api/pnl.html
Parameters
• account (str) – Subscribe to this account.
• modelCode (str) – Filter for this account model.
• conId (int) – Filter for this contract ID.
Return type PnLSingle
cancelPnLSingle(account, modelCode, conId)
Cancel PnLSingle subscription for the given account, modelCode and conId.
Parameters
• account (str) – Cancel for this account name.
• modelCode (str) – Cancel for this account model.
• conId (int) – Cancel for this contract ID.
reqContractDetails(contract)
Get a list of contract details that match the given contract. If the returned list is empty then the contract is
not known; If the list has multiple values then the contract is ambiguous.
The fully qualified contract is available in the the ContractDetails.contract attribute.
This method is blocking.
https://interactivebrokers.github.io/tws-api/contract_details.html
Parameters contract (Contract) – The contract to get details for.
Return type List[ContractDetails]

16 Chapter 2. API docs


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.

18 Chapter 2. API docs


ib_insync, Release 0.9.70

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

• snapshot (bool) – If True then request a one-time snapshot, otherwise subscribe to a


stream of realtime tick data.
• regulatorySnapshot (bool) – Request NBBO snapshot (may incur a fee).
• mktDataOptions (Optional[List[TagValue]]) – Unknown
Return type Ticker
cancelMktData(contract)
Unsubscribe from realtime streaming tick data.
Parameters contract (Contract) – The exact contract object that was used to subscribe with.
reqTickByTickData(contract, tickType, numberOfTicks=0, ignoreSize=False)
Subscribe to tick-by-tick data and return the Ticker that holds the ticks in ticker.tickByTicks.
https://interactivebrokers.github.io/tws-api/tick_data.html
Parameters
• contract (Contract) – Contract of interest.
• tickType (str) – One of ‘Last’, ‘AllLast’, ‘BidAsk’ or ‘MidPoint’.
• numberOfTicks (int) – Number of ticks or 0 for unlimited.
• ignoreSize (bool) – Ignore bid/ask ticks that only update the size.
Return type Ticker
cancelTickByTickData(contract, tickType)
Unsubscribe from tick-by-tick data
Parameters contract (Contract) – The exact contract object that was used to subscribe with.

20 Chapter 2. API docs


ib_insync, Release 0.9.70

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

– ’RESC’: Analyst Estimates


– ’CalendarReport’: Company’s calendar
• fundamentalDataOptions (List[TagValue]) – Unknown
Return type str
reqScannerData(subscription, scannerSubscriptionOptions=[], scannerSubscriptionFilterOptions=[])
Do a blocking market scan by starting a subscription and canceling it after the initial list of results are in.
This method is blocking.
https://interactivebrokers.github.io/tws-api/market_scanners.html
Parameters
• subscription (ScannerSubscription) – Basic filters.
• scannerSubscriptionOptions (List[TagValue]) – Unknown.
• scannerSubscriptionFilterOptions (List[TagValue]) – Advanced generic filters.
Return type ScanDataList
reqScannerSubscription(subscription, scannerSubscriptionOptions=[],
scannerSubscriptionFilterOptions=[])
Subscribe to market scan data.
https://interactivebrokers.github.io/tws-api/market_scanners.html
Parameters
• subscription (ScannerSubscription) – What to scan for.
• scannerSubscriptionOptions (List[TagValue]) – Unknown.
• scannerSubscriptionFilterOptions (List[TagValue]) – Unknown.
Return type ScanDataList
cancelScannerSubscription(dataList)
Cancel market data subscription.
https://interactivebrokers.github.io/tws-api/market_scanners.html
Parameters dataList (ScanDataList) – The scan data list that was obtained from
reqScannerSubscription().
reqScannerParameters()
Requests an XML list of scanner parameters.
This method is blocking.
Return type str
calculateImpliedVolatility(contract, optionPrice, underPrice, implVolOptions=[])
Calculate the volatility given the option price.
This method is blocking.
https://interactivebrokers.github.io/tws-api/option_computations.html
Parameters
• contract (Contract) – Option contract.
• optionPrice (float) – Option price to use in calculation.

22 Chapter 2. API docs


ib_insync, Release 0.9.70

• underPrice (float) – Price of the underlier to use in calculation


• implVolOptions (List[TagValue]) – Unknown
Return type OptionComputation
calculateOptionPrice(contract, volatility, underPrice, optPrcOptions=[])
Calculate the option price given the volatility.
This method is blocking.
https://interactivebrokers.github.io/tws-api/option_computations.html
Parameters
• contract (Contract) – Option contract.
• volatility (float) – Option volatility to use in calculation.
• underPrice (float) – Price of the underlier to use in calculation
• implVolOptions – Unknown
Return type OptionComputation
reqSecDefOptParams(underlyingSymbol, futFopExchange, underlyingSecType, underlyingConId)
Get the option chain.
This method is blocking.
https://interactivebrokers.github.io/tws-api/options.html
Parameters
• underlyingSymbol (str) – Symbol of underlier contract.
• futFopExchange (str) – Exchange (only for FuturesOption, otherwise leave blank).
• underlyingSecType (str) – The type of the underlying security, like ‘STK’ or ‘FUT’.
• underlyingConId (int) – conId of the underlying contract.
Return type List[OptionChain]
exerciseOptions(contract, exerciseAction, exerciseQuantity, account, override)
Exercise an options contract.
https://interactivebrokers.github.io/tws-api/options.html
Parameters
• contract (Contract) – The option contract to be exercised.
• exerciseAction (int) –
– 1 = exercise the option
– 2 = let the option lapse
• exerciseQuantity (int) – Number of contracts to be exercised.
• account (str) – Destination account.
• override (int) –
– 0 = no override
– 1 = override the system’s natural action

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) –

24 Chapter 2. API docs


ib_insync, Release 0.9.70

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

Return type List[Contract]

async reqTickersAsync(*contracts, regulatorySnapshot=False)

Return type List[Ticker]

whatIfOrderAsync(contract, order)

Return type Awaitable[OrderState]

reqCurrentTimeAsync()

Return type Awaitable[datetime]

reqAccountUpdatesAsync(account)

Return type Awaitable[None]

reqAccountUpdatesMultiAsync(account, modelCode='')

Return type Awaitable[None]

async accountSummaryAsync(account='')

Return type List[AccountValue]

reqAccountSummaryAsync()

Return type Awaitable[None]

reqOpenOrdersAsync()

Return type Awaitable[List[Order]]

reqAllOpenOrdersAsync()

2.1. IB 25
ib_insync, Release 0.9.70

Return type Awaitable[List[Order]]

reqCompletedOrdersAsync(apiOnly)

Return type Awaitable[List[Trade]]

reqExecutionsAsync(execFilter=None)

Return type Awaitable[List[Fill]]

reqPositionsAsync()

Return type Awaitable[List[Position]]

reqContractDetailsAsync(contract)

Return type Awaitable[List[ContractDetails]]

async reqMatchingSymbolsAsync(pattern)

Return type Optional[List[ContractDescription]]

async reqMarketRuleAsync(marketRuleId)

Return type Optional[List[PriceIncrement]]

async reqHistoricalDataAsync(contract, endDateTime, durationStr, barSizeSetting, whatToShow,


useRTH, formatDate=1, keepUpToDate=False, chartOptions=[],
timeout=60)

Return type BarDataList

reqHistoricalScheduleAsync(contract, numDays, endDateTime='', useRTH=True)

Return type Awaitable[HistoricalSchedule]

reqHistoricalTicksAsync(contract, startDateTime, endDateTime, numberOfTicks, whatToShow, useRth,


ignoreSize=False, miscOptions=[])

Return type Awaitable[List]

reqHeadTimeStampAsync(contract, whatToShow, useRTH, formatDate)

Return type Awaitable[datetime]

reqMktDepthExchangesAsync()

Return type Awaitable[List[DepthMktDataDescription]]

reqHistogramDataAsync(contract, useRTH, period)

Return type Awaitable[List[HistogramData]]

reqFundamentalDataAsync(contract, reportType, fundamentalDataOptions=[])

26 Chapter 2. API docs


ib_insync, Release 0.9.70

Return type Awaitable[str]

async reqScannerDataAsync(subscription, scannerSubscriptionOptions=[],


scannerSubscriptionFilterOptions=[])

Return type ScanDataList

reqScannerParametersAsync()

Return type Awaitable[str]

async calculateImpliedVolatilityAsync(contract, optionPrice, underPrice, implVolOptions=[])

Return type Optional[OptionComputation]

async calculateOptionPriceAsync(contract, volatility, underPrice, optPrcOptions=[])

Return type Optional[OptionComputation]

reqSecDefOptParamsAsync(underlyingSymbol, futFopExchange, underlyingSecType, underlyingConId)

Return type Awaitable[List[OptionChain]]

reqNewsProvidersAsync()

Return type Awaitable[List[NewsProvider]]

reqNewsArticleAsync(providerCode, articleId, newsArticleOptions)

Return type Awaitable[NewsArticle]

async reqHistoricalNewsAsync(conId, providerCodes, startDateTime, endDateTime, totalResults,


historicalNewsOptions=None)

Return type Optional[HistoricalNews]

async requestFAAsync(faDataType)

2.2 Client

Socket client for communicating with Interactive Brokers.


class ib_insync.client.Client(wrapper)
Replacement for ibapi.client.EClient that uses asyncio.
The client is fully asynchronous and has its own event-driven networking code that replaces the networking code
of the standard EClient. It also replaces the infinite loop of EClient.run() with the asyncio event loop. It can
be used as a drop-in replacement for the standard EClient as provided by IBAPI.
Compared to the standard EClient this client has the following additional features:
• client.connect() will block until the client is ready to serve requests; It is not necessary to wait for
nextValidId to start requests as the client has already done that. The reqId is directly available with
getReqId().

2.2. Client 27
ib_insync, Release 0.9.70

• client.connectAsync() is a coroutine for connecting asynchronously.


• When blocking, client.connect() can be made to time out with the timeout parameter (default 2 sec-
onds).
• Optional wrapper.priceSizeTick(reqId, tickType, price, size) that combines price and size
instead of the two wrapper methods priceTick and sizeTick.
• Automatic request throttling.
• Optional wrapper.tcpDataArrived() method; If the wrapper has this method it is invoked directly after
a network packet has arrived. A possible use is to timestamp all data in the packet with the exact same time.
• Optional wrapper.tcpDataProcessed() method; If the wrapper has this method it is invoked after the
network packet’s data has been handled. A possible use is to write or evaluate the newly arrived data in one
batch instead of item by item.
MaxRequests
Throttle the number of requests to MaxRequests per RequestsInterval seconds. Set to 0 to disable
throttling.
Type int
RequestsInterval
Time interval (in seconds) for request throttling.
Type float
MinClientVersion
Client protocol version.
Type int
MaxClientVersion
Client protocol version.
Type int

Events:
• apiStart ()
• apiEnd ()
• apiError (errorMsg: str)
• throttleStart ()
• throttleEnd ()

events = ('apiStart', 'apiEnd', 'apiError', 'throttleStart', 'throttleEnd')


MaxRequests = 45
RequestsInterval = 1
MinClientVersion = 157
MaxClientVersion = 167
DISCONNECTED = 0
CONNECTING = 1
CONNECTED = 2
reset()

28 Chapter 2. API docs


ib_insync, Release 0.9.70

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()

30 Chapter 2. API docs


ib_insync, Release 0.9.70

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

Order types used by Interactive Brokers.

32 Chapter 2. API docs


ib_insync, Release 0.9.70

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 = ''

34 Chapter 2. API docs


ib_insync, Release 0.9.70

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

2.3. Order 35
ib_insync, Release 0.9.70

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: List[ib_insync.contract.TagValue]
smartComboRoutingParams: List[ib_insync.contract.TagValue]
algoId: str = ''
whatIf: bool = False
notHeld: bool = False
solicited: bool = False
modelCode: str = ''
orderComboLegs: List[ib_insync.order.OrderComboLeg]
orderMiscOptions: List[ib_insync.contract.TagValue]
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

36 Chapter 2. API docs


ib_insync, Release 0.9.70

lmtPriceOffset: float = 1.7976931348623157e+308


conditions: List[ib_insync.order.OrderCondition]
conditionsCancelOrder: bool = False
conditionsIgnoreRth: bool = False
extOperator: str = ''
softDollarTier: ib_insync.objects.SoftDollarTier
cashQty: float = 1.7976931348623157e+308
mifid2DecisionMaker: str = ''
mifid2DecisionAlgo: str = ''
mifid2ExecutionTrader: str = ''
mifid2ExecutionAlgo: str = ''
dontUseAutoPriceForHedge: bool = False
isOmsContainer: bool = False
discretionaryUpToLimitPrice: bool = False
autoCancelDate: str = ''
filledQuantity: float = 1.7976931348623157e+308
refFuturesConId: int = 0
autoCancelParent: bool = False
shareholder: str = ''
imbalanceOnly: bool = False
routeMarketableToBbo: bool = False
parentPermId: int = 0
usePriceMgmtAlgo: bool = False
duration: int = 2147483647
postToAts: int = 2147483647
advancedErrorOverride: 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 37
ib_insync, Release 0.9.70

Return type object


class ib_insync.order.LimitOrder(action, totalQuantity, lmtPrice, **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.MarketOrder(action, totalQuantity, **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]

38 Chapter 2. API docs


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

40 Chapter 2. API docs


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

Return type object


class ib_insync.order.OrderComboLeg(price: float = 1.7976931348623157e+308)
price: float = 1.7976931348623157e+308
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.Trade(contract: ib_insync.contract.Contract = <factory>, order:
ib_insync.order.Order = <factory>, orderStatus: ib_insync.order.OrderStatus =
<factory>, fills: typing.List[ib_insync.objects.Fill] = <factory>, log:
typing.List[ib_insync.objects.TradeLogEntry] = <factory>, advancedError: str
= '')
Trade keeps track of an order, its status and all its fills.
Events:
• statusEvent (trade: Trade)
• modifyEvent (trade: Trade)
• fillEvent (trade: Trade, fill: Fill)
• commissionReportEvent (trade: Trade, fill: Fill, commissionReport: CommissionReport)
• filledEvent (trade: Trade)
• cancelEvent (trade: Trade)
• cancelledEvent (trade: Trade)
events: ClassVar = ('statusEvent', 'modifyEvent', 'fillEvent',
'commissionReportEvent', 'filledEvent', 'cancelEvent', 'cancelledEvent')
contract: ib_insync.contract.Contract
order: ib_insync.order.Order
orderStatus: ib_insync.order.OrderStatus
fills: List[ib_insync.objects.Fill]
log: List[ib_insync.objects.TradeLogEntry]
advancedError: str = ''
isActive()
True if eligible for execution, false otherwise.

42 Chapter 2. API docs


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

class ib_insync.order.PriceCondition(condType: int = 1, conjunction: str = 'a', isMore: bool = True,


price: float = 0.0, conId: int = 0, exch: str = '', triggerMethod: int =
0)
condType: int = 1
conjunction: str = 'a'
isMore: bool = True
price: float = 0.0
conId: int = 0
exch: str = ''
triggerMethod: 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.order.TimeCondition(condType: int = 3, conjunction: str = 'a', isMore: bool = True, time:
str = '')
condType: int = 3
conjunction: str = 'a'
isMore: bool = True
time: 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.

44 Chapter 2. API docs


ib_insync, Release 0.9.70

Return type object


class ib_insync.order.MarginCondition(condType: int = 4, conjunction: str = 'a', isMore: bool = True,
percent: int = 0)
condType: int = 4
conjunction: str = 'a'
isMore: bool = True
percent: 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.order.ExecutionCondition(condType: int = 5, conjunction: str = 'a', secType: str = '',
exch: str = '', symbol: str = '')
condType: int = 5
conjunction: str = 'a'
secType: str = ''
exch: str = ''
symbol: str = ''
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type 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 45
ib_insync, Release 0.9.70

class ib_insync.order.VolumeCondition(condType: int = 6, conjunction: str = 'a', isMore: bool = True,


volume: int = 0, conId: int = 0, exch: str = '')
condType: int = 6
conjunction: str = 'a'
isMore: bool = True
volume: int = 0
conId: int = 0
exch: 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.order.PercentChangeCondition(condType: int = 7, conjunction: str = 'a', isMore: bool =
True, changePercent: float = 0.0, conId: int = 0, exch: str
= '')
condType: int = 7
conjunction: str = 'a'
isMore: bool = True
changePercent: float = 0.0
conId: int = 0
exch: 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

46 Chapter 2. API docs


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

Financial instrument types used by Interactive Brokers.


class ib_insync.contract.Contract(secType: str = '', conId: int = 0, symbol: str = '',
lastTradeDateOrContractMonth: str = '', strike: float = 0.0, right: str =
'', multiplier: str = '', exchange: str = '', primaryExchange: str = '',
currency: str = '', localSymbol: str = '', tradingClass: str = '',
includeExpired: bool = False, secIdType: str = '', secId: str = '',
comboLegsDescrip: str = '', comboLegs:
typing.List[ib_insync.contract.ComboLeg] = <factory>,
deltaNeutralContract:
typing.Optional[ib_insync.contract.DeltaNeutralContract] = None)
Contract(**kwargs) can create any contract using keyword arguments. To simplify working with contracts,
there are also more specialized contracts that take optional positional arguments. Some examples:

Contract(conId=270639)
Stock('AMD', 'SMART', 'USD')
Stock('INTC', 'SMART', 'USD', primaryExchange='NASDAQ')
Forex('EURUSD')
CFD('IBUS30')
Future('ES', '20180921', 'GLOBEX')
Option('SPY', '20170721', 240, 'C', 'SMART')
Bond(secIdType='ISIN', secId='US03076KAA60')
Crypto('BTC', 'PAXOS', 'USD')

Parameters
• conId (int) – The unique IB contract identifier.
• symbol (str) – The contract (or its underlying) symbol.
• secType (str) – 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.

secType: str = ''


conId: int = 0
symbol: str = ''
lastTradeDateOrContractMonth: str = ''
strike: float = 0.0
right: str = ''
multiplier: str = ''
exchange: str = ''

48 Chapter 2. API docs


ib_insync, Release 0.9.70

primaryExchange: str = ''


currency: str = ''
localSymbol: str = ''
tradingClass: str = ''
includeExpired: bool = False
secIdType: str = ''
secId: str = ''
comboLegsDescrip: str = ''
comboLegs: List[ib_insync.contract.ComboLeg]
deltaNeutralContract: Optional[ib_insync.contract.DeltaNeutralContract] = None
static create(**kwargs)
Create and a return a specialized contract based on the given secType, or a general Contract if secType is
not given.
Return type Contract
isHashable()
See if this contract can be hashed by conId.
Note: Bag contracts always get conId=28812380, so they’re not hashable.
Return type bool
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.Stock(symbol='', exchange='', currency='', **kwargs)
Stock contract.
Parameters
• symbol (str) – Symbol name.
• exchange (str) – Destination exchange.
• currency (str) – Underlying currency.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.

2.4. Contract 49
ib_insync, Release 0.9.70

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.Option(symbol='', lastTradeDateOrContractMonth='', strike=0.0, right='',
exchange='', multiplier='', currency='', **kwargs)
Option 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’.
• exchange (str) – Destination exchange.
• multiplier (str) – The contract multiplier.
• currency (str) – Underlying currency.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type 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]

50 Chapter 2. API docs


ib_insync, Release 0.9.70

class ib_insync.contract.Future(symbol='', lastTradeDateOrContractMonth='', exchange='',


localSymbol='', multiplier='', currency='', **kwargs)
Future 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
• exchange (str) – Destination exchange.
• localSymbol (str) – The contract’s symbol within its primary exchange.
• multiplier (str) – The contract multiplier.
• currency (str) – Underlying currency.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type 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.ContFuture(symbol='', exchange='', localSymbol='', multiplier='', currency='',
**kwargs)
Continuous future contract.
Parameters
• symbol (str) – Symbol name.
• exchange (str) – Destination exchange.
• localSymbol (str) – The contract’s symbol within its primary exchange.
• multiplier (str) – The contract multiplier.
• currency (str) – Underlying currency.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict
nonDefaults()
For a dataclass instance get the fields that are different from the default values and return as dict.

2.4. Contract 51
ib_insync, Release 0.9.70

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.Forex(pair='', exchange='IDEALPRO', symbol='', currency='', **kwargs)
Foreign exchange currency pair.
Parameters
• pair (str) – Shortcut for specifying symbol and currency, like ‘EURUSD’.
• exchange (str) – Destination exchange.
• symbol (str) – Base currency.
• currency (str) – Quote currency.
pair()
Short name of pair.
Return type 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
comboLegs: List[ib_insync.contract.ComboLeg]
class ib_insync.contract.Index(symbol='', exchange='', currency='', **kwargs)
Index.
Parameters
• symbol (str) – Symbol name.
• exchange (str) – Destination exchange.
• currency (str) – Underlying currency.

52 Chapter 2. API docs


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

54 Chapter 2. API docs


ib_insync, Release 0.9.70

• exchange (str) – Destination exchange.


• multiplier (str) – The contract multiplier.
• currency (str) – Underlying currency.
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type 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.MutualFund(**kwargs)
Mutual fund.
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.Warrant(**kwargs)
Warrant option.
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

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

56 Chapter 2. API docs


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
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 = ''

58 Chapter 2. API docs


ib_insync, Release 0.9.70

evRule: str = ''


evMultiplier: int = 0
mdSizeMultiplier: int = 1
aggGroup: int = 0
underSymbol: str = ''
underSecType: str = ''
marketRuleIds: str = ''
secIdList: List[ib_insync.contract.TagValue]
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 = ''
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.

2.4. Contract 59
ib_insync, Release 0.9.70

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.ContractDescription(contract: Union[ib_insync.contract.Contract, NoneType]
= None, derivativeSecTypes: List[str] = <factory>)
contract: Optional[ib_insync.contract.Contract] = None
derivativeSecTypes: List[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.contract.ScanData(rank: int, contractDetails: ib_insync.contract.ContractDetails, distance:
str, benchmark: str, projection: str, legsStr: str)
rank: int
contractDetails: ib_insync.contract.ContractDetails
distance: str
benchmark: str
projection: str
legsStr: 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

60 Chapter 2. API docs


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

Access to realtime market information.


class ib_insync.ticker.Ticker(contract: typing.Optional[ib_insync.contract.Contract] = None, time:
typing.Optional[datetime.datetime] = None, marketDataType: int = 1, bid:
float = nan, bidSize: float = nan, ask: float = nan, askSize: float = nan, last:
float = nan, lastSize: float = nan, prevBid: float = nan, prevBidSize: float =
nan, prevAsk: float = nan, prevAskSize: float = nan, prevLast: float = nan,
prevLastSize: float = nan, volume: float = nan, open: float = nan, high: float
= nan, low: float = nan, close: float = nan, vwap: float = nan, low13week:
float = nan, high13week: float = nan, low26week: float = nan, high26week:
float = nan, low52week: float = nan, high52week: float = nan, bidYield: float
= nan, askYield: float = nan, lastYield: float = nan, markPrice: float = nan,
halted: float = nan, rtHistVolatility: float = nan, rtVolume: float = nan,
rtTradeVolume: float = nan, rtTime: typing.Optional[datetime.datetime] =
None, avVolume: float = nan, tradeCount: float = nan, tradeRate: float =
nan, volumeRate: float = nan, shortableShares: float = nan,
indexFuturePremium: float = nan, futuresOpenInterest: float = nan,
putOpenInterest: float = nan, callOpenInterest: float = nan, putVolume: float
= nan, callVolume: float = nan, avOptionVolume: float = nan, histVolatility:
float = nan, impliedVolatility: float = nan, dividends:
typing.Optional[ib_insync.objects.Dividends] = None, fundamentalRatios:
typing.Optional[ib_insync.objects.FundamentalRatios] = None, ticks:
typing.List[ib_insync.objects.TickData] = <factory>, tickByTicks:
typing.List[typing.Union[ib_insync.objects.TickByTickAllLast,
ib_insync.objects.TickByTickBidAsk, ib_insync.objects.TickByTickMidPoint]]
= <factory>, domBids: typing.List[ib_insync.objects.DOMLevel] =
<factory>, domAsks: typing.List[ib_insync.objects.DOMLevel] = <factory>,
domTicks: typing.List[ib_insync.objects.MktDepthData] = <factory>,
bidGreeks: typing.Optional[ib_insync.objects.OptionComputation] = None,
askGreeks: typing.Optional[ib_insync.objects.OptionComputation] = None,
lastGreeks: typing.Optional[ib_insync.objects.OptionComputation] = None,
modelGreeks: typing.Optional[ib_insync.objects.OptionComputation] =
None, auctionVolume: float = nan, auctionPrice: float = nan,
auctionImbalance: float = nan, regulatoryImbalance: float = nan)
Current market data such as bid, ask, last price, etc. for a contract.
Streaming level-1 ticks of type TickData are stored in the ticks list.
Streaming level-2 ticks of type MktDepthData are stored in the domTicks list. The order book (DOM) is
available as lists of DOMLevel in domBids and domAsks.
Streaming tick-by-tick ticks are stored in tickByTicks.
For options the OptionComputation values for the bid, ask, resp. last price are stored in the bidGreeks,
askGreeks resp. lastGreeks attributes. There is also modelGreeks that conveys the greeks as calculated by
Interactive Brokers’ option model.
Events:

2.5. Ticker 61
ib_insync, Release 0.9.70

• updateEvent (ticker: Ticker)


events: ClassVar = ('updateEvent',)
contract: Optional[ib_insync.contract.Contract] = None
time: Optional[datetime.datetime] = None
marketDataType: int = 1
bid: float = nan
bidSize: float = nan
ask: float = nan
askSize: float = nan
last: float = nan
lastSize: float = nan
prevBid: float = nan
prevBidSize: float = nan
prevAsk: float = nan
prevAskSize: float = nan
prevLast: float = nan
prevLastSize: float = nan
volume: float = nan
open: float = nan
high: float = nan
low: float = nan
close: float = nan
vwap: float = nan
low13week: float = nan
high13week: float = nan
low26week: float = nan
high26week: float = nan
low52week: float = nan
high52week: float = nan
bidYield: float = nan
askYield: float = nan
lastYield: float = nan
markPrice: float = nan
halted: float = nan
rtHistVolatility: float = nan
rtVolume: float = nan

62 Chapter 2. API docs


ib_insync, Release 0.9.70

rtTradeVolume: float = nan


rtTime: Optional[datetime.datetime] = None
avVolume: float = nan
tradeCount: float = nan
tradeRate: float = nan
volumeRate: float = nan
shortableShares: float = nan
indexFuturePremium: float = nan
futuresOpenInterest: float = nan
putOpenInterest: float = nan
callOpenInterest: float = nan
putVolume: float = nan
callVolume: float = nan
avOptionVolume: float = nan
histVolatility: float = nan
impliedVolatility: float = nan
dividends: Optional[ib_insync.objects.Dividends] = None
fundamentalRatios: Optional[ib_insync.objects.FundamentalRatios] = None
ticks: List[ib_insync.objects.TickData]
tickByTicks: List[Union[ib_insync.objects.TickByTickAllLast,
ib_insync.objects.TickByTickBidAsk , ib_insync.objects.TickByTickMidPoint]]
domBids: List[ib_insync.objects.DOMLevel]
domAsks: List[ib_insync.objects.DOMLevel]
domTicks: List[ib_insync.objects.MktDepthData]
bidGreeks: Optional[ib_insync.objects.OptionComputation] = None
askGreeks: Optional[ib_insync.objects.OptionComputation] = None
lastGreeks: Optional[ib_insync.objects.OptionComputation] = None
modelGreeks: Optional[ib_insync.objects.OptionComputation] = None
auctionVolume: float = nan
auctionPrice: float = nan
auctionImbalance: float = nan
regulatoryImbalance: float = nan
hasBidAsk()
See if this ticker has a valid bid and ask.
Return type bool
midpoint()
Return average of bid and ask, or NaN if no valid bid and ask are available.

2.5. Ticker 63
ib_insync, Release 0.9.70

Return type float


marketPrice()
Return the first available one of
• last price if within current bid/ask;
• average of bid and ask (midpoint);
• close price.

Return type float

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.

64 Chapter 2. API docs


ib_insync, Release 0.9.70

Parameters args – Argument values to emit to listeners.


timebars(timer)
Aggregate ticks into time bars, where the timing of new bars is derived from a timer event. Emits a com-
pleted Bar.
This event stores a BarList of all created bars in the bars property.
Parameters timer (Event) – Event for timing when a new bar starts.
Return type TimeBars
tickbars(count)
Aggregate ticks into bars that have the same number of ticks. Emits a completed Bar.
This event stores a BarList of all created bars in the bars property.
Parameters count (int) – Number of ticks to use to form one bar.
Return type TickBars
class ib_insync.ticker.Midpoints(tickTypes, source=None)
on_source(ticker)
Emit a new value to all connected listeners.
Parameters args – Argument values to emit to listeners.
class ib_insync.ticker.Bar(time: Union[datetime.datetime, NoneType], open: float = nan, high: float = nan,
low: float = nan, close: float = nan, volume: int = 0, count: int = 0)
time: Optional[datetime.datetime]
open: float = nan
high: float = nan
low: float = nan
close: float = nan
volume: int = 0
count: int = 0
class ib_insync.ticker.BarList(*args)
class ib_insync.ticker.TimeBars(timer, source=None)
Aggregate ticks into time bars, where the timing of new bars is derived from a timer event. Emits a completed
Bar.
This event stores a BarList of all created bars in the bars property.
Parameters timer – Event for timing when a new bar starts.
bars: ib_insync.ticker.BarList
on_source(time, price, size)
Emit a new value to all connected listeners.
Parameters args – Argument values to emit to listeners.
class ib_insync.ticker.TickBars(count, source=None)
Aggregate ticks into bars that have the same number of ticks. Emits a completed Bar.
This event stores a BarList of all created bars in the bars property.
Parameters count – Number of ticks to use to form one bar.
bars: ib_insync.ticker.BarList

2.5. Ticker 65
ib_insync, Release 0.9.70

on_source(time, price, size)


Emit a new value to all connected listeners.
Parameters args – Argument values to emit to listeners.

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 = ''

66 Chapter 2. API docs


ib_insync, Release 0.9.70

stockTypeFilter: 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.SoftDollarTier(name: str = '', val: str = '', displayName: str = '')
name: str = ''
val: str = ''
displayName: 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.Execution(execId: str = '', time: datetime.datetime = datetime.datetime(1970, 1, 1,
0, 0, tzinfo=datetime.timezone.utc), acctNumber: str = '', exchange: str
= '', side: str = '', shares: float = 0.0, price: float = 0.0, permId: int = 0,
clientId: int = 0, orderId: int = 0, liquidation: int = 0, cumQty: float =
0.0, avgPrice: float = 0.0, orderRef: str = '', evRule: str = '',
evMultiplier: float = 0.0, modelCode: str = '', lastLiquidity: int = 0)
execId: str = ''
time: datetime.datetime = datetime.datetime(1970, 1, 1, 0, 0,
tzinfo=datetime.timezone.utc)
acctNumber: str = ''
exchange: str = ''

2.6. Objects 67
ib_insync, Release 0.9.70

side: str = ''


shares: float = 0.0
price: float = 0.0
permId: int = 0
clientId: int = 0
orderId: int = 0
liquidation: int = 0
cumQty: float = 0.0
avgPrice: float = 0.0
orderRef: str = ''
evRule: str = ''
evMultiplier: float = 0.0
modelCode: str = ''
lastLiquidity: 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.CommissionReport(execId: str = '', commission: float = 0.0, currency: str = '',
realizedPNL: float = 0.0, yield_: float = 0.0,
yieldRedemptionDate: int = 0)
execId: str = ''
commission: float = 0.0
currency: str = ''
realizedPNL: float = 0.0
yield_: float = 0.0
yieldRedemptionDate: int = 0
dict()
Return dataclass values as dict. This is a non-recursive variant of dataclasses.asdict.
Return type dict

68 Chapter 2. API docs


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

close: float = 0.0


volume: float = 0
average: float = 0.0
barCount: 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.RealTimeBar(time: datetime.datetime = datetime.datetime(1970, 1, 1, 0, 0,
tzinfo=datetime.timezone.utc), endTime: int = - 1, open_: float = 0.0,
high: float = 0.0, low: float = 0.0, close: float = 0.0, volume: float =
0.0, wap: float = 0.0, count: int = 0)
time: datetime.datetime = datetime.datetime(1970, 1, 1, 0, 0,
tzinfo=datetime.timezone.utc)
endTime: int = -1
open_: float = 0.0
high: float = 0.0
low: float = 0.0
close: float = 0.0
volume: float = 0.0
wap: 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

70 Chapter 2. API docs


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

72 Chapter 2. API docs


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

74 Chapter 2. API docs


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

76 Chapter 2. API docs


ib_insync, Release 0.9.70

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

class ib_insync.objects.PriceIncrement(lowEdge, increment)


Create new instance of PriceIncrement(lowEdge, increment)
property lowEdge
property increment
class ib_insync.objects.PortfolioItem(contract, position, marketPrice, marketValue, averageCost,
unrealizedPNL, realizedPNL, account)
Create new instance of PortfolioItem(contract, position, marketPrice, marketValue, averageCost, unrealizedPNL,
realizedPNL, account)
property contract
property position
property marketPrice
property marketValue
property averageCost
property unrealizedPNL
property realizedPNL
property account
class ib_insync.objects.Position(account, contract, position, avgCost)
Create new instance of Position(account, contract, position, avgCost)
property account
property contract
property position
property avgCost
class ib_insync.objects.Fill(contract, execution, commissionReport, time)
Create new instance of Fill(contract, execution, commissionReport, time)
property contract
property execution
property commissionReport
property time
class ib_insync.objects.OptionComputation(tickAttrib, impliedVol, delta, optPrice, pvDividend, gamma,
vega, theta, undPrice)
Create new instance of OptionComputation(tickAttrib, impliedVol, delta, optPrice, pvDividend, gamma, vega,
theta, undPrice)
property tickAttrib
property impliedVol
property delta
property optPrice
property pvDividend
property gamma
property vega

78 Chapter 2. API docs


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:

80 Chapter 2. API docs


ib_insync, Release 0.9.70

• updateEvent (bars: RealTimeBarList, hasNewBar: bool)


reqId: int
contract: ib_insync.contract.Contract
barSize: int
whatToShow: str
useRTH: bool
realTimeBarsOptions: List[ib_insync.contract.TagValue]
class ib_insync.objects.ScanDataList(*args)
List of ScanData that also stores all request parameters.
Events:
• updateEvent (ScanDataList)
reqId: int
subscription: ib_insync.objects.ScannerSubscription
scannerSubscriptionOptions: List[ib_insync.contract.TagValue]
scannerSubscriptionFilterOptions: List[ib_insync.contract.TagValue]
class ib_insync.objects.DynamicObject(**kwargs)
class ib_insync.objects.FundamentalRatios(**kwargs)
See: https://interactivebrokers.github.io/tws-api/fundamental_ratios_tags.html
class ib_insync.wrapper.RequestError(reqId, code, message)
Exception to raise when the API reports an error that can be tied to a single request.
Parameters
• reqId (int) – Original request ID.
• code (int) – Original error code.
• message (str) – Original error message.

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

Return type tuple


ib_insync.util.dataclassNonDefaults(obj)
For a dataclass instance get the fields that are different from the default values and return as dict.
Return type dict
ib_insync.util.dataclassUpdate(obj, *srcObjs, **kwargs)
Update fields of the given dataclass object from zero or more dataclass source objects and/or from keyword
arguments.
Return type object
ib_insync.util.dataclassRepr(obj)
Provide a culled representation of the given dataclass instance, showing only the fields with a non-default
value.
Return type str
ib_insync.util.isnamedtupleinstance(x)
From https://stackoverflow.com/a/2166841/6067848
ib_insync.util.tree(obj)
Convert object to a tree of lists, dicts and simple values. The result can be serialized to JSON.
ib_insync.util.barplot(bars, title='', upColor='blue', downColor='red')
Create candlestick plot for the given bars. The bars can be given as a DataFrame or as a list of bar objects.
ib_insync.util.allowCtrlC()
Allow Control-C to end program.
ib_insync.util.logToFile(path, level=20)
Create a log handler that logs to the given file.
ib_insync.util.logToConsole(level=20)
Create a log handler that logs to the console.
ib_insync.util.isNan(x)
Not a number test.
Return type bool
ib_insync.util.formatSI(n)
Format the integer or float n to 3 significant digits + SI prefix.
Return type str
class ib_insync.util.timeit(title='Run')
Context manager for timing.
ib_insync.util.run(*awaitables, timeout=None)
By default run the event loop forever.
When awaitables (like Tasks, Futures or coroutines) are given then run the event loop until each has completed
and return their results.
An optional timeout (in seconds) can be given that will raise asyncio.TimeoutError if the awaitables are not ready
within the timeout period.
ib_insync.util.schedule(time, callback, *args)
Schedule the callback to be run at the given time with the given arguments. This will return the Event Handle.
Parameters

82 Chapter 2. API docs


ib_insync, Release 0.9.70

• time (Union[time, datetime]) – Time to run callback. If given as datetime.time then


use today as date.
• callback (Callable) – Callable scheduled to run.
• args – Arguments for to call callback with.
ib_insync.util.sleep(secs=0.02)
Wait for the given amount of seconds while everything still keeps processing in the background. Never use
time.sleep().
Parameters secs (float) – Time in seconds to wait.
Return type bool
ib_insync.util.timeRange(start, end, step)
Iterator that waits periodically until certain time points are reached while yielding those time points.
Parameters
• start (Union[time, datetime]) – Start time, can be specified as datetime.datetime, or as
datetime.time in which case today is used as the date
• end (Union[time, datetime]) – End time, can be specified as datetime.datetime, or as
datetime.time in which case today is used as the date
• step (float) – The number of seconds of each period
Return type Iterator[datetime]
ib_insync.util.waitUntil(t)
Wait until the given time t is reached.
Parameters t (Union[time, datetime]) – The time t can be specified as datetime.datetime, or as
datetime.time in which case today is used as the date.
Return type bool
async ib_insync.util.timeRangeAsync(start, end, step)
Async version of timeRange().
Return type AsyncIterator[datetime]
async ib_insync.util.waitUntilAsync(t)
Async version of waitUntil().
Return type bool
ib_insync.util.patchAsyncio()
Patch asyncio to allow nested event loops.
ib_insync.util.startLoop()
Use nested asyncio event loop for Jupyter notebooks.
ib_insync.util.useQt(qtLib='PyQt5', period=0.01)
Run combined Qt5/asyncio event loop.
Parameters
• qtLib (str) – Name of Qt library to use:
– PyQt5
– PyQt6
– PySide2

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

Access to account statement webservice.


exception ib_insync.flexreport.FlexError
class ib_insync.flexreport.FlexReport(token=None, queryId=None, path=None)
Download and parse IB account statements via the Flex Web Service. https://www.interactivebrokers.com/en/
software/am/am/reports/flex_web_service_version_3.htm
Make sure to use a XML query (not CSV). A large query can take a few minutes. In the weekends the query
servers can be down.
Download a report by giving a valid token and queryId, or load from file by giving a valid path.
topics()
Get the set of topics that can be extracted from this report.
extract(topic, parseNumbers=True)
Extract items of given topic and return as list of objects.
The topic is a string like TradeConfirm, ChangeInDividendAccrual, Order, etc.
Return type list
df(topic, parseNumbers=True)
Same as extract but return the result as a pandas DataFrame.
download(token, queryId)
Download report for the given token and queryId.
load(path)
Load report from XML file.
save(path)
Save report to XML file.

84 Chapter 2. API docs


ib_insync, Release 0.9.70

2.9 IBC

class ib_insync.ibcontroller.IBC(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 = '')
Programmatic control over starting and stopping TWS/Gateway using IBC (https://github.com/IbcAlpha/IBC).
Parameters
• twsVersion (int) – (required) The major version number for TWS or gateway.
• gateway (bool) –
– True = gateway
– False = TWS
• tradingMode (str) – ‘live’ or ‘paper’.
• userid (str) – IB account username. It is recommended to set the real username/password
in a secured IBC config file.
• password (str) – IB account password.
• twsPath (str) – Path to the TWS installation folder. Defaults:
– Linux: ~/Jts
– OS X: ~/Applications
– Windows: C:\Jts
• twsSettingsPath (str) – Path to the TWS settings folder. Defaults:
– Linux: ~/Jts
– OS X: ~/Jts
– Windows: Not available
• ibcPath (str) – Path to the IBC installation folder. Defaults:
– Linux: /opt/ibc
– OS X: /opt/ibc
– Windows: C:\IBC
• ibcIni (str) – Path to the IBC configuration file. Defaults:
– Linux: ~/ibc/config.ini
– OS X: ~/ibc/config.ini
– Windows: %%HOMEPATH%%\DocumentsIBC\config.ini
• javaPath (str) – Path to Java executable. Default is to use the Java VM included with
TWS/gateway.
• fixuserid (str) – FIX account user id (gateway only).
• fixpassword (str) – FIX account password (gateway only).
This is not intended to be run in a notebook.
To use IBC on Windows, the proactor (or quamash) event loop must have been set:

2.9. IBC 85
ib_insync, Release 0.9.70

import asyncio
asyncio.set_event_loop(asyncio.ProactorEventLoop())

Example usage:

ibc = IBC(976, gateway=True, tradingMode='live',


userid='edemo', password='demouser')
ibc.start()
IB.run()

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.

86 Chapter 2. API docs


ib_insync, Release 0.9.70

Return type object

2.10 IBController

class ib_insync.ibcontroller.IBController(APP: str = 'TWS', TWS_MAJOR_VRSN: str = '969',


TRADING_MODE: str = 'live', IBC_INI: str =
'~/IBController/IBController.ini', IBC_PATH: str =
'~/IBController', TWS_PATH: str = '~/Jts', LOG_PATH: str =
'~/IBController/Logs', TWSUSERID: str = '',
TWSPASSWORD: str = '', JAVA_PATH: str = '',
TWS_CONFIG_PATH: str = '')
For new installations it is recommended to use IBC instead.
Programmatic control over starting and stopping TWS/Gateway using IBController (https://github.com/
ib-controller/ib-controller).
On Windows the the proactor (or quamash) event loop must have been set:

import asyncio
asyncio.set_event_loop(asyncio.ProactorEventLoop())

This is not intended to be run in a notebook.


APP: str = 'TWS'
TWS_MAJOR_VRSN: str = '969'
TRADING_MODE: str = 'live'
IBC_INI: str = '~/IBController/IBController.ini'
IBC_PATH: str = '~/IBController'
TWS_PATH: str = '~/Jts'
LOG_PATH: str = '~/IBController/Logs'
TWSUSERID: str = ''
TWSPASSWORD: str = ''
JAVA_PATH: str = ''
TWS_CONFIG_PATH: str = ''
start()
Launch TWS/IBG.
stop()
Cleanly shutdown TWS/IBG.
terminate()
Terminate TWS/IBG.
async startAsync()
async stopAsync()
async terminateAsync()
async monitorAsync()

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

class ib_insync.ibcontroller.Watchdog(controller: Union[ib_insync.ibcontroller.IBC,


ib_insync.ibcontroller.IBController], ib: ib_insync.ib.IB, host: str
= '127.0.0.1', port: int = 7497, clientId: int = 1, connectTimeout:
float = 2, appStartupTime: float = 30, appTimeout: float = 20,
retryDelay: float = 2, readonly: bool = False, account: str = '',
probeContract: ib_insync.contract.Contract = Forex('EURUSD',
exchange='IDEALPRO'), probeTimeout: float = 4)
Start, connect and watch over the TWS or gateway app and try to keep it up and running. It is intended to be
used in an event-driven application that properly initializes itself upon (re-)connect.
It is not intended to be used in a notebook or in imperative-style code. Do not expect Watchdog to magically
shield you from reality. Do not use Watchdog unless you understand what it does and doesn’t do.
Parameters
• controller (Union[IBC, IBController]) – (required) IBC or IBController instance.
• ib (IB) – (required) IB instance to be used. Do no connect this instance as Watchdog takes
care of that.
• host (str) – Used for connecting IB instance.
• port (int) – Used for connecting IB instance.
• clientId (int) – Used for connecting IB instance.
• connectTimeout (float) – Used for connecting IB instance.
• readonly (bool) – Used for connecting IB instance.
• appStartupTime (float) – Time (in seconds) that the app is given to start up. Make sure
that it is given ample time.
• appTimeout (float) – Timeout (in seconds) for network traffic idle time.
• retryDelay (float) – Time (in seconds) to restart app after a previous failure.
• probeContract (Contract) – Contract to use for historical data probe requests (default is
EURUSD).

88 Chapter 2. API docs


ib_insync, Release 0.9.70

• probeTimeout (float); Timeout (in seconds) –


The idea is to wait until there is no traffic coming from the app for a certain amount of time (the appTimeout
parameter). This triggers a historical request to be placed just to see if the app is still alive and well. If yes, then
continue, if no then restart the whole app and reconnect. Restarting will also occur directly on errors 1100 and
100.
Example usage:

def onConnected():
print(ib.accountValues())

ibc = IBC(974, gateway=True, tradingMode='paper')


ib = IB()
ib.connectedEvent += onConnected
watchdog = Watchdog(ibc, ib, port=4002)
watchdog.start()
ib.run()

Events:
• startingEvent (watchdog: Watchdog)
• startedEvent (watchdog: Watchdog)
• stoppingEvent (watchdog: Watchdog)
• stoppedEvent (watchdog: Watchdog)
• softTimeoutEvent (watchdog: Watchdog)
• hardTimeoutEvent (watchdog: Watchdog)

events = ['startingEvent', 'startedEvent', 'stoppingEvent', 'stoppedEvent',


'softTimeoutEvent', 'hardTimeoutEvent']
controller: Union[ib_insync.ibcontroller.IBC, ib_insync.ibcontroller.IBController]
ib: ib_insync.ib.IB
host: str = '127.0.0.1'
port: int = 7497
clientId: int = 1
connectTimeout: float = 2
appStartupTime: float = 30
appTimeout: float = 20
retryDelay: float = 2
readonly: bool = False
account: str = ''
probeContract: ib_insync.contract.Contract = Forex('EURUSD', exchange='IDEALPRO')
probeTimeout: float = 4
start()
stop()

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

90 Chapter 2. API docs


CHAPTER

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

Collection of useful patterns, snippets and recipes.


When using the recipes in a notebook, don’t forget to use util.startLoop().

4.1 Fetching consecutive historical data

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)

contract = Stock('TSLA', 'SMART', 'USD')

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)

# save to CSV file


allBars = [b for bars in reversed(barsList) for b in bars]
df = util.df(allBars)
df.to_csv(contract.symbol + '.csv', index=False)

93
ib_insync, Release 0.9.70

4.2 Scanner data (blocking)

allParams = ib.reqScannerParameters())
print(allParams)

sub = ScannerSubscription(
instrument='FUT.US',
locationCode='FUT.GLOBEX',
scanCode='TOP_PERC_GAIN')
scanData = ib.reqScannerData(sub)
print(scanData)

4.3 Scanner data (streaming)

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)

4.4 Option calculations

option = Option('EOE', '20171215', 490, 'P', 'FTA', multiplier=100)

calc = ib.calculateImpliedVolatility(
option, optionPrice=6.1, underPrice=525))
print(calc)

calc = ib.calculateOptionPrice(
option, volatility=0.14, underPrice=525))
print(calc)

94 Chapter 4. Code recipes


ib_insync, Release 0.9.70

4.5 Order book

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])

4.6 Minimum price increments

usdjpy = Forex('USDJPY')
cd = ib.reqContractDetails(usdjpy)[0]
print(cd.marketRuleIds)

rules = [
ib.reqMarketRule(ruleId)
for ruleId in cd.marketRuleIds.split(',')]
print(rules)

4.7 News articles

newsProviders = ib.reqNewsProviders()
print(newsProviders)
codes = '+'.join(np.code for np in newsProviders)

amd = Stock('AMD', 'SMART', 'USD')


ib.qualifyContracts(amd)
headlines = ib.reqHistoricalNews(amd.conId, codes, '', '', 10)
latest = headlines[0]
print(latest)
article = ib.reqNewsArticle(latest.providerCode, latest.articleId)
print(article)

4.8 News bulletins

ib.reqNewsBulletins(True)
ib.sleep(5)
print(ib.newsBulletins())

4.5. Order book 95


ib_insync, Release 0.9.70

4.9 Dividends

contract = Stock('INTC', 'SMART', 'USD')


ticker = ib.reqMktData(contract, '456')
ib.sleep(2)
print(ticker.dividends)

Output:

Dividends(past12Months=1.2, next12Months=1.2, nextDate=datetime.date(2019, 2, 6),␣


˓→nextAmount=0.3)

4.10 Fundemental ratios

contract = Stock('IBM', 'SMART', 'USD')


ticker = ib.reqMktData(contract, '258')
ib.sleep(2)
print(ticker.fundamentalRatios)

4.11 Async streaming ticks

import asyncio

import ib_insync as ibi

class App:

async def run(self):


self.ib = ibi.IB()
with await self.ib.connectAsync():
contracts = [
ibi.Stock(symbol, 'SMART', 'USD')
for symbol in ['AAPL', 'TSLA', 'AMD', 'INTC']]
for contract in contracts:
self.ib.reqMktData(contract)

async for tickers in self.ib.pendingTickersEvent:


for ticker in tickers:
print(ticker)

def stop(self):
self.ib.disconnect()

app = App()
try:
asyncio.run(app.run())
(continues on next page)

96 Chapter 4. Code recipes


ib_insync, Release 0.9.70

(continued from previous page)


except (KeyboardInterrupt, SystemExit):
app.stop()

4.12 Integration with PyQt5 or PySide2

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.

4.12. Integration with PyQt5 or PySide2 97


ib_insync, Release 0.9.70

4.13 Integration with Tkinter

To integrate with the Tkinter event loop, take a look at this example app.

98 Chapter 4. Code recipes


CHAPTER

FIVE

SOURCE CODE

99
ib_insync, Release 0.9.70

100 Chapter 5. Source code


CHAPTER

SIX

CHANGELOG

6.1 0.9

6.1.1 Version 0.9.70

• Fixed: issue 413: Set the appropriate events as done on disconnect.


• Exported symbols are now static so that the VSCode/PyLance code analyzer can understand it.

6.1.2 Version 0.9.69

• Fixed: issue 403: Change validity test for whatIfOrder response.

6.1.3 Version 0.9.68

• Fixed: issue 402: Downloading historical ticks for crypto currencies.

6.1.4 Version 0.9.67

• 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

6.1.5 Version 0.9.66

• Fixed: issue 360: Improved disconnect.


• Fixed issue with duplicate orderId.
• Update Order default values to work with the latest beta TWS/gateway.
• pull 348: Added PySide6 support.

6.1.6 Version 0.9.65

• Fixed: issue 337.


• pull 317: Update and order’s totalQuantity, lmtPrice, auxPrice and orderType when the order is modi-
fied externally.
• pull 332: Typo.

6.1.7 Version 0.9.64

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

6.1.8 Version 0.9.63

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

6.1.9 Version 0.9.62

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

102 Chapter 6. Changelog


ib_insync, Release 0.9.70

6.1.10 Version 0.9.61

• Ticker.marketDataType added to indicate the delayed/frozen status of the reqMktData ticks.

6.1.11 Version 0.9.60

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

6.1.12 Version 0.9.59

• PR #205 adds more typing annotations.


• dataclasses are now used for objects (instead of inheriting from a base Object). For Python 3.6.* install it
with pip install dataclasses

6.1.13 Version 0.9.58

• PR #196 treats error 492 as a warning so that scanner results can still be used.

6.1.14 Version 0.9.57

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

6.1. 0.9 103


ib_insync, Release 0.9.70

6.1.15 Version 0.9.56

• Fix bug #178: Order.totalQuantity is now float.

6.1.16 Version 0.9.55

• Sphinx update for documentation.

6.1.17 Version 0.9.54

• ContractDetails.stockType added.
• Fixed Trade.filled() for combo (BAG) contracts.
• Server version check added to make sure TWS/gateway version is at least 972.

6.1.18 Version 0.9.53

• Fix bug #155 (IB.commissionReportEvent not firing).


• Help editors with the code completion for Events.

6.1.19 Version 0.9.52

• Fix Client.exerciseOptions (bug #152).

6.1.20 Version 0.9.51

• Fix ib.placeOrder for older TWS/gateway versions.


• Better handling of unclean disconnects.

6.1.21 Version 0.9.50

• Fix execDetailsEvent regression.


• Added readonly argument to ib.connect method. Set this to True when the API is in read-only mode.

6.1.22 Version 0.9.49

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

104 Chapter 6. Changelog


ib_insync, Release 0.9.70

6.1.23 Version 0.9.48

• Ticker.halted field added.


• Client.reqFundamentalData fixed.

6.1.24 Version 0.9.47

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

6.1.25 Version 0.9.46

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

6.1.26 Version 0.9.45

• Event.merge() added.
• TagValue serialization fixed.

6.1.27 Version 0.9.44

• Event.any() and Event.all() added.


• Ticker fields added: tradeCount, tradeRate, volumeRate, avOptionVolume, markPrice,
histVolatility, impliedVolatility, rtHistVolatility and indexFuturePremium.
• Parse ticker.fundamentalRatios into FundamentalRatios object.
• util.timeRangeAsync() and waitUntilAsync() added.
• ib.pendingTickersEvent now emits a set of Tickers instead of a list.
• Tick handling has been streamlined.
• For harvesting tick data, an imperative code style with a waitOnUpdate loop should not be used anymore!

6.1. 0.9 105


ib_insync, Release 0.9.70

6.1.28 Version 0.9.43

• Fixed issue #132.


• Event.aiter() added, all events can now be used as asynchronous iterators.
• Event.wait() added, all events are now also awaitable.
• Decreased default throttling to 95 requests per 2 sec.

6.1.29 Version 0.9.42

• Ticker.shortableShares added (for use with generic tick 236).


• ib.reqAllOpenOrders() request added.
• tickByTick subscription will update ticker’s bid, ask, last, etc.
• Drop redundant bid/ask ticks from reqMktData.
• Fixed occasional “Group name cannot be null” error message on connect.
• Watchdog code rewritten to not need util.patchAsyncio.
• Watchdog.start() is no longer blocking.

6.1.30 Version 0.9.41

• Fixed bug #117.


• Fixed order modifications with TWS/gateway 974.

6.1.31 Version 0.9.40

• Ticker.fundamentalRatios added (for use with generic tick 258).


• Fixed reqHistoricalTicks with MIDPOINT.

6.1.32 Version 0.9.39

• Handle partially filled dividend data.


• Use secType='WAR' for warrants.

6.1.33 Version 0.9.38

• ibapi v97.4 is now required.


• fixed tickByTick wrappers.

106 Chapter 6. Changelog


ib_insync, Release 0.9.70

6.1.34 Version 0.9.37

• Backward compatibility with older ibapi restored.

6.1.35 Version 0.9.36

• Compatibility with ibapi v974.


• Client.setConnectOptions() added (for PACEAPI).

6.1.36 Version 0.9.35

• Ticker.hasBidAsk() added.
• IB.newsBulletinEvent added.
• Various small fixes.

6.1.37 Version 0.9.34

• Old event system (ib.setCallback) removed.


• Compatibility fix with previous ibapi version.

6.1.38 Version 0.9.33

• Market scanner subscription improved.


• IB.scannerDataEvent now emits the full list of ScanData.
• ScanDataList added.

6.1.39 Version 0.9.32

• Autocompletion with Jedi plugin as used in Spyder and VS Code working again.

6.1.40 Version 0.9.31

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

6.1. 0.9 107


ib_insync, Release 0.9.70

6.1.41 Version 0.9.30

• Watchdog.stop() will not trigger restart now.


• Fixed bug #93.

6.1.42 Version 0.9.29

• util.patchAsyncio() updated for Python 3.7.

6.1.43 Version 0.9.28

• IB.RequestTimeout added.
• util.schedule() accepts tz-aware datetimes now.
• Let client.disconnect() complete when no event loop is running.

6.1.44 Version 0.9.27

• Fixed bug #77.

6.1.45 Version 0.9.26

• PR #74 merged (ib.reqCurrentTime() method added).


• Fixed bug with order error handling.

6.1.46 Version 0.9.25

• Default throttling rate now compatible with reqTickers.


• Fixed issue with ib.waitOnUpdate() in combination. with ib.pendingTickersEvent.
• Added timeout parameter for ib.waitOnUpdate().

6.1.47 Version 0.9.24

• ticker.futuresOpenInterest added.
• execution.time was string, is now parsed to UTC datetime.
• ib.reqMarketRule() request added.

108 Chapter 6. Changelog


ib_insync, Release 0.9.70

6.1.48 Version 0.9.23

• Compatability with Tornado 5 as used in new Jupyter notebook server.

6.1.49 Version 0.9.22

• updated ib.reqNewsArticle and ib.reqHistoricalNews to ibapi v9.73.07.

6.1.50 Version 0.9.21

• updated ib.reqTickByTickData() signature to ibapi v9.73.07 while keeping backward compatibility.

6.1.51 Version 0.9.20

• Fixed watchdog bug.

6.1.52 Version 0.9.19

• Don’t overwrite exchange='SMART' in qualifyContracts.

6.1.53 Version 0.9.18

• Merged PR #65 (Fix misnamed event).

6.1.54 Version 0.9.17

• New IB events disconnectedEvent, newOrderEvent, orderModifyEvent and cancelOrderEvent.


• Watchdog improvements.

6.1.55 Version 0.9.16

• New event system that will supersede IB.setCallback().


• Notebooks updated to use events.
• Watchdog must now be given an IB instance.

6.1.56 Version 0.9.15

• Fixed bug in default order conditions.


• Fixed regression from v0.9.13 in placeOrder.

6.1. 0.9 109


ib_insync, Release 0.9.70

6.1.57 Version 0.9.14

• Fixed orderStatus callback regression.

6.1.58 Version 0.9.13

• Log handling improvements.


• Client with clientId=0 can now manage manual TWS orders.
• Client with master clientId can now monitor manual TWS orders.

6.1.59 Version 0.9.12

• Run IBC and IBController directly instead of via shell.

6.1.60 Version 0.9.11

• Fixed bug when collecting ticks using ib.waitOnUpdate().


• Added ContFuture class (continuous futures).
• Added Ticker.midpoint().

6.1.61 Version 0.9.10

• ib.accountValues() fixed for use with multiple accounts.

6.1.62 Version 0.9.9

• Fixed issue #57

6.1.63 Version 0.9.8

• Fix for ib.reqPnLSingle().

6.1.64 Version 0.9.7

• Profit and Loss (PnL) funcionality added.

110 Chapter 6. Changelog


ib_insync, Release 0.9.70

6.1.65 Version 0.9.6

• IBC added.
• PR #53 (delayed greeks) merged.
• Ticker.futuresOpenInterest field removed.

6.1.66 Version 0.9.5

• Fixed canceling bar and tick subscriptions.

6.1.67 Version 0.9.4

• Fixed issue #49.

6.1.68 Version 0.9.3

• Watchdog class added.


• ib.setTimeout() added.
• Ticker.dividends added for use with genericTickList 456.
• Errors and warnings will now log the contract they apply to.
• IB error() callback signature changed to include contract.
• Fix for issue #44.

6.1.69 Version 0.9.2

• Historical ticks and realtime bars now return time in UTC.

6.1.70 Version 0.9.1

• IBController added.
• openOrder callback added.
• default arguments for ib.connect() and ib.reqMktData().

6.1.71 Version 0.9.0

• minimum API version is v9.73.06.


• tickByTick support.
• automatic request throttling.
• ib.accountValues() now works for multiple accounts.
• AccountValue.modelCode added.
• Ticker.rtVolume added.

6.1. 0.9 111


ib_insync, Release 0.9.70

6.2 0.8

6.2.1 Version 0.8.17

• workaround for IBAPI v9.73.06 for Contract.lastTradeDateOrContractMonth format.

6.2.2 Version 0.8.16

• util.tree() method added.


• error callback signature changed to (reqId, errorCode, errorString).
• accountValue and accountSummary callbacks added.

6.2.3 Version 0.8.15

• util.useQt() fixed for use with Windows.

6.2.4 Version 0.8.14

• Fix for ib.schedule().

6.2.5 Version 0.8.13

• Import order conditions into ib_insync namespace.


• util.useQtAlt() added for using nested event loops on Windows with Qtl
• ib.schedule() added.

6.2.6 Version 0.8.12

• Fixed conditional orders.

6.2.7 Version 0.8.11

• FlexReport added.

6.2.8 Version 0.8.10

• Fixed issue #22.

112 Chapter 6. Changelog


ib_insync, Release 0.9.70

6.2.9 Version 0.8.9

• Ticker.vwap field added (for use with generic tick 233).


• Client with master clientId can now monitor orders and trades of other clients.

6.2.10 Version 0.8.8

• barUpdate event now used also for reqRealTimeBars responses


• reqRealTimeBars will return RealTimeBarList instead of list.
• realtime bars example added to bar data notebook.
• fixed event handling bug in Wrapper.execDetails.

6.2.11 Version 0.8.7

• 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.2.12 Version 0.8.6

• ticker.marketPrice adjusted to ignore price of -1.


• ticker.avVolume handling fixed.

6.2.13 Version 0.8.5

• realtimeBar wrapper fix.


• context manager for IB and IB.connect().

6.2.14 Version 0.8.4

• compatibility with upcoming ibapi changes.


• added error event to IB.
• notebooks updated to use loopUntil.
• small fixes and performance improvements.

6.2. 0.8 113


ib_insync, Release 0.9.70

6.2.15 Version 0.8.3

• new IB.reqHistoricalTicks() API method.


• new IB.loopUntil() method.
• fixed issues #4, #6, #7.

6.2.16 Version 0.8.2

• fixed swapped ticker.putOpenInterest vs ticker.callOpenInterest.

6.2.17 Version 0.8.1

• fixed wrapper.tickSize regression.

6.2.18 Version 0.8.0

• support for realtime bars and keepUpToDate for historical bars


• added option greeks to Ticker.
• new IB.waitUntil() and IB.timeRange() scheduling methods.
• notebooks no longer depend on PyQt5 for live updates.
• notebooks can be run in one go (‘run all’).
• tick handling bypasses ibapi decoder for more efficiency.

6.3 0.7

6.3.1 Version 0.7.3

• IB.whatIfOrder() added.
• Added detection and warning about common setup problems.

6.3.2 Version 0.7.2

• Removed import from ipykernel.

6.3.3 Version 0.7.1

• Removed dependencies for installing via pip.

114 Chapter 6. Changelog


ib_insync, Release 0.9.70

6.3.4 Version 0.7.0

• added lots of request methods.


• order book (DOM) added.
• notebooks updated.

6.4 0.6

6.4.1 Version 0.6.1

• Added UTC timezone to some timestamps.


• Fixed issue #1.

6.4.2 Version 0.6.0

• Initial release.

6.4. 0.6 115


ib_insync, Release 0.9.70

116 Chapter 6. Changelog


CHAPTER

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

118 Chapter 7. Links


CHAPTER

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

pip install ib_insync

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

This is a complete script to download historical data:


from ib_insync import *
# util.startLoop() # uncomment this line when in a notebook

ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)

(continues on next page)

119
ib_insync, Release 0.9.70

(continued from previous page)


contract = Forex('EURUSD')
bars = ib.reqHistoricalData(
contract, endDateTime='', durationStr='30 D',
barSizeSetting='1 hour', whatToShow='MIDPOINT', useRTH=True)

# convert to pandas dataframe:


df = util.df(bars)
print(df)

Output:

date open high low close volume \


0 2019-11-19 23:15:00 1.107875 1.108050 1.107725 1.107825 -1
1 2019-11-20 00:00:00 1.107825 1.107925 1.107675 1.107825 -1
2 2019-11-20 01:00:00 1.107825 1.107975 1.107675 1.107875 -1
3 2019-11-20 02:00:00 1.107875 1.107975 1.107025 1.107225 -1
4 2019-11-20 03:00:00 1.107225 1.107725 1.107025 1.107525 -1
.. ... ... ... ... ... ...
705 2020-01-02 14:00:00 1.119325 1.119675 1.119075 1.119225 -1

8.3 Documentation

The complete API documentation.


Changelog.

8.4 Discussion

The insync user group is the place to discuss IB-insync and anything related to it.

8.5 Consultancy & Development

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!)

120 Chapter 8. Introduction


ib_insync, Release 0.9.70

8.6 Disclaimer

The software is provided on the conditions of the simplified BSD license.


This project is not affiliated with Interactive Brokers Group, Inc.’s.
Good luck and enjoy,
author Ewald de Wit <[email protected]>

8.6. Disclaimer 121


ib_insync, Release 0.9.70

122 Chapter 8. Introduction


PYTHON MODULE INDEX

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

124 Python Module Index


INDEX

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

auctionVolume (ib_insync.ticker.Ticker attribute), 63 bondType (ib_insync.contract.ContractDetails attribute),


autoCancelDate (ib_insync.order.Order attribute), 37 59
autoCancelParent (ib_insync.order.Order attribute), BracketOrder (class in ib_insync.order), 43
37 bracketOrder() (ib_insync.ib.IB method), 13
auxPrice (ib_insync.order.Order attribute), 34
average (ib_insync.objects.BarData attribute), 70 C
averageCost (ib_insync.objects.PortfolioItem property), calculateImpliedVolatility()
78 (ib_insync.client.Client method), 30
averageOptionVolumeAbove calculateImpliedVolatility() (ib_insync.ib.IB
(ib_insync.objects.ScannerSubscription at- method), 22
tribute), 66 calculateImpliedVolatilityAsync()
avgCost (ib_insync.objects.Position property), 78 (ib_insync.ib.IB method), 27
avgFillPrice (ib_insync.order.OrderStatus attribute), calculateOptionPrice() (ib_insync.client.Client
40 method), 30
avgPrice (ib_insync.objects.Execution attribute), 68 calculateOptionPrice() (ib_insync.ib.IB method),
avOptionVolume (ib_insync.ticker.Ticker attribute), 63 23
avVolume (ib_insync.ticker.Ticker attribute), 63 calculateOptionPriceAsync() (ib_insync.ib.IB
method), 27
B callable (ib_insync.contract.ContractDetails attribute),
Bag (class in ib_insync.contract), 56 59
Bar (class in ib_insync.ticker), 65 callOpenInterest (ib_insync.ticker.Ticker attribute),
barCount (ib_insync.objects.BarData attribute), 70 63
BarData (class in ib_insync.objects), 69 callVolume (ib_insync.ticker.Ticker attribute), 63
BarDataList (class in ib_insync.objects), 80 canAutoExecute (ib_insync.objects.TickAttrib at-
BarList (class in ib_insync.ticker), 65 tribute), 71
barplot() (in module ib_insync.util), 82 cancelAccountSummary() (ib_insync.client.Client
bars (ib_insync.ticker.TickBars attribute), 65 method), 30
bars (ib_insync.ticker.TimeBars attribute), 65 cancelAccountUpdatesMulti()
barSize (ib_insync.objects.RealTimeBarList attribute), (ib_insync.client.Client method), 31
81 cancelCalculateImpliedVolatility()
barSizeSetting (ib_insync.objects.BarDataList at- (ib_insync.client.Client method), 30
tribute), 80 cancelCalculateOptionPrice()
basisPoints (ib_insync.order.Order attribute), 35 (ib_insync.client.Client method), 30
basisPointsType (ib_insync.order.Order attribute), 35 cancelFundamentalData() (ib_insync.client.Client
belowPrice (ib_insync.objects.ScannerSubscription at- method), 30
tribute), 66 cancelHeadTimeStamp() (ib_insync.client.Client
benchmark (ib_insync.contract.ScanData attribute), 60 method), 31
bid (ib_insync.ticker.Ticker attribute), 62 cancelHistogramData() (ib_insync.client.Client
bidasks() (ib_insync.ticker.TickerUpdateEvent method), 31
method), 64 cancelHistoricalData() (ib_insync.client.Client
bidGreeks (ib_insync.ticker.Ticker attribute), 63 method), 30
bidPastLow (ib_insync.objects.TickAttribBidAsk at- cancelHistoricalData() (ib_insync.ib.IB method),
tribute), 71 18
bidPrice (ib_insync.objects.TickByTickBidAsk prop- Cancelled (ib_insync.order.OrderStatus attribute), 40
erty), 77 cancelMktData() (ib_insync.client.Client method), 29
bids() (ib_insync.ticker.TickerUpdateEvent method), 64 cancelMktData() (ib_insync.ib.IB method), 20
bidSize (ib_insync.objects.TickByTickBidAsk property), cancelMktDepth() (ib_insync.client.Client method), 30
77 cancelMktDepth() (ib_insync.ib.IB method), 21
bidSize (ib_insync.ticker.Ticker attribute), 62 cancelNewsBulletins() (ib_insync.client.Client
bidYield (ib_insync.ticker.Ticker attribute), 62 method), 30
bitNumber (ib_insync.objects.SmartComponent prop- cancelNewsBulletins() (ib_insync.ib.IB method), 24
erty), 80 cancelOrder() (ib_insync.client.Client method), 29
blockOrder (ib_insync.order.Order attribute), 34 cancelOrder() (ib_insync.ib.IB method), 14
Bond (class in ib_insync.contract), 54 cancelPnL() (ib_insync.client.Client method), 31

126 Index
ib_insync, Release 0.9.70

cancelPnL() (ib_insync.ib.IB method), 16 comboLegs (ib_insync.contract.Forex attribute), 52


cancelPnLSingle() (ib_insync.client.Client method), comboLegs (ib_insync.contract.Future attribute), 51
31 comboLegs (ib_insync.contract.FuturesOption attribute),
cancelPnLSingle() (ib_insync.ib.IB method), 16 55
cancelPositions() (ib_insync.client.Client method), comboLegs (ib_insync.contract.Index attribute), 53
30 comboLegs (ib_insync.contract.MutualFund attribute),
cancelPositionsMulti() (ib_insync.client.Client 55
method), 31 comboLegs (ib_insync.contract.Option attribute), 50
cancelRealTimeBars() (ib_insync.client.Client comboLegs (ib_insync.contract.Stock attribute), 50
method), 30 comboLegs (ib_insync.contract.Warrant attribute), 56
cancelRealTimeBars() (ib_insync.ib.IB method), 17 comboLegsDescrip (ib_insync.contract.Contract
cancelScannerSubscription() attribute), 49
(ib_insync.client.Client method), 30 commission (ib_insync.objects.CommissionReport at-
cancelScannerSubscription() (ib_insync.ib.IB tribute), 68
method), 22 commission (ib_insync.order.OrderState attribute), 41
cancelTickByTickData() (ib_insync.client.Client commissionCurrency (ib_insync.order.OrderState at-
method), 31 tribute), 41
cancelTickByTickData() (ib_insync.ib.IB method), CommissionReport (class in ib_insync.objects), 68
20 commissionReport (ib_insync.objects.Fill property), 78
cancelWshEventData() (ib_insync.client.Client Commodity (class in ib_insync.contract), 53
method), 32 completedStatus (ib_insync.order.OrderState at-
cancelWshMetaData() (ib_insync.client.Client tribute), 41
method), 32 completedTime (ib_insync.order.OrderState attribute),
cashQty (ib_insync.order.Order attribute), 37 41
category (ib_insync.contract.ContractDetails attribute), conditions (ib_insync.order.LimitOrder attribute), 38
58 conditions (ib_insync.order.MarketOrder attribute), 38
CFD (class in ib_insync.contract), 53 conditions (ib_insync.order.Order attribute), 37
changePercent (ib_insync.order.PercentChangeCondition conditions (ib_insync.order.StopLimitOrder attribute),
attribute), 46 39
chartOptions (ib_insync.objects.BarDataList at- conditions (ib_insync.order.StopOrder attribute), 39
tribute), 80 conditionsCancelOrder (ib_insync.order.Order
clearingAccount (ib_insync.order.Order attribute), 36 attribute), 37
clearingIntent (ib_insync.order.Order attribute), 36 conditionsIgnoreRth (ib_insync.order.Order at-
Client (class in ib_insync.client), 27 tribute), 37
clientId (ib_insync.ibcontroller.Watchdog attribute), condType (ib_insync.order.ExecutionCondition at-
89 tribute), 45
clientId (ib_insync.objects.Execution attribute), 68 condType (ib_insync.order.MarginCondition attribute),
clientId (ib_insync.objects.ExecutionFilter attribute), 45
69 condType (ib_insync.order.PercentChangeCondition at-
clientId (ib_insync.order.Order attribute), 34 tribute), 46
clientId (ib_insync.order.OrderStatus attribute), 40 condType (ib_insync.order.PriceCondition attribute), 44
close (ib_insync.objects.BarData attribute), 69 condType (ib_insync.order.TimeCondition attribute), 44
close (ib_insync.objects.RealTimeBar attribute), 70 condType (ib_insync.order.VolumeCondition attribute),
close (ib_insync.ticker.Bar attribute), 65 46
close (ib_insync.ticker.Ticker attribute), 62 conId (ib_insync.contract.ComboLeg attribute), 57
code (ib_insync.objects.NewsProvider attribute), 72 conId (ib_insync.contract.Contract attribute), 48
ComboLeg (class in ib_insync.contract), 57 conId (ib_insync.contract.DeltaNeutralContract at-
comboLegs (ib_insync.contract.Bag attribute), 56 tribute), 57
comboLegs (ib_insync.contract.Bond attribute), 54 conId (ib_insync.objects.PnLSingle attribute), 74
comboLegs (ib_insync.contract.CFD attribute), 53 conId (ib_insync.order.PercentChangeCondition at-
comboLegs (ib_insync.contract.Commodity attribute), 54 tribute), 46
comboLegs (ib_insync.contract.ContFuture attribute), 52 conId (ib_insync.order.PriceCondition attribute), 44
comboLegs (ib_insync.contract.Contract attribute), 49 conId (ib_insync.order.VolumeCondition attribute), 46
comboLegs (ib_insync.contract.Crypto attribute), 57

Index 127
ib_insync, Release 0.9.70

conjunction (ib_insync.order.ExecutionCondition at- couponRateAbove (ib_insync.objects.ScannerSubscription


tribute), 45 attribute), 66
conjunction (ib_insync.order.MarginCondition at- couponRateBelow (ib_insync.objects.ScannerSubscription
tribute), 45 attribute), 66
conjunction (ib_insync.order.PercentChangeCondition couponType (ib_insync.contract.ContractDetails at-
attribute), 46 tribute), 59
conjunction (ib_insync.order.PriceCondition at- create() (ib_insync.contract.Contract static method),
tribute), 44 49
conjunction (ib_insync.order.TimeCondition attribute), createClass() (ib_insync.order.OrderCondition static
44 method), 43
conjunction (ib_insync.order.VolumeCondition at- Crypto (class in ib_insync.contract), 56
tribute), 46 cumQty (ib_insync.objects.Execution attribute), 68
connect() (ib_insync.client.Client method), 29 currency (ib_insync.contract.Contract attribute), 49
connect() (ib_insync.ib.IB method), 9 currency (ib_insync.objects.AccountValue property), 76
connectAsync() (ib_insync.client.Client method), 29 currency (ib_insync.objects.CommissionReport at-
connectAsync() (ib_insync.ib.IB method), 25 tribute), 68
CONNECTED (ib_insync.client.Client attribute), 28 cusip (ib_insync.contract.ContractDetails attribute), 59
CONNECTING (ib_insync.client.Client attribute), 28
ConnectionStats (class in ib_insync.objects), 80 D
connectionStats() (ib_insync.client.Client method), dailyPnL (ib_insync.objects.PnL attribute), 73
29 dailyPnL (ib_insync.objects.PnLSingle attribute), 74
connectTimeout (ib_insync.ibcontroller.Watchdog at- dataclassAsDict() (in module ib_insync.util), 81
tribute), 89 dataclassAsTuple() (in module ib_insync.util), 81
ContFuture (class in ib_insync.contract), 51 dataclassNonDefaults() (in module ib_insync.util),
continuousUpdate (ib_insync.order.Order attribute), 82
35 dataclassRepr() (in module ib_insync.util), 82
Contract (class in ib_insync.contract), 47 dataclassUpdate() (in module ib_insync.util), 82
contract (ib_insync.contract.ContractDescription at- date (ib_insync.objects.BarData attribute), 69
tribute), 60 delta (ib_insync.contract.DeltaNeutralContract at-
contract (ib_insync.contract.ContractDetails attribute), tribute), 57
58 delta (ib_insync.objects.OptionComputation property),
contract (ib_insync.objects.BarDataList attribute), 80 78
contract (ib_insync.objects.Fill property), 78 delta (ib_insync.order.Order attribute), 35
contract (ib_insync.objects.PortfolioItem property), 78 deltaNeutralAuxPrice (ib_insync.order.Order at-
contract (ib_insync.objects.Position property), 78 tribute), 35
contract (ib_insync.objects.RealTimeBarList attribute), deltaNeutralClearingAccount
81 (ib_insync.order.Order attribute), 35
contract (ib_insync.order.Trade attribute), 42 deltaNeutralClearingIntent
contract (ib_insync.ticker.Ticker attribute), 62 (ib_insync.order.Order attribute), 35
ContractDescription (class in ib_insync.contract), 60 deltaNeutralConId (ib_insync.order.Order attribute),
ContractDetails (class in ib_insync.contract), 58 35
contractDetails (ib_insync.contract.ScanData at- DeltaNeutralContract (class in ib_insync.contract),
tribute), 60 57
contractMonth (ib_insync.contract.ContractDetails at- deltaNeutralContract (ib_insync.contract.Contract
tribute), 58 attribute), 49
controller (ib_insync.ibcontroller.Watchdog attribute), deltaNeutralDesignatedLocation
89 (ib_insync.order.Order attribute), 35
convertible (ib_insync.contract.ContractDetails deltaNeutralOpenClose (ib_insync.order.Order
attribute), 59 attribute), 35
count (ib_insync.objects.HistogramData attribute), 72 deltaNeutralOrderType (ib_insync.order.Order
count (ib_insync.objects.RealTimeBar attribute), 70 attribute), 35
count (ib_insync.ticker.Bar attribute), 65 deltaNeutralSettlingFirm (ib_insync.order.Order
coupon (ib_insync.contract.ContractDetails attribute), attribute), 35
59

128 Index
ib_insync, Release 0.9.70

deltaNeutralShortSale (ib_insync.order.Order dict() (ib_insync.objects.PnLSingle method), 74


attribute), 35 dict() (ib_insync.objects.RealTimeBar method), 70
deltaNeutralShortSaleSlot (ib_insync.order.Order dict() (ib_insync.objects.ScannerSubscription method),
attribute), 35 67
DepthMktDataDescription (class in dict() (ib_insync.objects.SoftDollarTier method), 67
ib_insync.objects), 73 dict() (ib_insync.objects.TickAttrib method), 71
derivativeSecTypes (ib_insync.contract.ContractDescription dict() (ib_insync.objects.TickAttribBidAsk method), 71
attribute), 60 dict() (ib_insync.objects.TickAttribLast method), 71
descAppend (ib_insync.contract.ContractDetails at- dict() (ib_insync.objects.TradeLogEntry method), 74
tribute), 59 dict() (ib_insync.order.ExecutionCondition method),
designatedLocation (ib_insync.contract.ComboLeg 45
attribute), 57 dict() (ib_insync.order.LimitOrder method), 38
designatedLocation (ib_insync.order.Order at- dict() (ib_insync.order.MarginCondition method), 45
tribute), 34 dict() (ib_insync.order.MarketOrder method), 38
df() (ib_insync.flexreport.FlexReport method), 84 dict() (ib_insync.order.Order method), 37
df() (in module ib_insync.util), 81 dict() (ib_insync.order.OrderComboLeg method), 42
dict() (ib_insync.contract.Bag method), 56 dict() (ib_insync.order.OrderCondition method), 43
dict() (ib_insync.contract.Bond method), 54 dict() (ib_insync.order.OrderState method), 41
dict() (ib_insync.contract.CFD method), 53 dict() (ib_insync.order.OrderStatus method), 40
dict() (ib_insync.contract.ComboLeg method), 57 dict() (ib_insync.order.PercentChangeCondition
dict() (ib_insync.contract.Commodity method), 53 method), 46
dict() (ib_insync.contract.ContFuture method), 51 dict() (ib_insync.order.PriceCondition method), 44
dict() (ib_insync.contract.Contract method), 49 dict() (ib_insync.order.StopLimitOrder method), 39
dict() (ib_insync.contract.ContractDescription dict() (ib_insync.order.StopOrder method), 39
method), 60 dict() (ib_insync.order.TimeCondition method), 44
dict() (ib_insync.contract.ContractDetails method), 59 dict() (ib_insync.order.Trade method), 43
dict() (ib_insync.contract.Crypto method), 56 dict() (ib_insync.order.VolumeCondition method), 46
dict() (ib_insync.contract.DeltaNeutralContract dict() (ib_insync.ticker.Ticker method), 64
method), 57 disconnect() (ib_insync.client.Client method), 29
dict() (ib_insync.contract.Forex method), 52 disconnect() (ib_insync.ib.IB method), 9
dict() (ib_insync.contract.Future method), 51 DISCONNECTED (ib_insync.client.Client attribute), 28
dict() (ib_insync.contract.FuturesOption method), 55 discretionaryAmt (ib_insync.order.Order attribute),
dict() (ib_insync.contract.Index method), 52 35
dict() (ib_insync.contract.MutualFund method), 55 discretionaryUpToLimitPrice
dict() (ib_insync.contract.Option method), 50 (ib_insync.order.Order attribute), 37
dict() (ib_insync.contract.ScanData method), 60 displayName (ib_insync.objects.SoftDollarTier at-
dict() (ib_insync.contract.Stock method), 49 tribute), 67
dict() (ib_insync.contract.Warrant method), 55 displaySize (ib_insync.order.Order attribute), 34
dict() (ib_insync.ibcontroller.IBC method), 86 distance (ib_insync.contract.ScanData attribute), 60
dict() (ib_insync.ibcontroller.IBController method), 87 Dividends (class in ib_insync.objects), 79
dict() (ib_insync.ibcontroller.Watchdog method), 90 dividends (ib_insync.ticker.Ticker attribute), 63
dict() (ib_insync.objects.BarData method), 70 domAsks (ib_insync.ticker.Ticker attribute), 63
dict() (ib_insync.objects.CommissionReport method), domBids (ib_insync.ticker.Ticker attribute), 63
68 DOMLevel (class in ib_insync.objects), 77
dict() (ib_insync.objects.DepthMktDataDescription domTicks (ib_insync.ticker.Ticker attribute), 63
method), 73 DoneStates (ib_insync.order.OrderStatus attribute), 40
dict() (ib_insync.objects.Execution method), 68 dontUseAutoPriceForHedge (ib_insync.order.Order
dict() (ib_insync.objects.ExecutionFilter method), 69 attribute), 37
dict() (ib_insync.objects.HistogramData method), 72 download() (ib_insync.flexreport.FlexReport method),
dict() (ib_insync.objects.HistoricalSchedule method), 84
75 duration (ib_insync.objects.ConnectionStats property),
dict() (ib_insync.objects.HistoricalSession method), 75 80
dict() (ib_insync.objects.NewsProvider method), 72 duration (ib_insync.order.Order attribute), 37
dict() (ib_insync.objects.PnL method), 73

Index 129
ib_insync, Release 0.9.70

durationStr (ib_insync.objects.BarDataList attribute), excludeConvertible (ib_insync.objects.ScannerSubscription


80 attribute), 66
DynamicObject (class in ib_insync.objects), 81 execId (ib_insync.objects.CommissionReport attribute),
68
E execId (ib_insync.objects.Execution attribute), 67
endDateTime (ib_insync.objects.BarDataList attribute), Execution (class in ib_insync.objects), 67
80 execution (ib_insync.objects.Fill property), 78
endDateTime (ib_insync.objects.HistoricalSchedule at- ExecutionCondition (class in ib_insync.order), 45
tribute), 75 ExecutionFilter (class in ib_insync.objects), 69
endDateTime (ib_insync.objects.HistoricalSession at- executions() (ib_insync.ib.IB method), 12
tribute), 75 exemptCode (ib_insync.contract.ComboLeg attribute),
endTime (ib_insync.objects.RealTimeBar attribute), 70 57
equityWithLoanAfter (ib_insync.order.OrderState at- exemptCode (ib_insync.order.Order attribute), 35
tribute), 41 exerciseOptions() (ib_insync.client.Client method),
equityWithLoanBefore (ib_insync.order.OrderState 30
attribute), 41 exerciseOptions() (ib_insync.ib.IB method), 23
equityWithLoanChange (ib_insync.order.OrderState expirations (ib_insync.objects.OptionChain property),
attribute), 41 79
errorCode (ib_insync.objects.TradeLogEntry attribute), extOperator (ib_insync.order.Order attribute), 37
74 extract() (ib_insync.flexreport.FlexReport method), 84
eTradeOnly (ib_insync.order.Order attribute), 35 extraData (ib_insync.objects.NewsTick property), 79
events (ib_insync.client.Client attribute), 28
events (ib_insync.ib.IB attribute), 9 F
events (ib_insync.ibcontroller.Watchdog attribute), 89 faGroup (ib_insync.order.Order attribute), 34
events (ib_insync.order.Trade attribute), 42 faMethod (ib_insync.order.Order attribute), 34
events (ib_insync.ticker.Ticker attribute), 62 FamilyCode (class in ib_insync.objects), 80
evMultiplier (ib_insync.contract.ContractDetails at- familyCodeStr (ib_insync.objects.FamilyCode prop-
tribute), 59 erty), 80
evMultiplier (ib_insync.objects.Execution attribute), faPercentage (ib_insync.order.Order attribute), 34
68 faProfile (ib_insync.order.Order attribute), 34
evRule (ib_insync.contract.ContractDetails attribute), Fill (class in ib_insync.objects), 78
58 Filled (ib_insync.order.OrderStatus attribute), 40
evRule (ib_insync.objects.Execution attribute), 68 filled (ib_insync.order.OrderStatus attribute), 40
exch (ib_insync.order.ExecutionCondition attribute), 45 filled() (ib_insync.order.Trade method), 43
exch (ib_insync.order.PercentChangeCondition at- filledQuantity (ib_insync.order.Order attribute), 37
tribute), 46 fills (ib_insync.order.Trade attribute), 42
exch (ib_insync.order.PriceCondition attribute), 44 fills() (ib_insync.ib.IB method), 12
exch (ib_insync.order.VolumeCondition attribute), 46 firmQuoteOnly (ib_insync.order.Order attribute), 35
exchange (ib_insync.contract.ComboLeg attribute), 57 fixpassword (ib_insync.ibcontroller.IBC attribute), 86
exchange (ib_insync.contract.Contract attribute), 48 fixuserid (ib_insync.ibcontroller.IBC attribute), 86
exchange (ib_insync.objects.DepthMktDataDescription FlexError, 84
attribute), 73 FlexReport (class in ib_insync.flexreport), 84
exchange (ib_insync.objects.Execution attribute), 67 Forex (class in ib_insync.contract), 52
exchange (ib_insync.objects.ExecutionFilter attribute), formatDate (ib_insync.objects.BarDataList attribute),
69 80
exchange (ib_insync.objects.HistoricalTickLast prop- formatIBDatetime() (in module ib_insync.util), 84
erty), 76 formatSI() (in module ib_insync.util), 82
exchange (ib_insync.objects.OptionChain property), 79 FundamentalRatios (class in ib_insync.objects), 81
exchange (ib_insync.objects.SmartComponent prop- fundamentalRatios (ib_insync.ticker.Ticker attribute),
erty), 80 63
exchange (ib_insync.objects.TickByTickAllLast prop- Future (class in ib_insync.contract), 50
erty), 77 futuresOpenInterest (ib_insync.ticker.Ticker at-
exchangeLetter (ib_insync.objects.SmartComponent tribute), 63
property), 80 FuturesOption (class in ib_insync.contract), 54

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

mifid2DecisionMaker (ib_insync.order.Order at- newsBulletins() (ib_insync.ib.IB method), 13


tribute), 37 NewsProvider (class in ib_insync.objects), 72
mifid2ExecutionAlgo (ib_insync.order.Order at- NewsTick (class in ib_insync.objects), 79
tribute), 37 newsTicks() (ib_insync.ib.IB method), 13
mifid2ExecutionTrader (ib_insync.order.Order next12Months (ib_insync.objects.Dividends property),
attribute), 37 79
MinClientVersion (ib_insync.client.Client attribute), nextAmount (ib_insync.objects.Dividends property), 79
28 nextDate (ib_insync.objects.Dividends property), 79
minCommission (ib_insync.order.OrderState attribute), nextOptionDate (ib_insync.contract.ContractDetails
41 attribute), 59
minQty (ib_insync.order.Order attribute), 34 nextOptionPartial (ib_insync.contract.ContractDetails
minSize (ib_insync.contract.ContractDetails attribute), attribute), 59
59 nextOptionType (ib_insync.contract.ContractDetails
minTick (ib_insync.contract.ContractDetails attribute), attribute), 59
58 nonDefaults() (ib_insync.contract.Bag method), 56
mktCapPrice (ib_insync.order.OrderStatus attribute), 40 nonDefaults() (ib_insync.contract.Bond method), 54
MktDepthData (class in ib_insync.objects), 77 nonDefaults() (ib_insync.contract.CFD method), 53
modelCode (ib_insync.objects.AccountValue property), nonDefaults() (ib_insync.contract.ComboLeg
76 method), 57
modelCode (ib_insync.objects.Execution attribute), 68 nonDefaults() (ib_insync.contract.Commodity
modelCode (ib_insync.objects.PnL attribute), 73 method), 54
modelCode (ib_insync.objects.PnLSingle attribute), 74 nonDefaults() (ib_insync.contract.ContFuture
modelCode (ib_insync.order.Order attribute), 36 method), 51
modelGreeks (ib_insync.ticker.Ticker attribute), 63 nonDefaults() (ib_insync.contract.Contract method),
module 49
ib_insync.client, 27 nonDefaults() (ib_insync.contract.ContractDescription
ib_insync.contract, 47 method), 60
ib_insync.flexreport, 84 nonDefaults() (ib_insync.contract.ContractDetails
ib_insync.ib, 7 method), 59
ib_insync.objects, 66 nonDefaults() (ib_insync.contract.Crypto method), 56
ib_insync.order, 32 nonDefaults() (ib_insync.contract.DeltaNeutralContract
ib_insync.ticker, 61 method), 57
ib_insync.util, 81 nonDefaults() (ib_insync.contract.Forex method), 52
monitorAsync() (ib_insync.ibcontroller.IBC method), nonDefaults() (ib_insync.contract.Future method), 51
86 nonDefaults() (ib_insync.contract.FuturesOption
monitorAsync() (ib_insync.ibcontroller.IBController method), 55
method), 87 nonDefaults() (ib_insync.contract.Index method), 53
moodyRatingAbove (ib_insync.objects.ScannerSubscriptionnonDefaults() (ib_insync.contract.MutualFund
attribute), 66 method), 55
moodyRatingBelow (ib_insync.objects.ScannerSubscriptionnonDefaults() (ib_insync.contract.Option method), 50
attribute), 66 nonDefaults() (ib_insync.contract.ScanData method),
msgId (ib_insync.objects.NewsBulletin property), 79 60
msgType (ib_insync.objects.NewsBulletin property), 79 nonDefaults() (ib_insync.contract.Stock method), 50
multiplier (ib_insync.contract.Contract attribute), 48 nonDefaults() (ib_insync.contract.Warrant method),
multiplier (ib_insync.objects.OptionChain property), 55
79 nonDefaults() (ib_insync.ibcontroller.IBC method), 86
MutualFund (class in ib_insync.contract), 55 nonDefaults() (ib_insync.ibcontroller.IBController
method), 88
N nonDefaults() (ib_insync.ibcontroller.Watchdog
name (ib_insync.objects.NewsProvider attribute), 72 method), 90
name (ib_insync.objects.SoftDollarTier attribute), 67 nonDefaults() (ib_insync.objects.BarData method), 70
nbboPriceCap (ib_insync.order.Order attribute), 35 nonDefaults() (ib_insync.objects.CommissionReport
NewsArticle (class in ib_insync.objects), 79 method), 68
NewsBulletin (class in ib_insync.objects), 79 nonDefaults() (ib_insync.objects.DepthMktDataDescription

Index 133
ib_insync, Release 0.9.70

method), 73 nonDefaults() (ib_insync.order.TimeCondition


nonDefaults() (ib_insync.objects.Execution method), method), 44
68 nonDefaults() (ib_insync.order.Trade method), 43
nonDefaults() (ib_insync.objects.ExecutionFilter nonDefaults() (ib_insync.order.VolumeCondition
method), 69 method), 46
nonDefaults() (ib_insync.objects.HistogramData nonDefaults() (ib_insync.ticker.Ticker method), 64
method), 72 notes (ib_insync.contract.ContractDetails attribute), 59
nonDefaults() (ib_insync.objects.HistoricalSchedule notHeld (ib_insync.order.Order attribute), 36
method), 75 numberOfRows (ib_insync.objects.ScannerSubscription
nonDefaults() (ib_insync.objects.HistoricalSession attribute), 66
method), 75 numBytesRecv (ib_insync.objects.ConnectionStats prop-
nonDefaults() (ib_insync.objects.NewsProvider erty), 80
method), 72 numBytesSent (ib_insync.objects.ConnectionStats prop-
nonDefaults() (ib_insync.objects.PnL method), 73 erty), 80
nonDefaults() (ib_insync.objects.PnLSingle method), numMsgRecv (ib_insync.objects.ConnectionStats prop-
74 erty), 80
nonDefaults() (ib_insync.objects.RealTimeBar numMsgSent (ib_insync.objects.ConnectionStats prop-
method), 70 erty), 80
nonDefaults() (ib_insync.objects.ScannerSubscription
method), 67 O
nonDefaults() (ib_insync.objects.SoftDollarTier ocaGroup (ib_insync.order.Order attribute), 34
method), 67 ocaType (ib_insync.order.Order attribute), 34
nonDefaults() (ib_insync.objects.TickAttrib method), on_source() (ib_insync.ticker.Midpoints method), 65
71 on_source() (ib_insync.ticker.TickBars method), 65
nonDefaults() (ib_insync.objects.TickAttribBidAsk on_source() (ib_insync.ticker.Tickfilter method), 64
method), 71 on_source() (ib_insync.ticker.TimeBars method), 65
nonDefaults() (ib_insync.objects.TickAttribLast oneCancelsAll() (ib_insync.ib.IB static method), 14
method), 72 open (ib_insync.objects.BarData attribute), 69
nonDefaults() (ib_insync.objects.TradeLogEntry open (ib_insync.ticker.Bar attribute), 65
method), 74 open (ib_insync.ticker.Ticker attribute), 62
nonDefaults() (ib_insync.order.ExecutionCondition open_ (ib_insync.objects.RealTimeBar attribute), 70
method), 45 openClose (ib_insync.contract.ComboLeg attribute), 57
nonDefaults() (ib_insync.order.LimitOrder method), openClose (ib_insync.order.Order attribute), 35
38 openOrders() (ib_insync.ib.IB method), 12
nonDefaults() (ib_insync.order.MarginCondition openTrades() (ib_insync.ib.IB method), 12
method), 45 operation (ib_insync.objects.MktDepthData property),
nonDefaults() (ib_insync.order.MarketOrder method), 77
38 Option (class in ib_insync.contract), 50
nonDefaults() (ib_insync.order.Order method), 37 OptionChain (class in ib_insync.objects), 79
nonDefaults() (ib_insync.order.OrderComboLeg OptionComputation (class in ib_insync.objects), 78
method), 42 optOutSmartRouting (ib_insync.order.Order at-
nonDefaults() (ib_insync.order.OrderCondition tribute), 35
method), 43 optPrice (ib_insync.objects.OptionComputation prop-
nonDefaults() (ib_insync.order.OrderState method), erty), 78
41 Or() (ib_insync.order.OrderCondition method), 43
nonDefaults() (ib_insync.order.OrderStatus method), Order (class in ib_insync.order), 32
40 order (ib_insync.order.Trade attribute), 42
nonDefaults() (ib_insync.order.PercentChangeCondition OrderComboLeg (class in ib_insync.order), 42
method), 46 orderComboLegs (ib_insync.order.LimitOrder at-
nonDefaults() (ib_insync.order.PriceCondition tribute), 38
method), 44 orderComboLegs (ib_insync.order.MarketOrder at-
nonDefaults() (ib_insync.order.StopLimitOrder tribute), 38
method), 39 orderComboLegs (ib_insync.order.Order attribute), 36
nonDefaults() (ib_insync.order.StopOrder method), 39

134 Index
ib_insync, Release 0.9.70

orderComboLegs (ib_insync.order.StopLimitOrder at- pendingTickers() (ib_insync.ib.IB method), 13


tribute), 39 percent (ib_insync.order.MarginCondition attribute), 45
orderComboLegs (ib_insync.order.StopOrder attribute), PercentChangeCondition (class in ib_insync.order),
39 46
OrderCondition (class in ib_insync.order), 43 percentOffset (ib_insync.order.Order attribute), 34
orderId (ib_insync.objects.Execution attribute), 68 permId (ib_insync.objects.Execution attribute), 68
orderId (ib_insync.order.Order attribute), 34 permId (ib_insync.order.Order attribute), 34
orderId (ib_insync.order.OrderStatus attribute), 40 permId (ib_insync.order.OrderStatus attribute), 40
orderMiscOptions (ib_insync.order.LimitOrder at- placeOrder() (ib_insync.client.Client method), 29
tribute), 38 placeOrder() (ib_insync.ib.IB method), 14
orderMiscOptions (ib_insync.order.MarketOrder at- PnL (class in ib_insync.objects), 73
tribute), 38 pnl() (ib_insync.ib.IB method), 11
orderMiscOptions (ib_insync.order.Order attribute), PnLSingle (class in ib_insync.objects), 74
36 pnlSingle() (ib_insync.ib.IB method), 12
orderMiscOptions (ib_insync.order.StopLimitOrder at- port (ib_insync.ibcontroller.Watchdog attribute), 89
tribute), 39 portfolio() (ib_insync.ib.IB method), 11
orderMiscOptions (ib_insync.order.StopOrder at- PortfolioItem (class in ib_insync.objects), 78
tribute), 39 Position (class in ib_insync.objects), 78
orderRef (ib_insync.objects.Execution attribute), 68 position (ib_insync.objects.MktDepthData property),
orderRef (ib_insync.order.Order attribute), 34 77
orders() (ib_insync.ib.IB method), 12 position (ib_insync.objects.PnLSingle attribute), 74
OrderState (class in ib_insync.order), 41 position (ib_insync.objects.PortfolioItem property), 78
OrderStatus (class in ib_insync.order), 40 position (ib_insync.objects.Position property), 78
orderStatus (ib_insync.order.Trade attribute), 42 positions() (ib_insync.ib.IB method), 11
orderType (ib_insync.order.Order attribute), 34 postToAts (ib_insync.order.Order attribute), 37
orderTypes (ib_insync.contract.ContractDetails at- preOpen (ib_insync.objects.TickAttrib attribute), 71
tribute), 58 PreSubmitted (ib_insync.order.OrderStatus attribute),
origExchange (ib_insync.objects.NewsBulletin prop- 40
erty), 80 prevAsk (ib_insync.ticker.Ticker attribute), 62
origin (ib_insync.order.Order attribute), 35 prevAskSize (ib_insync.ticker.Ticker attribute), 62
outsideRth (ib_insync.order.Order attribute), 34 prevBid (ib_insync.ticker.Ticker attribute), 62
overridePercentageConstraints prevBidSize (ib_insync.ticker.Ticker attribute), 62
(ib_insync.order.Order attribute), 34 prevLast (ib_insync.ticker.Ticker attribute), 62
prevLastSize (ib_insync.ticker.Ticker attribute), 62
P price (ib_insync.contract.DeltaNeutralContract at-
pair() (ib_insync.contract.Forex method), 52 tribute), 57
parent (ib_insync.order.BracketOrder property), 43 price (ib_insync.objects.DOMLevel property), 77
parentId (ib_insync.order.Order attribute), 34 price (ib_insync.objects.Execution attribute), 68
parentId (ib_insync.order.OrderStatus attribute), 40 price (ib_insync.objects.HistogramData attribute), 72
parentPermId (ib_insync.order.Order attribute), 37 price (ib_insync.objects.HistoricalTick property), 76
parseIBDatetime() (in module ib_insync.util), 84 price (ib_insync.objects.HistoricalTickLast property),
password (ib_insync.ibcontroller.IBC attribute), 86 76
past12Months (ib_insync.objects.Dividends property), price (ib_insync.objects.MktDepthData property), 77
79 price (ib_insync.objects.TickByTickAllLast property), 77
pastLimit (ib_insync.objects.TickAttrib attribute), 71 price (ib_insync.objects.TickData property), 76
pastLimit (ib_insync.objects.TickAttribLast attribute), price (ib_insync.order.OrderComboLeg attribute), 42
71 price (ib_insync.order.PriceCondition attribute), 44
patchAsyncio() (in module ib_insync.util), 83 priceAsk (ib_insync.objects.HistoricalTickBidAsk prop-
peggedChangeAmount (ib_insync.order.Order at- erty), 76
tribute), 36 priceBid (ib_insync.objects.HistoricalTickBidAsk prop-
PendingCancel (ib_insync.order.OrderStatus attribute), erty), 76
40 PriceCondition (class in ib_insync.order), 43
PendingSubmit (ib_insync.order.OrderStatus attribute), PriceIncrement (class in ib_insync.objects), 77
40

Index 135
ib_insync, Release 0.9.70

priceMagnifier (ib_insync.contract.ContractDetails referenceChangeAmount (ib_insync.order.Order


attribute), 58 attribute), 36
primaryExchange (ib_insync.contract.Contract at- referenceContractId (ib_insync.order.Order at-
tribute), 48 tribute), 36
probeContract (ib_insync.ibcontroller.Watchdog referenceExchangeId (ib_insync.order.Order at-
attribute), 89 tribute), 36
probeTimeout (ib_insync.ibcontroller.Watchdog at- referencePriceType (ib_insync.order.Order at-
tribute), 89 tribute), 35
projection (ib_insync.contract.ScanData attribute), 60 refFuturesConId (ib_insync.order.Order attribute), 37
providerCode (ib_insync.objects.HistoricalNews prop- regulatoryImbalance (ib_insync.ticker.Ticker at-
erty), 79 tribute), 63
providerCode (ib_insync.objects.NewsTick property), remaining (ib_insync.order.OrderStatus attribute), 40
79 remaining() (ib_insync.order.Trade method), 43
putable (ib_insync.contract.ContractDetails attribute), replaceFA() (ib_insync.client.Client method), 30
59 replaceFA() (ib_insync.ib.IB method), 25
putOpenInterest (ib_insync.ticker.Ticker attribute), 63 reqAccountSummary() (ib_insync.client.Client
putVolume (ib_insync.ticker.Ticker attribute), 63 method), 30
pvDividend (ib_insync.objects.OptionComputation reqAccountSummary() (ib_insync.ib.IB method), 15
property), 78 reqAccountSummaryAsync() (ib_insync.ib.IB method),
25
Q reqAccountUpdates() (ib_insync.client.Client
qualifyContracts() (ib_insync.ib.IB method), 13 method), 29
qualifyContractsAsync() (ib_insync.ib.IB method), reqAccountUpdates() (ib_insync.ib.IB method), 14
25 reqAccountUpdatesAsync() (ib_insync.ib.IB method),
queryDisplayGroups() (ib_insync.client.Client 25
method), 31 reqAccountUpdatesMulti() (ib_insync.client.Client
method), 31
R reqAccountUpdatesMulti() (ib_insync.ib.IB method),
RaiseRequestErrors (ib_insync.ib.IB attribute), 8, 9 14
randomizePrice (ib_insync.order.Order attribute), 35 reqAccountUpdatesMultiAsync() (ib_insync.ib.IB
randomizeSize (ib_insync.order.Order attribute), 35 method), 25
rank (ib_insync.contract.ScanData attribute), 60 reqAllOpenOrders() (ib_insync.client.Client method),
ratings (ib_insync.contract.ContractDetails attribute), 30
59 reqAllOpenOrders() (ib_insync.ib.IB method), 15
ratio (ib_insync.contract.ComboLeg attribute), 57 reqAllOpenOrdersAsync() (ib_insync.ib.IB method),
readonly (ib_insync.ibcontroller.Watchdog attribute), 25
89 reqAutoOpenOrders() (ib_insync.client.Client
realExpirationDate (ib_insync.contract.ContractDetails method), 30
attribute), 59 reqAutoOpenOrders() (ib_insync.ib.IB method), 15
realizedPNL (ib_insync.objects.CommissionReport at- reqCompletedOrders() (ib_insync.client.Client
tribute), 68 method), 31
realizedPnL (ib_insync.objects.PnL attribute), 73 reqCompletedOrders() (ib_insync.ib.IB method), 15
realizedPnL (ib_insync.objects.PnLSingle attribute), 74 reqCompletedOrdersAsync() (ib_insync.ib.IB
realizedPNL (ib_insync.objects.PortfolioItem property), method), 26
78 reqContractDetails() (ib_insync.client.Client
RealTimeBar (class in ib_insync.objects), 70 method), 30
RealTimeBarList (class in ib_insync.objects), 80 reqContractDetails() (ib_insync.ib.IB method), 16
realtimeBars() (ib_insync.ib.IB method), 13 reqContractDetailsAsync() (ib_insync.ib.IB
realTimeBarsOptions method), 26
(ib_insync.objects.RealTimeBarList attribute), reqCurrentTime() (ib_insync.client.Client method), 30
81 reqCurrentTime() (ib_insync.ib.IB method), 14
refDate (ib_insync.objects.HistoricalSession attribute), reqCurrentTimeAsync() (ib_insync.ib.IB method), 25
75 reqExecutions() (ib_insync.client.Client method), 30
reqExecutions() (ib_insync.ib.IB method), 15

136 Index
ib_insync, Release 0.9.70

reqExecutionsAsync() (ib_insync.ib.IB method), 26 reqMatchingSymbolsAsync() (ib_insync.ib.IB


reqFamilyCodes() (ib_insync.client.Client method), 31 method), 26
reqFundamentalData() (ib_insync.client.Client reqMktData() (ib_insync.client.Client method), 29
method), 30 reqMktData() (ib_insync.ib.IB method), 19
reqFundamentalData() (ib_insync.ib.IB method), 21 reqMktDepth() (ib_insync.client.Client method), 30
reqFundamentalDataAsync() (ib_insync.ib.IB reqMktDepth() (ib_insync.ib.IB method), 21
method), 26 reqMktDepthExchanges() (ib_insync.client.Client
reqGlobalCancel() (ib_insync.client.Client method), method), 31
30 reqMktDepthExchanges() (ib_insync.ib.IB method),
reqGlobalCancel() (ib_insync.ib.IB method), 14 20
reqHeadTimeStamp() (ib_insync.client.Client method), reqMktDepthExchangesAsync() (ib_insync.ib.IB
31 method), 26
reqHeadTimeStamp() (ib_insync.ib.IB method), 19 reqNewsArticle() (ib_insync.client.Client method), 31
reqHeadTimeStampAsync() (ib_insync.ib.IB method), reqNewsArticle() (ib_insync.ib.IB method), 24
26 reqNewsArticleAsync() (ib_insync.ib.IB method), 27
reqHistogramData() (ib_insync.client.Client method), reqNewsBulletins() (ib_insync.client.Client method),
31 30
reqHistogramData() (ib_insync.ib.IB method), 21 reqNewsBulletins() (ib_insync.ib.IB method), 24
reqHistogramDataAsync() (ib_insync.ib.IB method), reqNewsProviders() (ib_insync.client.Client method),
26 31
reqHistoricalData() (ib_insync.client.Client reqNewsProviders() (ib_insync.ib.IB method), 23
method), 30 reqNewsProvidersAsync() (ib_insync.ib.IB method),
reqHistoricalData() (ib_insync.ib.IB method), 17 27
reqHistoricalDataAsync() (ib_insync.ib.IB method), reqOpenOrders() (ib_insync.client.Client method), 29
26 reqOpenOrders() (ib_insync.ib.IB method), 15
reqHistoricalNews() (ib_insync.client.Client reqOpenOrdersAsync() (ib_insync.ib.IB method), 25
method), 31 reqPnL() (ib_insync.client.Client method), 31
reqHistoricalNews() (ib_insync.ib.IB method), 24 reqPnL() (ib_insync.ib.IB method), 16
reqHistoricalNewsAsync() (ib_insync.ib.IB method), reqPnLSingle() (ib_insync.client.Client method), 31
27 reqPnLSingle() (ib_insync.ib.IB method), 16
reqHistoricalSchedule() (ib_insync.ib.IB method), reqPositions() (ib_insync.client.Client method), 30
18 reqPositions() (ib_insync.ib.IB method), 15
reqHistoricalScheduleAsync() (ib_insync.ib.IB reqPositionsAsync() (ib_insync.ib.IB method), 26
method), 26 reqPositionsMulti() (ib_insync.client.Client
reqHistoricalTicks() (ib_insync.client.Client method), 31
method), 31 reqRealTimeBars() (ib_insync.client.Client method),
reqHistoricalTicks() (ib_insync.ib.IB method), 18 30
reqHistoricalTicksAsync() (ib_insync.ib.IB reqRealTimeBars() (ib_insync.ib.IB method), 17
method), 26 reqScannerData() (ib_insync.ib.IB method), 22
reqId (ib_insync.objects.BarDataList attribute), 80 reqScannerDataAsync() (ib_insync.ib.IB method), 27
reqId (ib_insync.objects.RealTimeBarList attribute), 81 reqScannerParameters() (ib_insync.client.Client
reqId (ib_insync.objects.ScanDataList attribute), 81 method), 30
reqIds() (ib_insync.client.Client method), 30 reqScannerParameters() (ib_insync.ib.IB method),
reqManagedAccts() (ib_insync.client.Client method), 22
30 reqScannerParametersAsync() (ib_insync.ib.IB
reqMarketDataType() (ib_insync.client.Client method), 27
method), 30 reqScannerSubscription() (ib_insync.client.Client
reqMarketDataType() (ib_insync.ib.IB method), 19 method), 30
reqMarketRule() (ib_insync.client.Client method), 31 reqScannerSubscription() (ib_insync.ib.IB method),
reqMarketRule() (ib_insync.ib.IB method), 17 22
reqMarketRuleAsync() (ib_insync.ib.IB method), 26 reqSecDefOptParams() (ib_insync.client.Client
reqMatchingSymbols() (ib_insync.client.Client method), 31
method), 31 reqSecDefOptParams() (ib_insync.ib.IB method), 23
reqMatchingSymbols() (ib_insync.ib.IB method), 16 reqSecDefOptParamsAsync() (ib_insync.ib.IB

Index 137
ib_insync, Release 0.9.70

method), 27 scaleProfitOffset (ib_insync.order.Order attribute),


reqSmartComponents() (ib_insync.client.Client 36
method), 31 scaleRandomPercent (ib_insync.order.Order at-
reqSoftDollarTiers() (ib_insync.client.Client tribute), 36
method), 31 scaleSubsLevelSize (ib_insync.order.Order at-
reqTickByTickData() (ib_insync.client.Client tribute), 35
method), 31 scaleTable (ib_insync.order.Order attribute), 36
reqTickByTickData() (ib_insync.ib.IB method), 20 scanCode (ib_insync.objects.ScannerSubscription
reqTickers() (ib_insync.ib.IB method), 13 attribute), 66
reqTickersAsync() (ib_insync.ib.IB method), 25 ScanData (class in ib_insync.contract), 60
RequestError (class in ib_insync.wrapper), 81 ScanDataList (class in ib_insync.objects), 81
requestFA() (ib_insync.client.Client method), 30 scannerSettingPairs
requestFA() (ib_insync.ib.IB method), 24 (ib_insync.objects.ScannerSubscription at-
requestFAAsync() (ib_insync.ib.IB method), 27 tribute), 66
RequestsInterval (ib_insync.client.Client attribute), ScannerSubscription (class in ib_insync.objects), 66
28 scannerSubscriptionFilterOptions
RequestTimeout (ib_insync.ib.IB attribute), 8, 9 (ib_insync.objects.ScanDataList attribute),
reqUserInfo() (ib_insync.client.Client method), 32 81
reqWshEventData() (ib_insync.client.Client method), scannerSubscriptionOptions
32 (ib_insync.objects.ScanDataList attribute),
reqWshMetaData() (ib_insync.client.Client method), 31 81
reset() (ib_insync.client.Client method), 28 schedule() (ib_insync.ib.IB static method), 10
retryDelay (ib_insync.ibcontroller.Watchdog attribute), schedule() (in module ib_insync.util), 82
89 secId (ib_insync.contract.Contract attribute), 49
right (ib_insync.contract.Contract attribute), 48 secIdList (ib_insync.contract.ContractDetails at-
routeMarketableToBbo (ib_insync.order.Order at- tribute), 59
tribute), 37 secIdType (ib_insync.contract.Contract attribute), 49
rtHistVolatility (ib_insync.ticker.Ticker attribute), secType (ib_insync.contract.Contract attribute), 48
62 secType (ib_insync.objects.DepthMktDataDescription
rtTime (ib_insync.ticker.Ticker attribute), 63 attribute), 73
rtTradeVolume (ib_insync.ticker.Ticker attribute), 62 secType (ib_insync.objects.ExecutionFilter attribute), 69
rtVolume (ib_insync.ticker.Ticker attribute), 62 secType (ib_insync.order.ExecutionCondition attribute),
rule80A (ib_insync.order.Order attribute), 34 45
run() (ib_insync.client.Client method), 29 send() (ib_insync.client.Client method), 29
run() (ib_insync.ib.IB static method), 9 sendMsg() (ib_insync.client.Client method), 29
run() (in module ib_insync.util), 82 serverVersion() (ib_insync.client.Client method), 28
runAsync() (ib_insync.ibcontroller.Watchdog method), serviceDataType (ib_insync.objects.DepthMktDataDescription
89 attribute), 73
sessions (ib_insync.objects.HistoricalSchedule at-
S tribute), 75
save() (ib_insync.flexreport.FlexReport method), 84 setConnectOptions() (ib_insync.client.Client
scaleAutoReset (ib_insync.order.Order attribute), 36 method), 29
scaleInitFillQty (ib_insync.order.Order attribute), setServerLogLevel() (ib_insync.client.Client
36 method), 30
scaleInitLevelSize (ib_insync.order.Order at- setTimeout() (ib_insync.ib.IB method), 11
tribute), 35 settlingFirm (ib_insync.order.Order attribute), 36
scaleInitPosition (ib_insync.order.Order attribute), shareholder (ib_insync.order.Order attribute), 37
36 shares (ib_insync.objects.Execution attribute), 68
scalePriceAdjustInterval (ib_insync.order.Order shortableShares (ib_insync.ticker.Ticker attribute), 63
attribute), 36 shortSaleSlot (ib_insync.contract.ComboLeg at-
scalePriceAdjustValue (ib_insync.order.Order tribute), 57
attribute), 36 shortSaleSlot (ib_insync.order.Order attribute), 35
scalePriceIncrement (ib_insync.order.Order at- side (ib_insync.objects.Execution attribute), 67
tribute), 35 side (ib_insync.objects.ExecutionFilter attribute), 69

138 Index
ib_insync, Release 0.9.70

side (ib_insync.objects.MktDepthData property), 77 method), 87


size (ib_insync.objects.DOMLevel property), 77 startDateTime (ib_insync.objects.HistoricalSchedule
size (ib_insync.objects.HistoricalTick property), 76 attribute), 75
size (ib_insync.objects.HistoricalTickLast property), 76 startDateTime (ib_insync.objects.HistoricalSession at-
size (ib_insync.objects.MktDepthData property), 77 tribute), 75
size (ib_insync.objects.TickByTickAllLast property), 77 startingPrice (ib_insync.order.Order attribute), 35
size (ib_insync.objects.TickData property), 76 startLoop() (in module ib_insync.util), 83
sizeAsk (ib_insync.objects.HistoricalTickBidAsk prop- startTime (ib_insync.objects.ConnectionStats prop-
erty), 76 erty), 80
sizeBid (ib_insync.objects.HistoricalTickBidAsk prop- status (ib_insync.objects.TradeLogEntry attribute), 74
erty), 76 status (ib_insync.order.OrderState attribute), 41
sizeIncrement (ib_insync.contract.ContractDetails at- status (ib_insync.order.OrderStatus attribute), 40
tribute), 59 Stock (class in ib_insync.contract), 49
sleep() (ib_insync.ib.IB static method), 10 stockRangeLower (ib_insync.order.Order attribute), 35
sleep() (in module ib_insync.util), 83 stockRangeUpper (ib_insync.order.Order attribute), 35
smartComboRoutingParams stockRefPrice (ib_insync.order.Order attribute), 35
(ib_insync.order.LimitOrder attribute), 38 stockType (ib_insync.contract.ContractDetails at-
smartComboRoutingParams tribute), 59
(ib_insync.order.MarketOrder attribute), stockTypeFilter (ib_insync.objects.ScannerSubscription
38 attribute), 66
smartComboRoutingParams (ib_insync.order.Order at- stop() (ib_insync.ibcontroller.IBController method), 87
tribute), 36 stop() (ib_insync.ibcontroller.Watchdog method), 89
smartComboRoutingParams stopAsync() (ib_insync.ibcontroller.IBController
(ib_insync.order.StopLimitOrder attribute), method), 87
39 StopLimitOrder (class in ib_insync.order), 39
smartComboRoutingParams stopLoss (ib_insync.order.BracketOrder property), 43
(ib_insync.order.StopOrder attribute), 39 StopOrder (class in ib_insync.order), 39
SmartComponent (class in ib_insync.objects), 80 strike (ib_insync.contract.Contract attribute), 48
SoftDollarTier (class in ib_insync.objects), 67 strikes (ib_insync.objects.OptionChain property), 79
softDollarTier (ib_insync.order.LimitOrder at- subcategory (ib_insync.contract.ContractDetails
tribute), 38 attribute), 58
softDollarTier (ib_insync.order.MarketOrder at- Submitted (ib_insync.order.OrderStatus attribute), 40
tribute), 38 subscribeToGroupEvents() (ib_insync.client.Client
softDollarTier (ib_insync.order.Order attribute), 37 method), 31
softDollarTier (ib_insync.order.StopLimitOrder at- subscription (ib_insync.objects.ScanDataList at-
tribute), 39 tribute), 81
softDollarTier (ib_insync.order.StopOrder attribute), suggestedSizeIncrement
39 (ib_insync.contract.ContractDetails attribute),
solicited (ib_insync.order.Order attribute), 36 59
specialConditions (ib_insync.objects.HistoricalTickLastsweepToFill (ib_insync.order.Order attribute), 34
property), 76 symbol (ib_insync.contract.Contract attribute), 48
specialConditions (ib_insync.objects.TickByTickAllLast symbol (ib_insync.objects.ExecutionFilter attribute), 69
property), 77 symbol (ib_insync.order.ExecutionCondition attribute),
spRatingAbove (ib_insync.objects.ScannerSubscription 45
attribute), 66
spRatingBelow (ib_insync.objects.ScannerSubscription T
attribute), 66 tag (ib_insync.contract.TagValue property), 57
start() (ib_insync.ibcontroller.IBC method), 86 tag (ib_insync.objects.AccountValue property), 76
start() (ib_insync.ibcontroller.IBController method), TagValue (class in ib_insync.contract), 57
87 takeProfit (ib_insync.order.BracketOrder property),
start() (ib_insync.ibcontroller.Watchdog method), 89 43
startApi() (ib_insync.client.Client method), 31 terminate() (ib_insync.ibcontroller.IBC method), 86
startAsync() (ib_insync.ibcontroller.IBC method), 86 terminate() (ib_insync.ibcontroller.IBController
startAsync() (ib_insync.ibcontroller.IBController method), 87

Index 139
ib_insync, Release 0.9.70

terminateAsync() (ib_insync.ibcontroller.IBC time (ib_insync.ticker.Ticker attribute), 62


method), 86 TimeBars (class in ib_insync.ticker), 65
terminateAsync() (ib_insync.ibcontroller.IBController timebars() (ib_insync.ticker.Tickfilter method), 65
method), 87 TimeCondition (class in ib_insync.order), 44
theta (ib_insync.objects.OptionComputation property), timeit (class in ib_insync.util), 82
78 timeRange() (ib_insync.ib.IB static method), 10
TickAttrib (class in ib_insync.objects), 71 timeRange() (in module ib_insync.util), 83
tickAttrib (ib_insync.objects.OptionComputation timeRangeAsync() (ib_insync.ib.IB static method), 10
property), 78 timeRangeAsync() (in module ib_insync.util), 83
TickAttribBidAsk (class in ib_insync.objects), 71 timeStamp (ib_insync.objects.NewsTick property), 79
tickAttribBidAsk (ib_insync.objects.HistoricalTickBidAsk timeZone (ib_insync.objects.HistoricalSchedule at-
property), 76 tribute), 75
tickAttribBidAsk (ib_insync.objects.TickByTickBidAsk timeZoneId (ib_insync.contract.ContractDetails at-
property), 77 tribute), 58
TickAttribLast (class in ib_insync.objects), 71 TimezoneTWS (ib_insync.ib.IB attribute), 8, 9
tickAttribLast (ib_insync.objects.HistoricalTickLast topics() (ib_insync.flexreport.FlexReport method), 84
property), 76 totalQuantity (ib_insync.order.Order attribute), 34
tickAttribLast (ib_insync.objects.TickByTickAllLast Trade (class in ib_insync.order), 42
property), 77 tradeCount (ib_insync.ticker.Ticker attribute), 63
TickBars (class in ib_insync.ticker), 65 TradeLogEntry (class in ib_insync.objects), 74
tickbars() (ib_insync.ticker.Tickfilter method), 65 tradeRate (ib_insync.ticker.Ticker attribute), 63
TickByTickAllLast (class in ib_insync.objects), 77 trades() (ib_insync.ib.IB method), 12
TickByTickBidAsk (class in ib_insync.objects), 77 trades() (ib_insync.ticker.TickerUpdateEvent method),
TickByTickMidPoint (class in ib_insync.objects), 77 64
tickByTicks (ib_insync.ticker.Ticker attribute), 63 TRADING_MODE (ib_insync.ibcontroller.IBController at-
TickData (class in ib_insync.objects), 76 tribute), 87
Ticker (class in ib_insync.ticker), 61 tradingClass (ib_insync.contract.Contract attribute),
ticker() (ib_insync.ib.IB method), 12 49
tickers() (ib_insync.ib.IB method), 12 tradingClass (ib_insync.objects.OptionChain prop-
TickerUpdateEvent (class in ib_insync.ticker), 64 erty), 79
Tickfilter (class in ib_insync.ticker), 64 tradingHours (ib_insync.contract.ContractDetails at-
ticks (ib_insync.ticker.Ticker attribute), 63 tribute), 58
tickType (ib_insync.objects.TickByTickAllLast prop- tradingMode (ib_insync.ibcontroller.IBC attribute), 86
erty), 77 trailingPercent (ib_insync.order.Order attribute), 34
tickType (ib_insync.objects.TickData property), 76 trailStopPrice (ib_insync.order.Order attribute), 34
tif (ib_insync.order.Order attribute), 34 transmit (ib_insync.order.Order attribute), 34
time (ib_insync.objects.Execution attribute), 67 tree() (in module ib_insync.util), 82
time (ib_insync.objects.ExecutionFilter attribute), 69 triggerMethod (ib_insync.order.Order attribute), 34
time (ib_insync.objects.Fill property), 78 triggerMethod (ib_insync.order.PriceCondition at-
time (ib_insync.objects.HistoricalNews property), 79 tribute), 44
time (ib_insync.objects.HistoricalTick property), 76 triggerPrice (ib_insync.order.Order attribute), 36
time (ib_insync.objects.HistoricalTickBidAsk property), tuple() (ib_insync.contract.Bag method), 56
76 tuple() (ib_insync.contract.Bond method), 54
time (ib_insync.objects.HistoricalTickLast property), 76 tuple() (ib_insync.contract.CFD method), 53
time (ib_insync.objects.MktDepthData property), 77 tuple() (ib_insync.contract.ComboLeg method), 57
time (ib_insync.objects.RealTimeBar attribute), 70 tuple() (ib_insync.contract.Commodity method), 54
time (ib_insync.objects.TickByTickAllLast property), 77 tuple() (ib_insync.contract.ContFuture method), 52
time (ib_insync.objects.TickByTickBidAsk property), 77 tuple() (ib_insync.contract.Contract method), 49
time (ib_insync.objects.TickByTickMidPoint property), tuple() (ib_insync.contract.ContractDescription
77 method), 60
time (ib_insync.objects.TickData property), 76 tuple() (ib_insync.contract.ContractDetails method),
time (ib_insync.objects.TradeLogEntry attribute), 74 59
time (ib_insync.order.TimeCondition attribute), 44 tuple() (ib_insync.contract.Crypto method), 56
time (ib_insync.ticker.Bar attribute), 65

140 Index
ib_insync, Release 0.9.70

tuple() (ib_insync.contract.DeltaNeutralContract tuple() (ib_insync.order.TimeCondition method), 44


method), 58 tuple() (ib_insync.order.Trade method), 43
tuple() (ib_insync.contract.Forex method), 52 tuple() (ib_insync.order.VolumeCondition method), 46
tuple() (ib_insync.contract.Future method), 51 tuple() (ib_insync.ticker.Ticker method), 64
tuple() (ib_insync.contract.FuturesOption method), 55 TWS_CONFIG_PATH (ib_insync.ibcontroller.IBController
tuple() (ib_insync.contract.Index method), 53 attribute), 87
tuple() (ib_insync.contract.MutualFund method), 55 TWS_MAJOR_VRSN (ib_insync.ibcontroller.IBController
tuple() (ib_insync.contract.Option method), 50 attribute), 87
tuple() (ib_insync.contract.ScanData method), 60 TWS_PATH (ib_insync.ibcontroller.IBController at-
tuple() (ib_insync.contract.Stock method), 50 tribute), 87
tuple() (ib_insync.contract.Warrant method), 55 TWSPASSWORD (ib_insync.ibcontroller.IBController
tuple() (ib_insync.ibcontroller.IBC method), 86 attribute), 87
tuple() (ib_insync.ibcontroller.IBController method), twsPath (ib_insync.ibcontroller.IBC attribute), 86
88 twsSettingsPath (ib_insync.ibcontroller.IBC at-
tuple() (ib_insync.ibcontroller.Watchdog method), 90 tribute), 86
tuple() (ib_insync.objects.BarData method), 70 TWSUSERID (ib_insync.ibcontroller.IBController at-
tuple() (ib_insync.objects.CommissionReport method), tribute), 87
69 twsVersion (ib_insync.ibcontroller.IBC attribute), 86
tuple() (ib_insync.objects.DepthMktDataDescription
method), 73 U
tuple() (ib_insync.objects.Execution method), 68 underConId (ib_insync.contract.ContractDetails at-
tuple() (ib_insync.objects.ExecutionFilter method), 69 tribute), 58
tuple() (ib_insync.objects.HistogramData method), 72 underlyingConId (ib_insync.objects.OptionChain
tuple() (ib_insync.objects.HistoricalSchedule method), property), 79
75 underSecType (ib_insync.contract.ContractDetails at-
tuple() (ib_insync.objects.HistoricalSession method), tribute), 59
75 underSymbol (ib_insync.contract.ContractDetails
tuple() (ib_insync.objects.NewsProvider method), 72 attribute), 59
tuple() (ib_insync.objects.PnL method), 73 undPrice (ib_insync.objects.OptionComputation prop-
tuple() (ib_insync.objects.PnLSingle method), 74 erty), 79
tuple() (ib_insync.objects.RealTimeBar method), 70 unrealizedPnL (ib_insync.objects.PnL attribute), 73
tuple() (ib_insync.objects.ScannerSubscription unrealizedPnL (ib_insync.objects.PnLSingle attribute),
method), 67 74
tuple() (ib_insync.objects.SoftDollarTier method), 67 unrealizedPNL (ib_insync.objects.PortfolioItem prop-
tuple() (ib_insync.objects.TickAttrib method), 71 erty), 78
tuple() (ib_insync.objects.TickAttribBidAsk method), unreported (ib_insync.objects.TickAttribLast attribute),
71 71
tuple() (ib_insync.objects.TickAttribLast method), 72 unsubscribeFromGroupEvents()
tuple() (ib_insync.objects.TradeLogEntry method), 74 (ib_insync.client.Client method), 31
tuple() (ib_insync.order.ExecutionCondition method), update() (ib_insync.contract.Bag method), 56
45 update() (ib_insync.contract.Bond method), 54
tuple() (ib_insync.order.LimitOrder method), 38 update() (ib_insync.contract.CFD method), 53
tuple() (ib_insync.order.MarginCondition method), 45 update() (ib_insync.contract.ComboLeg method), 57
tuple() (ib_insync.order.MarketOrder method), 38 update() (ib_insync.contract.Commodity method), 54
tuple() (ib_insync.order.Order method), 37 update() (ib_insync.contract.ContFuture method), 52
tuple() (ib_insync.order.OrderComboLeg method), 42 update() (ib_insync.contract.Contract method), 49
tuple() (ib_insync.order.OrderCondition method), 43 update() (ib_insync.contract.ContractDescription
tuple() (ib_insync.order.OrderState method), 41 method), 60
tuple() (ib_insync.order.OrderStatus method), 40 update() (ib_insync.contract.ContractDetails method),
tuple() (ib_insync.order.PercentChangeCondition 60
method), 46 update() (ib_insync.contract.Crypto method), 56
tuple() (ib_insync.order.PriceCondition method), 44 update() (ib_insync.contract.DeltaNeutralContract
tuple() (ib_insync.order.StopLimitOrder method), 39 method), 58
tuple() (ib_insync.order.StopOrder method), 39 update() (ib_insync.contract.Forex method), 52

Index 141
ib_insync, Release 0.9.70

update() (ib_insync.contract.Future method), 51 update() (ib_insync.order.TimeCondition method), 44


update() (ib_insync.contract.FuturesOption method), update() (ib_insync.order.Trade method), 43
55 update() (ib_insync.order.VolumeCondition method),
update() (ib_insync.contract.Index method), 53 46
update() (ib_insync.contract.MutualFund method), 55 update() (ib_insync.ticker.Ticker method), 64
update() (ib_insync.contract.Option method), 50 updateDisplayGroup() (ib_insync.client.Client
update() (ib_insync.contract.ScanData method), 60 method), 31
update() (ib_insync.contract.Stock method), 50 updateReqId() (ib_insync.client.Client method), 29
update() (ib_insync.contract.Warrant method), 56 usePriceMgmtAlgo (ib_insync.order.Order attribute),
update() (ib_insync.ibcontroller.IBC method), 86 37
update() (ib_insync.ibcontroller.IBController method), useQt() (in module ib_insync.util), 83
88 userid (ib_insync.ibcontroller.IBC attribute), 86
update() (ib_insync.ibcontroller.Watchdog method), 90 useRTH (ib_insync.objects.BarDataList attribute), 80
update() (ib_insync.objects.BarData method), 70 useRTH (ib_insync.objects.RealTimeBarList attribute), 81
update() (ib_insync.objects.CommissionReport
method), 69 V
update() (ib_insync.objects.DepthMktDataDescription val (ib_insync.objects.SoftDollarTier attribute), 67
method), 73 validExchanges (ib_insync.contract.ContractDetails
update() (ib_insync.objects.Execution method), 68 attribute), 58
update() (ib_insync.objects.ExecutionFilter method), value (ib_insync.contract.TagValue property), 57
69 value (ib_insync.objects.AccountValue property), 76
update() (ib_insync.objects.HistogramData method), 72 value (ib_insync.objects.PnLSingle attribute), 74
update() (ib_insync.objects.HistoricalSchedule vega (ib_insync.objects.OptionComputation property),
method), 75 78
update() (ib_insync.objects.HistoricalSession method), verifyAndAuthMessage() (ib_insync.client.Client
75 method), 31
update() (ib_insync.objects.NewsProvider method), 72 verifyAndAuthRequest() (ib_insync.client.Client
update() (ib_insync.objects.PnL method), 73 method), 31
update() (ib_insync.objects.PnLSingle method), 75 verifyMessage() (ib_insync.client.Client method), 31
update() (ib_insync.objects.RealTimeBar method), 70 verifyRequest() (ib_insync.client.Client method), 30
update() (ib_insync.objects.ScannerSubscription volatility (ib_insync.order.Order attribute), 35
method), 67 volatilityType (ib_insync.order.Order attribute), 35
update() (ib_insync.objects.SoftDollarTier method), 67 volume (ib_insync.objects.BarData attribute), 70
update() (ib_insync.objects.TickAttrib method), 71 volume (ib_insync.objects.RealTimeBar attribute), 70
update() (ib_insync.objects.TickAttribBidAsk method), volume (ib_insync.order.VolumeCondition attribute), 46
71 volume (ib_insync.ticker.Bar attribute), 65
update() (ib_insync.objects.TickAttribLast method), 72 volume (ib_insync.ticker.Ticker attribute), 62
update() (ib_insync.objects.TradeLogEntry method), 74 VolumeCondition (class in ib_insync.order), 45
update() (ib_insync.order.ExecutionCondition method), volumeRate (ib_insync.ticker.Ticker attribute), 63
45 vwap (ib_insync.ticker.Ticker attribute), 62
update() (ib_insync.order.LimitOrder method), 38
update() (ib_insync.order.MarginCondition method), W
45
waitOnUpdate() (ib_insync.ib.IB method), 10
update() (ib_insync.order.MarketOrder method), 38
waitUntil() (ib_insync.ib.IB static method), 10
update() (ib_insync.order.Order method), 37
waitUntil() (in module ib_insync.util), 83
update() (ib_insync.order.OrderComboLeg method), 42
waitUntilAsync() (in module ib_insync.util), 83
update() (ib_insync.order.OrderCondition method), 43
wap (ib_insync.objects.RealTimeBar attribute), 70
update() (ib_insync.order.OrderState method), 41
warningText (ib_insync.order.OrderState attribute), 41
update() (ib_insync.order.OrderStatus method), 40
Warrant (class in ib_insync.contract), 55
update() (ib_insync.order.PercentChangeCondition
Watchdog (class in ib_insync.ibcontroller), 88
method), 46
whatIf (ib_insync.order.Order attribute), 36
update() (ib_insync.order.PriceCondition method), 44
whatIfOrder() (ib_insync.ib.IB method), 14
update() (ib_insync.order.StopLimitOrder method), 39
whatIfOrderAsync() (ib_insync.ib.IB method), 25
update() (ib_insync.order.StopOrder method), 39

142 Index
ib_insync, Release 0.9.70

whatToShow (ib_insync.objects.BarDataList attribute),


80
whatToShow (ib_insync.objects.RealTimeBarList at-
tribute), 81
whyHeld (ib_insync.order.OrderStatus attribute), 40

Y
yield_ (ib_insync.objects.CommissionReport attribute),
68
yieldRedemptionDate
(ib_insync.objects.CommissionReport at-
tribute), 68

Index 143

You might also like