DEV Community

Cover image for Calculating ATR (Average True Range) using JavaScript
Mustafa Onur Çelik
Mustafa Onur Çelik

Posted on

Calculating ATR (Average True Range) using JavaScript

ATR (Average True Range) is a technical analysis indicator that shows the average range of a security’s price over a given period of time. It is calculated using the following steps:

  1. Calculate the true range (TR) of each period.
  2. Calculate the ATR for each period using the previous periods’ ATR values.

Here is some example code in JavaScript that demonstrates how to calculate ATR using the above steps:

function calculateATR(prices, periods) {
  let atr = [];

  for (let i = 0; i < prices.length; i++) {
    // Calculate the true range (TR)
    let tr = Math.max(
      prices[i].high - prices[i].low,
      Math.abs(prices[i].high - prices[i - 1].close),
      Math.abs(prices[i].low - prices[i - 1].close)
    );

    // Calculate the ATR
    let atrValue = 0;
    if (i < periods) {
      atrValue = tr;
    } else {
      atrValue = (atr[i - 1] * (periods - 1) + tr) / periods;
    }
    atr.push(atrValue);
  }

  return atr;
}
Enter fullscreen mode Exit fullscreen mode

In this example, the calculateATR function takes an array of price data and the number of periods to use in the calculation as input, and returns an array of ATR values.

You can use this function to calculate ATR for any security by passing in an array of its historical price data and the desired number of periods.

Top comments (0)