Hi !
Following tutorials, I wanted to implement a simple strategy: if a currency price declines: open a Long position with trailing SL. If it increases: open a Short positon with trailing SL.
Unfortunately only opening short positions works correctly. When I want to combine both rules, I receive this error:
object has no attribute 'Long' at OnData if self.Long is not None and self.Securities ["SPY"].Close > self.highestSPYPrice: at Python.Runtime.PythonException.ThrowLastAsClrException() at Python.Runtime.PyObject.Invoke(PyTuple args in main.py: line 40
I can't get my head around this error, as each trailing SL is just the opposite of the other one. Probably there is a minor mistake somewhere, which I can't detect on my own. Could you please help me with this?
# region imports
from AlgorithmImports import *
# endregion
class UpgradedYellowScorpion(QCAlgorithm):
stopMarketTicket = None
stopMarketOrderFillTime = datetime.min
highestSPYPrice = -1
def Initialize(self):
self.SetStartDate(2020, 1, 1)
self.SetEndDate(2022, 1, 1)
self.SetCash(10000)
spy = self.AddEquity("SPY" , Resolution.Daily)
spy.SetDataNormalizationMode(DataNormalizationMode.Raw)
self.Pair = "SPY"
self.symbols = [self.Pair]
self.prevPrices = { symbol : RollingWindow[TradeBar](7) for symbol in self.symbols }
def OnData(self, data):
for symbol in self.symbols:
if data.ContainsKey(symbol):
self.prevPrices[symbol].Add( data[symbol] )
if not all([ window.IsReady for window in self.prevPrices.values() ]):
return
Pair1_window = self.prevPrices[self.Pair]
Pair1_1D = Pair1_window[1].Close
Pair1_0D = Pair1_window[0].Close
# short position
if not self.Portfolio.Invested and Pair1_0D > Pair1_1D:
self.Short = self.MarketOrder("SPY", -1)
self.stopMarketTicket = self.StopMarketOrder("SPY", 1, 1.1 * self.Securities["SPY"].Close)
if self.Short is not None and self.Securities ["SPY"].Close < self.highestSPYPrice:
self.highestSPYPrice = self.Securities ["SPY"].Close
updateFields = UpdateOrderFields()
updateFields.StopPrice = self.highestSPYPrice * 1.1
self.stopMarketTicket.Update(updateFields)
# long position
if not self.Portfolio.Invested and Pair1_0D < Pair1_1D:
self.Long = self.MarketOrder("SPY", 1)
self.stopMarketTicket = self.StopMarketOrder("SPY", -1, 0.9 * self.Securities["SPY"].Close)
if self.Long is not None and self.Securities ["SPY"].Close > self.highestSPYPrice:
self.highestSPYPrice = self.Securities ["SPY"].Close
updateFields = UpdateOrderFields()
updateFields.StopPrice = self.highestSPYPrice * 0.9
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