Previously working indicator index out of range error
Created at 23 May 2022, 13:50
Previously working indicator index out of range error
23 May 2022, 13:50
Hi,
I was looking at an indicator that used to work previously, does not anymore:
using cAlgo.API;
using System.Linq;
namespace cAlgo
{
[Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class ThreeStrike : Indicator
{
[Parameter("Vertical Alignment", Group = "Position", DefaultValue = VerticalAlignment.Top)]
public VerticalAlignment vAlignment { get; set; }
[Parameter("Horizontal Alignment", Group = "Position", DefaultValue = HorizontalAlignment.Right)]
public HorizontalAlignment hAlignment { get; set; }
private ChartStaticText _text;
protected override void Initialize()
{
_text = Chart.DrawStaticText("idtext_red", string.Empty, this.vAlignment, this.hAlignment, Color.Chocolate);
}
public override void Calculate(int index)
{
if (index < 3)
return;
var lastThreeBars = new Bar[]
{
Bars.Last(index++),
Bars.Last(index + 2),
Bars.Last(index + 3)
};
if (lastThreeBars.All(bar => bar.Close > bar.Open))
{
_text.Text = "Wait For Red Engulfing";
_text.Color = Color.Red;
if (Bars.ClosePrices.Last(index) < Bars.OpenPrices.Last(index++))
{
_text.Text = "Sell";
_text.Color = Color.Red;
Chart.DrawVerticalLine("Sell", Bars.OpenTimes.LastValue, Color.OrangeRed);
}
}
else if (lastThreeBars.All(bar => bar.Close < bar.Open))
{
_text.Text = "Wait For Green Engulfing";
_text.Color = Color.Green;
if (Bars.ClosePrices.Last(index) > Bars.OpenPrices.Last(index++))
{
_text.Text = "Buy";
_text.Color = Color.Green;
Chart.DrawVerticalLine("Buy", Bars.OpenTimes.LastValue, Color.LimeGreen);
}
}
else
{
_text.Text = "Do Not Trade";
_text.Color = Color.Gray;
}
}
}
}
The error I get is: Crashed in Calculate with ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index.
Is index < 3 return supposed to handle this?
amusleh
24 May 2022, 10:21
Hi,
Your code is not correct, your indicator should not work at all, not sure how it was working previously.
You are passing index + x to Bars Last method, the last method starts from 1 and it allows you to access bars in reverse order from most recent bars.
If you want to access three last bars you have to change it to:
@amusleh