HoldMinBars conditionally

Hello,
I'm trying to find a way to apply HoldMinBars only to select Sell conditions. In the code below, HoldMinBars applies to all trades. I would like to make it apply only to the first sell condition "Sell1".

Buy = Cross(C,EMA(C,25));
Sell1 = Cross(EMA(C,25),C);
Sell2 = ROC(C,3)<-5;
Sell = Sell1 OR Sell2;

SetOption("HoldMinBars",15);

I would use BarsSince(Buy) however there are redundant Buy signals that prevent this from working.

I appreciate any input that someone here might have. I would prefer to avoid looping if possible.

Thank you.

Thank you for that amazing piece of work fxshrat. Using ExRem twice is not something I would have thought of. I will keep testing it but the logic appears correct.

I have tested the code and I don't believe it's working quite right. I modified the code below so I code test it using only the first sell condition compared. When I uncomment the first three lines, I get a different result than when I run it at shown below. Shouldn't this produce the same result?

//SetOption("HoldMinBars",15);
//Buy = Cross(C,EMA(C,25));
//Sell = Cross(EMA(C,25),C);




Buy1 = Cross(C,EMA(C,25));

Sell1 = Cross(EMA(C,25),C);
Sell2 = 0;//ROC(C,3)<-5;

Buy = Buy1;
Sell = Sell2;

Buy1 = ExRem(Buy1, Sell1);
Sell1 = ExRem(Sell1, Buy1);

Sell = Sell OR (Sell1 AND BarsSince(Buy1) > 14);

Buy = ExRem(Buy, Sell);
Sell = ExRem(Sell, Buy);

Write loop then it works.

Buy = Cross(C,EMA(C,25));
Sell1 = Cross(EMA(C,25),C);
Sell2 = ROC(C,3)<-5;

nbars = 15;
buyentrybar = Sell = 0; 
/// Delay just one of several Sell rules
/// for a min. amount of bars having passed after Buy entry
/// @link https://forum.amibroker.com/t/holdminbars-conditionally/20095/5
/// @link http://www.amibroker.com/guide/h_backtest.html
for ( i = 0; i < BarCount; i++ ) {	
	if ( Buy[ i ] && buyentrybar == 0 ) 
		buyentrybar = i;
	else Buy[ i ] = 0;

	SellSignal1 = Sell1[ i ] AND i > buyentrybar + nbars;
	SellSignal2 = Sell2[ i ];
	SellSignal = SellSignal1 OR SellSignal2;	
	if ( SellSignal && buyentrybar > 0 ) {
		Sell[ i ] = 1;    
		buyentrybar = 0;
	} else Sell[ i ] = 0;	 
} 

Plot( C, "Price", colorDefault, styleBar );
PlotShapes( Buy * shapeUpArrow + Sell * shapeDownArrow,
            IIf( Buy, colorGreen, IIf(Sell == Sell1 AND Sell!=Sell2, colorRed, colorOrange) ), 
            0, y = IIf( Buy, L, H ) );
PlotShapes( Buy * shapeSmallCircle + Sell * shapeSmallCircle,
            IIf( Buy, colorGreen, IIf(Sell == Sell1 AND Sell!=Sell2, colorRed, colorOrange) ), 0,
            y = IIf( Buy, BuyPrice, SellPrice ), 0 );
3 Likes

If I change it to "nbars = 14" it works perfectly.

Thank you for your help fxshrat.