// -------------------------------------------------------------------------------------------------
//
//    This code is a cAlgo API example.
//    Please read carefully and you will get a clear understanding of
//    how to create a more advanced indicator.
//    
// -------------------------------------------------------------------------------------------------
//In this indicator we want to use a nested indicator (MovingAverage) in order to make calculations
//for the Standard Deviation.
using System;
using cAlgo.API;
using cAlgo.API.Indicators;

namespace cAlgo.Indicators
{
    [Indicator]
    public class SampleStandardDeviation : Indicator
    {
        [Parameter]
        public DataSeries Source { get; set; }

        [Parameter(DefaultValue = 14, MinValue = 2)]
        public int Periods { get; set; }

        [Parameter("MA Type", DefaultValue = MovingAverageType.Simple)]
        public MovingAverageType MAType { get; set; }

        [Output("Result", Color = Colors.Orange)]
        public IndicatorDataSeries Result { get; set; }

        private MovingAverage movingAverage;//movingAverage is where we want to store the indicator 
        //"MovingAverage"

        protected override void Initialize()//In the initialize method we store the indicators we want
        // to use in the main logic section of the indicator.
        {
            movingAverage = Indicators.MovingAverage(Source, Periods, MAType);//The indicators object 
        //contains all methods for built-in indicators.Here we store the indicator to a variable called 
        //"movingAverage"  
        }

        public override void Calculate(int index)//This is where the main logic will be placed
        {
            var average = movingAverage.Result[index];

            double sum = 0;

            for (var period = 0; period <  Periods; period++)
            {
                sum += Math.Pow(Source[index - period] - average, 2.0);
            }

            Result[index] = Math.Sqrt(sum / Periods);
        }
    }
}