# How to reference a signal/condition occurred x number of bars ago

Hi,

Below is a line of my AFL code that looks for a bar’s high, which is higher than the day’s 2 times standard deviation of VWAP and also either of its previous two bars’ low is lower than a specified open range high (open range high is defined as highest high of first 45mins).

``````above2std = H>=(VWAP+2*SD) AND (Ref(L,-1)<ORBH OR Ref(L,-2)<ORBH);
``````

Note - VWAP, SD etc variables are all defined correctly and i’ve tested the above code.

Now, i want to look for a bar that satisfies the follow condition -

1. the current bar’s closing price is crossing the 1 standard deviation of VWAP from below (i know how to code this condition)

2. with the above2std condition from mentioned above occurred within the last 120 bars (on a 3mins chart, so it means triggered either some time yesterday or today in conjunction with condition 1 above).

I tried using BarsSince(above2std), but the returned scan result didn’t seem right.

Is using BarsSince function the right way to accomplish what i want to do?

Any guidance would be much appreciated.

Regards,
Tony

Hi Tony,

BarsSince() will tell you how many bars have elapsed since a condition occurred. If you want the actual bar number where a condition occurred, you might want to look at the ValueWhen function. Something similar to the following might work for you:

``````above2stdBarNum = ValueWhen(above2std, BarIndex(), 1);
``````

If you just want to know whether or not the above2std condition has occurred at least N times during the past 120 bars but don’t really care about WHICH bar(s) the condition occurred on, then I would suggest something like this:

``````recentlyAbove2std = sum(above2std, 120) > N;
``````

Matt

1 Like