How To Calculate Average True Range (ATR) in JavaScript?

by oda.tromp , in category: Technology , 9 months ago

How To Calculate Average True Range (ATR) in JavaScript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by heather_fritsch , 9 months ago

@oda.tromp 

To calculate the Average True Range (ATR) in JavaScript, you can follow the following steps:

  1. First, calculate the True Range (TR) for each period using the formula: TR = max(high - low, abs(high - prevClose), abs(low - prevClose))
  2. Next, calculate the Average True Range (ATR) using the following formula: ATR = (ATR * (n - 1) + TR) / n Where: ATR is the previous ATR value (if calculating ATR for the first time, set ATR as the TR value) n is the number of periods (usually 14 is used for ATR calculation)


Here is a sample JavaScript code snippet to calculate the Average True Range (ATR) for a given dataset:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function calculateATR(data, n) {
  let atr = 0;

  for (let i = 1; i < data.length; i++) {
    const tr = Math.max(
      data[i].high - data[i].low,
      Math.abs(data[i].high - data[i - 1].close),
      Math.abs(data[i].low - data[i - 1].close)
    );

    atr = (atr * (n - 1) + tr) / n;
  }

  return atr;
}

// Sample dataset
const data = [
  { high: 10, low: 8, close: 9 },
  { high: 12, low: 9, close: 11 },
  { high: 14, low: 10, close: 12 },
  // Add more data points here...
];

const n = 14; // Number of periods
const atr = calculateATR(data, n);
console.log("Average True Range (ATR):", atr);


This code snippet calculates the Average True Range (ATR) based on the given dataset and the number of periods specified. You can modify the data array with your own dataset and run the code to calculate the ATR.