I can't seem to access the Top Of Book (Aka, level 1) data at a given instant with my code. 

The logs show that for each Bid/AskSize quote I receive, either the BidSize field or the Ask Size field is left empty. The tick only contains the most recent order and doesn't show the current best orders. Does anyone know how I can fix this and get access to the current Top Of Book data?
 

caleb-eldredge_1734538672.jpg
  1. from AlgorithmImports import *
  2. class BidAskImbalanceAlgorithm(QCAlgorithm):
  3. def Initialize(self):
  4. self.SetStartDate(2024, 6, 1) # Set Start Date
  5. self.SetEndDate(2024, 6, 10) # Set End Date
  6. self.SetCash(100000) # Set Strategy Cash
  7. self.symbol = self.AddEquity("AMD", Resolution.Tick).Symbol
  8. self.target_percentage = 0.25
  9. self.imbalance_threshold = 0.7
  10. def OnData(self, data):
  11. if self.symbol not in data.Ticks:
  12. return
  13. ticks = data.Ticks[self.symbol]
  14. for tick in ticks:
  15. if tick.TickType != TickType.Quote:
  16. continue
  17. bid_size = tick.BidSize
  18. ask_size = tick.AskSize
  19. total_size = bid_size + ask_size
  20. if total_size == 0:
  21. self.Debug(f"Total size is zero. Bid: {bid_size}, Ask: {ask_size}")
  22. continue
  23. bid_imbalance = bid_size / total_size
  24. self.Debug(f"BidSize: {bid_size}, AskSize: {ask_size}, Bid Imbalance: {bid_imbalance}")
  25. holdings = self.Portfolio[self.symbol].Quantity
  26. self.Debug(f"Current Holdings: {holdings}, Bid Imbalance: {bid_imbalance}")
  27. if bid_imbalance > self.imbalance_threshold and holdings <= 0:
  28. self.Debug("Entering a long position.")
  29. self.SetHoldings(self.symbol, self.target_percentage)
  30. elif bid_imbalance < self.imbalance_threshold and holdings > 0:
  31. self.Debug("Exiting the position.")
  32. self.Liquidate(self.symbol)
+ Expand

Author

Caleb Eldredge

December 2024