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 math
from QuantConnect.Statistics import *
from QuantConnect.Python import PythonQuandl
import numpy as np


class Squirtle(QCAlgorithm):

    def Initialize(self):
        
        self.SetStartDate(2021, 8, 1)
        self.SetEndDate(2021, 12, 21)
        self.SetCash(10000)  
        
        self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)
        
        #-- Variables
        self.exitPeriod = 10
        self.entryPeriod = 20
        self.resolution = Resolution.Daily
        self.predictionInterval = Time.Multiply(Extensions.ToTimeSpan(Resolution.Daily), self.entryPeriod)
        
        #-- Futures to trade. For loop subs each continuous contract
        futuresSymbols = [Futures.Metals.Gold, Futures.Indices.SP500EMini, Futures.Financials.EuroDollar]
        
        self.Data = {}
        for symbol in futuresSymbols:
            future = self.AddFuture(symbol, 
                                    Resolution.Minute, 
                                    dataNormalizationMode = DataNormalizationMode.BackwardsRatio,
                                    dataMappingMode = DataMappingMode.FirstDayMonth,
                                    contractDepthOffset = 0)
                         
        self.Schedule.On(self.DateRules.Every(DayOfWeek.Friday), self.TimeRules.At(12, 0), self.EveryFriAtNoon)
        
        #-- Debugging
        self.check = False
        self.x = 0
        
        #-- Live trading
        self.DefaultOrderProperties = InteractiveBrokersOrderProperties()
        self.DefaultOrderProperties.TimeInForce = TimeInForce.GoodTilCanceled
        self.DefaultOrderProperties.OutsideRegularTradingHours = False
        
        #-- Trade Builder
        tradeBuilder = TradeBuilder(FillGroupingMethod.FillToFill,FillMatchingMethod.FIFO)    
        self.SetTradeBuilder(tradeBuilder)

        self.SetWarmUp(120, Resolution.Daily)

    def EveryFriAtNoon(self):
        
        self.Debug(f"Fri at 12pm: {self.Time}")


    def OnData(self, data):
        
        if self.IsWarmingUp:
            return
        
        if self.check == True:
            return
        

        for symbol, symbolData in self.Data.items():
            
            price = self.Securities[symbolData.Symbol].Price
            
            security = self.Securities[symbolData.Symbol]
            
            breakoutUp = symbolData.LongEntry.Current.Value
            breakoutDown = symbolData.ShortEntry.Current.Value
            
            if self.x == 10000:
                self.Debug(f"Price: {price}, Period High: {breakoutUp}, Period Low: {breakoutDown}")
                self.x = 0
            else:
                self.x += 1
         

    #-- Checks if trad criteria are met   
    def greenLight(self, symbol):
        
        return True
    
    #-- Gets Trade size
    def getSize(self, price):
        
        return 1
      
    def OnOrderEvent(self, orderevent):
        
        self.previousPNL = None
        
        # check if orderevent is a fill
        if orderevent.Status == OrderStatus.Filled:
            
            
            
            symbol = orderevent.Symbol
            self.Debug(f"Order Filled: {symbol}")
            
            fillPrice = orderevent.FillPrice
            
            #-- Creates trade list to track P/L's for risk management
            tradeList = []
            for trade in self.TradeBuilder.ClosedTrades:
                tradeList.append(trade.ProfitLoss)
            
            #-- Showing in console previous trades P/L   
            #self.Debug(f" ")
            
            if tradeList:
                
                #-- Checks Weekly risk if Order Filled was to close a position 
                #--     by checking if that symbol is still in the portfolio
                if not self.Portfolio[trade.Symbol].Invested:
                
                    self.newestTrade = int(tradeList[-1])
                    
                    #-- Run previous trades PNL through weekly risk check
                    self.hitWeeklyRisk(self.newestTrade)
                    
                    #-- Print stats for trade and current targets in console
                    #self.Debug(f" ")
                    self.Debug(f"Entry Date: {trade.EntryTime}, Exit Date: {trade.ExitTime}")
                    self.Debug(f"Profit/Loss: {self.newestTrade}, Unit Size: {self.Unit}, N: {self.N}")
                    self.Debug(f"Losing Streak: {self.losingStreak}, Weekly Loss %: {self.weeklyLossPercent}")
                    self.Debug("---------------------------")
                #-- If the symbol for last Order Filled is still in the Portfolio, print opened trade
                else:
                    self.Debug("---------------------------")
                    self.Debug(f"Entered Position In {trade.Symbol}")
            else:
                #self.Debug(f"No Closed Trades Yet On {symbol}")
                return
            
    
                 
    def OnSecuritiesChanged(self, changes):
        
            for added in changes.AddedSecurities:
                symbolData = self.Data.get(added.Symbol)
                if symbolData is None:
                    
                    #-- Create high and low indicators
                    symbolData = SymbolData(added)
                    
                    #-- Creating Indicators
                    symbolData.ShortEntry = self.MIN(added.Symbol, self.entryPeriod)
                    symbolData.ShortExit = self.MAX(added.Symbol, self.exitPeriod)
                    symbolData.LongEntry = self.MAX(added.Symbol, self.entryPeriod)
                    symbolData.LongExit = self.MIN(added.Symbol, self.exitPeriod)
                    
                    
                    #-- Registering Indicators
                    self.RegisterIndicator(added.Symbol, symbolData.ShortEntry, timedelta(days = self.entryPeriod))
                    self.RegisterIndicator(added.Symbol, symbolData.ShortExit, timedelta(days = self.exitPeriod))
                    self.RegisterIndicator(added.Symbol, symbolData.LongEntry, timedelta(days = self.entryPeriod))
                    self.RegisterIndicator(added.Symbol, symbolData.LongExit, timedelta(days = self.exitPeriod))
    
                    self.Data[added.Symbol] = symbolData
                else:
                    #-- A security that was already initialized was re-added, reset the indicators
                    
                    symbolData.ShortEntry.Reset()
                    symbolData.ShortExit.Reset()
                    symbolData.LongEntry.Reset()
                    symbolData.LongExit.Reset()
                    
    
   
class SymbolData:
    
    def __init__(self, security):
        self.Security = security
        self.Symbol = security.Symbol

        self.ShortEntry = None
        self.ShortExit = None
        self.LongEntry = None
        self.LongExit = None

        self.PriceIsUnderShort = False
        self.PriceIsOverLong = False
        
        

    @property
    def PriceIsOverShort(self):
        return not self.PriceIsUnderShort
        
    @property
    def PriceIsUnderLong(self):
        return not self.PriceIsOverLong