Overall Statistics
Total Trades
0
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Net Profit
0%
Sharpe Ratio
0
Probabilistic Sharpe Ratio
0%
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0
Beta
0
Annual Standard Deviation
0
Annual Variance
0
Information Ratio
0
Tracking Error
0
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
import numpy as np
from AlgorithmImports import *

class IntradayBreakout(QCAlgorithm):

    def Initialize(self):
        self.UniverseSettings.Resolution = Resolution.Minute
        self.SetStartDate(2021, 3, 14)
        self.SetEndDate(2022, 3, 16)
        self.SetWarmUp(timedelta(days = 1))
        self.resolution = Resolution.Minute
        
        self.SetCash(100000)
        self.SetTimeZone("America/New_York")
        self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)

        self.stopLossPercentLong = .995
        self.stopLossPercentLong2 = .985
        self.takeProfitPercentLong = 1.005
        self.takeProfitPercentLong2 = 1.005
       
        self.stopLossPercentShort = 1.005
        self.stopLossPercentShort2 = 1.0015
        self.takeProfitPercentShort = .995
        self.takeProfitPercentShort2 = .995
        
        
        
        
        self.symbolData = {}

        tickers = ["AAPL", "MSFT", "TSLA", "NVDA", "AMD",]
        for ticker in tickers:
            symbol = self.AddEquity(ticker).Symbol
            self.symbolData[symbol] = SymbolData(self, symbol)

        everyday = self.DateRules.EveryDay(symbol)
        
        self.Schedule.On(everyday, self.TimeRules.BeforeMarketClose(symbol, 10), self.Liquidate)
        
        
       
    
    def OnEndOfDay(self):
        
        for data in self.symbolData.values():
            data.longTrade = True
            data.shortTrade = True
   
    
    
    
    def OnData(self, slice):
       
       
       
        if not all([data.IsReady for data in self.symbolData.values()]):
            return
        
        for symbol, data in self.symbolData.items():
            if slice.Bars.ContainsKey(symbol):
                data.window10min.Add(slice.Bars[symbol])
                #####self.Debug(f'{symbol} test')
        
        
        if self.Time.hour >= 15 and self.Time.minute > 30:
            return
        
        
        for symbol, data in self.symbolData.items():
            price = self.Securities[symbol].Price
            ####important operation where things have been going wrong
            ##### for each symbol, this window should hold the 39 floats(not tradebars) representing the true range of 39 most recent consolidated 10 minute bars(390 min in a session/10), which I then then derive std deviation from, and multiply by 3
            stdbarDelta = (2 * (np.std(list([(x.High - x.Low) for x in data.windowonedayTradeBar]))))
            #self.Debug(f'{symbol} {stdbarDelta} test')
            
            
            if (data.smaVol10.Current.Value / data.smaVol390.Current.Value) > 3.0: 
                if data.window10min.IsReady:
                    windowDelta = data.window10min[0].Close - data.window10min[9].Open
                    ##### for each symbol, this window should hold the 39 floats(not tradebars) representing the true range of 39 most recent consolidated 10 minute bars(390 min in a session/10), which I then then derive the std deviation from, and multiply by 3
                    if windowDelta > stdbarDelta:
                        if data.longTrade: 
                           marketorderticket = self.SetHoldings(symbol, 0.15)
                           data.stopmarketorderticket = self.StopMarketOrder(symbol, -self.Portfolio[symbol].Quantity, price * self.stopLossPercentLong)
                           data.limitorderticket = self.LimitOrder(symbol, round(-self.Portfolio[symbol].Quantity / 2), price * self.takeProfitPercentLong)
                           data.longTrade = False
                    
        
        ##need to implement logic for shorts and convert high/low differential to absolute value
        '''for symbol, data in self.symbolData.items():
            price = self.Securities[symbol].Price
            stdbarDeltaShort = (-3 * np.std([x.High - x.Low for x in data.Bars.windowonedayTradeBar]))
            
            
            if (data.smaVol10.Current.Value / data.smaVol390.Current.Value) > 3.0:
                if  data.window10min.IsReady:
                    windowDelta = data.window10min[0].Close - data.window10min[9].Open
                    if windowDelta < data.std:
                        if data.shortTrade: 
                            marketorderticketshort = self.SetHoldings(symbol, -0.15)
                            data.stopmarketorderticketshort = self.StopMarketOrder(symbol, -self.Portfolio[symbol].Quantity, price * self.stopLossPercentShort)
                            data.limitorderticketshort = self.LimitOrder(symbol, round(-self.Portfolio[symbol].Quantity / 2), price * self.takeProfitPercentShort)
                            data.shortTrade = False'''
                  
              
               
            
            
    def OnOrderEvent(self, orderEvent):
        
        data = self.symbolData.get(orderEvent.Symbol, None)
        if not data or orderEvent.Status != OrderStatus.Filled:
            return
        
        for symbol, data in self.symbolData.items():
            price = self.Securities[symbol].Price
            
            if orderEvent.Status != OrderStatus.Filled:
                return
        
        
            if data.stopmarketorderticket != None and data.stopmarketorderticket.OrderId == orderEvent.OrderId:
                data.limitorderticket.Cancel()
                
                
            if data.limitorderticket != None and data.limitorderticket.OrderId == orderEvent.OrderId:
                data.stopmarketorderticket.Cancel()
                data.limitorderticket2 = self.LimitOrder(symbol, -self.Portfolio[symbol].Quantity, price * self.takeProfitPercentLong2)
                data.stopmarketorderticket2 = self.StopMarketOrder(symbol, -self.Portfolio[symbol].Quantity, price * self.stopLossPercentLong2)
                
                
            if data.limitorderticket2 != None and data.limitorderticket2.OrderId == orderEvent.OrderId:
                  data.stopmarketorderticket2.Cancel()  
                  
                  
            if data.stopmarketorderticket2 != None and data.stopmarketorderticket2.OrderId == orderEvent.OrderId:
                data.limitorderticket2.Cancel()
            
            
            
            if data.stopmarketorderticketshort != None and data.stopmarketorderticketshort.OrderId == orderEvent.OrderId:
                data.limitorderticketshort.Cancel()
               
                
            if data.limitorderticketshort != None and data.limitorderticketshort.OrderId == orderEvent.OrderId:
                data.stopmarketorderticketshort.Cancel()
                data.limitorderticketshort2 = self.LimitOrder(symbol, -self.Portfolio[symbol].Quantity, price * self.takeProfitPercentShort2)
                data.stopmarketorderticketshort2 = self.StopMarketOrder(symbol, -self.Portfolio[symbol].Quantity, price * self.stopLossPercentShort2)
                
                
            if data.limitorderticketshort2 != None and data.limitorderticketshort2.OrderId == orderEvent.OrderId:
                  data.stopmarketorderticketshort2.Cancel()  
                  
                  
            if data.stopmarketorderticketshort2 != None and data.stopmarketorderticketshort2.OrderId == orderEvent.OrderId:
                data.limitorderticketshort2.Cancel()
            


