Overall Statistics
#import clr
#import decimal as d
#import pandas as pd
#from Alphas.MacdAlphaModel import MacdAlphaModel

class MyStruggles(QCAlgorithm):

    def Initialize(self):
        
        self.contract = None

        self.SetStartDate(2021, 10, 25)    #Set Start Date
        self.SetEndDate(2021, 10,29)      #Set End Date
        self.SetCash(5000)             #Set Strategy Cash
        self.SetWarmUp(TimeSpan.FromDays(3)) # Set warm up
        # Subscribe and set our expiry filter for the futures chain
        futureHG = self.AddFuture(Futures.Metals.Copper, Resolution.Tick)
        futureHG.SetFilter(7, 182)
        
        self.macd = MovingAverageConvergenceDivergence(12, 26, 9, MovingAverageType.Exponential)
        self.PlotIndicator("MACD", True, self.macd, self.macd.Signal)


        
    def OnData(self, slice):
        
        for chain in slice.FutureChains:
            contracts = [contract for contract in chain.Value]
            if len(contracts) == 0:
                self.oi_contract = None
                self.macd = None
                break
            
            self.popularContracts = [contract for contract in chain.Value if contract.OpenInterest > 1000]
 
            if len(self.popularContracts) == 0:
                continue
            
            contract = sorted(self.popularContracts, key=lambda k : k.OpenInterest, reverse=True)
            self.liquidContract = contract
            
            # Set up consolidators.
            on512T = TickConsolidator(512)
            on512T.DataConsolidated += self.On512TData
            #self.SubscriptionManager.AddConsolidator(contract, self.On512TData)
           
    def On512TData(self, sender, bar):
        #self.macd = MovingAverageConvergenceDivergence(12, 26, 9, MovingAverageType.Exponential)
        self.RegisterIndicator(contract, self.macd, self.On512TData)
        
        if (self.macd.IsReady):#self.macd != None and self.macd.IsReady):
            if bar.Symbol == self.contract.Symbol:
                tolerance = 0.00
                signalDeltaPercent = (self.macd.Current.Value - self.macd.Signal.Current.Value)/self.macd.Fast.Current.Value
                
                if signalDeltaPercent < -tolerance:
                #if self.macd.Current.Value < 0
                #Go long
                    self.MarketOrder(symbol, 1)

                elif signalDeltaPercent > tolerance:
            #if self.macd.Current.Value > 0
            #Go short
                    self.MarketOrder(symbol, -1)
            
                else:
                    self.Liquidate
                    
            self.Debug(f"Last price: {data[symbol].LastPrice}")

        
        else:
            self.Log('MACDs not ready yet')