Overall Statistics
from datetime import datetime, timedelta
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Indicators")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
from QuantConnect.Data.Market import *
from QuantConnect.Data.Consolidators import *
class DataConsolidationAlgorithm(QCAlgorithm):

    def Initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
        self.SetStartDate(2016,1,1)  #Set Start Date
        self.SetEndDate(2016,1,20)   #Set End Date
        self.AddEquity("SPY", Resolution.Minute)
        self.macd = self.MACD("SPY", 12, 26, 9, MovingAverageType.Exponential, Resolution.Minute)
        
        thirtyMinuteConsolidator = TradeBarConsolidator(timedelta(minutes=30))
        thirtyMinuteConsolidator.DataConsolidated += self.ThirtyMinuteBarHandler
        
        self.SubscriptionManager.AddConsolidator("SPY", thirtyMinuteConsolidator)
        self.RegisterIndicator("SPY", self.macd, thirtyMinuteConsolidator)

    def ThirtyMinuteBarHandler(self, sender, bar):
        '''This is our event handler for our 30-minute trade bar defined above in Initialize(). So each time the consolidator produces a new 30-minute bar, this function will be called automatically. The sender parameter will be the instance of the IDataConsolidator that invoked the event '''
        #self.Debug(str(self.Time) + " " + str(bar))
        if not self.macd.IsReady: 
            return
        
        if self.Portfolio["SPY"].Quantity == 0 and self.macd.Current.Value > self.macd.Signal.Current.Value:  
        #if self.Portfolio["SPY"].Quantity == 0 and self.macd.Current.Value >0:  
                print("MACD VALUE :",self.macd.Current.Value)
                print("SIGNAL VALUE :",self.macd.Signal.Current.Value)
                self.Buy("SPY",100)
                
        elif self.Portfolio["SPY"].Quantity > 0 and self.macd.Current.Value < self.macd.Signal.Current.Value:
        #elif self.Portfolio["SPY"].Quantity > 0 and self.macd.Current.Value < 0:
                print("MACD VALUE :",self.macd.Current.Value)
                print("SIGNAL VALUE :",self.macd.Signal.Current.Value)
                self.Liquidate()        
                
        
        #self.Plot("Charting", "MACD",self.macd)        
        
    def OnData(self, data):
        pass