Bars since higher or equal value

Since your original algorithm needs two nested loops AND inner loop does NOT have fixed length (known in advance) then it is difficult to write pure array code.

Additional problem with this particular algorithm is that the inner loop works backwards (from newest to oldest) which is not natural direction of array processing functions. So solution needs some trickery (reversing arrays).

General array solution would be twisted, and probably not worth the effort, but in your case, in your example AFL formula you are just using selected value, so you could write simpler code like this that does not require loops:

function BarsSinceHigherValueSelectedVal( SrcArray )
{
	bi = BarIndex();
	sbi = SelectedValue( bi );
	
	hs = Reverse( HighestSinceBars( Reverse( bi == sbi ), Reverse( SrcArray ) ) ) ;
	
	hs = Ref( bi - ValueWhen( hs == 0, bi ), -1 ) + 1;
		
	shs = SelectedValue( hs );
	
	return IIf( bi >= sbi - shs AND bi <= sbi, SrcArray[ sbi ], Null );
}

Plot( C, "", colorDefault, styleCandle );
Plot( BarsSinceHigherValueSelectedVal( High ), "array", colorOrange );
7 Likes