Category Trend  Published on 17/06/2020

Mean Reversion Overlay

Description


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

namespace cAlgo
{
    [Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class MeanReversionOverlay : 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;
            Result2[index] = buyAverage;
            Result3[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: MeanReversionOverlay.algo
  • Rating: 0
  • Installs: 1070
Comments
Log in to add a comment.
lorenzopvella's avatar
lorenzopvella · 3 years ago

Hi! And thanks for sharing this indicator.

While using it in a cBot I tried loading with data from a different timeframe, but that failed.

So, I modified it to support multi timeframe and also shared it, mentioning your source code.

Here's the link if you want to check it out: https://ctrader.com/algos/indicators/show/2602