# Function that does the following counted for loop

I need to duplicate the following for loop with different arguments. Is there an existing AMI broker function that does the below or should I define my own function to do this? I feel like such function should exist but I can't find it anywhere in the forum.

``````for( i = 1; i < BarCount; i++ )
{
if ( ema20[ i ] > ema20[ i - 1 ] )
{
consecutiveEMARising[i]=consecutiveEMARising[i-1]+1;
}
else
{
consecutiveEMARising[i]=0;
}

}
``````

Hi.
This is precisely why AFL is an Array programming language.

``````ema20 = EMA(C,20);

// loop code
for( i = 1; i < BarCount; i++ )
{
if ( ema20[ i ] > ema20[ i - 1 ] )
{
consecutiveEMARising[i]=consecutiveEMARising[i-1]+1;
}
else
{
consecutiveEMARising[i]=0;
}

}

// Vectorized
pema20 = Ref(ema20, -1);
compareE = ema20 > pema20;
newcon = SumSince( compareE == 0, compareE);

// plotting
Plot(C, "", colorDefault);

//Plot(consecutiveEMARising, "ce", colorRed,styleOwnScale);
// uncomment above to see overlap

Plot(newcon, "nce", colorGreen,styleOwnScale);
``````
1 Like

Or shorter

``````consecutiveEMARising = BarsSince( ROC( ema20, 1 ) <= 0 );
``````

This uses reverse logic, counts bars since it was falling or unchanged

2 Likes