Barssince Moving Averages Crossed

I’m trying to create an exploration that counts how many bars since 3 moving averages have crossed (i.e. MA20>MA50>MA100). I only know how to create a count for a simple 2 moving average cross (i.e. ma20>ma100). Any help would be very much appreciated. Thanks!

@sheridan Use the BarsSince() function to count bars. I’m not 100% certain what you are asking for. Perhaps this code snippet will work for you.

condition = MA20 > MA50 && MA50 > MA100;
numBars = BarSince(!conditon);
1 Like

exactly what i needed. did not thought it was that simple. thank you! :slight_smile:

When two moving averages cross, for example, Buy= Cross(MA( C, 8 ), MA( C, 10 ));, how do I use the Barssince to have a buy when the cross in 2 days ago is lower than today's open? Here is an example from Amibroker, barssince( macd() < 0 ). Here is what I have, Buy= barssince(Cross(MA( C, 8 ), MA( C, 10 ))()<2);. is this a correct way of using Barssince function?

Hi Sheridan,
Can you share how you create a count for 2 moving average cross, for example ma20>ma50?

try this. :slight_smile:

condition20cross50 = ma20>ma50;
ma20cross50 = BarsSince(!condition20cross50);

Thanks, Sheridan.
Let say if I have the cross between those two moving averages (MA20, MA50) in the past two days and want to buy on the third day, should it be like this,CrossCond=(MA20>MA50)-2; Buy=BarsSince(!CrossCond);?

i've tried that, but not count bars after crossing. the result is only appear 1 bar with that afl.
i want to count bar after crossing MA5, MA20 and before crossing MA20, MA5.

condition = MA5>MA20 AND MA20<MA5 ; (it doesn't work)
Bars = BarsSince(condition);

thank you before

For cross you need to use (surprise!) Cross() function not 'greater than' because 'greater then' will give you 'state' form while you really need impulse.

You have to read a lot about BASICS:

  2. How do I debug my formula?
  3. State vs impulse:

Condition = Cross(MA5,MA20) ;
Bars = BarsSince (!condition);

only 1 bar appear

Re-read what I wrote. Learn the basics first. You are having problem because you are using "NOT" operator. The exclamation mark means "NOT".
If you apply NOT operator to result of Cross (which gives you impulse when MA crossed) you will get the reverse of impulse (ALL bars set to True except impulse bar).

This can be easily illustrated using debugging techniques I pointed out earlier. Just read that and use!

Condition = Cross(MA5,MA20) ;
Plot( Condition, "Impulse", colorRed );
Plot( ! Condition, "Reverse of impulse", colorGreen ); // ! is "NOT" operator 

Obviously applying BarsSince to such array makes no sense. The only thing that makes sense is applying BarsSince to impulse form, i.e:

Condition = Cross(MA5,MA20);
bars_since_cross = BarsSince( Conditition ); // WITHOUT exclamation mark
1 Like