How To Compute Average True Range (ATR) using Java?

Member

by dortha , in category: SEO Tools , 2 months ago

How To Compute Average True Range (ATR) using Java?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by cameron_walter , 2 months ago

@dortha 

To compute Average True Range (ATR) using Java, 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
38
39
public class ATRCalculator {
    
    public double calculateATR(double[] highs, double[] lows, double[] closes, int period) {
        double[] trueRanges = new double[highs.length];
        
        // Calculate True Range for each period
        for (int i = 1; i < highs.length; i++) {
            double trueRange = Math.max(highs[i] - lows[i], Math.max(Math.abs(highs[i] - closes[i - 1]), Math.abs(lows[i] - closes[i - 1])));
            trueRanges[i] = trueRange;
        }
        
        // Calculate Average True Range using Exponential Moving Average (EMA)
        double atr = 0;
        double multiplier = 2.0 / (period + 1);
        
        for (int i = 0; i < period; i++) {
            atr += trueRanges[i];
        }
        
        atr /= period;
        
        for (int i = period; i < highs.length; i++) {
            atr = ((trueRanges[i] - atr) * multiplier) + atr;
        }
        
        return atr;
    }
    
    public static void main(String[] args) {
        double[] highs = {10, 12, 14, 15, 16};
        double[] lows = {8, 10, 12, 13, 14};
        double[] closes = {9, 11, 13, 14, 15};
        
        ATRCalculator atrCalculator = new ATRCalculator();
        double atr = atrCalculator.calculateATR(highs, lows, closes, 3);
        
        System.out.println("Average True Range (ATR): " + atr);
    }
}


In this code snippet, the calculateATR method takes as input arrays of highs, lows, and closing prices, as well as the period for which the ATR is calculated. It then calculates the True Range for each period and uses Exponential Moving Average (EMA) to compute the Average True Range (ATR). The main method demonstrates how to use this method with sample data.