#!/usr/bin/env python # coding: utf-8 # # Bar data # In[1]: from ib_insync import * util.startLoop() ib = IB() ib.connect('127.0.0.1', 7497, clientId=14) # ## Historical data # 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) # 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] # 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]: get_ipython().run_line_magic('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); # ## Historical data with realtime updates # # A new feature of the API is to get live updates for historical bars. This is done by setting `endDateTime` to an empty string and the `keepUpToDate` parameter to `True`. # # Let's get some bars with an keepUpToDate subscription: # 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) # Realtime bars # ------------------ # # With ``reqRealTimeBars`` a subscription is started that sends a new bar every 5 seconds. # # First we'll set up a event handler for bar updates: # 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[ ]: