Amibroker AFL Average True Range ATR Calculation

In this post I share with you a function that calculates the ATR (Average True Range) of a time series of prices as calculated by Amibroker’s built-in native function.

The AFL function is:

SetBarsRequired( sbrAll , -1 );

Periods = Param( "Periods", 14, 1, 200, 1 );

C1 = Ref( C, -1 );
TrueRange = Max( abs( H - C1 ), abs( L - C1 ) );
TrueRange = Max( H - L, TrueRange );
TrueRange[0] = H[0] - L[0];

AverageTrueRange = Null;
AverageTrueRange[Periods-1] = 0;

for ( i = 0; i < Periods; i++ )
    AverageTrueRange[Periods-1] = AverageTrueRange[Periods-1] + TrueRange[i];

AverageTrueRange[Periods-1] = AverageTrueRange[Periods-1] / Periods;

for ( i = Periods; i < BarCount; i++ )
    AverageTrueRange[i] = ( TrueRange[i] + ( periods - 1 ) * AverageTrueRange[i-1] ) / Periods;

AverageTrueRange[Periods-1] = Null;

Color = ParamColor( "Color", colorCycle );
Style = ParamStyle( "Style" );

Plot( AverageTrueRange, "ATR" + _PARAM_VALUES(), Color, Style );

In the image below you can see the built-in ATR and the calculated one. The values are the same for each bar.

Comparison between built-in ATR and reverse engineered calculation

You can download the script here

Here is also an Excel spreadsheet with the same calculation on some sample data, only to clarify the steps and verify the coincidence of the results between the output of the native function and the proposed calculation. The example in the spreadsheet covers an ATR of 14 periods.

and the spreadsheet here

If you find useful this post, please leave a comment, thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *