In [1]:
%gui qt5
import datetime
from collections import defaultdict
import ibapi
from tws_async import TWSClientQt, iswrapper, util, Stock
util.logToConsole()
In [2]:
# sample application
class TWS(TWSClientQt):
def __init__(self):
TWSClientQt.__init__(self)
self._reqIdSeq = 0
self._histData = defaultdict(list)
def popHistData(self, reqId):
"""
Remove and return the historical data that was downloaded for the given reqId.
"""
return self._histData.pop(reqId)
@iswrapper
def tickPrice(self, reqId: int,
tickType: ibapi.ticktype.TickType,
price: float,
attrib: ibapi.common.TickAttrib):
print('{} price {}'.format(reqId, price))
@iswrapper
def tickSize(self, reqId: int,
tickType: ibapi.ticktype.TickType,
size: int):
print('{} size {}'.format(reqId, size))
@iswrapper
def historicalData(self, reqId: int, date: str, open: float, high: float,
low: float, close: float, volume: int, barCount: int,
WAP: float, hasGaps: int):
self._histData[reqId].append((date, open, high, low, close, volume))
@iswrapper
def historicalDataEnd(self, reqId: int, start: str, end: str):
print('Historical request {} is finished'.format(reqId))
if 'tws' in locals():
tws.disconnect()
tws = TWS()
tws.connect('127.0.0.1', 7497, clientId=1)
In [3]:
# request historical bar data
contract = Stock('TSLA')
reqId = tws.getReqId()
tws.reqHistoricalData(reqId, contract,
endDateTime=datetime.datetime.utcnow().strftime('%Y%m%d %H:%M:%S UTC'),
durationStr='60 D',
barSizeSetting='1 hour',
whatToShow='TRADES',
useRTH=False,
formatDate=1,
chartOptions=None)
In [4]:
# fetch data when it's finished
data = tws.popHistData(reqId)
In [5]:
# process data
import pandas as pd
df = pd.DataFrame.from_records(data)
df.columns = ['datetime', 'open', 'high', 'low', 'close', 'volume']
df['datetime'] = pd.to_datetime(df['datetime'])
# df.set_index('datetime', inplace=True)
display(df.head())
display(df.tail())
In [6]:
# plot data
%matplotlib inline
import seaborn as sns
df.plot(y='close', figsize=(12,8))
Out[6]:
In [7]:
# subscribe to realtime tick data
reqId = tws.getReqId()
tws.reqMktData(reqId, contract, genericTickList='', snapshot=False,
regulatorySnapshot=False, mktDataOptions=[])
In [8]:
# cancel realtime ticks
tws.cancelMktData(reqId)
In [9]:
# asyncio integration
import asyncio
import quamash
async def coro(seconds):
print('starting coroutine...')
await asyncio.sleep(seconds)
print('coroutine finished')
loop = quamash.QEventLoop()
asyncio.set_event_loop(loop)
task = asyncio.ensure_future(coro(seconds=1))
# note that the Qt event loop doesn't need to be started as it's already running
In [ ]: