I've done the Bootcamp lesson 'Buy and Hold with a trailing stop'. It is very clear and useful. But, it sets the trailing stop using the previous day's closing price. I want to create a variant in which the trailing stop is based on the intraday high price. I have been working on it for quite some time now, but have not been able to get that to work - though I suppose it cannot be all that hard. My attempts don't build correctly yet, so I couldn't attach a backtest.

Could anyone please give me some hints on how to change the example Bootcamp solution to minute time resolution? Thanks!


Link to Bootcamp page: Creating-a-Trailing-Stop-Loss

Bootcamp solution for daily time resolution, using previous closing price:


class BootCampTask(QCAlgorithm):

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

def Initialize(self):
self.SetStartDate(2018, 12, 1)
self.SetEndDate(2018, 12, 10)
spy = self.AddEquity("SPY", Resolution.Daily)

def OnData(self, data):

if (self.Time - self.stopMarketOrderFillTime).days < 15:

if not self.Portfolio.Invested:
self.MarketOrder("SPY", 500)
self.stopMarketTicket = self.StopMarketOrder("SPY", -500, 0.9 * self.Securities["SPY"].Close)


#1. Check if the SPY price is higher that highestSPYPrice.
if self.Securities["SPY"].Close > self.highestSPYPrice:

#2. Save the new high to highestSPYPrice; then update the stop price to 90% of highestSPYPrice
self.highestSPYPrice = self.Securities["SPY"].Close
updateFields = UpdateOrderFields()
updateFields.StopPrice = self.highestSPYPrice * 0.9

#3. Print the new stop price with Debug()
self.Debug("SPY: " + str(self.highestSPYPrice) + " Stop: " + str(updateFields.StopPrice))

def OnOrderEvent(self, orderEvent):
if orderEvent.Status != OrderStatus.Filled:
if self.stopMarketTicket is not None and self.stopMarketTicket.OrderId == orderEvent.OrderId:
self.stopMarketOrderFillTime = self.Time