In [1]:
from ib_insync import *
util.startLoop()
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=14)
Out[1]:
To get the earliest date of available bar data the "head timestamp" can be requested:
In [2]:
contract = Stock('TSLA', 'SMART', 'USD')
ib.reqHeadTimeStamp(contract, whatToShow='TRADES', useRTH=True)
Out[2]:
To request hourly data of the last 60 trading days:
In [3]:
bars = ib.reqHistoricalData(
contract,
endDateTime='',
durationStr='60 D',
barSizeSetting='1 hour',
whatToShow='TRADES',
useRTH=True,
formatDate=1)
In [4]:
bars[0]
Out[4]:
Convert the list of bars to a data frame and print the first and last rows:
In [5]:
df = util.df(bars)
display(df.head())
display(df.tail())
Instruct the notebook to draw plot graphics inline:
In [6]:
%matplotlib inline
Plot the close data
In [7]:
df.plot(y='close');
There is also a utility function to plot bars as a candlestick plot. It can accept either a DataFrame or a list of bars. Here it will print the last 100 bars:
In [8]:
util.barplot(bars[-100:], title=contract.symbol);
In [9]:
contract = Forex('EURUSD')
bars = ib.reqHistoricalData(
contract,
endDateTime='',
durationStr='900 S',
barSizeSetting='10 secs',
whatToShow='MIDPOINT',
useRTH=True,
formatDate=1,
keepUpToDate=True)
Replot for every change of the last bar:
In [10]:
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
def onBarUpdate(bars, hasNewBar):
plt.close()
plot = util.barplot(bars)
clear_output(wait=True)
display(plot)
bars.updateEvent += onBarUpdate
ib.sleep(10)
ib.cancelHistoricalData(bars)
In [11]:
def onBarUpdate(bars, hasNewBar):
print(bars[-1])
Then do the real request and connect the event handler,
In [12]:
bars = ib.reqRealTimeBars(contract, 5, 'MIDPOINT', False)
bars.updateEvent += onBarUpdate
let it run for half a minute and then cancel the realtime bars.
In [13]:
ib.sleep(30)
ib.cancelRealTimeBars(bars)
The advantage of reqRealTimeBars is that it behaves more robust when the connection to the IB server farms is interrupted. After the connection is restored, the bars from during the network outage will be backfilled and the live bars will resume.
reqHistoricalData + keepUpToDate will, at the moment of writing, leave the whole API inoperable after a network interruption.
In [14]:
ib.disconnect()
In [ ]: