#!/usr/bin/env python # coding: utf-8 # In[1]: # Prepare environment import os, sys sys.path.insert(0, os.path.abspath('..')) from IPython.display import display from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" # ## Example starts here # ------ # In[2]: import asyncio from ibstract import IB from ibstract import MarketDataBlock from ibstract import HistDataReq from ibstract.utils import dtest, dtcst, dtutc # ### Instantiate IB and connect to Gateway/TWS # **When connecting to IB Gateway/TWS, an internal semaphore is acquired for up to 32 clients operating concurrently.** # In[3]: ib = IB('127.0.0.1', 4002) ib2 = IB() ib2.connect('127.0.0.1', 4002) print('ib connected? ', ib.connected) print('ib2 connected? ', ib2.connected) ib ib2 # ### HistDataReq - A request object for historical data # ** HistDataReq constructor signature: ** # HistDataReq(sectype, symbol, barsize, timedur, timeend=None, datatype='TRADES', exchange='SMART', currency='USD') # In[4]: req_list = [ HistDataReq('Stock', 'GS', '1 hour', '5 d', dtest(2017,9,12,12)), HistDataReq('Stock', 'BAC', '1 day', '10 d'), # timeend=None means datetime.now(tz=pytz.utc) HistDataReq('Stock', 'AMZN', '1 hour', '3 d', dtest(2017, 9, 12)), HistDataReq('Stock', 'GOOG', '30 mins', '3 d', dtutc(2017, 9, 12, 23)), HistDataReq('Stock', 'FB', '10 mins', '5 d', dtest(2017, 9, 12, 16)), HistDataReq('Stock', 'TVIX', '5 mins', '5 d', dtcst(2017, 9, 12, 16)), ] for req in req_list: req # ### Download data from IB requested by a HistDataReq # ** Request contract details for a HistDataReq by the coroutine IB.hist_data_req_contract_details(). ** # In[5]: req = HistDataReq('Stock', 'GS', '1 hour', '5 d', dtest(2017,9,12,12)) loop = asyncio.get_event_loop() contract_details_list = loop.run_until_complete(ib.hist_data_req_contract_details(req)) contract_details_list # ** The coroutine IB.hist_data_req_timezone() downloads the exchange time zone for the requested security. ** # In[6]: req = HistDataReq('Stock', 'GS', '1 hour', '5 d', dtest(2017,9,12,12)) loop = asyncio.get_event_loop() xchg_tz = loop.run_until_complete(ib.hist_data_req_timezone(req)) xchg_tz # ** The coroutine IB.get_hist_data_async(*reqs) downloads historical data for one or multiple HistDataReqs concurrently, and output a list of MarketDataBlock instances in the order of input requests.** # In[7]: loop = asyncio.get_event_loop() blk_list = loop.run_until_complete(ib.req_hist_data_async(*req_list[:3])) for blk in blk_list: blk.df.head() # #### A blocking function IB.get_hist_data() is also available without using asyncio event loop. It drives the coroutine version internally. # In[8]: req = HistDataReq('Stock', 'GS', '1 hour', '5 d', dtest(2017,9,12,12)) blk = ib.req_hist_data(req)[0] blk