2026
Order Flow Analysis System
PythonConcurrencyasyncReal Time Programming
screener.py
...
self.reqTickByTickData(1, contract, "AllLast", 0, True)
self.reqTickByTickData(2, contract, "BidAsk", 0 , True)
def tickByTickAllLast(self, reqId, tickType, time, price, size, tickAttribLast : TickAttribLast, exchange, specialConditions):
with self.lock:
quote = self.quote_reqId_to_ticker[reqId]
side = classify_side(price, quote)
self.trade_socket.send_multipart([])
tick = msg.TradeTick(
symbol = self.allLast_reqId_to_ticker[reqId],
ts = time,
ts_received = python_time.time(),
price = price,
size = int(size),
bid_price = quote.bid,
ask_price = quote.ask,
exchange = exchange,
pastLimit = bool(tickAttribLast.pastLimit),
side = side,
unreported = bool(tickAttribLast.unreported),
special_conditions = specialConditions,
)
print(tick)
self.trade_socket.send_multipart([tick.symbol.encode('utf-8'), tick.SerializeToString()])
print("TICK BY TICK ALL LAST")
def tickByTickBidAsk(self, reqId: TickerId, time: TickerId, bidPrice: float, askPrice: float, bidSize: Decimal, askSize: Decimal, tickAttribBidAsk: TickAttribBidAsk):
with self.lock:
quote = self.quote_reqId_to_ticker[reqId]
quote.bid = bidPrice
quote.ask = askPrice
quote.bid_size = bidSize
quote.ask_size = askSize
quote.ts = time
def error(self, reqId: TickerId, errorTime: TickerId, errorCode: TickerId, errorString: str, advancedOrderRejectJson=""):
print(errorCode, errorString)
# client not connected error
if errorCode == 504 or errorCode == 502:
if not self.failed_to_connect:
# UNEXPECTED RUNNING ERRORS ALSO HAPPEN HERE
# self.pn.send_notif("@everyone ORDER MASTER ERROR: " + errorString)
with self.lock:
self.failed_to_connect = True
# contract not found
elif errorCode == 201:
# Order Rejected
pass
# Server Error
elif errorCode == 321:
if not self.server_error:
self.pn.send_notif("@everyone server error:"+ errorString)
with self.lock:
self.server_error = True
elif errorCode in (2104, 2107, 2158):
print(errorCode, errorString)
else:
self.pn.send_notif(str(errorCode) + " " + errorString)