Reputation: 61
I need to calculate the ATR the same way as in Pine Script, the trading view code. I'm talking about the Average True Range indicator in technical analysis for stocks or FX. In the documentation in Pine Script says is calculated like this:
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.
I have tried the same way as in the documentation in MQL5, and the results of the strategy are not similar at all, something is wrong with the ATR. Calculate the True Range is straightforward, I know the problem is in how is calculated this RMA (rolling moving average?). It says is calculated as in the original RSI indicator. Can someone explain better please how is calculated the ATR in Pine Script, hopefully with a example. At the moment I used the EMA with alpha= 1 / ATR_Period , as in the documentation, but seems is not the same. Bellow is the code for the new ATR, basically is the same as the default in MT5, I only changed the last part, where is calculated. Thank you for the help!
//--- 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);
}
//+------------------------------------------------------------------+
Upvotes: 2
Views: 15567
Reputation: 2410
Pine version 5 and 6:
//@version=6
myAtr = ta.atr(14)
Pine version 4:
//@version=4
myAtr = atr(14)
https://www.tradingview.com/pine-script-reference/v6/#fun_ta.atr
Upvotes: 5
Reputation: 551
Quoting Michael, I just was realized that implementation means in practice
(tr1+tr2+...tr_n)/n
where n
means periods back. So it means that atr(periods)
means the average
of tr
in each bar along n
periods. Michal do that in pinescript because all in pinescripte is a serie and needs recursion hack back the past sum.
Take a look of the refactored same code, so you will realize about what I'm saying:
/@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))
Upvotes: 0
Reputation: 2821
That's ATR implementation in Pine Script
//@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))
Upvotes: 3