In [1]:
import ib_insync
print(ib_insync.__all__)
In [2]:
from ib_insync import *
util.startLoop()
Note that startLoop() only works in notebooks, not in regular Python programs.
In [3]:
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=10)
Out[3]:
If the connection failed, then verify that the application has the API port enabled and double-check the hostname and port. For IB Gateway the default port is 4002. Make sure the clientId is not already in use.
If the connection succeeded, then ib will be synchronized with TWS/IBG. The "current state" is now available via methods such as ib.positions(), ib.trades(), ib.openTrades(), ib.accountValues() or ib.tickers(). Let's list the current positions:
In [4]:
ib.positions()
Out[4]:
Or filter the account values to get the liquidation value:
In [5]:
[v for v in ib.accountValues() if v.tag == 'NetLiquidationByCurrency' and v.currency == 'BASE']
Out[5]:
The "current state" will automatically be kept in sync with TWS/IBG. So an order fill will be added as soon as it is reported, or account values will be updated as soon as they change in TWS.
Contracts can be specified in different ways:
Some examples:
In [6]:
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');
In [7]:
contract = Stock('TSLA', 'SMART', 'USD')
ib.reqContractDetails(contract)
Out[7]:
Doing a request involves network traffic going up and down and can take considerable time. The current state on the other hand is always immediately available. So it is preferable to use the current state methods over requests. For example, use ib.openOrders() in preference over ib.reqOpenOrders(), or ib.positions() over ib.reqPositions(), etc:
In [8]:
%time l = ib.positions()
In [9]:
%time l = ib.reqPositions()
In [10]:
util.logToConsole()
To see all debug messages (including network traffic):
In [11]:
import logging
util.logToConsole(logging.DEBUG)
In [12]:
ib.disconnect()