Trading Evolution

Markets are never wrong - opinions often are

RSI (relative strength index) in C#

The RSI (relative strength index) is a momentum indicator that compares the average of recent gains to average of recent losses. It is calculated using the following formula:

RSI = 100 - 100/(1 + RS)

RS = Average of x days' up closes / Average of x days' down closes.

Below is the implementation of the formula in C#:

	public class Rsi
	{
		int		_period;
		int		_valueCount;
		decimal _last;
		decimal _previousValue;
		decimal _averageGain;
		decimal _averageLoss;

		public Rsi(int period)
		{
			if (period <= 1 || 1000 < period)
				throw new ArgumentOutOfRangeException("period");

			_period = period;
		}

		public bool AddValue(decimal value)
		{
			_last = 0;

			if (_previousValue <= 0)
			{
				_previousValue = value;
				return false;
			}

			if (_valueCount < _period - 1)
			{
				if (_previousValue < value)
					_averageGain += value - _previousValue;
				else
					_averageLoss += _previousValue - value;
				_valueCount++;
				_previousValue = value;
				return false;
			}

			if (_valueCount == _period - 1)
			{
				if (_previousValue < value)
					_averageGain += value - _previousValue;
				else
					_averageLoss += _previousValue - value;
				_valueCount++;

				_averageGain   /= _period;
				_averageLoss   /= _period;
			}
			else
			{
				_valueCount++;
				if (_previousValue < value)
				{
					_averageGain = (_averageGain * (_period - 1.0m) + (value - _previousValue))/_period;
					_averageLoss = (_averageLoss * (_period - 1.0m))/_period;
				}
				else
				{
					_averageGain = (_averageGain * (_period - 1.0m))/_period;
					_averageLoss = (_averageLoss * (_period - 1.0m) + (_previousValue - value))/_period;
				}
			}

			if (_averageLoss != 0)
				_last = 100.0m - 100.0m / (1.0m + _averageGain/_averageLoss);
			else
				_last = 100;

			_previousValue = value;

			return true;
		}

		public decimal Last
		{
			get
			{
				return _last;
			}
		}
	}

 

Loading