Overall Statistics
Total Trades
0
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Net Profit
0%
Sharpe Ratio
0
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0
Beta
0
Annual Standard Deviation
0
Annual Variance
0
Information Ratio
0
Tracking Error
0
Treynor Ratio
0
Total Fees
$0.00
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));
            	}
            } 
            
        }
    }
}

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

}