Overall Statistics
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
from QuantConnect.Data.Market import TradeBar

### <summary>
### Using rolling windows for efficient storage of historical data; which automatically clears after a period of time.
### </summary>
### <meta name="tag" content="using data" />
### <meta name="tag" content="history and warm up" />
### <meta name="tag" content="history" />
### <meta name="tag" content="warm up" />
### <meta name="tag" content="indicators" />
### <meta name="tag" content="rolling windows" />
class RollingWindowAlgorithm(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(2019,10,1)  #Set Start Date
        self.SetEndDate(datetime.now())  #Set End Date
        self.SetCash(25000)           #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data
        self.AddEquity("TQQQ", Resolution.Minute)
        self.AddEquity("SQQQ", Resolution.Minute)
    
        # Creates a Rolling Window indicator to keep the 2 TradeBar
        self.windowtqqq = RollingWindow[TradeBar](2)    # For other security types, use QuoteBar
    
        
        #add tqqqrsi indicator in a rolling window
        self.tqqqrsi = self.RSI("TQQQ", 13)
        self.tqqqrsi.Updated += self.tqqqrsiUpdated
        self.tqqqrsirw = RollingWindow[IndicatorDataPoint](13)
        
        
        # create the 30-minutes data consolidator
        thirtyMinuteConsolidator = TradeBarConsolidator(timedelta(minutes=30))
        thirtyMinuteConsolidator.DataConsolidated += self.thirtyMinuteBarHandler
        
        
        # register the 30-minute consolidated bar data to automatically update the indicator
        self.RegisterIndicator("TQQQ", self.tqqqrsi, thirtyMinuteConsolidator)

        self.SubscriptionManager.AddConsolidator("TQQQ", thirtyMinuteConsolidator)
        
        
        #Sets the benchmark, brokerage model and warm up time
        self.SetBenchmark("TQQQ")
        self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage)
        self.SetWarmUp(13)


    def tqqqrsiUpdated(self, sender, updated):
        '''Adds updated values to rolling window'''
        self.tqqqrsirw.Add(updated)


    def OnData(self, data):
        pass
        
        
    def thirtyMinuteBarHandler(self, sender, consolidated):
        # Wait for windows to be ready.
        if not (self.tqqqrsirw.IsReady): return

        
        currtqqqrsi = self.tqqqrsirw[0]  # Current SMA had index zero.
        
        
        self.Log("currtqqqrsi: {0}".format(currtqqqrsi))