He does **not** want to count forward from signal.

He wants to count **backward** from signal.

It is pretty clearly mentioned in thread subject and 1st post ("*bars back*", and in pictures).

Here is (a) solution function.

(Do **not** copy it to other forums. It is available from AmiBroker forum here only. Also not for commercial use.) If you use it then hit thanks. If you don't use it then don't but I am tired of copycats and people just grabbing what they can with their two hands.

```
function fxMxBackwardCross(sig, cross_array) {
/// @link https://forum.amibroker.com/t/counting-the-number-of-bars-back-to-a-price/10897/7
/// by fxshrat@gmail.com
Version(6.0);
bir = Status("barvisible" );// chart area array
cums = Cum(IIf(bir, sig, 0));
lastcum = LastVisibleValue(cums);//LastValue(cums);
stop_mat = Matrix(3, Max(1,lastcum), 0);
colnum = MxGetSize(stop_mat, 1);
for ( i = 0, n = 0; i < BarCount; i++ ) {
if ( bir[i] ) {
if ( sig[i] ) {
if ( n < colnum ) {
stop_mat[0][n] = i; // start bar
stop_mat[1][n] = 0; // end bar
stop_mat[2][n] = cross_array[i]; // level
for ( j = i; j >= 0; j-- ) {
if ( L[j] < stop_mat[2][n] ) {
stop_mat[1][n] = j; // end bar
break;
}
}
}
n++;
}
}
}
printf( "#lines: %g, BarCount: %g", colnum, BarCount );
for ( n = 0; n < colnum; n++ ) {
GfxMoveTo(x1 = stop_mat[0][n], y = stop_mat[2][n] );
GfxLineTo(x2 = stop_mat[1][n], y );
GfxTextOut(StrFormat("-%g bars", x1-x2), x2, y );
}
return stop_mat;
}
```

Function used in his example code:

```
// Do NOT forget to insert upper function to this example!!
// Long only for Bull Engulfing
Bull_Engulfing = Ref(C < O, -1) AND C > O AND O <= Ref(C,-1) AND C > Ref(O,-1);
Buy = C > EMA(C,30) AND Bull_Engulfing;
// Buy at todays close
BuyPrice = Close;
Sell = 0;
// Low value and Barindex number at 'Buy' Signal
Hx = Valuewhen(Buy, Low);
RequestTimedRefresh( 1 );
SetChartOptions( 0, chartShowDates | chartShowArrows | chartWrapTitle );
Plot( C, "Price", colorDefault, styleBar );
PlotShapes( Buy * shapeUpArrow, colorGreen, 0, L, -15 );
//Plot( Hx, "Hx", Colorblack, styleStaircase | styleThick );
GfxSetZOrder( 1 );
GfxSetCoordsMode( 1 );
GfxSetBkMode(2);
GfxSetTextAlign(2|0);
GfxSetTextColor( colorLightYellow );
GfxSelectFont("Arial", 8, 500 );
GfxSetBkColor( colorRed);
GfxSelectPen( colorRed, 1, 0 );
mat = fxMxBackwardCross(Buy, cross_array = L);
printf( "\n%s", MxToString(mat));
```

You should not use array functions inside Barcount loop.

It's called hundreds/thousands of times. Your code will slow down everything.

Besides using status("lastvisiblebar") will result in error because of exceeding barcount range.

You should read here Understanding how AFL works

There aren't no inbuilt candlestick pattern functions.

What you use there is a 32-bit 3rd party DLL.