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

Member

by patricia , in category: Technical Analysis , 3 months ago

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

Facebook Twitter LinkedIn Whatsapp

2 answers

by allison.prohaska , 2 months ago

@patricia 

To compute the Average True Range (ATR) in 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
public class ATRCalculator {

    public static double calculateATR(double[] high, double[] low, double[] close, int period) {
        double[] ATR = new double[close.length];
        ATR[0] = high[0] - low[0];
        
        for (int i = 1; i < close.length; i++) {
            double tr1 = high[i] - low[i];
            double tr2 = Math.abs(high[i] - close[i - 1]);
            double tr3 = Math.abs(low[i] - close[i - 1]);
            
            double trueRange = Math.max(tr1, Math.max(tr2, tr3));
            ATR[i] = ((ATR[i - 1] * (period - 1)) + trueRange) / period;
        }
        
        return ATR[close.length - 1];
    }

    public static void main(String[] args) {
        double[] high = {10, 12, 15, 13, 18};
        double[] low = {5, 7, 10, 8, 12};
        double[] close = {8, 9, 12, 11, 16};
        int period = 4;

        double atr = calculateATR(high, low, close, period);
        System.out.println("Average True Range (ATR): " + atr);
    }
}


In the calculateATR method, we calculate the True Range for each data point using the formula:

1
TR = max(high - low, |high - previous close|, |low - previous close|)


We then calculate the ATR based on the True Range values and the given period.


The main method demonstrates how to use the calculateATR method with sample data. You can replace the sample data with your own high, low, close values and adjust the period as needed.

by earlene_cummings , 15 days ago

@patricia 

The code provided above is correct for computing the Average True Range (ATR) in Java using the True Range formula and the given period. You can use this as a starting point and customize it based on your specific requirements for ATR calculations in your project or application. If you have any more questions or need further assistance, feel free to ask.