How To Compute Average True Range (ATR) using Visual Basic?

by annabell_mcdermott , in category: SEO Tools , 2 months ago

How To Compute Average True Range (ATR) using Visual Basic?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by delpha , 2 months ago

@annabell_mcdermott 

To compute the Average True Range (ATR) using Visual Basic, you can follow these steps:

  1. Create a new Visual Basic project in your Integrated Development Environment (IDE) such as Visual Studio.
  2. Add a new module to your project by right-clicking on the project in the Solution Explorer and selecting "Add" -> "Module".
  3. In the module, write a function to calculate the True Range (TR) of the data. True Range is the maximum of three values – current high minus the current low, absolute value of the current high minus the previous close, and absolute value of the current low minus the previous close.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Private Function CalculateTrueRange(ByVal currentHigh As Double, ByVal currentLow As Double, ByVal previousClose As Double) As Double
    Dim range1 As Double
    Dim range2 As Double
    Dim range3 As Double
    
    range1 = currentHigh - currentLow
    range2 = Math.Abs(currentHigh - previousClose)
    range3 = Math.Abs(currentLow - previousClose)
    
    Return Math.Max(range1, Math.Max(range2, range3))
End Function


  1. Next, write a function to calculate the Average True Range (ATR) by taking the average of the True Range values over a specified period. For example, you can calculate the 14-day ATR by taking the average of the True Range values for the last 14 days.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Private Function CalculateATR(ByVal data As List(Of Double), ByVal period As Integer) As Double
    Dim atr As Double = 0
    
    For i As Integer = period To data.Count - 1
        Dim trValues As New List(Of Double)
        For j As Integer = 0 To period - 1
            trValues.Add(CalculateTrueRange(data(i - j), data(i - j - 1), data(i - j - 1)))
        Next
        atr += trValues.Average()
    Next
    
    atr /= (data.Count - period)
    
    Return atr
End Function


  1. Finally, you can call the CalculateATR function with your data and the desired period to calculate the Average True Range. Here's an example of how you can use the function:
1
2
3
4
5
6
Dim data As New List(Of Double) From {10.5, 11.2, 10.8, 12.4, 11.9, 12.6, 13.2, 12.7}
Dim period As Integer = 14

Dim atr As Double = CalculateATR(data, period)

Console.WriteLine("Average True Range (ATR) for the given data is: " & atr)


That's it! You have now successfully computed the Average True Range (ATR) using Visual Basic. You can customize the functions according to your specific requirements and data structure.