我需要像在Pine Script(交易视图代码(中一样计算ATR。我说的是股票或外汇技术分析中的平均真实范围指标。在Pine脚本的文档中说是这样计算的:
plot(rma(close, 15))
// same on pine, but much less efficient
pine_rma(x, y) =>
alpha = y
sum = 0.0
sum := (x + (alpha - 1) * nz(sum[1])) / alpha
plot(pine_rma(close, 15))
RETURNS
Exponential moving average of x with alpha = 1 / y.
我已经尝试了与 MQL5 文档中相同的方法,策略的结果根本不相似,ATR 有问题。计算真实范围很简单,我知道问题在于如何计算这个 RMA(滚动移动平均线?它说是按照原始 RSI 指标计算的。有人可以更好地解释一下如何在 Pine 脚本中计算 ATR,希望有一个例子。目前我使用了 EMA 与 alpha= 1/ATR_Period ,就像在文档中一样,但似乎不一样。波纹管是新ATR的代码,基本和MT5中的默认值相同,我只更改了最后一部分,在哪里计算。谢谢你的帮助!
//--- the main loop of calculations
for(i=limit;i<rates_total && !IsStopped();i++)
{
ExtTRBuffer[i]=MathMax(high[i],close[i-1])-MathMin(low[i],close[i-1]);
ExtATRBuffer[i]=(ExtTRBuffer[i] - ExtATRBuffer[i-1]) * (1 / ATR_Period) +ExtATRBuffer[i-1] ; // Here I calculated the EMA of the True Range
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
在 Pine 版本 4 上,您可以使用:
//@version=4
myAtr = atr(14)
https://www.tradingview.com/pine-script-reference/#fun_atr
Pine 脚本中的 ATR 实现
//@version=3
study(title="Average True Range", shorttitle="ATR", overlay=false)
pine_rma(x, y) =>
alpha = y
sum = 0.0
sum := (x + (alpha - 1) * nz(sum[1])) / alpha
true_range() =>
max(high - low, max(abs(high - close[1]), abs(low - close[1])))
plot(pine_rma(true_range(), 14), color=red)
//plot(atr(14))
引用迈克尔的话,我刚刚意识到实施意味着在实践中
(TR1+TR2+...tr_n(/n
其中n
表示经期倒退。因此,这意味着atr(periods)
表示每个柱线沿n
周期tr
average
。Michal在pinescript中这样做,因为pinescripte中的所有内容都是一个系列,需要递归破解过去的总和。
看看重构的相同代码,这样你就会意识到我在说什么:
/@version=3
study(title="Average True Range", shorttitle="ATR", overlay=false)
averageTrueRange(tr, periods) =>
sum = 0.0
sum := (tr + (periods - 1) * nz(sum[1])) / periods
currentTrueRange() =>
max(high - low, max(abs(high - close[1]), abs(low - close[1])))
plot(averageTrueRange(currentTrueRange(), 15))