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
using System;
using MathNet.Numerics.Statistics;
using QuantConnect.Data;
using QuantConnect.Securities.Future;
using QuantConnect.Interfaces;

using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;





//using QuantConnect.

namespace QuantConnect.Algorithm.CSharp
{
    public class Intermarket_ES : QCAlgorithm
    {

        private Symbol _contractSymbol;

        // S&P 500 EMini futures
        private const string RootSP500 = Futures.Indices.SP500EMini;
        public Symbol SP500_Symbol = QuantConnect.Symbol.Create(RootSP500, SecurityType.Future, Market.USA);

        // Gold futures
          //private const string RootGold = Futures.Metals.Gold;
          //public Symbol Gold = QuantConnect.Symbol.Create(RootGold, SecurityType.Future, Market.USA);

       // Swiss Franc futures
        private const string RootSF = Futures.Currencies.CHF;
        public Symbol SF_Symbol = QuantConnect.Symbol.Create(RootSF, SecurityType.Future, Market.USA);

       // public Symbol HYG_Symbol = QuantConnect.Symbol.Create("HYG", SecurityType.Equity, Market.USA);

        private double coefficient1;
        private double coefficient2;

        private RollingWindow<decimal> Close_ES;
        private RollingWindow<decimal> Close_HYG;
        private RollingWindow<decimal> Close_SF;

        public override void Initialize()
        {
            SetStartDate(2016, 1, 2);   //Set Start Date
            SetEndDate(2016, 3, 30);
            SetCash(100000);             //Set Strategy Cash
            
            var future_ES = AddFuture(RootSP500,Resolution.Minute);
            var future_SF = AddFuture(RootSF,Resolution.Minute);

            // set our expiry filter for this futures chain
            future_ES.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
            future_SF.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));

            //Close_ES  = new RollingWindow<decimal>(34);
            //Close_HYG  = new RollingWindow<decimal>(34);
            //Close_SF  = new RollingWindow<decimal>(34);

           // Schedule.On(DateRules.EveryDay("ES"), TimeRules.BeforeMarketClose("ES",182), () =>
           // {
           //     out_str(" --> EveryDay.SPY 10 min before close: Fired at: " + Time);
           // });

            AddEquity("HYG", Resolution.Minute);
            
