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.264
Tracking Error
0.104
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
using QuantConnect.Securities.Future;

namespace QuantConnect.Algorithm.CSharp
{
    public class ESFuturesGlobexConsolidator : QCAlgorithm
    {
    	
    	private Future es;
    	private RollingWindow<TradeBar> esDaily;
    	private TradeBar esYesterday;
    	private TradeBar firstBar;
    	private HashSet<Symbol> _esFutureContracts = new HashSet<Symbol>();
    	private Dictionary<Symbol, TradeBarConsolidator> consolidators;
    	
    	Func<DateTime, CalendarInfo> GlobexDay =  dt =>
        {
            DateTime start;

            if (dt.TimeOfDay >= TimeSpan.FromHours(17))
            {
                start = new DateTime(dt.Year, dt.Month, dt.Day, 17, 00, 00);
            }
            else
            {
                DateTime temp = dt.AddDays(-1);
                start = new DateTime(temp.Year, temp.Month, temp.Day, 17, 00, 00);
            }

            DateTime end;
            if (dt.TimeOfDay >= TimeSpan.FromHours(17))
            {
                DateTime temp = dt.AddDays(1);
                end = new DateTime(temp.Year, temp.Month, temp.Day, 16, 00, 00);
            }
            else
            {
                end = new DateTime(dt.Year, dt.Month, dt.Day, 16, 00, 00);
            }                  

            return new CalendarInfo(start, end - start);
        };
            
    	
        public override void Initialize()
        {
        	// set timezone to CST - US/Chicago
        	SetTimeZone(TimeZones.NewYork);
        	
        	// set start and end date for backtesting
            SetStartDate(2021, 10, 01);  
            //SetEndDate(2021, 04, 02);  
            SetEndDate(DateTime.Now.Date.AddDays(-1)); // we test until EOD yesterday
            
            // warm up 2 days of data, we need at least 2 days of data to determine the gap up/down entry for this algo
            SetWarmUp(TimeSpan.FromDays(2));
            
            // set portfolio cash to 100000 USD ; increased to compensate margin
            SetCash(100000);
            
            // add E-mini S&P 500 futures contract
            es = AddFuture(Futures.Indices.SP500EMini, Resolution.Minute);
            
            // select only the front month contracts
            es.SetFilter(x => x.FrontMonth().OnlyApplyFilterAtMarketOpen());
           
        	// Creates a Rolling Window indicator to keep the 2 TradeBar
            esDaily = new RollingWindow<TradeBar>(1);
            
            consolidators = new Dictionary<Symbol, TradeBarConsolidator>();
        }

        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// Slice object keyed by symbol containing the stock data
        public override void OnData(Slice data)
        {
        	// foreach(var chain in data.FutureChains)
        	// {
        	// 	var popularContracts = chain.Value.Where(x=> x.OpenInterest > 1000).ToList();
        	
        	// 	if (popularContracts.Count == 0)
        	// 	{
        	// 		continue;
        	// 	}
         //   	var sortedByOIContracts = popularContracts.OrderByDescending(x => x.OpenInterest).ToList();
         //   	var liquidContract = sortedByOIContracts.FirstOrDefault();
            	
         //   	if (!_esFutureContracts.Contains(liquidContract.Symbol))
         //       {
         //           _esFutureContracts.Add(liquidContract.Symbol);

         //           var consolidator = new TradeBarConsolidator(GlobexDay);
         //           consolidator.DataConsolidated += OnDataConsolidated;
         //           SubscriptionManager.AddConsolidator(liquidContract.Symbol, consolidator);

         //           //Log("Added new consolidator for " + liquidContract.Symbol.Value);
         //       }
        	// }
        }
        
         public void OnDataConsolidated(object sender, TradeBar tradeBar)
        {
        	Debug(String.Format("OnDataConsolidated called at {0}", Time.Date.ToString()));
        	esDaily.Add(tradeBar);
        	Debug(tradeBar.ToString());
        }
        
        public override void OnSecuritiesChanged(SecurityChanges changes)
		{
			if (changes.AddedSecurities.Count > 0)
		    {
				foreach( var futuresContract in changes.AddedSecurities)
				{
					var consolidator = new TradeBarConsolidator(GlobexDay);
					consolidator.DataConsolidated += OnDataConsolidated;
					SubscriptionManager.AddConsolidator(futuresContract.Symbol, consolidator);
					consolidators[futuresContract.Symbol] = consolidator;
				}
				Debug("Securities added: " + 
		              string.Join(",", changes.AddedSecurities.Select(x => x.Symbol.Value)));
		    }
			
			if (changes.RemovedSecurities.Count > 0)
		    {
				foreach( var futuresContract in changes.RemovedSecurities)
				{
					var consolidator = consolidators[futuresContract.Symbol];
					SubscriptionManager.RemoveConsolidator(futuresContract.Symbol, consolidator);
					consolidator.DataConsolidated -= OnDataConsolidated;
					consolidators.Remove(futuresContract.Symbol);
				}
				
				Debug("Securities removed: " + 
		              string.Join(",", changes.RemovedSecurities.Select(x => x.Symbol.Value)));
		    }
		}
    }
}