Overall Statistics
Total Trades
5658
Average Win
0%
Average Loss
-0.03%
Compounding Annual Return
-21.626%
Drawdown
56.100%
Expectancy
-1
Net Profit
-56.109%
Sharpe Ratio
-15.525
Loss Rate
100%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
-0.236
Beta
-0.053
Annual Standard Deviation
0.016
Annual Variance
0
Information Ratio
-3.145
Tracking Error
0.126
Treynor Ratio
4.598
Total Fees
$14027.32
namespace QuantConnect
{
    public class EMACrossLongAlgorithm : QCAlgorithm
    {
        // There's no need to create another instance of algorithm. We are already in the algorithm.
        // So we create all variables we need here.
        RollingWindow<TradeBar> History = new RollingWindow<TradeBar>(3);

        string symbol = "MSFT";

        ExponentialMovingAverage fastEma;
        ExponentialMovingAverage slowEma;

        int fastEmaPeriod = 8;
        int slowEmaPeriod = 20;

        //algorithm PnL settings
        decimal targetProfit = 0.01m; // 1% target
        decimal maximumLoss = 0.005m; // 0.5% stop

        // Initialize function ----------------------------------------------------------------------------
        public override void Initialize() // backtest kickstart
        {
            SetStartDate(2012, 3, 12);
            SetEndDate(2015, 7, 28);
            SetCash(25000);
            AddSecurity(SecurityType.Equity, symbol, Resolution.Minute);

            var fifteenConsolidator = ResolveConsolidator(symbol, TimeSpan.FromMinutes(15));

            fastEma = new ExponentialMovingAverage(fastEmaPeriod);
            slowEma = new ExponentialMovingAverage(slowEmaPeriod);

            RegisterIndicator(symbol, fastEma, fifteenConsolidator, p => p.Value);
            RegisterIndicator(symbol, slowEma, fifteenConsolidator, p => p.Value);

            fifteenConsolidator.DataConsolidated += (s, e) => OnDataFifteen((TradeBar)e);
            PlotIndicator(symbol, fastEma);
            PlotIndicator(symbol, slowEma);
        }

        public bool MinimumProfitAchieved
        {
            get { return (Portfolio.TotalUnrealizedProfit / Portfolio.Cash) >= targetProfit; }
        }

        public bool MaximumLossAchieved
        {
            get { return (Portfolio.TotalUnrealizedProfit / Portfolio.Cash) <= -maximumLoss; }
        }

        // 15m timeframe handler -----------------------------------------------------------------------------

        private void OnDataFifteen(TradeBar consolidated)
        {
            History.Add(consolidated);

            if (fastEma.IsReady == false 
                || slowEma.IsReady == false
                || History.Count < 3)
                return;

            decimal profit = Portfolio.TotalUnrealizedProfit;
            decimal price = consolidated.Close;
            decimal high = consolidated.High;
            int holdings = Portfolio[symbol].Quantity;
            decimal avg = (consolidated.Open + consolidated.Close) / 2;
            decimal percentage = 0;

            //Algorithm Entry Section:==========================================
            //Entry Scenario Criteria ==========================================


            // CM Check - Scenario 1: 8EMA Crossover 20EMA

            // I replaced 'while' with 'if'. Tradebars will be coming, just check every tradebar.
            if (holdings <=0) // Holdings will never be < 1. I think you meant 0.
            {
                if (fastEma >= slowEma)
                {
                    // Most recent bar is History[0]. So make sure this is what you meant.
                    if (History[1].Close > History[2].Close)
                    {
                        if (avg > History[1].Close)
                        {
                            //percentage = 1.5m; 
                            // Holdings should have values between -1 and 1. -- 1.5 is not correct.
                            // if you meant 1.5%, then use 0.015 for holdings value. But let's go full size.
                            percentage = 1;
                            SetHoldings(symbol, percentage);
                        }
                    }
                }

            }

            //Algorithm Exit Section:===========================================

            if (MinimumProfitAchieved)
            {
                //Order(symbol, -holdings);
                // Just use Liquidate
                // Or, equivalently SetHoldings(0). Or, close long and open short with SetHoldings(-1).
                Liquidate(symbol);
            }

            if (MaximumLossAchieved)
            {
                //Order(symbol, -holdings);
                Liquidate(symbol);
            }
        }
    }
}