_indicatorKey = indicatorKey _periods = periods _firstPeriods = firstPeriods
' Get the underlying indicator values, indexed by bar index. Define values() As Number = IndicatorValues(_indicatorKey, barIndex, length + _periods + _firstPeriods + 1) ' Use for the gains. Define gains As Number ' Use for the losses. Define losses As Number Define diff As Number Define currentGain As Number Define currentLoss As Number Define smoothFactor As Number = 1 / _periods ' Use for the calculated indicator values, indexed by bar index. Define results(length - 1) As Number ' Calculate the indicator values for the specified bar range. For i As Integer = length - 1 To 0 Step -1 gains = 0 losses = 0 ' Calculate the indicator value for the current bar. For j As Integer = i + _periods + _firstPeriods To i Step -1 diff = values(j) - values(j+1) currentLoss = 0 currentGain = 0 If (diff > 0) Then currentGain = diff End If If (diff < 0) Then currentLoss = -1 * diff End If If (gains <> 0) Then gains = (1 - smoothFactor) * gains + smoothFactor * currentGain Else gains = currentGain End If If (losses <> 0) Then losses = (1 - smoothFactor) * losses + smoothFactor * currentLoss Else losses = currentLoss End If Next results(i) = 100 - (100 / (1 + (gains / losses))) Next Return results