Error while Locating Highest HIGH and Lowest LOW in last N days

I am drawing 4 year High / Low Lines. When all the the candle fits the screen i am able to see high and low Line. But as soon as i zoom and the even few candle goes out of the amibroker screen, it gives error " Array Subscript out of Range " .
Is there any other way to view High / Low Lines with getting above error.


My code is

// Locate Highest HIGH and Lowest LOW in last N days

N = Param("Days to go back(Excl today)", 1060, 1060, 2000, 1);
PriceStyle = ParamStyle("Chart Type", styleCandle, maskPrice);
LineStyle = ParamStyle("Line Style");

NDayHi = H[BarCount - 1 - N];
NDayLo = L[BarCount - 1 - N];
XH = XL = BarCount - 1 - N;
NDayHi_vol = V[BarCount - 1 - N];
NDayLo_vol = V[BarCount - 1 - N];

for(i = BarCount - 1 - N; i < BarCount - 1; i++)
if(H[i] > NDayHi)
NDayHi = H[i];
NDayHi_vol = V[i];
XH = i;
if(L[i] < NDayLo)
NDayLo = L[i];
NDayLo_vol = V[i];
XL = i;

// Define the Lines to be drawn

HLine = LineArray(BarCount - 1 - N, NDayHi, BarCount - 2, NDayHi);
LLine = LineArray(BarCount - 1 - N, NDayLo, BarCount - 2, NDayLo);

// Plot chart

_N(Title = StrFormat("{{NAME}} ({{INTERVAL}}) {{DATE}} {{OHLCX}} Vol=%1.0f\n{{VALUES}}", V));

Plot(C, "", colorGrey50, PriceStyle);
Plot(Hline, WriteVal(N, 1.0) + " Day Hi", colorBrightGreen, LineStyle);
Plot(LLine, WriteVal(N, 1.0) + " Day Lo", colorWhite, LineStyle);

@sanjaywalke, first of all, when you post/paste some code, you should use the Code button! (please, see this answer of @Tomasz).

The mistake in your code is that you use the variable N to calculate the first bar index and you DO NOT check for a valid range value.

Any function or line of code that uses a single element of an array variable employing the array subscript notation (i.e. the [ ] square brackets) you need to ensure that the value between the [] is in the range 0 (zero) to BarCount-1.

Take a look at this line of code:

NDayHi = H[BarCount - 1 - N];

What happens here if BarCount is 1000 and N is 1060? You get an array subscript out of range error since the subscript value will be (1000-1)-1060 = - 61 (outside of the valid range)

Detailed explanation of this kind of error is found here.

A simple fix to this error is to add to your code a line that will avoid such an invalid subscript value:

LineStyle = ParamStyle("Line Style");

N = Min(BarCount-1, N); // Add this line

NDayHi = H[BarCount - 1 - N];

Adding this line, when the BarCount is less than the value that you select in your N param, N will be reassigned to ensure that the first bar you'll access in your code is the [0] bar.



Thanks a lot. The changes suggested by you is working perfectly fine.

Thanks again.


Sanjay Walke

Recommended reading: