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

Member

by samara , in category: Third Party Scripts , 6 months ago

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

, 2 months ago

﻿@samara ﻿

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

1. Calculate the True Range (TR) for each period:
• TR = Max(High - Low, Abs(High - PreviousClose), Abs(Low - PreviousClose))
1. Calculate the +DI (Positive Directional Indicator) and -DI (Negative Directional Indicator) for each period:
• +DI = (H - H') / TR
• -DI = (L' - L) / TR
• Where H = High of the current period, L = Low of the current period, H' = High of the previous period, L' = Low of the previous period
1. Calculate the Directional Movement Index (DX) for each period:
• DX = Abs(+DI - -DI) / (+DI + -DI)
1. Calculate the Average Directional Index (ADX) using the Wilder's Smoothing Formula:
 ``` 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 ``` ```func calculateADX(highs: [Double], lows: [Double], closes: [Double]) -> [Double] { var plusDM = [Double]() var minusDM = [Double]() var tr = [Double]() var dx = [Double]() var adx = [Double]() for i in 1.. minusDirectionalMovement && plusDirectionalMovement > 0 { plusDM.append(plusDirectionalMovement) } else { plusDM.append(0) } if minusDirectionalMovement > plusDirectionalMovement && minusDirectionalMovement > 0 { minusDM.append(minusDirectionalMovement) } else { minusDM.append(0) } if i > 14 { let trSum = tr.suffix(14).reduce(0, +) let plusDMSum = plusDM.suffix(14).reduce(0, +) let minusDMSum = minusDM.suffix(14).reduce(0, +) let plusDI = (plusDMSum / trSum) * 100 let minusDI = (minusDMSum / trSum) * 100 let directionalIndex = abs(plusDI - minusDI) / (plusDI + minusDI) if dx.count < 14 { dx.append(directionalIndex) } else { let previousADX = adx.last ?? 0 let currentADX = ((previousADX * 13) + directionalIndex) / 14 adx.append(currentADX) } } } return adx } ```