ib-underscore-async-recipes.md
Collection of useful patterns, snippets and recipes.
When using the recipes in a notebook, don’t forget to use util.startLoop().
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 datetimefrom ib\_async import\*ib=IB()ib.connect('127.0.0.1',7497,clientId=1)contract=Stock('TSLA','SMART','USD')dt=''barsList=[]whileTrue:bars=ib.reqHistoricalData(contract,endDateTime=dt,durationStr='10 D',barSizeSetting='1 min',whatToShow='MIDPOINT',useRTH=True,formatDate=1)ifnotbars:breakbarsList.append(bars)dt=bars[0].dateprint(dt)# save to CSV fileallBars=[bforbarsinreversed(barsList)forbinbars]df=util.df(allBars)df.to\_csv(contract.symbol+'.csv',index=False)
allParams=ib.reqScannerParameters()print(allParams)sub=ScannerSubscription(instrument='FUT.US',locationCode='FUT.GLOBEX',scanCode='TOP\_PERC\_GAIN')scanData=ib.reqScannerData(sub)print(scanData)
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+=onScanDataib.sleep(60)ib.cancelScannerSubscription(scanData)
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)
eurusd=Forex('EURUSD')ticker=ib.reqMktDepth(eurusd)whileib.sleep(5):print([d.pricefordinticker.domBids],[d.pricefordinticker.domAsks])
usdjpy=Forex('USDJPY')cd=ib.reqContractDetails(usdjpy)[0]print(cd.marketRuleIds)rules=[ib.reqMarketRule(ruleId)forruleIdincd.marketRuleIds.split(',')]print(rules)
newsProviders=ib.reqNewsProviders()print(newsProviders)codes='+'.join(np.codefornpinnewsProviders)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)
ib.reqNewsBulletins(True)ib.sleep(5)print(ib.newsBulletins())
A Wall Street Horizon subscription is needed to get corporate event data.
from ib\_async import\*ib=IB()ib.connect('127.0.0.1',7497,clientId=1)# Get the conId of an instrument (IBM in this case):ibm=Stock('IBM','SMART','USD')ib.qualifyContracts(ibm)print(ibm.conId)# is 8314# Get the list of available filters and event types:meta=ib.getWshMetaData()print(meta)# For IBM (with conId=8314) query the:# - Earnings Dates (wshe\_ed)# - Board of Directors meetings (wshe\_bod)data=WshEventData(filter='''{ "country": "All", "watchlist": ["8314"], "limit\_region": 10, "limit": 10, "wshe\_ed": "true", "wshe\_bod": "true" }''')events=ib.getWshEventData(data)print(events)
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)
contract=Stock('IBM','SMART','USD')ticker=ib.reqMktData(contract,'258')ib.sleep(2)print(ticker.fundamentalRatios)
This IB socket protocol is designed to be used for a long-lived connection, lasting a day or so. For short connections, where for example just a few orders are fired of, it is best to add one second of delay before closing the connection. This gives the connection some time to flush the data that has not been sent yet.
ib=IB()ib.connect()...# create and submit some ordersib.sleep(1)# added delayib.disconnect()
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.
To integrate with the Tkinter event loop, take a look at this example app.
By calling ib.sleep from within the PyGame run loop, ib_async can periodically run for short whiles and keep up to date:
import ib\_async as ibiimport pygamedef onTicker(ticker):screen.fill(bg\_color)text=f'bid: {ticker.bid} ask: {ticker.ask}'quote=font.render(text,True,fg\_color)screen.blit(quote,(40,40))pygame.display.flip()pygame.init()screen=pygame.display.set\_mode((800,600))font=pygame.font.SysFont('arial',48)bg\_color=(255,255,255)fg\_color=(0,0,0)ib=ibi.IB()ib.connect()contract=ibi.Forex('EURUSD')ticker=ib.reqMktData(contract)ticker.updateEvent+=onTickerrunning=Truewhilerunning:# This updates IB-insync:ib.sleep(0.03)# This updates PyGame:foreventinpygame.event.get():ifevent.type==pygame.QUIT:running=Falsepygame.quit()