How To Calculate Average True Range (ATR) using Dart?

Member

by mose , in category: General Help , 8 months ago

How To Calculate Average True Range (ATR) using Dart?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by damian_mills , 8 months ago

@mose 

To calculate the Average True Range (ATR) using Dart, you can use the following code snippet:

 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
28
29
30
31
32
33
34
35
36
37
import 'dart:math';

// Function to calculate True Range
double trueRange(double high, double low, double previousClose) {
  return max(high - low, max((high - previousClose).abs(), (low - previousClose).abs()));
}

// Function to calculate Average True Range (ATR)
double averageTrueRange(List<double> highs, List<double> lows, List<double> closes, int period) {
  List<double> trueRanges = [];
  double atr = 0.0;

  for (int i = 1; i < highs.length; i++) {
    double tr = trueRange(highs[i], lows[i], closes[i - 1]);
    trueRanges.add(tr);

    if (i >= period) {
      double sum = 0.0;
      for (int j = i - period + 1; j <= i; j++) {
        sum += trueRanges[j];
      }
      atr = sum / period;
    }
  }

  return atr;
}

void main() {
  List<double> highs = [10.0, 12.0, 14.0, 15.0, 16.0];
  List<double> lows = [8.0, 10.0, 12.0, 13.0, 14.0];
  List<double> closes = [9.0, 11.0, 13.0, 14.0, 15.0];
  int period = 3;

  double atr = averageTrueRange(highs, lows, closes, period);
  print('Average True Range (ATR): $atr');
}


In this code snippet, the trueRange function calculates the True Range for each period, while the averageTrueRange function calculates the Average True Range using the True Ranges for the specified period. Finally, the main function demonstrates how to use the averageTrueRange function with sample data.


You can customize the input data (highs, lows, closes, period) as needed for your calculations.