Overall Statistics
from QuantConnect.Data.Market import TradeBar
from datetime import timedelta
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
import decimal as d 

class MyAlgorithm(QCAlgorithm):
    def Initialize(self):
       
        self.SetStartDate(2015,05,1) #Set Start Date
        self.SetEndDate(2015,07,19)
        self.SetCash(100000) #Set Strategy Cash
        self.AddEquity("SPY", Resolution.Second)

        consolidator = TradeBarConsolidator(timedelta(1))
        consolidator.DataConsolidated += self.OnDailyData
        self.SubscriptionManager.AddConsolidator("SPY", consolidator)
        
        consolidatorm = TradeBarConsolidator(60)
        consolidatorm.DataConsolidated += self.OnMinuteData
        self.SubscriptionManager.AddConsolidator("SPY", consolidatorm)

        self.daily = RollingWindow[TradeBar](2)
        self.minute = RollingWindow[TradeBar](2)
        self.window = RollingWindow[TradeBar](2)
        
        self.Schedule.On(self.DateRules.EveryDay(),  
                 self.TimeRules.At(9, 31, 01),  
                 Action(self.One))

    # Add daily bar to daily rolling window
    def OnDailyData(self, sender, bar):
        self.daily.Add(bar)
        
    def OnMinuteData(self, sender, bar):
        self.minute.Add(bar)
      
    def One(self):
        if not (self.window.IsReady and self.daily.IsReady and self.minute.IsReady): return
        currBar = self.window[0].Close
        yesterdayClose = self.daily[0].Close
        minuteBarClose = self.minute[0].Close
        minuteBarOpen = self.minute[0].Open
        if not self.Portfolio.Invested and currBar < yesterdayClose and minuteBarOpen < minuteBarClose:
            self.SetHoldings("SPY", 1)
        if not self.Portfolio.Invested and currBar > yesterdayClose and minuteBarOpen > minuteBarClose:
            self.SetHoldings("SPY", -1)

    def OnData(self, data):
        if data["SPY"] is None: 
         return
        self.window.Add(data["SPY"]) 
        if not (self.window.IsReady):
         return
        factor = d.Decimal(1.01)
        currBar = self.window[0].Close
        if self.Portfolio["SPY"].AveragePrice *factor< currBar:
            self.SetHoldings("SPY", 0)