I’m having an hard time debugging a Pinescript indicator. Here is the code
//@version=4
study("Trend Regularity Adaptive Moving Average","TRAMA",overlay=true)
length=input(99),src = input(close)
//----
ama = 0.
//debugging part
txt = tostring(ama[1])
x = bar_index
y = src
//end of debugging part
label.new(x, y, txt) // print value of close
hh = max(sign(change(highest(length))),0)
ll = max(sign(change(lowest(length))*-1),0)
tc = pow(sma(hh or ll ? 1 : 0,length),2)
ama := nz(ama[1]+tc*(src-ama[1]),src)
plot(ama,"Plot",#ff1100,2)
What i don’t understand is the value of ama[1]. Here ama is declared to be 0, but ama[1] returns a non zero value. From what i understood, in Pinescript [1] should return the value of the previous bar, but since in this case ama is set to be 0, how is it possible that it returns a non zero value?
>Solution :
It is because you are re-assigning a value to ama with ama := nz(ama[1]+tc*(src-ama[1]),src).
The way this works is, if ama[1]+tc*(src-ama[1]) is na, ama will be src. If it is not na, it will be ama[1]+tc*(src-ama[1]).
nz(source, replacement) → simple float
RETURNS
The value ofsource
if it is notna. If the value ofsourceisna, returns zero, or
thereplacementargument when one is used.ARGUMENTS
source (series int/float/bool/color) Series of values to process.
replacement (series int/float/bool/color) Value that will replace all ‘na’ values in thesourceseries.