0
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract 
import matplotlib.pyplot as plt
import pandas as pd
import threading
import time
import datetime


        
class IBapi(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        self.data = []

    def error(self, reqId, errorCode, errorString):
        print("Error: ", reqId, " ", errorCode, " ", errorString)
    
    def updateMktDepth(self, reqId, position: int, operation: int,
                       side: int, price: float, size):
        global df
        super().updateMktDepth(reqId, position, operation, side, price, size)
        self.data.append([reqId, position, operation, side, price, size])
        print("UpdateMarketDepth. ReqId:", reqId, "Position:", position, "Operation:",
              operation, "Side:", side, "Price:", price, "Size:", size) 
        
class DisconnectWrapper(EWrapper):
    def __init__(self):
        EWrapper.__init__(self)
        
    def error(self, reqId, errorCode, errorString):
        print(f"Error: {reqId} {errorCode} {errorString}")
        
        
def run_loop():
    app.run()

app = IBapi()
app.connect('127.0.0.1', 7497, 13217)

times = datetime.datetime.now()

cols = ['Time','ReqId','Position','Operation','Side','Price','Size']
data = [time,reqId,position,operation,side,price,size]
    
d2 = pd.DataFrame(data, cols)
d2 = d2.T
df = df.append(d2)
# df.to_csv(csv_file)

#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
contract = Contract()
contract.symbol = "SPY"
contract.secType = "STK"
contract.exchange = "ARCA"
contract.currency = "USD"

#Request Market Depth
app.reqMktDepth(1, contract, 5, False, [])

# plt.plot(df["Price"])

time.sleep(5) #sleep to allow enough time for data to be returned

client = EClient(DisconnectWrapper())
client.disconnect()
app.disconnect()

I have been attempting to organize the data received by updateMktDepth into a pandas dataframe, the data prints in the console just fine. But i cant get it into the dataframe.

Here is the error im getting:

File C:\Program Files\Spyder\pkgs\spyder_kernels\py3compat.py:356 in compat_exec exec(code, globals, locals)

File c:\users\equipo\desktop\programming finance\api tws\python\requesting live data market depth of an exchange.py:45 data = [time,reqId,position,operation,side,price,size]

NameError: name 'reqId' is not defined

Thanks!

beaker
  • 16,331
  • 3
  • 32
  • 49
Scieoner
  • 11
  • 1
  • 6
  • It should be app.reqId... but reqId isn't even defined in class IBapi. – Ori Yarden PhD Mar 03 '23 at 18:20
  • @OriYarden Hi! you mean define reqID in the following line? and define as reqId: int?: def updateMktDepth(self, reqId, position: int, operation: int, side: int, price: float, size): And it should be app.reqId in which line?? Thanks!!! – Scieoner Mar 04 '23 at 18:46
  • In the variable data all of its contents (i.e. [time,reqId,position,operation,side,price,size]) are missing. These need to be defined, I'm guessing you copied/pasted this code from somewhere so you should go back to the source and find out. – Ori Yarden PhD Mar 07 '23 at 19:01

0 Answers0