I have reviewed the OnOrderEvent documentation and - at least for me - it isn't quite clear how to reference the filled order data in the algorithm. If the algorithm logic dictates taking a long position, and the associated trailing stop-loss is hit, I do not want to re-enter long, rather, I want to wait until the indicator dictates taking a short position to trade again (and vice versa). To do this, I need to reference the most recent order ticket filled quantity as a short cover will be >0 and a long cover will be <0. Any suggestions?
The code below is a mashup of the ‘Trailing Stop Loss’ and ‘MACD Simplified’ templates provided by Quantconnect:
class MACDTrendAlgorithm(QCAlgorithm):
stopMarketTicket = None
stopMarketOrderFillTime = datetime.min
stopLoss = 0
fill_quantity = 0
def Initialize(self):
#algorith basics setup
self.SetStartDate(2018, 1, 1)
self.SetEndDate(2021, 10, 22)
self.SetCash(25000)
self.stock = self.AddEquity("TQQQ", Resolution.Minute)
# self.stock.SetDataNormalizationMode(DataNormalizationMode.Raw)
self.symbol = self.stock.Symbol
#indicator setup
self.macd = self.MACD(self.symbol, 6, 35, 6, MovingAverageType.Exponential, Resolution.Daily)
self.PlotIndicator("MACD", True, self.macd, self.macd.Signal)
self.PlotIndicator("TQQQ", self.macd.Fast, self.macd.Slow)
self.SetWarmUp(5*41, Resolution.Daily)
#risk-management setup
#self.SetRiskManagement(MaximumDrawdownPercentPerSecurity(0.10))
def OnData(self, data):
if self.IsWarmingUp or not self.macd.IsReady: return
tolerance = 0.0025
holdings = self.Portfolio[self.symbol].Quantity
signalDeltaPercent = (self.macd.Current.Value - self.macd.Signal.Current.Value)/self.macd.Fast.Current.Value
#if not invested, but previously was invested and stop loss was triggered, wait until signal flips to take position
if holdings <= 0 and signalDeltaPercent > tolerance and fill_quantity > 0: #need to add OnOrderEvent.FillQuantity logic to check for stop loss trigger
self.SetHoldings(self.symbol, 1.0)
self.stopMarketTicket = self.StopMarketOrder(self.stock, -self.Portfolio[self.stock].Quantity, 0.9 * self.Securities[self.stock].Close)
elif holdings >= 0 and signalDeltaPercent < -tolerance and fill_quantity < 0: #need to add OnOrderEvent.FillQuantity logic to check for stop loss trigger
self.SetHoldings(self.symbol, -1.0)
self.stopMarketTicket = self.StopMarketOrder(self.stock, self.Portfolio[self.stock].Quantity, 0.9 * self.Securities[self.stock].Close)
#if not invested, but previously was invested and stop loss wasn't triggered, flip position
elif holdings <= 0 and signalDeltaPercent > tolerance:
self.Liquidate()
self.SetHoldings(self.symbol, 1.0)
self.stopMarketTicket = self.StopMarketOrder(self.stock, -self.Portfolio[self.stock].Quantity, 0.9 * self.Securities[self.stock].Close)
elif holdings >= 0 and signalDeltaPercent < -tolerance:
self.Liquidate()
self.SetHoldings(self.symbol, -1.0)
self.stopMarketTicket = self.StopMarketOrder(self.stock, self.Portfolio[self.stock].Quantity, 0.9 * self.Securities[self.stock].Close)
#trailing stop loss logic if position is long
if self.Porfolio[self.stock] > 0 and self.Securities[self.stock].Close > self.stopLoss:
self.stopLoss = self.Securities[self.stock].Close
updateFields = UpdateOrderFields()
updateFields.StopPrice = self.stopLoss * 0.95
self.stopMarketTicket.Update(updateFields)
self.Debug("SPY: " + str(self.stopLoss) + " Stop: " + str(updateFields.StopPrice))
#trailing stop loss logic if position is short
elif self.Porfolio[self.stock] < 0 and self.Securities[self.stock].Close < self.stopLoss:
self.stopLoss = self.Securities[self.stock].Close
updateFields = UpdateOrderFields()
updateFields.StopPrice = self.stopLoss * 0.95
self.stopMarketTicket.Update(updateFields)
self.Debug("SPY: " + str(self.stopLoss) + " Stop: " + str(updateFields.StopPrice))
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
fill_quantity = self.Securities[self.stock].FillQuantity
Varad Kabade
Hi James,
Thank you for your patience.
We have found some bugs in the code snippet that are out of the scope of your question. We have fixed the bugs and you can find a working example below. If you have further questions, please let us know.
Best,
Varad Kabade
James Hawkins
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!