A MultiCharts .NET script can calculate twice as soon as price data is referenced. Why is that?

Code example

using System;
using System.Drawing;
using System.Linq;
using PowerLanguage.Function;

namespace PowerLanguage.Indicator
{
    [SameAsSymbol(true)]
    public class ExampleIndicator : IndicatorObject
    {
        public ExampleIndicator(object _ctx) : base(_ctx) { }
        private bool onlyOnce;

        protected override void StartCalc()
        {
            Output.WriteLine("This is the StartCalc() method");
            onlyOnce = false;
        }

        protected override void CalcBar()
        {
            if (Bars.LastBarOnChart && !onlyOnce)
            {
                Output.WriteLine("This is the last bar on the chart");

                Output.WriteLine("The last close was: " + Bars.Close[1]);

                onlyOnce = true;
            }
        }
    }
}

This indicator gives the following output:

This is the StartCalc() method
This is the last bar on the chart
This is the StartCalc() method
This is the last bar on the chart
The last close was: 1,37934

If we comment out line 26 in this example (which references Bars.Close[1]), the output is:

This is the StartCalc() method
This is the last bar on the chart

Now the indicator is only calculated once. What is going on here?

Script calculation and MultiCharts .NET’s MaxBarsBack

The reason for this behaviour is the automatic determination of the maximum number of bars that a study will reference, the so called MaxBarsBack value.

Initially, this MaxBarsBack value is assigned a value of zero (MultiCharts Support email communication, October 25, 2013). But when the code starts referencing any historical bars and the MaxBarsBack value is not high enough, the MaxBarsBack value is automatically increased and the script is recalculated.

In the above example, when line 26 is reached and price data is referenced, the default MaxBarsBack value is set too low. MultiCharts .NET will then automatically increase the MaxBarsBack value and recalculate the indicator again.

Solving automatic script recalculations

To prevent this behaviour from happening you can manually increase the amount of bars that the indicator will reference to a high enough value.

To do this, open the code source file in the PowerLanguage Editor and then go to File —> Properties. In the Indicator Properties window (see below) select ‘User Specified’ and specify the value.

Indicator Properties window of the PowerLanguage Editor

Alternatively, you can set the MaxBarsBack value programmatically.