Overall Statistics
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;

namespace QuantConnect 
{
    public partial class QCUMartingalePositionSizing : QCAlgorithm 
    {
		string iSymbol = "MSFT";
		string iChart = "Deals";

        public override void Initialize()
        {
        	SetCash(10000);
            SetStartDate(2017, 1, 1);
            SetEndDate(DateTime.Now.Date); 
            SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage);

			AddEquity(iSymbol, Resolution.Minute);

            var chart = new Chart(iChart);
			var seriesStock = new Series("Stock", SeriesType.Line, 0);
			var seriesBuy = new Series("Buy", SeriesType.Scatter, 0) { Color = Color.Blue, ScatterMarkerSymbol = ScatterMarkerSymbol.Triangle };
			var seriesSell = new Series("Sell", SeriesType.Scatter, 0) { Color = Color.Red, ScatterMarkerSymbol = ScatterMarkerSymbol.TriangleDown };
			var seriesBalance = new Series("Balance", SeriesType.Line, 1);
			var seriesEquity = new Series("Equity", SeriesType.Line, 1);
			var seriesIndicator = new Series("RSI", SeriesType.Line, 2);

			chart.AddSeries(seriesStock);
			chart.AddSeries(seriesBuy);
			chart.AddSeries(seriesSell);
			chart.AddSeries(seriesBalance);
			chart.AddSeries(seriesEquity);
			chart.AddSeries(seriesIndicator);            

            AddChart(chart);
        }
        
        public void OnData(TradeBars data) 
        {
        	if (IsMarketOpen(iSymbol) == false)
        	{
        		return;
        	}
        	
        	Plot(iChart, "Stock", data[iSymbol].Price);
        	Plot(iChart, "Balance", Portfolio.TotalProfit - Portfolio.TotalFees);
        	Plot(iChart, "Equity", Portfolio.TotalProfit + Portfolio.TotalUnrealizedProfit - Portfolio.TotalFees);

			if (Portfolio.Invested)
			{
				//Liquidate();
			}
			else
			{
				var price = Securities[iSymbol].Price;
				var contracts = OptionChainProvider.GetOptionContractList(iSymbol, Time);
				
				var OTM = 
					from c in contracts
                    where c.ID.OptionRight == OptionRight.Put
                    where price - c.ID.StrikePrice < 10 && price - c.ID.StrikePrice > 2
                    where (c.ID.Date - Time).TotalDays < 7 && (c.ID.Date - Time).TotalDays > 0
                    select c;

                var contract = OTM
                	.OrderBy(o => o.ID.Date)
                	.ThenByDescending(o => price - o.ID.StrikePrice)
					.FirstOrDefault();

				if (contract != null)
				{
	                AddOptionContract(contract, Resolution.Minute);
	                MarketOrder(contract, -1);
				}
			}
        }

        protected decimal GetBalance(bool equity = false) 
        {
        	var balance = 0m;

        	if (equity)
        	{
        		balance += Portfolio.TotalUnrealizedProfit;
        	}

        	return
        		balance + 
        		Portfolio.TotalProfit - 
        		Portfolio.TotalFees;
        }
    }
}