Overall Statistics
Total Trades
2
Average Win
0.96%
Average Loss
0%
Compounding Annual Return
0.286%
Drawdown
2.500%
Expectancy
0
Net Profit
0.964%
Sharpe Ratio
0.173
Probabilistic Sharpe Ratio
4.932%
Loss Rate
0%
Win Rate
100%
Profit-Loss Ratio
0
Alpha
0.001
Beta
0.012
Annual Standard Deviation
0.014
Annual Variance
0
Information Ratio
-0.777
Tracking Error
0.198
Treynor Ratio
0.213
Total Fees
$2.19
Estimated Strategy Capacity
$1900.00
class NadionResistanceShield(QCAlgorithm):



#class DataConsolidationAlgorithm(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2018, 1, 1)  # Set Start Date
        #self.SetEndDate(2020, 1, 1)
        self.SetCash(25000)  # Set Strategy Cash
        #self.tickers =  [ "TECL", "CURE", "FAS", "DRN", "NRGU", "NAIL", "RETL", "TPOR", "UTSL", "PBJ", "EWCO","ARKG", "OGIG", "TAN", "JETS", "GUSH", "VYM", "VOO", "THCF", "BLOK", "IVES", "BOTZ"] 
        self.tickers =  [ "OGIG"]
        self.symbolDataBySymbol = {}
        self.trade = True
        self.atr=[]
        self.ordered = 0

        self.MarketCaps = ["IWM", "MDY", "SPY", "QQQ"]  
        self.marketDataBySymbol = {}
        
   
        self.spy = "spy"
        
        for ticker_mark in self.MarketCaps:
            symbol = self.AddEquity(ticker_mark, Resolution.Daily).Symbol
            
            sma50 = self.SMA(symbol, 50, Resolution.Daily, Field.Close)
            sma200 = self.SMA(symbol, 200, Resolution.Daily, Field.Close)
        
            self.marketDataBySymbol[symbol] = symbolMarkData(symbol, sma50, sma200)
        
        
        
        for symbol in self.tickers:
            self.AddEquity(symbol, Resolution.Hour)
            
            '''For the below 3 EMA's, you can convert them to 4H bars using the colidator method'''
            
            ema10 = self.EMA(symbol, 10, Resolution.Hour, Field.Close)
            sma200 = self.SMA(symbol, 200, Resolution.Daily, Field.Close)
            sma7 = self.SMA(symbol, 7, Resolution.Hour, Field.Close)
            sma20 = self.SMA(symbol, 20, Resolution.Daily, Field.Close)
            sma50 = self.SMA(symbol, 50, Resolution.Daily, Field.Close)
            ema20 = self.EMA(symbol, 20, Resolution.Hour, Field.Close)
            ema50 = self.EMA(symbol, 50, Resolution.Hour, Field.Close)
            rsi = self.RSI(symbol, 14, Resolution.Daily)
            wilr = self.WILR(symbol, 14, Resolution.Daily)
            wilr_fast = self.WILR(symbol, 10, Resolution.Daily)
            atr = self.ATR(symbol, 20, Resolution.Daily)
            self.atr.append(self.ATR(symbol, 2, Resolution.Daily))
            
            # Set Boilinger Bands
            self.bb = self.BB(symbol, 100, 1, MovingAverageType.Exponential, Resolution.Daily)

            '''Consolidator method'''
            smaConsolidate = ExponentialMovingAverage(20, MovingAverageType.Simple)
            # create the 4 hour data consolidator
            fourHourConsolidator = TradeBarConsolidator(timedelta(hours=4))
            self.SubscriptionManager.AddConsolidator(symbol, fourHourConsolidator)
            # register the 4 hour consolidated bar data to automatically update the indicator
            self.RegisterIndicator(symbol, smaConsolidate, fourHourConsolidator)
            
            #self.Schedule.On(self.DateRules.EveryDay(self.tickers), 
            #self.TimeRules.AfterMarketOpen(self.tickers, -5), 
              #  Action(self.beforeTheOpen))
            
            #atr_stop =  
            
            symbolData = SymbolData(symbol, ema10, sma20, sma200, sma7, sma50, ema20, ema50, rsi, wilr, wilr_fast, atr, smaConsolidate)
            self.symbolDataBySymbol[symbol] = symbolData
        
        
        
        self.spy = self.AddEquity("SPY", Resolution.Daily)
        
        # Before the open
        self.Schedule.On(self.DateRules.EveryDay("SPY"), 
                self.TimeRules.AfterMarketOpen("SPY", -5), 
                Action(self.beforeTheOpen))
        
        #set the following between 1 - 4 hours depending on buy frequency    
        self.Schedule.On(self.DateRules.EveryDay("SPY"),
                 self.TimeRules.Every(timedelta(hours=2)),
                 self.buySignals)
                 
        self.Schedule.On(self.DateRules.EveryDay("SPY"),
                 self.TimeRules.Every(timedelta(hours=2)),
                 self.sellSignals)
        
        #self.Schedule.On(self.DateRules.EveryDay("SPY"),
       #          self.TimeRules.Every(timedelta(hours=4)),
        #         self.stopLoss)
    
                 
        self.Schedule.On(self.DateRules.EveryDay("SPY"),
                 self.TimeRules.AfterMarketOpen("SPY"),
                 self.tradeStart)
                 
        self.Schedule.On(self.DateRules.EveryDay("SPY"),
                 self.TimeRules.BeforeMarketClose("SPY"),
                 self.tradeEnd)

        #self.AddRiskManagement(TrailingStopRiskManagementModel(0.02))
        self.SetWarmUp(timedelta(days=200))
    
    def beforeTheOpen(self):
            for i in range(len(self.tickers)):
                self.Log("ATR for SL: {0}".format(self.atr[i].Current.Value * 2))
                
                
                
    def OnEndOfDay(self):
        self.Plot("BB", "MiddleBand", self.bb.MiddleBand.Current.Value)
        self.Plot("BB", "UpperBand", self.bb.UpperBand.Current.Value)
        self.Plot("BB", "LowerBand", self.bb.LowerBand.Current.Value)
        #self.Plot("$", "Price", self.Securities[symbol].Current.Value)
        
    def tradeStart(self):
        self.trade = True

    def tradeEnd(self):
        self.trade = False
    
      

        
    def buySignals(self):
        if self.trade == False:
            return
        
        # Return if benchmark is below SMA
        for symbolmark, symbolmarkData in self.marketDataBySymbol.items():
            if (self.Securities[symbolmark].Close > symbolmarkData.sma200.Current.Value):
                return
        
        for symbol, symbolData in self.symbolDataBySymbol.items():
           
           #if not self.Portfolio[symbol].Invested and (self.Securities[symbol].Close < self.bb.LowerBand.Current.Value):
           if not self.Portfolio[symbol].Invested and (self.Securities[symbol].Close > self.bb.UpperBand.Current.Value):
           #elif not self.Portfolio[symbol].Invested and (self.Securities[symbol].Close > self.atr.value) and (symbolData.wilr.Value < symbolData.wilr_fast.Value)  :
                #self.MarketOrder(symbol, .2, self.Time)
                self.SetHoldings(symbol, .2, False, "Buy Signal")
               # self.Plot("Stock Plot", "Buy", order.Price)

     #           stop_price = self.Securities[symbol].Price - (self.atr.Current.Value * 2)
                
         #  elif (symbolData.rsi.Current.Value > 50):
          #      self.SetHoldings(symbol, .2, False, "Buy Signal")
                    
                
    def sellSignals(self):
        if self.trade == False:
            return
        for symbol, symbolData in self.symbolDataBySymbol.items():
            
           # if self.Portfolio[symbol].Invested and (self.Securities[symbol].Close > self.bb.UpperBand.Current.Value):
            if  self.Portfolio[symbol].Invested and (self.Securities[symbol].Close < self.bb.LowerBand.Current.Value):
                self.Liquidate(symbol, "Sell Signal")
                #self.stopLossTicket = self.StopMarketOrder(symbol, .2, self.Time)
                #self.Plot("Stock Plot", "Sell", order.Price)
            #elif self.Portfolio[symbol].Invested and (self.Securities[symbol].Close < stop_price):
           #     self.StopMarketOrder(symbol, .2, self.Securities[symbol].Close)
            #    self.Liquidate(symbol, "Sell Signal")
                # Update our trailing stop loss as necessary
                
    def stopLoss(self):
        if self.trade == False:
            return
        for symbol, symboldata in self.symbolDataBySymbol.items():
            if self.Portfolio[symbol].Invested and (self.Securities[symbol].Close < stop_price):
                self.Liquidate(symbol, "Sell Signal")
        

    def OnData(self, data):
        if self.trade == False:
            return
        
        self.window.Add(data[self.symbol])
        if not (data.ContainsKey("SPY") or self.BB.IsReady): return
    
            
        # 1. Plot the current SPY price to "Data Chart" on series "Asset Price"
        self.Plot("Data Chart", "Asset Price", data["SPY"].Close)

        if (self.Time - self.stopMarketOrderFillTime).days < 15:
            return

            
            #2. Plot the moving stop price on "Data Chart" with "Stop Price" series name
            self.Plot("Data Chart", "Stop Price", self.stopMarketTicket.Get(OrderField.StopPrice))
            
            for symbol, symbolData in self.symbolDataBySymbol.items():
                if self.Portfolio[symbol].Invested and self.Securities[symbol].Close > self.highestsymbolPrice:
                
                    self.highestSPYPrice = self.Securities[symbol].Close
                    updateFields = UpdateOrderFields()
                    updateFields.StopPrice = self.highestsymbolPrice - self.atr[i].Current.Value *2
                    self.stopMarketTicket.Update(updateFields) 

    def OnOrderEvent(self, orderEvent):
        if self.trade == False:
            return
        order = self.Transactions.GetOrderById(orderEvent.OrderId)
        if orderEvent.Status == OrderStatus.Filled: 
            self.Log("{0}: {1}: {2}".format(self.Time, order.Type, orderEvent))

        #THIS IS HOW I WANT TO SET THE STOP LOSS below:
        #for i in range(len(self.tickers)):
            #self.Log("ATR: {0}".format(self.Portfolio[i].Invested and (self.Securities[i].Close - self.atr[i].Current.Value *2)))
        
       

    def OnData(self, slice):
        pass

class symbolMarkData:
    def __init__(self, symbol, sma50, sma200):
        self.Symbol = symbol
        self.sma50 = sma50
        self.sma200 = sma200


class SymbolData:
    def __init__(self, symbol, ema10, sma20, sma50, sma200, sma7, ema20, ema50, rsi, wilr, wilr_fast, atr, smaConsolidate):
        self.Symbol = symbol
        self.ema10 = ema10
        self.sma20 = sma20
        self.sma50 = sma50
        self.sma200 = sma200
        self.sma7 = sma7
        self.ema20 = ema20
        self.ema50 = ema50
        self.rsi = rsi
        self.wilr = wilr
        self.wilr_fast = wilr_fast
        self.atr = atr
        #self.emaConsolidate = emaConsolidate
        self.smaConsolidate = smaConsolidate