Simple AFL looping issue

I am testing a simple breakout system to learn AFL looping and I wish to find out the average duration where the trade closes above the 10-exponential MA in explore without using the Backtest (the #bars column in Backtest). I am getting durations of over 900 which do not make sense. May I know why this section of code has an issue? Thank you.

TenEMA = EMA(Close, 10);
Duration = 0;

for ( i = 0 ; i < BarCount - 1 ; i++)
{
if (Close[i] > TenEMA[i])
	{
	Duration = i + 1;
	}
}

AddColumn(duration, "duration");

AmiBroker just does what you tell it to do.
Your code returns the last index added by one where Close > EMA.

It does the same as this non loop line

Duration = LastValue(Ref(ValueWhen(C>EMA(C,10), BarIndex()+1),-1));
3 Likes

You should not use loop.

To get duration you just need single line of array function BarsSince().

cond = C>EMA(C,10);
duration = BarsSince(NOT cond);

Getting same result via (slower (!)) loop

n = Duration = 0;
cond = C > EMA(C, 10);
for ( i = 0; i < BarCount; i++) {
	if (NOT cond[ i ])	n = 0;
	else				n++;
	Duration[ i ] = n;
}
3 Likes

Thank you - your explanation on the erroneous code makes sense

@Mocazilla Thanks for asking the question and thanks to @fxshrat for your clear thinking and explanation. Connecting BarsSince and duration is a simple concept, I realize, but significant to my enlightenment.

Your code:

Duration = i + 1;

vs. fxshrat's code:

Duration[ i ] = n;

causes me to recommend that you read the following:
Understanding How AFL Works
AFL reminds me of Linux wherein "everything is a file", except in AFL, "everything is an array."

Unless it is a string or matrix or scalar or object. So "everything is an array" is not actually true.

See:

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.