Please see code at the end!
I'm creating a new version of the RSI, called Cutler's RSI. The difference with Wilder's RSI is that it uses simple moving averages instead of exponential moving averages.
So I created an indicator and a function.
The indicator does not perform any calculation, it simply plots data.
The function stores data and performs all calculations.
The problem is that a System.DivideByZeroException is thrown whenever I change the indicator's status to ON. I code in VS2010 and have tried debugging step by step (attaching MC process to the debugger) but I cannot find any division by zero in the code.
The exception is located at the last line in CalcBar(). However, relativeStrength is never equal to -1 so the denominator is never equal to 0...
Apparently, whenever I change the line
- relativeStrength = avgUp / avgDown
to
- relativeStrength = avgUp + avgDown
...there is no exception any longer. However, MC says that the exception is thrown at the last line of CalcBar(). This is confusing, also because avgDown is never equal to 0...
Community, please help!
Thanks in advance.
Regards,
PBJ
Please see below:
Code: Select all
namespace PowerLanguage.Function
{
public class RSICutler : FunctionSeries<double>
{
private VariableSeries<double> _upReturns;
private VariableSeries<double> _downReturns;
public ISeries<double> Price { get; set; }
public int Length { get; set; }
public RSICutler(CStudyControl ctx)
: base(ctx)
{
}
public RSICutler(CStudyControl ctx, int dataStream)
: base(ctx, dataStream)
{
}
protected override void Create()
{
_downReturns = new VariableSeries<double>((IStudyControl)this);
_upReturns = new VariableSeries<double>((IStudyControl)this);
}
protected override void StartCalc()
{
}
protected override double CalcBar()
{
if (Bars.CurrentBar < Length)
{
return 100;
}
var dayReturn = Price.Value - Price[1];
_upReturns.Value = Math.Max(0, dayReturn);
_downReturns.Value = Math.Min(0, dayReturn);
var relativeStrength = 100.00;
var avgUp = _upReturns.Average(Length);
var avgDown = _downReturns.Average(Length);
if (!PublicFunctions.DoubleEquals(avgDown, 0.0) && !PublicFunctions.DoubleEquals(avgUp, 0.0))
{
relativeStrength = avgUp / avgDown;
}
return 100 - (100 / (1 + relativeStrength));
}
}
}