Reputation: 11
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!
Upvotes: 0
Views: 132