Here is some code that I wrote, it prints out a graph of historical data in your browser with plotly, see below. It is not what you asked for specifically but it can help with a template for someone completely lost.
To save data, as you have asked, initialise a list in the __init__()
function and then, with the correct function, here it is historicalData()
for me, save that data as it streams back to you from TWS by appending that initialised list.
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
import threading
import time
class IBapi(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
self.data = []
def historicalData(self, reqId, bar):
#print("Time: {} Close: {}".format(bar.date, bar.close))
self.data.append([bar.date, bar.open, bar.close, bar.low, bar.high])
def run_loop():
app.run()
app = IBapi()
app.connect('127.0.0.1', 7497, 123)
#Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()
time.sleep(1) #Sleep interval to allow time for connection to server
#Create contract object
eurusd_contract = Contract()
eurusd_contract.symbol = 'EUR'
eurusd_contract.secType = 'CASH'
eurusd_contract.exchange = 'IDEALPRO'
eurusd_contract.currency = 'USD'
#Request historical candles
app.reqHistoricalData(1, eurusd_contract, '', '2 D', '1 hour', 'BID', 0, 2, False, [])
time.sleep(5) #sleep to allow enough time for data to be returned
import pandas as pd
import matplotlib.pyplot as plt
import plotly.graph_objects as go
df = pd.DataFrame(app.data, columns=['DateTime','Open','Close','Low','High'])
df['DateTime'] = pd.to_datetime(df['DateTime'], unit='s')
df.to_csv('EURUSD_Hourly.csv')
fig = go.Figure(data=[go.Candlestick(x=df['DateTime'],
open=df['Open'],
high = df['High'],
low=df['Low'],
close=df['Close'])])
fig.show()
print(df)
app.disconnect()