Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the ATR like in Pine Script

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);
  }
//+------------------------------------------------------------------+
like image 365
cristianc Avatar asked Dec 08 '25 09:12

cristianc


1 Answers

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

like image 164
OlivierLarue Avatar answered Dec 11 '25 23:12

OlivierLarue



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!