Category Oscilators  Published on 17/07/2020

Mean Reversion Oscillator

Description

Referencing price and averages to the mean


using System;
using cAlgo.API;
using cAlgo.API.Internals;
using cAlgo.API.Indicators;
using cAlgo.Indicators;

namespace cAlgo
{
    [Indicator(IsOverlay = false, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class MeanReversionOscillator : Indicator
    {
        [Output("sellAverage", LineColor = "lightGreen")]
        public IndicatorDataSeries Result1 { get; set; }

        [Output("buyAverage", LineColor = "Red")]
        public IndicatorDataSeries Result2 { get; set; }

        [Output("Mean", LineColor = "Aqua")]
        public IndicatorDataSeries Result3 { get; set; }

        private Bars tf;

        private int idx;
        private int previousIdx;
        private int buyPeriod;
        private int sellPeriod;

        private double buyAverage;
        private double sellAverage;
        private int savedbp;
        private int savedsp;
        private double mean;

        protected override void Initialize()
        {
            tf = MarketData.GetBars(Bars.TimeFrame);
        }

        public override void Calculate(int index)
        {
            idx = tf.OpenTimes.GetIndexByTime(Bars.OpenTimes[index]);
            if (idx > previousIdx)
            {
                buyPeriod++;
                savedbp = buyPeriod;
                sellPeriod++;
                savedsp = sellPeriod;
            }

            if (buyPeriod == 0)
                buyPeriod = savedbp;

            if (sellPeriod == 0)
                sellPeriod = savedsp;

            buyAverage = Bars.OpenPrices.Sum(buyPeriod) / buyPeriod;
            sellAverage = Bars.OpenPrices.Sum(sellPeriod) / sellPeriod;

            if (Bars.ClosePrices[index] > buyAverage)
            {
                buyAverage = Bars.ClosePrices[index];
                buyPeriod = 0;
            }

            if (Bars.ClosePrices[index] < sellAverage)
            {
                sellAverage = Bars.ClosePrices[index];
                sellPeriod = 0;
            }

            mean = (buyAverage + sellAverage) / 2;

            Result1[index] = sellAverage - mean;
            Result2[index] = buyAverage - mean;
            Result3[index] = Bars.ClosePrices[index] - mean;

            previousIdx = idx;
        }
    }
}


srm_bcn's avatar
srm_bcn

Joined on 01.09.2019

  • Distribution: Free
  • Language: C#
  • Trading platform: cTrader Automate
  • File name: MeanReversionOscillator.algo
  • Rating: 5
  • Installs: 1251
Comments
Log in to add a comment.
No comments found.