Overall Statistics

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;
    	}
    	
    }

}
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);
            
            //Add as many securities as you like. All the data will be passed into the event handler:
            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));
            	}
            } 
            
        }
    }
}