I am trying to create a a program that buys SPY if it breaks out above the first 10 minute consolidated bar then has a trailing stop loss at 2%. However, I am getting the following error when I run it.

Runtime Error: AttributeError : 'NoneType' object has no attribute 'Update'
at OnData in main.py:line 37 :: self.stopMarketTicket.Update(updateFields)
AttributeError : 'NoneType' object has no attribute 'Update' (Open Stacktrace)

 

Here is my code

 

class Trial3(QCAlgorithm):

# Order ticket for our stop order, Datetime when stop order was last hit
stopMarketTicket = None
stopMarketOrderFillTime = datetime.min
highestPrice = 0
openingBar = None

def Initialize(self):
self.SetStartDate(2020, 5, 16)
self.SetEndDate(2020, 12, 10)
self.SetCash(100000)
spy = self.AddEquity("SPY", Resolution.Minute)
spy.SetDataNormalizationMode(DataNormalizationMode.Raw)
spy = self.Consolidate("SPY", timedelta(minutes=10), self.OnDataConsolidated)

def OnData(self, data):
if self.Portfolio.Invested or self.openingBar is None:
self.Debug("Part1")
return
if (self.Time - self.stopMarketOrderFillTime).days < 30:
self.Debug(self.Securities["SPY"].Price)
return
if self.openingBar.High < self.Securities["SPY"].Price:
self.MarketOrder("SPY", 50)
self.stopMarketTicket = self.StopMarketOrder("SPY", -50, 0.98 * self.Securities["SPY"].Close)
self.Debug("Part3")
if self.Securities["SPY"].Price > self.highestPrice:
self.Debug("Part4")
self.highestPrice = self.Securities["SPY"].Price
updateFields = UpdateOrderFields()
updateFields.StopPrice = self.highestPrice * 0.98
self.stopMarketTicket.Update(updateFields)
def OnOrderEvent(self, orderEvent):
if orderEvent.Status != OrderStatus.Filled:
return
if self.stopMarketTicket is not None and self.stopMarketTicket.OrderId == orderEvent.OrderId:
self.stopMarketOrderFillTime = self.Time
def OnDataConsolidated(self, bar):
if bar.Time.hour == 9 and bar.Time.minute == 30:
self.openingBar = bar

Could someone please explain the problem and how I would fix it? Thank you so much!