How To Calculate Average Directional Index (ADX) in Golang?

Member

by mitchell , in category: Technology , 2 months ago

How To Calculate Average Directional Index (ADX) in Golang?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by braeden , 2 months ago

@mitchell 

To calculate the Average Directional Index (ADX) in Golang, you can use the following steps:

  1. Install the "gonum.org/v1/gonum" package, which provides functions for calculating the ADX.
  2. Implement a function that takes a slice of high prices, low prices, and closing prices for a certain period, usually 14 days. The function should calculate the true range (TR), directional movement (DM), average true range (ATR), and the ADX.
  3. Here is a sample code snippet to calculate the ADX in Golang:
 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
40
41
42
43
44
45
46
47
48
49
50
51
package main

import (
	"fmt"
	"math"
	"github.com/danev/gonum/stat"
)

func CalculateADX(high []float64, low []float64, close []float64) float64 {
	TR := make([]float64, len(high))
	DMPlus := make([]float64, len(high))
	DMMinus := make([]float64, len(high))

	for i := 1; i < len(high); i++ {
		highLow := high[i] - low[i]
		highClose := math.Abs(high[i] - close[i-1])
		lowClose := math.Abs(low[i] - close[i-1])

		TR[i] = math.Max(highLow, highClose)
		TR[i] = math.Max(TR[i], lowClose)

		moveUp := high[i] - high[i-1]
		moveDown := low[i-1] - low[i]

		if moveUp > moveDown && moveUp > 0 {
			DMPlus[i] = moveUp
		}

		if moveDown > moveUp && moveDown > 0 {
			DMMinus[i] = moveDown
		}
	}

	ADX := stat.Mean(TR[15:], nil) // Average True Range	
	ADX += stat.Mean(DMPlus[15:], nil) // Positive Directional Movement
	ADX += stat.Mean(DMMinus[15:], nil) // Negative Directional Movement
	ADX = (ADX / 3) * 100 // Calculate ADX

	return ADX
}

func main() {
	// Example data for high, low, and close prices
	high := []float64{100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150}
	low := []float64{95, 100, 105, 110, 115, 120, 125, 130, 135, 140, 145}
	close := []float64{97, 103, 108, 113, 118, 123, 128, 133, 138, 143, 148}

	adx := CalculateADX(high, low, close)
	fmt.Printf("ADX: %f
", adx)
}


This code snippet calculates the ADX using the True Range (TR), Positive Directional Movement (DMPlus), and Negative Directional Movement (DMMinus) based on the input high, low, and close prices data. It then calculates the ADX value and prints it to the console.