class SymbolData:
    def __init__(self, algorithm, symbol):
        
        # likely the problem area
        
        #ten minute bars for window
        tenMinuteConsolidator = TradeBarConsolidator(timedelta(minutes=10))
        self.subscribe = algorithm.SubscriptionManager.AddConsolidator(symbol, tenMinuteConsolidator)
        #window for 39 ten minute bars of consolidated minute data
        self.windowonedayTradeBar = RollingWindow[TradeBar](39)
        tenMinuteConsolidator.DataConsolidated += self.barHandler10min
        
        #most recent 10 minutes
        self.window10min = RollingWindow[TradeBar](10)
        
        
        
        self.smaVol390 = algorithm.SMA(symbol, 390, Resolution.Minute, Field.Volume)
        self.smaVol10 = algorithm.SMA(symbol, 10, Resolution.Minute, Field.Volume)
        
        
        self.longTrade = True
        self.shortTrade = True
        
        self.stopmarketorderticket = None
        self.stopmarketorderticket2 = None
        self.limitorderticket = None
        self.limitorderticket2 = None
        
        self.stopmarketorderticketshort = None
        self.stopmarketorderticketshort2 = None
        self.limitorderticketshort = None
        self.limitorderticketshort2 = None
        
    def barHandler10min(self, sender, updated):
        pass
        

       
    @property 
    def IsReady(self):
        
         return all
         ([windowonedayTradeBar.IsReady for window in self.windowonedayTradeBar.values()]) 
         #([atr.IsReady for atr in self.atr.values()])
         ([window10min.IsReady for window10 in self.window10min.values()])