Overall Statistics
Total Trades
232
Average Win
1.04%
Average Loss
-1.05%
Compounding Annual Return
105.196%
Drawdown
18.200%
Expectancy
0.031
Net Profit
2.190%
Sharpe Ratio
-0.818
Probabilistic Sharpe Ratio
28.183%
Loss Rate
48%
Win Rate
52%
Profit-Loss Ratio
0.99
Alpha
0
Beta
0
Annual Standard Deviation
0.982
Annual Variance
0.965
Information Ratio
-0.818
Tracking Error
0.982
Treynor Ratio
0
Total Fees
$573.04
Estimated Strategy Capacity
$0
Lowest Capacity Asset
GC Y6A3DH1FMBVH
#region imports
from AlgorithmImports import *
import collections
from numpy.random import randn
import numpy as np
from numpy.random import seed
from scipy.stats import pearsonr
import numpy as np
import math
import requests
import json
#endregion
class DynamicCalibratedContainmentField(QCAlgorithm):

        def Initialize(self):
            self.SetStartDate(datetime.now() - timedelta(days=20))  # Set Start Date
            self.SetEndDate(datetime.now()- timedelta(days=10))    #Set End Date
            self.SetCash(30000) 
            self.delta = 0
            self.contract = None
            self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash)
            
            self.ticker = Futures.Metals.Gold
            self.future = self.AddFuture(self.ticker, Resolution.Tick, extendedMarketHours=True)
            self.future.SetFilter(0, 90)
            self.ticket = None
            self.enter = None
            self.EnableAutomaticIndicatorWarmUp = True
            self.days_left = 0
            self.amount_trades = 0
            self.StopTrading=False
            self.DefaultOrderProperties.TimeInForce = TimeInForce.GoodTilCanceled
            chart = Chart("CLOSING")
            self.AddChart(chart)
            chart.AddSeries(Series("Liquidation_signal", SeriesType.Scatter, "$", Color.Red, ScatterMarkerSymbol.Circle))
            chart.AddSeries(Series("barHandler_after_ST", SeriesType.Scatter, "$", Color.Blue, ScatterMarkerSymbol.Circle))
            chart.AddSeries(Series("barHandler_before_ST", SeriesType.Scatter, "$", Color.Green, ScatterMarkerSymbol.Circle))
            self.consolidator_by_symbol = {}
            self.option_contract = None
          
      

        def OnData(self, data):
            #selects new contract
            if not self.Portfolio.Invested and self.contract is None:   
                for chain in data.FutureChains:
                    contracts = list(chain.Value)
                    if len(contracts) == 0:
                        continue
                    
                    sortedByOIContracts = sorted(contracts, key=lambda k : k.OpenInterest, reverse=True)
                    contract = sortedByOIContracts[0]
                    self.contract = contract
                    #self.Buy(self.contract.Symbol, 1)
                    CountConsolidator = TickConsolidator(timedelta(minutes=1)) 
                    CountConsolidator.DataConsolidated += self.BarHandler
                    self.SubscriptionManager.AddConsolidator(contract.Symbol, CountConsolidator)
                    self.consolidator_by_symbol[contract.Symbol] = CountConsolidator
                    self.days_left = self.contract.Expiry
                  

            if not self.Portfolio.Invested and self.option_contract is None:     
                for continuous_future_symbol, futures_chain in data.FuturesChains.items():
                    # Select a Future Contract and create its canonical FOP Symbol
                    futures_contract = [contract for contract in futures_chain][0]
                    canonical_fop_symbol = Symbol.CreateCanonicalOption(futures_contract.Symbol)
                    fop_chain = data.OptionChains.get(canonical_fop_symbol) 
                    
                   
                    if fop_chain is not None:
                        self.enter = fop_chain
                        

                    
            if self.contract is None: return
            if self.Time > self.days_left:
                self.contract = None  

            #check if current date is open
            hours = self.Securities[self.future.Symbol].Exchange.Hours
            #if hours.IsDateOpen(self.Time):
            self.StopTrading = False
            #get next open/close date
            self.todayOpen = hours.GetNextMarketOpen(self.Time, True)
            self.todayClose = hours.GetNextMarketClose(self.Time, True)

            #liquidate position 15 minutes before close if unrealized profit > 30
            if self.todayClose - timedelta(minutes=15) < self.Time and self.StopTrading is not True:
                if self.Portfolio[self.future.Symbol].UnrealizedProfit > 30:
                    self.StopTrading = True
                    self.Liquidate()
                    self.Plot("CLOSING", "Liquidation_signal",1.5)
                    self.Transactions.CancelOpenOrders()
                    
            #liquidate position 2 minutes before close
            if self.todayClose - timedelta(minutes=2) < self.Time and self.StopTrading is not True:
                self.StopTrading = True
                self.Liquidate() 
                self.Plot("CLOSING", "Liquidation_signal",0.5) 
                self.Transactions.CancelOpenOrders() 
                
            #activate trading 2 minutes before open
            if self.todayOpen - timedelta(minutes=2) < self.Time:
                selfStopTrading = False

              
        def BarHandler(self, sender, bar):

            if self.IsWarmingUp:
                return
      
            self.Plot("CLOSING", "barHandler_before_ST",1)
            #self.Plot("CLOSING", "up", self.Portfolio[self.future.Symbol].UnrealizedProfit)

            if self.StopTrading is True:
                return
            self.Plot("CLOSING", "barHandler_after_ST",1.5)
            currentContract = self.Securities[self.future.Mapped]
            
            
            if not self.Portfolio.Invested:
                quantity = 1
                self.entry = self.MarketOrder(currentContract.Symbol, quantity)
                   
        def OnOrderEvent(self, orderEvent):
            currentContract = self.Securities[self.future.Mapped]
            quantity = 1
            order = self.Transactions.GetOrderById(orderEvent.OrderId)
            if order.Status == OrderStatus.Filled and order.Type == OrderType.Market and order.Direction == 0:
                entry_price = orderEvent.FillPrice
                self.limOrder =self.LimitOrder(currentContract.Symbol, -quantity, orderEvent.FillPrice + 2)
                self.stopOrder1 = self.StopMarketOrder(currentContract.Symbol, -quantity, orderEvent.FillPrice - 2)
            if order.Status == OrderStatus.Filled and order.Type == OrderType.Market and order.Direction == 1:
                self.LimitOrder(currentContract.Symbol, quantity, orderEvent.FillPrice + 2)
                stopOrder = self.StopMarketOrder(currentContract.Symbol, quantity, orderEvent.FillPrice - 2)
            if order.Status == OrderStatus.Filled:
                if order.Type == OrderType.Limit or order.Type == OrderType.StopMarket:
                    self.Plot("PROFIT", "value", self.Portfolio[currentContract.Symbol].LastTradeProfit)
                    self.Transactions.CancelOpenOrders(order.Symbol)
                    self.ticket = None
                    self.highest = 0 
                    
            
        def OnEndOfDay(self):
            #self.Debug(f"{self.Securities[self.future.Mapped].Exchange.Hours.GetMarketHours(self.Time)}")
            
            self.Plot("Price","on close",self.future.Price)