I am trying to convert this script from v2 to v4. I've managed to migrate most of it. But I can't find a way to solve this last one.
In version 4, security()
function doesn't accept mutable
variable as its 3rd argument anymore. In order to pass mutable variable to the function, I have to wrap it in a function.
The problem is, my series variable, nAMA
, was a global variable in v2. But after I put it in a function for v4, it will be re-initialized everytime when the function is called. Thus the series is not correctly calculated. I also cannot declare nAMA outside a function, because I will get Cannot modify global variable in function
error.
I have googled and found this thread. That suggests using an array. But I didn't quite understand how to apply that with my case.
I am very new to pine script. Any advice would be very appreciated. Thanks.
Here are part of the scripts:
v2
//@version=2
study("Test", overlay=true)
res1 = input(title="HA TF", type=resolution, defval="240")
shift = input(1,"HA Shift")
sloma = input(20,"Slow EMA Period")
Length = input(5, minval=1)
xPrice = input(hlc3)
xvnoise = abs(xPrice - xPrice[1])
Fastend = input(2.5,step=.5)
Slowend = input(20)
nfastend = 2/(Fastend + 1)
nslowend = 2/(Slowend + 1)
nsignal = abs(xPrice - xPrice[Length])
nnoise = sum(xvnoise, Length)
nefratio = iff(nnoise != 0, nsignal / nnoise, 0)
nsmooth = pow(nefratio * (nfastend - nslowend) + nslowend, 2)
nAMA = nz(nAMA[1]) + nsmooth * (xPrice - nz(nAMA[1])) //<---------------
ha_t = heikinashi(tickerid)
ha_close = security(ha_t, period, nAMA) //<---------------
mha_close = security(ha_t, res1, hlc3)
fma = ema(mha_close[shift],1)
sma = ema(ha_close,sloma)
plot(fma,title="MA",color=black,linewidth=2,style=line)
plot(sma,title="SMA",color=red,linewidth=2,style=line)
v4
//@version=4
study("Test", overlay=true)
res1 = input(title="HA TF", type=input.resolution, defval="240")
shift = input(1,"HA Shift")
sloma = input(20,"Slow EMA Period")
Length = input(5, minval=1)
xPrice = input(hlc3)
xvnoise = abs(xPrice - xPrice[1])
Fastend = input(2.5,step=.5)
Slowend = input(20)
nfastend = 2/(Fastend + 1)
nslowend = 2/(Slowend + 1)
nsignal = abs(xPrice - xPrice[Length])
nnoise = sum(xvnoise, Length)
nefratio = iff(nnoise != 0, nsignal / nnoise, 0)
nsmooth = pow(nefratio * (nfastend - nslowend) + nslowend, 2)
calc() =>
nAMA = 0.0
nAMA := nz(nAMA[1]) + nsmooth * (xPrice - nz(nAMA[1])) //<---------------
ha_t = heikinashi(syminfo.tickerid)
ha_close = security(ha_t, timeframe.period, calc()) //<---------------
mha_close = security(ha_t, res1, hlc3)
fma = ema(mha_close[shift],1)
sma = ema(ha_close,sloma)
plot(fma,title="MA",color=color.black,linewidth=2,style=plot.style_line)
plot(sma,title="SMA",color=color.red,linewidth=2,style=plot.style_line)