Overall Statistics
using QuantConnect.Securities.Future;

namespace QuantConnect
{
	public partial class BootCampTask : QCAlgorithm
    {
    	private decimal notionalValue;
    	private decimal contractsToBuy;
    	private FuturesChain contractChain;
    	private Future future;
    	private FuturesContract liquidContract;
    	
    	public override void Initialize()
    	{
    		SetStartDate(2016, 12, 1);
        	SetEndDate(2016, 12, 31);
        	SetCash(1000000); 
        	AddEquity("SPY");
        	future = AddFuture("ZB");
        	future.SetFilter(0, 190);
        	
        	Schedule.On(DateRules.EveryDay("SPY"), TimeRules.AfterMarketOpen("SPY", 30), () =>
            {
            	if(liquidContract != null)
            	{
		            var oldFuture = (Future)Securities[liquidContract.Symbol];
	        		if (oldFuture.Holdings.Quantity != 0)
	            	{
	            		//MarketOrder(liquidContract.Symbol, -oldFuture.Holdings.Quantity);
	            	}
            	}
            	
            	if(contractChain != null && contractChain.Count() >= 1)
            	{
	                var contracts = contractChain.OrderBy(x => x.Expiry);
	            	liquidContract = contracts.First();
	            	
	            	var oldContract = liquidContract;
	            	
	            	if (liquidContract.Expiry <= Time.Date.AddDays(8) & contractChain.Count() >= 2)
	            	{
	            		liquidContract = contracts.Skip(1).First();
	            	}
	            	
	            	var ContractFuture = (Future)Securities[liquidContract.Symbol];
	            	if (ContractFuture.Holdings.Quantity == 0)
	            	{
	            		var oldFuture = (Future)Securities[oldContract.Symbol];
	        			if (oldFuture.Holdings.Quantity != 0)
	            		{
	            			MarketOrder(oldContract.Symbol, -oldFuture.Holdings.Quantity);
	            		}
	            		
	            		decimal midPrice = (ContractFuture.AskPrice + future.BidPrice)/2;
                		var notionalValue = midPrice * ContractFuture.SymbolProperties.ContractMultiplier;
	            		var MaxSafeQty = Portfolio.TotalPortfolioValue / notionalValue; // SHOULD NEVER GET MARGIN CALLED!!!
	            		
	            		MarketOrder(liquidContract.Symbol, MaxSafeQty);
	            	}
            	}
            
            });
            
            Schedule.On(DateRules.EveryDay("SPY"), TimeRules.AfterMarketOpen("SPY", 60), () =>
            {
            	
            });
    	}
    	
    	public override void OnMarginCallWarning()
    	{
    		Error("You received a Margin Call Warning! The assets will be liquidated to cover losses.");
        }
    	
    	public void OnData(Slice slice)
    	{
    		FuturesChain chain;
    		if (slice.FuturesChains.TryGetValue(future.Symbol, out chain))
			{
			   contractChain = chain;
			}
    	}
    }
}