How To Calculate Average True Range (ATR) VB.NET?

by cristobal , in category: Technology , 2 months ago

How To Calculate Average True Range (ATR) VB.NET?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by bailey_conroy , 2 months ago

@cristobal 

To calculate the Average True Range (ATR) in VB.NET, 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
Public Function CalculateATR(data As List(Of Decimal), period As Integer) As List(Of Decimal)
    Dim atrValues As New List(Of Decimal)

    For i As Integer = 0 To data.Count - 1
        If i >= period Then
            Dim atr As Decimal = CalculateCurrentATR(data, i, period)
            atrValues.Add(atr)
        Else
            atrValues.Add(0)
        End If
    Next

    Return atrValues
End Function

Private Function CalculateCurrentATR(data As List(Of Decimal), index As Integer, period As Integer) As Decimal
    Dim trueRangeValues As New List(Of Decimal)

    For i As Integer = index - period + 1 To index
        Dim trueRange As Decimal = CalculateTrueRange(data, i)
        trueRangeValues.Add(trueRange)
    Next

    Dim atr As Decimal = trueRangeValues.Average()
    Return atr
End Function

Private Function CalculateTrueRange(data As List(Of Decimal), index As Integer) As Decimal
    Dim high = data(index)
    Dim low = data(index)
    Dim close = data(index - 1)
    
    Dim trueRange1 = Math.Abs(high - low)
    Dim trueRange2 = Math.Abs(high - close)
    Dim trueRange3 = Math.Abs(low - close)
    
    Return Math.Max(Math.Max(trueRange1, trueRange2), trueRange3)
End Function


You can use the CalculateATR function to calculate the ATR values for a given list of price data and a specified period. The function loops through the data and calculates the ATR for each data point using the CalculateCurrentATR function, which in turn calculates the true range for each period using the CalculateTrueRange function. Finally, the ATR values are calculated by averaging the true range values for each period.