Overall Statistics
using System;
using System.Collections;
using System.Collections.Generic;
using QuantConnect.Securities;
using QuantConnect.Models;

namespace QuantConnect {

    
    
    public class RunningAvg{
        private decimal _num=0 , _avg=0;
        
        public decimal updateAndReturn(decimal price){
            ++_num;
            _avg = 1/_num*price + (1-_num)/_num*_avg;
            return _avg;
        }
    }
    

}
using System;
using System.Collections;
using System.Collections.Generic; 
using QuantConnect.Securities;  
using QuantConnect.Models; 
using Newtonsoft.Json;

namespace QuantConnect 
{   
    // Name your algorithm class anything, as long as it inherits QCAlgorithm
    public class BasicTemplateAlgorithm : QCAlgorithm
    {
        private decimal  cost ;
        private int num ;
        private string stockname = "MSFT";
        private RunningAvg avg = new RunningAvg();
        //Initialize the data and resolution you require for your strategy:
        public override void Initialize()
        {
            SetStartDate(2013, 1, 1);         
            SetEndDate(DateTime.Now.Date.AddDays(-1)); 
            SetCash(25000);
            AddSecurity(SecurityType.Equity, stockname, Resolution.Minute);
            cost = 0;
            num = 0;
        }

        //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 val = avg.updateAndReturn(data[stockname].Close);
            if (this.cost<data[stockname].Close || data[stockname].Close < val ) 
            {
                Order(stockname, (int)Math.Floor(Portfolio.Cash / data[stockname].Close) );
                Debug("Debug Purchased MSFT"+stockname);
                this.cost = data[stockname].Close;
                this.num += (int)Math.Floor(Portfolio.Cash / data[stockname].Close) ;
            }else{
                Order(stockname, -num);
                Debug("Debug Sold "+stockname);
                
                this.cost = 0;
                this.num = 0;
            }
            Debug(Dump(num));
            Debug(Dump(Portfolio.Cash));
        }
        
        public static string Dump(object obj)
        {
            return JsonConvert.SerializeObject(obj , Formatting.Indented);
        }
    }
}