Saturday, March 10, 2007

Algorithm to Find Maximum Equity in an Array

Recently I've been working on learning Visual Basic .NET and applying it to writing some simple and some not-so-simple trading systems.

It took me a while to figure it out since I'm a little new to using For..Next and Do..Until/While loops in code but here's the way to find the current maximum equity if you have an array with equity values stored in each array cell:

For i as Integer = 0 to numberOfTrades - 1
If i = 0 Then ' no drawdown (obviously) before 1st trade is taken
maximumEquity = savedEquityArray(i)
Else ' for all other trades besides the first one
maximumEquity = savedEquityArray(i)
Do
If maximumEquity >= savedEquityArray(i - k) Then
maximumEquity = maximumEquity
Else
maximumEquity = savedEquityArray(i - k)
End If
Loop Until i - k = 0
End If
Next i

Then if you wanted to compute the drawdown up to that point you could say:

drawdown = Math.Round(((savedEquityArray(i) / maximumEquity) - 1) * 100, 2, MidpointRounding.AwayFromZero)