How to make this code shorter using an AFL function

Hi,

I have the following code. Is there a way to make this shorter and more efficient ie. If i want to to a repetition of 50 bars i don't want to copy and paste "ref(A,offset)>B" 50 times.

Note, cutoffPriceNearTop is not a constant it's an array.

countClosedWithinTopRange = 
Ref(High,-8)>cutoffPriceNearTop + Ref(High,-7)>cutoffPriceNearTop + Ref(High,-6)>cutoffPriceNearTop +
Ref(High,-5)>cutoffPriceNearTop + Ref(High,-4)>cutoffPriceNearTop + Ref(High,-3)>cutoffPriceNearTop +
Ref(High,-2)>cutoffPriceNearTop + Ref(High,-1)>cutoffPriceNearTop;

The best option i can come up with is:

for ( i = 1; i <= 8; i++ )
{
	countClosedWithinTopRange +=Ref(High,-i)>cutoffPriceNearTop;
}

You want to count Higher Highs from the source array(cutoff) in this code.

The closest might be this, a relatively new function though over a year ago.
AFL Function Reference - BARSSINCECOMPARE (amibroker.com)

countClosedWithinTopRange = BarsSinceCompare( H, ">", cutoffPriceNearTop );

discussed here

Thanks but this isn't a counted loop I only want the past 8 bars for the look back. While BarsSinceCompared will count from earliest event and that can be 50 bars ago.

The loop you provided is already a short form of the inlined verbose way above it. Both gives you a count of the last 8 bars.

nsm51 mentioned a way to get more than 8 bars but then you said you only wanted 8 bars, so what is it that you are after exactly?

Also, a loop under 100,000 elements, does not need to made more efficient. Your computer can deal with that in microseconds. You can try this out yourself looking at the AFL exec timing.

2 Likes

You can also use Percentile function AFL Function Reference - PERCENTILE

See Function of Nth highest function in AFL - #10 by Tomasz

But quite frankly if that is just 8 elements, then Ref() inside 8-step loop is probably the fastest solution, really. No need to overoptimize. Ref()s are super fast.

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