please see the bottom attached src of my "Returns" function.
I am plotting the values of returns.percentChange.Value (a VariableSeries).
Here seems to be the bug:
1) if I do not access returns.Value, the plotted values of returns.percentChange.Value are delayed by 1 bar.
2) However if I access returns.Value (even if I don't actually do anything with the results) the plotted values are not delayed by 1 bar. (simply adding the line var noop = this.returns.Value; makes the plot align properly)
Code: Select all
using System;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
namespace PowerLanguage
{
namespace Function
{
public sealed class Returns : FunctionSeries<System.Double>
{
public Returns(CStudyControl _master) : base(_master) { }
public Returns(CStudyControl _master, int _ds) : base(_master, _ds) { }
public VariableSeries<double> percentChange;
public VariableSeries<double> cumulativeChange;
public VariableSeries<bool> isNewDay;
public IInstrument Instrument { get; private set; }
public void Initialize(IInstrument instrument)
{
this.Instrument = instrument;
}
protected override void Create()
{
// create variable objects and function objects
this.percentChange = new VariableSeries<double>(this);
this.cumulativeChange = new VariableSeries<double>(this);
this.isNewDay = new VariableSeries<bool>(this);
}
protected override void StartCalc()
{
// assign inputs
}
protected override System.Double CalcBar()
{
// function logic
var change = this._GetInstrumentChange(this.Instrument);
this.percentChange.Value = change.Item1;
this.isNewDay.Value = change.Item2;
if (this.isNewDay.Value == true)
{
this.cumulativeChange.Value = 0.0;
}
else
{
this.cumulativeChange.Value = this.percentChange.Value + this.cumulativeChange[1];
}
return this.percentChange.Value;
}
private Tuple<double, bool> _GetInstrumentChange(IInstrument instrument)
{
if (instrument.Info.Resolution.IsDayOrHigher())
{
//don't let our close of yesterday impact returns today
//this.Output.WriteLine("daily");
}
else if (instrument.Time[1].Day != instrument.Time[0].Day)
{
//this.Output.WriteLine("start of day");
return Tuple.Create(0.0, true);
}
var closes = instrument.Close;
var isNewDay = false;
var percentChange = (closes[0] - closes[1]) / closes[1];
return Tuple.Create(percentChange, isNewDay);
}
}
}
}