@noemy.bosco
To calculate the Average Directional Index (ADX) using C#, 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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
using System; using System.Collections.Generic; using System.Linq; namespace ADXCalculator { class Program { static void Main(string[] args) { List<double> highPrices = new List<double> { 100, 102, 105, 98, 110, 115, 112, 108 }; List<double> lowPrices = new List<double> { 95, 98, 101, 94, 105, 110, 108, 104 }; List<double> closePrices = new List<double> { 98, 101, 104, 98, 108, 112, 110, 105 }; int period = 14; List<double> positiveDMs = new List<double>(); List<double> negativeDMs = new List<double>(); for (int i = 1; i < highPrices.Count; i++) { double highDiff = highPrices[i] - highPrices[i - 1]; double lowDiff = lowPrices[i - 1] - lowPrices[i]; double positiveDM = highDiff > lowDiff && highDiff > 0 ? highDiff : 0; double negativeDM = lowDiff > highDiff && lowDiff > 0 ? lowDiff : 0; positiveDMs.Add(positiveDM); negativeDMs.Add(negativeDM); } List<double> trueRanges = new List<double>(); for (int i = 0; i < closePrices.Count - 1; i++) { double trueRange = Math.Max(highPrices[i + 1] - lowPrices[i + 1], Math.Max(Math.Abs(highPrices[i + 1] - closePrices[i]), Math.Abs(lowPrices[i + 1] - closePrices[i]))); trueRanges.Add(trueRange); } List<double> smoothPositiveDMs = new List<double>(); List<double> smoothNegativeDMs = new List<double>(); List<double> DXs = new List<double>(); smoothPositiveDMs.Add(positiveDMs.Take(period).Sum() / period); smoothNegativeDMs.Add(negativeDMs.Take(period).Sum() / period); int j = 0; for (int i = period; i < positiveDMs.Count; i++) { smoothPositiveDMs.Add((smoothPositiveDMs[j] * (period - 1) + positiveDMs[i]) / period); smoothNegativeDMs.Add((smoothNegativeDMs[j] * (period - 1) + negativeDMs[i]) / period); j++; } for (int i = 0; i < smoothPositiveDMs.Count; i++) { double DX = Math.Abs((smoothPositiveDMs[i] - smoothNegativeDMs[i]) / (smoothPositiveDMs[i] + smoothNegativeDMs[i])) * 100; DXs.Add(DX); } double ADX = DXs.Take(period).Sum() / period; Console.WriteLine("ADX: " + ADX); } } } |
Replace the highPrices
, lowPrices
, and closePrices
lists with your actual price data and adjust the period
parameter as needed. This code calculates the ADX based on the Wilder's Smoothing Method.