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 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
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
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.
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 !
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:
Your code is wrong because it self-references HAV_Curr variable. You need to first read
Understand AFL. It is essential reading. This HAV_Curr = sqrt(0.94 (Ref(HAV_Curr,-1)^2))+(.06 HAV^2); is incorrect. You are trying just to exponentially smooth the HAV (1st order IIR). This should be properly done using EMA or AMA HAV_Curr = sqrt( AMA( HAV ^ 2, 0.06 ) ); See AMA() function.
Thanks for that. Just what I was looking for. Sorry about the code formatting.
@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.