I followed the QuantConnect tutorial at: https://www.youtube.com/watch?v=uv1phsM2Pgw as closely as possible (code below). Other than the fact this video was published in ’04 there are signs the tutorial is out of date due to deprecated or renamed functions. Despite everything I was able to reproduce output, up to the point the algorithm checks for holdings.  After that the algorithm produces 0 trades.  I attempted to use Console.WriteLine() to output number of holdings etc. however it only outputs one iteration and stops with no error or indication of output throttling.  Please tell me what I am doing wrong.

 

// Main.cs 

namespace QuantConnect 
{   

    public partial class MovingAverageDemo : QCAlgorithm
    {
        string symbol = "SPY";
        ExponentialMovingAverage emaFast = new ExponentialMovingAverage(10);
        ExponentialMovingAverage emaSlow = new ExponentialMovingAverage(50);
        
        //Initialize the data and resolution you require for your strategy:
        public override void Initialize() 
        {
            //Start and End Date range for the backtest:
            SetStartDate(2014, 01, 01);         
            SetEndDate(2014, 04, 01);
            
            //Cash allocation
            SetCash(30000);
            
            AddSecurity(SecurityType.Equity, symbol, Resolution.Minute);
        }

        //Data Event Handler: New data arrives here. "TradeBars" type is a dictionary of strings so you can access it by symbol.
        public void OnData(TradeBars data) 
        {   
            decimal price = data[symbol].Close;
            int myholdings = Portfolio[symbol].Quantity;

            emaFast.AddSample(price);
            emaSlow.AddSample(price);
    
            if(myholdings == 0 || myholdings < 0) {
                if(emaFast.EMA > emaSlow.EMA) {
                    Order(symbol, Math.Abs(myholdings) + 100);
                }
            } else if(myholdings == 0 || myholdings > 0 ) {
                  if(emaFast.EMA < emaSlow.EMA) {
                    Order(symbol, -(100 + myholdings));
                }
            } 
            
        }
    }
}

 

// ExponentialMovingAverage.cs

namespace QuantConnect {
    using QuantConnect.Models;

    public class ExponentialMovingAverage
    {
        private decimal _period;
        private decimal _ema;
        private int _samples;
        
        public decimal EMA {
            get { return _ema;}
        }
        
        public ExponentialMovingAverage(decimal period)
        {
            this._period = period;  // formula constant equals period
            this._samples = 0;
            
        }
        
        public decimal AddSample(decimal price)
        {
            if(_samples == 0) {
                _ema = price;
            } else {
                _ema = (1/_period + ((_period -1)/_period) * _ema);
                
            }
            
            _samples++;
            return _ema;
        }
        
    }

}