Get BarsSince() for nth occurrence instead of 1st occurrence

The function BarsSince() will return number of bars (time periods) that have passed since ARRAY was true (or 1) for the 1st occurrence of the condition true.
https://www.amibroker.com/guide/afl/barssince.html

For example, I have an array like this;

arr_test = [1 0 0 0 1 0 0 1 0 0 1 0 0];

BarsSince(arr_test) will return 3 as that is the first occurrence of 1.

What if I want to find out the number of bars that have passed for the nth occurrence of the true condition? As illustration, I would like to have a function such that
BarsSince_N(arr_test, n=2) will return 6.

Thank you.

It is a bit unclear and it gets confusing in the middle of your post.
especially

BarSince() returns an Array

What you can do is use ValueWhen() with the nth occurrence to get the DateTime, and do a BarSince() on the DateTime to know how many bars have passed.

2 Likes

Recommended reading: http://www.amibroker.com/guide/h_understandafl.html
As @travick wrote, BarsSince would return not 3 but an array that holds different values. You can use exploration (see How do I debug my formula?) to find out how functions work.

Also you don't need DateTimes involved you can just do this

bi = BarIndex();
bars_since_2nd = bi - ValueWhen(  arr_test, bi, 2 );
2 Likes