Count the green bars since a buy

I'm trying to set for a sell condition that there are 5 green or up bars since the buy. In this example code, it would appear that the count is resetting each time it sees a new buy condition. Can anyone point out my error?

Buy = Cross( MACD(), Signal() );

NumberBars = BarsSince( Buy );
UpBar = Close > Open;
BarsConditionTrue = Sum( UpBar, NumberBars );
Sell = iif( BarsConditionTrue > 5, 1, 0 );
Short = Cover = 0;

//remove excess Buy,Sell,Short,Cover signals
Buy=ExRem(Buy,Sell);
Sell=ExRem(Sell,Buy);

image

1 Like

It is similar to one previous thread of yours

Buy = Cross( MACD(), Signal() );
UpBar = Close > Open;

/// Similar to
/// @link https://forum.amibroker.com/t/do-i-need-to-make-a-loop-for-self-referencing-code/17705/2
Sell = 0;
cnt_array = Null;
bprice = cnt = 0; 
for ( i = 0; i < BarCount; i++ ) {	
	if ( Buy[ i ] && bprice == 0 ) {
		bprice = BuyPrice[ i ];
	} else Buy[ i ] = 0;
	
	if ( bprice > 0  ) {	
		if ( UpBar[i] ) 
			cnt++;
	
		// exit if count of UpBar > n
		if (cnt > 5) {
			Sell[ i ] = 1;    
			bprice = cnt = 0;
		}		
		cnt_array[ i ] = cnt;	// store cnt to array
	} 	
}

Plot( C, "Price", colorDefault, styleBar );
PlotShapes( Buy * shapeUpArrow + Sell * shapeDownArrow,
            IIf( Buy, colorGreen, colorRed ), 0, IIf( Buy, L, H ) );
Plot( cnt_array, "UpBarCount", colorYellow, styleOwnScale );
3 Likes

Thank you so much again @fxshrat , I hope all is well with you.

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