Overall Statistics
namespace QuantConnect 
{   
    public class ShortVXX : QCAlgorithm
    {
    	private int MINIMUM_BLOCK_SIZE = 100;
    	private double MINIMUM_EXPOSURE = 25; // percent
    	// Due to data error with split
    	private Tuple<long, long> [] blackPeriods = {
    		new Tuple<long, long>(Convert.ToDateTime("08/07/2016").Ticks, Convert.ToDateTime("08/09/2016").Ticks),
    		new Tuple<long, long>(Convert.ToDateTime("11/03/2013").Ticks, Convert.ToDateTime("11/10/2013").Ticks),
    		new Tuple<long, long>(Convert.ToDateTime("10/01/2012").Ticks, Convert.ToDateTime("10/06/2012").Ticks)
    	};
    	
        public override void Initialize() 
        {
            SetStartDate(2010, 1, 1);
            SetEndDate(DateTime.Now);
            SetCash(250000);
            AddEquity("VXX", Resolution.Hour);
            //Securities["VXX"].SetLeverage(5.0m);
            //Securities["VXX"].MarginModel = (Securities.ISecurityMarginModel)MarginCallModel.Null;
            Chart plotter = new Chart("VXX short");
            plotter.AddSeries(new Series("Position", SeriesType.Line));
            AddChart(plotter);
        }
        
        private bool isBlackPeriod(DateTime dt)
        {
        	return false;
        	long dtTicks = dt.Ticks;
        	foreach (var period in blackPeriods)	
        	{
        		if ((dtTicks >= period.Item1) && (dtTicks <= period.Item2))
        		{
        			return true;
        		}
        	}
        	return false;
        }

        public void OnData(TradeBars data) 
        {
        	if (!data.ContainsKey("VXX"))
        	{
        		return;
        	}
            TradeBar dataBar = data["VXX"];
            if (dataBar.EndTime.Hour != 15) // rebalance at the start of the trading day
            {
            	return;
            }
            int positionShares = Math.Abs(Portfolio["VXX"].Quantity);
            
            var closePrice = (double)dataBar.Close; 
            var positionSize = positionShares * (double)closePrice;

            if (isBlackPeriod(dataBar.EndTime))
            {
            	if (positionShares > 0)
            	{
            		Debug("Black period liquidation=" + positionShares + " "+dataBar.EndTime);
					Order("VXX",  positionShares);
            	}
            	return;	
            }

            var delta  = (MINIMUM_EXPOSURE/100)*(double)Portfolio.Cash - positionSize;
           	int amount = (int)Math.Ceiling(delta/closePrice);
           	if (amount >= MINIMUM_BLOCK_SIZE)
            {
           		Debug("NET=" + Portfolio.Cash + " positionShares=" + (-positionShares) + " price=" + closePrice + " amount=" + (-amount));
               	Order("VXX",  -amount);
            	//Plot("VXX short", "Position", positionSize);  
            }
        }
        
    }
}