BarsSince returns NULL

I have the following AFL code.

MA_50 = MA(C,50);
bars = BarsSince( Close <= MA_50 );
printf("Bars : %g\n",bars);

For ticker symbol CUB, BarsSince returns -1e+010. I notice in this situation, all Close values are above 50MA. Possible to make it return the bar value since close is less or equal to 50MA or when 50MA change from EMPTY to non EMPTY?
Thanks in advance.

It is hard to understand what you mean by this.
EMPTY may never change to non Empty.

As a general band aid, which may not be the right way is to manipulate it as such:

MA_50 = MA(C,50);
bars = BarsSince( Close <= MA_50 );

bars_new = IIF( IsNull( bars ), BarIndex(), bars );

"return bar value", means BarIndex() ?

This screen image of CUB might help provide a better picture. Since CUB is rather a new ticker, there is no 50MA before the 50th bar so the 50MA is empty before the 50th bar. However, from the 50th bar onward, the 50MA is not empty. The BarsSince( Close <= MA_50 ) is never triggered because all the Close values are above MA_50. I need to track the number of bars when is Close is above MA_50. Can the transition empty MA_50 to non-empty be used as a trigger ? Thanks in advance.

this is subjective, i can help with writing code that does what it should. without the full algo logic, the side-effects or pros/cons are unknown.

@nsm51,

This afl code seems to work.

not_empty_ma50 = IIf(!IsEmpty(MA_50),1,0);
above_50ma_flag = IIf(not_empty_ma50 AND Close >= MA_50, 1, 0);
bars_close_ge_ma50 = BarsSince(above_50ma_flag==0);

I think something like this would also work:

bars = BarsSince( Nz(Close <= MA_50, 1) );

This

bars = BarsSince( Close <= MA_50 );

would return NULL, if CLOSE was always ABOVE MA_50 (for all bars since the beginning).

Possible to make it return the bar value since close is less or equal to 50MA or when 50MA change from EMPTY to non EMPTY?

If you want to do that you can simple CODE exactly what you are after

bars = BarsSince( Close <= MA_50 OR IsEmpty( MA_50 ) );
2 Likes