            var benchmark = AddEquity("SPY", Resolution.Minute);
            SetBenchmark(benchmark.Symbol);

        }

        /// 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 slice)
        //-----------------------------------------------------------------
        {
            decimal act_Close_Price = 0.0m;
            DateTime act_Close_Time;
            Symbol act_contract_symbol ="";
            decimal act_Close_Price_ES = 0.0m;
            decimal act_Close_Price_SF = 0.0m;
        
            Symbol SF_contract_symbol ="";
            Symbol ES_contract_symbol ="";
        
            FuturesChain chain2;
        
        
            var keys = slice.Keys;
            foreach (var key in keys)
            {
               //if (key.ToString().IndexOf("HYG") >= 0)
                  Debug("Key using To.String() method: " + key.ToString());
                //var ticker_sym = key.ToString();
            } 
        
            // Explore the future contract chain
            if (slice.FuturesChains.TryGetValue(SP500_Symbol, out chain2))
            {
              //var underlying = chain2.Underlying;
              var contracts = chain2.Contracts.Values; 
              foreach (var contract in contracts)
               {
               	 ES_contract_symbol = contract.Symbol;
               	 _contractSymbol = contract.Symbol;
               	 act_Close_Price_ES = contract.LastPrice;
                }
             }
        
            if (slice.FuturesChains.TryGetValue(SF_Symbol, out chain2))
            {
              var contracts = chain2.Contracts.Values; 
              foreach (var contract in contracts)
               {
               	 SF_contract_symbol =contract.Symbol;
               	 act_Close_Price_SF = contract.LastPrice;
                 // out_str ("Price=" + contract.LastPrice + " " + contract.Symbol);
                }
             }
        
            var x1 = 0.0m;
            /*
            var HYGTradeBar = slice.Bars["HYG"];
            out_str(HYGTradeBar.Close.ToString());
            
            try { 
                x1 = slice[HYG_Symbol].Close;
                var _symbol = slice[HYG_Symbol].Symbol.ToString();
            } catch (Exception e)  {
                    Debug($"{e}");
                    Log(Time.Date.ToShortDateString() + " Exception Data Error");
            } */
            
            //if (slice.ContainsKey("HYG")) {
              //x1 = slice.Bars[HYG_Symbol].Close;
            out_str (Time.Date.ToString() + " " + 
                 ES_contract_symbol + "=" +  act_Close_Price_ES + " " + 
                 SF_contract_symbol + "=" +  act_Close_Price_SF + " HYG=" + x1);
           // }
        	//MarketOrder(act_contract_symbol, 1);

            // if (!Portfolio.Invested)
            // {
            //    SetHoldings(_spy, 1);
            //    Debug("Purchased Stock");
            //}
        }


        public void OnData(TradeBars data)
        //---------------------------------------------------------
        {

            //Debug(data["HYG"].Close.ToString ("##.###") ); 
            //TradeBar chain;
  

        	//Debug( //data[_symb_name].Open.ToString ("##.###") +  "\",\"" + 
              	 //data[_symb_name].High.ToString ("##.###") + "\",\"" + 
              	 //data[_symb_name].Low.ToString ("##.###")  + "\",\"" +  
              	 //+ data[_symb_name].Volume);
        	  //   data["HYG"].Close.ToString ("##.###") ); 
        }

        private void find_futureContract_toBe_rolled(Slice slice) {
        //-----------------------------------------------------------	
            decimal act_Close_Price = 0.0m;
            DateTime act_Close_Time;
            Symbol act_contract_symbol ="";
            decimal act_Close_Price_ES = 0.0m;
        
               foreach(var chain in slice.FutureChains)
                {
                    // find the front contract expiring no earlier than in 90 days
                   // out_str(" in future chain");
                    var contract = (
                        from futuresContract in chain.Value.OrderBy(x => x.Expiry)
                        where futuresContract.Expiry > Time.Date.AddDays(90)
                        select futuresContract
                        ).FirstOrDefault();

                    // if found, trade it
                    if (contract != null)
                    {
                        //if (Time.Minute % 60 == 0)	
                        //  MarketOrder(contract.Symbol, quantity);
                        act_Close_Price = contract.LastPrice;
                        act_Close_Time = contract.Time;
                        act_contract_symbol = contract.Symbol;
                        _contractSymbol = act_contract_symbol;
                        
                        act_Close_Price_ES = act_Close_Price;
                        
                        MarketOrder(act_contract_symbol, 1);
                       // out_str ("Price=" + contract.LastPrice + " " + contract.Symbol);
                    }
                }    
        

            
        }

        /// <summary>
        /// Order fill event handler. On an order fill update the resulting information is passed to this method.
        /// </summary>
        /// <param name="orderEvent">Order event details containing details of the evemts</param>
        /// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
        public override void OnOrderEvent(OrderEvent orderEvent)
        {
            Log(orderEvent.ToString());
        }


        public override void OnEndOfAlgorithm()
        {
            // Get the margin requirements
            var buyingPowerModel = Securities[_contractSymbol].BuyingPowerModel;
            var futureMarginModel = buyingPowerModel as FutureMarginModel;
            if (buyingPowerModel == null)
            {
                throw new Exception($"Invalid buying power model. Found: {buyingPowerModel.GetType().Name}. Expected: {nameof(FutureMarginModel)}");
            }
            var initialOvernight = futureMarginModel?.InitialMarginRequirement;
            var maintenanceOvernight = futureMarginModel?.MaintenanceMarginRequirement;
        }

        public void out_str(string _string)
        //---------------------------------------------------
        {
        	//Log(_string);
        	Debug(_string);
        	
        	if (LiveMode) {
        		Log(_string);
        	    Debug(_string);
        	}
        	
        }

    }
    
    public class calc_pair_Correlation
    //-------------------------------------------
    {
        public calc_pair_Correlation(string ticker1, string ticker2)
        	{
	      		Ticker=ticker1;
        	}	
        	
    	public string Ticker;
        double[] x; 	
        double[] y1; 	
        
        public void Update(decimal value1, decimal value2) {
      
           var coefficient1 = Correlation.Pearson(x, y1); 	
        }  	
    }
    
}