Okay I will have to check again on the async part, thanks for this group info, I will surely put a post there.
The part I'm not sure is that where do we build the dataframe, inside the TestWrapper class where the callbacks happen (that is where we print the data to the console) or inside the app function. Where exactly are we operating on the data? Within the app function or the TestWrapper class that we defined?
Was mucking around last time. Wonder if this helps. Under strategy class, define the method. Then below, add a prefix of req (check against official API page). I'm unfamiliar with order book depth stuff; you have to explore.
# Import necessary libraries
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from threading import Timer
import pandas as pd
import time
# Define strategy class - inherits from EClient and EWrapper
class Strategy(EClient, EWrapper):
# Initialize the class - and inherited classes
def __init__(self):
EClient.__init__(self, self)
self.df = pd.DataFrame(columns=['Time', 'Open', 'Close'])
# Receive historical bars from TWS
def historicalData(self, reqId, bar):
dictionary = {'Time':bar.date,'Open': bar.open, 'Close': bar.close}
self.df = self.df.append(dictionary, ignore_index=True)
print(f'Time: {bar.date}, Open: {bar.open}, Close: {bar.close}')
# Display a message once historical data is retreived
def historicalDataEnd(self, reqId, start, end):
print('\nHistorical Data Retrieved\n')
print(self.df.head())
# elf.df.to_csv('Historical_data.csv')
# -------------------------x-----------------------x---------------------------
# Create object of the strategy class
app = Strategy()
# Connect strategy to IB TWS
app.connect(host='127.0.0.1', port=7497, clientId=2)
print('Is application connected to IB TWS:', app.isConnected())
# Wait for sometime to connect to the server
time.sleep(1)
# Create object for contract
eurusd_contract = Contract()
eurusd_contract.symbol = 'EUR'
eurusd_contract.currency = 'USD'
eurusd_contract.secType = 'CASH'
eurusd_contract.exchange = 'IDEALPRO'
# Request for historical data
app.reqHistoricalData(reqId=33,
contract=eurusd_contract,
endDateTime='',
durationStr='300 S',
barSizeSetting='1 secs',
whatToShow='MIDPOINT',
useRTH=0,
formatDate=1,
keepUpToDate=False,
chartOptions=[])
# Invoke another thread that will disconnect the strategy from TWS
Timer(10, app.disconnect).start()
# Run the strategy
app.run()