Doubt when using self referencing

Hi Guys,

Just bought Amibroker and getting the hang of AFL. I have a doubt on when you self reference a variable.

For Ex: a = (ref(a,-1)) + 2

Generally this would result in an error unless I initialize a[0] and then use for loop for the rest of the array. Is there a work around to this. For Ex. In tradingview they have a simple function called nz() which would erase all null values.

Moderator comment: Initialization is MINOR issue. Initializing only hides more important issue presented in second reply.

Before you reference any array, here it’s the a inside Ref(a, -1), you must first initialise the values in the array.


a = Close;
a = Ref(a, -1) + 2;  // This value will vary with the price of Close as the input

// Or 
a = 500;
a = Ref(a, -1) + 2; // This value will remain constant as the initial input was fixed

No need for any looping or Nz(), although it also exists in Amibroker,

Also, please read the banner at the top of this site regarding formatting code you post.

That is NOT proper way to get self-referencing bar-by-bar calculation.

Did you read Understand AFL tutorial?
It is essential and MOST important reading you need to swallow and understand. If it does not sink re-read it.

The most important thing to understand is that ENTIRE ARRAY is processed AT ONCE.

So statement like this:

a = 3;
a = (ref(a,-1)) + 2; // INCORRECT CODE

will produce array filled with 5 in ALL cells because “a” on the right side of equation is entire array filled with 3 and 2 is added to ALL cells AT ONCE !

This is VECTOR processing!

If you are trying to accumulate values on bar-by-bar basis there are functions for that.
In that case

a = Cum( 2 ); // accumulate 2 correctly

Self-referencing in the sense of recursive use of previous values to build next values on bar by bar basis can be solved with loops but it is better to use specialized built-in functions:

See also:


Thanks for that. Just what I was looking for. Sorry about the code formatting.

But @HelixTrader answer was incorrect because it did not point the fact that your code is techncially wrong and it is not issue of initialization.

Thank you for the input Tom.

Thanks for stepping in @Tomasz. I didn’t immediately see what the OP was trying to achieve.

@HelixTrader I think that your post (with commentary) is useful. Without that people could ask, “but I just want to initialize”. Your post shows that initialization alone removes “error message” but does not make it self-referencing in calculation.


The most important thing to understand is that ENTIRE ARRAY is processed AT ONCE.

Okay, only now did I get it. Thanks for that line.

1 Like