0

I am a beginner user of the TWS API for Python and I have been trying to store the information provided by the API response into a variable. For example, saving the lows of the day of a stock at a given time, to use it as the auxiliar price of a stop loss. However, I have found this impossible.

I saw the previous question related to this here: IbPy: How to extract API response into a variable

The issue is that IbPy was the old TWS API Python Wrapper, which is not used anymore. In the answer provided there, it uses the class Downloader and the key function seems to be self.tws.register, but I am unable to find it in the new API for Python.

How to access that function? Any examples of code to make this work?

desertnaut
  • 57,590
  • 26
  • 140
  • 166
VV33
  • 11
  • 2

1 Answers1

0

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()
BigH
  • 340
  • 4
  • 6