Overall Statistics
from System import *
from QuantConnect import *
from QuantConnect.Data.Consolidators import *
from QuantConnect.Data.Market import *
from QuantConnect.Orders import OrderStatus
from QuantConnect.Algorithm import QCAlgorithm
from QuantConnect.Indicators import *
import numpy as np
from datetime import timedelta, datetime




### <summary>
### Example structure for structuring an algorithm with indicator and consolidator data for many tickers.
### </summary>
### <meta name="tag" content="consolidating data" />
### <meta name="tag" content="indicators" />
### <meta name="tag" content="using data" />
### <meta name="tag" content="strategy example" />
class MultipleSymbolConsolidationAlgorithm(QCAlgorithm):

    # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
    def Initialize(self):

        #self.SetStartDate(2014, 8, 1)
        self.SetStartDate(2020, 8, 3)

        # self.SetEndDate(2015, 2, 1)

        self.SetEndDate(datetime.now().date())
        self.SetCash(100000)  # Set Strategy Cash

        # This is the period of bars we'll be creating
        # Holds all of our data keyed by each symbol
        self.Data = {}
        self.daily = {}
        self.window = {}
        self.securities = []
        # consolidation_size = 24
        consolidation_size = 1440

        EquitySymbols = ["AAPL", "SPY", "IBM"]
        # Contains all of our forex symbols
        ForexSymbols = ["EURUSD", "USDJPY", "EURGBP", "EURCHF", "USDCAD", "USDCHF", "AUDUSD", "NZDUSD"]

        CryptoSymbols = ["BTCUSD", "ETHUSD", "LTCUSD", "BCHUSD", "XRPUSD", "BCHUSD", "XLMUSD", "EOSUSD", "REPUSD",
                         "XTZUSD", "ETCUSD", "ZRXUSD"]

 
        self.cryptosymbols = []
        for symbol in CryptoSymbols:
            crypto = self.AddCrypto(symbol, Resolution.Minute, Market.GDAX).Symbol
            self.securities.append(crypto)

            HourlyConsolidator = TradeBarConsolidator(consolidation_size)
            HourlyConsolidator.DataConsolidated += self.HourlyConsolidator
            self.SubscriptionManager.AddConsolidator(crypto, HourlyConsolidator)

            self.daily[crypto] = RollingWindow[TradeBar](3 * consolidation_size)
            self.window[crypto] = RollingWindow[TradeBar](3 * consolidation_size)
            self.cryptosymbols.append(crypto)
           
        self.equitysymbols = []    
        for symbol in EquitySymbols:
            equity = self.AddEquity(symbol, Resolution.Minute, Market.USA).Symbol
            self.equitysymbols.append(equity)
            HourlyConsolidator = TradeBarConsolidator(consolidation_size)
            HourlyConsolidator.DataConsolidated += self.HourlyConsolidator
            self.SubscriptionManager.AddConsolidator(equity, HourlyConsolidator)

            self.daily[crypto] = RollingWindow[TradeBar](3 * consolidation_size)
            self.window[crypto] = RollingWindow[TradeBar](3 * consolidation_size)
            self.equitysymbols.append(equity)
        
    #consolidates daily data for crypto so far        
    def HourlyConsolidator(self, sender, bar):
        self.daily[bar.Symbol].Add(bar)
        
       
    def OnData(self, data):

        # for symbol in self.securities:

        sell_len = 120
        buy_len = 180

        buy_ticks = list(range(0, buy_len))
        sell_ticks = list(range(0, sell_len))

        # solves issue of  wasn't found in the TradeBars object, likely because there was no-data at this moment in time and it wasn't possible to fillforward historical data
        if not all([data.Bars.ContainsKey(symbol) for symbol in self.cryptosymbols]):
            return

        
        for symbol in self.cryptosymbols:
            # self.Debug(symbol)
            if not data.ContainsKey(symbol):
                return
            # if not slice.Bars.ContainsKey(symbol):
            #     return
            self.window[symbol].Add(data.Bars[symbol])

            # Access bar properties from the `window`
            if not self.window[symbol].IsReady:
                continue
            latest_bar = self.window[symbol][0]
            close_of_latest_bar = latest_bar.Close
           

            close_lst = [self.window[symbol][0].Close, self.window[symbol][1].Close, self.window[symbol][120].Close]

            # Acessing previous bar properties from the daily bar
            previous_daily_bar = self.daily[symbol][1]
            close_of_previous_daily_bar = previous_daily_bar.Close
            high_of_previous_daily_bar = previous_daily_bar.High
            low_of_previous_daily_bar = previous_daily_bar.Low

          
            sell_dic = {}
            buy_dic = {}

            sell_len = []
            buy_len = []

            for num in buy_ticks:
                minute_bar = self.window[symbol][num]
                close_bar = minute_bar.Close
                buy_len.append(close_bar)
                # orders prices in chronological order left to right in the lst
            buy_dic[symbol] = buy_len[::-1]

            for num in sell_ticks:
                minute_bar = self.window[symbol][num]
                close_bar = minute_bar.Close
                sell_len.append(close_bar)
                # orders prices in chronological order left to right in the lst
            sell_dic[symbol] = sell_len[::-1]

        if not all([data.Bars.ContainsKey(symbol) for symbol in self.equitysymbols]):
            return
            
        for symbol in self.equitysymbols:
            # self.Debug(symbol)
            if not data.ContainsKey(symbol):
                return
          
            self.window[symbol].Add(data.Bars[symbol])

            #self.window[symbol].Add(data[symbol])

            # Access bar properties from the `window`
            if not self.window[symbol].IsReady:
                continue
            latest_bar = self.window[symbol][0]
            close_of_latest_bar = latest_bar.Close
        

            # 120 minutes--> sell signals
            # 180 minutes--> buy signals

            close_lst = [self.window[symbol][0].Close, self.window[symbol][1].Close, self.window[symbol][120].Close]


            # Acessing previous bar properties from the daily bar
            previous_daily_bar = self.daily[symbol][1]
            close_of_previous_daily_bar = previous_daily_bar.Close
            high_of_previous_daily_bar = previous_daily_bar.High
            low_of_previous_daily_bar = previous_daily_bar.Low
            
            sell_dic = {}
            buy_dic = {}

            sell_len = []
            buy_len = []

            for num in buy_ticks:
                minute_bar = self.window[symbol][num]
                close_bar = minute_bar.Close
                buy_len.append(close_bar)
                # orders prices in chronological order left to right in the lst
            buy_dic[symbol] = buy_len[::-1]

            for num in sell_ticks:
                minute_bar = self.window[symbol][num]
                close_bar = minute_bar.Close
                sell_len.append(close_bar)
                # orders prices in chronological order left to right in the lst
            sell_dic[symbol] = sell_len[::-1]