class BBConsolidatorTest(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2020, 5, 1)
self.SetEndDate(2020, 6, 4)
self.SetCash(100000)
future = self.AddFuture(Futures.Indices.SP500EMini, Resolution.Minute)
future.SetFilter(lambda x: x.FrontMonth().OnlyApplyFilterAtMarketOpen())
self.symbol = None
self.BBIndicator = BollingerBands(20, 2, MovingAverageType.Simple)
self.BBUpperWindow = RollingWindow[float](4)
self.BBLowerWindow = RollingWindow[float](4)
self.RSIIndicator = RelativeStrengthIndex(10, MovingAverageType.Exponential)
self.RSIWindow = RollingWindow[float](4)
self.curr_contract = None
self.SetWarmUp(timedelta(days=30))
def OnData(self, slice):
for i, chain in enumerate(slice.FutureChains):
contracts = [contract for contract in chain.Value]
if len(contracts) > 0:
contract = contracts[0]
if self.curr_contract is not None and self.curr_contract != contract:
self.curr_contract = contracts[0]
self.BBIndicator.Reset()
self.BBUpperWindow.Reset()
self.BBLowerWindow.Reset()
self.RSIIndicator.Reset()
self.BBIndicator.Update(slice.Time, contract.LastPrice)
if self.BBIndicator.IsReady:
self.BBUpperWindow.Add(self.BBIndicator.UpperBand.Current.Value)
self.BBLowerWindow.Add(self.BBIndicator.LowerBand.Current.Value)
if self.RSIIndicator.IsReady:
self.RSIWindow.Add(self.RSIIndicator.Current.Value)
if self.symbol is not None:
price = self.Securities[self.symbol].Price
if not self.Portfolio.Invested:
if price < self.BBLowerWindow[0]:
if self.RSIWindow[0] > self.RSIWindow[1]:
self.MarketOrder(self.curr_contract, 1)
def OnSecuritiesChanged(self, changes):
if len(changes.RemovedSecurities) > 0:
if self.symbol is not None and self.consolidator is not None:
self.BBIndicator.Reset()
self.RSIIndicator.Reset()
self.symbol = changes.AddedSecurities[0].Symbol