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

Member

by mike , in category: SEO Tools , 7 months ago

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

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by cameron_walter , 7 months ago

@mike 

To compute 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
Public Function CalculateATR(values As List(Of Double), period As Integer) As Double
    Dim atr As Double = 0

    If values.Count >= period Then
        Dim trList As New List(Of Double)
        
        For i As Integer = 1 To values.Count - 1
            Dim tr As Double = Math.Max(values(i), values(i - 1)) - Math.Min(values(i), values(i - 1))
            trList.Add(tr)
        Next

        Dim sumATR As Double = 0
        For i As Integer = 0 To period - 1
            sumATR += trList(i)
        Next

        atr = sumATR / period
    End If

    Return atr
End Function


To use this function, pass a list of price values and the period for which you want to calculate the ATR. The function calculates the True Range (TR) for each period and then computes the average of those values to get the ATR.


Here's an example of how you can use this function in your code:

1
2
3
4
5
6
Dim priceList As New List(Of Double) From {10.0, 10.5, 11.0, 10.8, 11.2, 11.5, 12.0, 11.7, 11.2, 11.0}
Dim period As Integer = 5

Dim atr As Double = CalculateATR(priceList, period)

Console.WriteLine("Average True Range (ATR): " & atr)


In this example, we calculate the ATR for a list of price values with a period of 5. The calculated ATR value will be displayed in the console.