Hi, I'm new to QuantConnect and I'm trying to implement a simple strategy to learn how the platform works. The strategy is to go long when the RSI is under 28, then either take profit or stop loss, then look for another trade opportunity and do it all over again. 

I understand that I should use LimitOrder for take profit and StopMarketOrder for the stop loss, however what my algorithm does is it buys 1 SPY, then it reaches the take profit level, it sells the 1 stake in SPY, and then it also executes the StopMarketOrder and sells one more stake. So at the end of the test period it's only done 3 trades and it's holding that last trade for the entire period.

I've to cancel the LimitOrder/StopMarketOrder when the other has been fulfilled, but that hasn't worked either.

I've been stuck on this for a week now, it there somethign that I'm missing?

This is my code:

class OptimizedCalibratedCompensator(QCAlgorithm):

def Initialize(self):
self.SetStartDate(2020, 3, 1) # Set Start Date
self.SetEndDate(2020,4,30) # set end date
self.SetCash(1000) # Set Strategy Cash
self._symbol = 'SPY'
self.AddEquity(self._symbol, Resolution.Minute)


# define a 14-period daily RSI indicator with shortcut helper method
self.rsi = self.RSI(self._symbol, 14, MovingAverageType.Simple, Resolution.Minute)
self.SetWarmUp(14, Resolution.Minute)

self.stopMarketTicket = None
self.orderTicket = None
self.limitOrderTicket = None

def OnData(self, data):
# check if this algorithm is still warming up
if self.Portfolio.Invested or not self.rsi.IsReady:


# get the current RSI value
rsi_value = self.rsi.Current.Value
entryprice = self.Securities[self._symbol].Close

if rsi_value < 28:
self.orderTicket = self.MarketOrder( self._symbol, 1)
self.limitOrderTicket = self.LimitOrder( self._symbol, -1, 1.001 * entryprice)
self.stopMarketTicket = self.StopMarketOrder( self._symbol, -1, 0.9993 * entryprice)

def OnOrderEvent(self, orderEvent):

if orderEvent.Status == OrderStatus.Filled and self.limitOrderTicket is not None and self.stopMarketTicket is not None :
if orderEvent.OrderId == self.limitOrderTicket.OrderId:
self.stopMarketTicket.Cancel('hit take profit')
elif orderEvent.OrderId == self.stopMarketTicket.OrderId:
self.limitOrderTicket.Cancel('hit stop loss')
self.Log("{0}: {1}".format(self.Time, orderEvent))