amibroker

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.

I am using Amibroker ver6.30.5


Solution

  • You might want to look at Valuewhen.

    So, then you can do something like:

    bi = ValueWhen(arr_test > 0, BarIndex(), "nth occurence - 0 is the latest");
    bars_since = LastValue(Close) - bi;
    

    Here, I'm just using LastValue to get the last barnumber of the entire price series. This is untested, but you should get the idea.