首页 > 解决方案 > 无法将可变参数传递给安全功能

问题描述

我正在尝试将此脚本从 v2 转换为 v4。我已经设法迁移了大部分。但我找不到解决最后一个问题的方法。

在版本 4 中,security()函数不再接受mutable变量作为其第三个参数为了将可变变量传递给函数,我必须将它包装在一个函数中。

问题是,我的系列变量nAMA是 v2 中的全局变量。但是在我将它放入 v4 的函数后,每次调用该函数时都会重新初始化它。因此,该系列没有正确计算。我也不能在函数之外声明 nAMA,因为我会得到Cannot modify global variable in function错误。

我已经用谷歌搜索并找到了这个线程。这建议使用数组。但我不太明白如何在我的案例中应用它。

我对松树脚本很陌生。任何建议将不胜感激。谢谢。


以下是部分脚本:

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)

标签: pine-script

解决方案


看起来您的 nAMA 应该是考夫曼的自适应移动平均线,但使用的是 Heikin Ashi 值。为了正确计算效率比等,需要在安全调用的上下文中完成。因此它使用 HA 值而不是标准条的值。

您必须将所有输入传递给函数并在函数内进行所有计算:

f_KAMA(_src, _len, _fastlen, _slowlen) =>
    _mom = abs(_src - nz(_src[_len]))
    _volatility = sum(abs(_src - nz(_src[1])), _len)
    _er = _volatility != 0 ? _mom / _volatility : 0
    _fastalpha = 2 / (_fastlen + 1)
    _slowalpha = 2 / (_slowlen + 1)
    _sc = pow(_er * (_fastalpha - _slowalpha) + _slowalpha, 2)
    float _kama = na
    _kama := _sc * _src + (1 - _sc) * nz(_kama[1], _src)


ha_t = heikinashi(syminfo.tickerid)
ha_close = security(ha_t, timeframe.period, f_KAMA(xPrice, Length, Fastend, Slowend))

推荐阅读