Overall Statistics
import pandas as pd
import numpy as np
import talib

class MyTestAlgo(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2017,8,1)
        
        self.stocks = ["SPY","AAPL"]
        for s in self.stocks:
            self.AddEquity(s)
        
        ##Run it everyday after 15 minutes of market open
        self.Schedule.On(self.DateRules.EveryDay(self.stocks), self.TimeRules.AfterMarketOpen(self.syl,15),Action(self.SetSignal))
        # History request using list of tickers
        hist = self.History(self.stocks, 100, Resolution.Minute)
        
        ##No idea how to turn hist dataframe into a dataframe with 5 minute resolution (with 5 minute ohlc info)
        
        # Check if returns an empty list. It should not.
        if hist.empty:
            self.Log(str(self.Time) + " empty hist")
            return
        
        self.Bolband = self.BB(self.stocks, 40, 3, MovingAverageType.Simple, Resolution.Minute)
    def SetSignal(self):    
        
        ##Create a binary column for the highest high in 15 bars
        ##Want to use pandas even if it can be done in other ways as i will do more manipulations in pandas
        window = 15
        hist['High15'] = df['high'].rolling(window=15,min_periods=5,center=False).max()
        hist['SignalBar'] = np.where(df['high'] > df['High20'].shift() , 1, 0).cumsum()
        
        ##If SignalBar = 1 in the last row of pandas hist dataframe, then buy with a stop order at the high of the current bar
        ##after the current bar finishes
        ##self.buypoint = hist['High15'].iloc[-1]
        
        ##If Current Bar's high is the highest high in 15 bars and it is within upper and lower bollinger band
        ##then place  a stop order to buy at the high of the current bar 5 seconds before the current bar finishes
        
    def OnOrderEvent(self, orderEvent):
        #self.Log(str(orderEvent))
        if orderEvent.Status != OrderStatus.Filled:
            return
        
        if self.entry_ticket is not None:
            # When entry order is filled, place TP and SL orders
            if orderEvent.OrderId == self.entry_ticket.OrderId:
                price = orderEvent.FillPrice
                self.LimitOrder(orderEvent.Symbol, -3, price + d.Decimal(0.04))
                self.StopMarketOrder(orderEvent.Symbol, -3, price - d.Decimal(0.03))
            
            ## as of every bar after trade entry edit the live profit taking limit order to upper band of bollinger band
            ##as of every bar after trade entry edit the live stop loss order to the lower band of bollinger band
            #upperband = self.Bolband.UpperBand.Current.Value
            #lowrband = self.Bolband.LowerBand.Current.Value
            
            # Otherwise, one of the exit orders was filled, so cancel the open orders
            else:
                self.Transactions.CancelOpenOrders(orderEvent.Symbol)
                self.entry_ticket = None