Buy signals are repeated when using loop

Hi everyone,

I wrote a trading strategy with 2 exit conditions. Condition 1: exit when stoploss is reached. Condition 2: when profit exceeds 25%, start using trailing stop. The problem is that it repeats the buy signal and each time it uses the stop from the first condition.
I have read some other posts on the forum but have not been able to resolve this issue. Please help me fix it

Plot(C,"" , colorBlueGrey,styleCandle);
Ema25 = EMA(C,25);
Plot(Ema25,"EMA25",colorBlack);

HL1 = abs(Ref(H,-1) - Ref(L,-1))/2;
OC1 = abs(Ref(O,-1) - Ref(C,-1))/2;

fkupbar = L < Ref(L,-1) AND Cross(C , (Ref(C,-1)+OC1)) AND C > Ema25  AND V > Ref(V,-1);

Buy = fkupbar ;

PlotShapes(IIf(Buy,shapeSmallUpTriangle,shapeNone),colorGreen,0,L);

Sell = 0; // replace with your sell rule

entry = ValueWhen(Buy,Close);
countT = BarsSince(Buy);

maxprofit =  (HHV(C,countT)-entry)/entry*100;


StopLevel1 = 1 - Param("stoploss %", 7, 0.0, 10, 0.1)/100;
StopLevel2 = 1 + Param("trailing stop %", 10, 0.0, 20, 0.1)/100;

add = 0;
addarray = Null;
trailARRAY = Null;
trailstop = 0;

for( i = 1; i < BarCount; i++ )
 {

   if( trailstop == 0 AND Buy[ i ] ) 
    { 
       trailstop = entry[ i ] * stoplevel1;
    }
    else Buy[ i ] = 0; // remove excess buy signals
	
	if( trailstop > 0 AND Low[ i ] < trailstop  AND countT[i]>=2)
    {
       Sell[ i ] = 1;
       SellPrice[ i ] = trailstop;
       trailstop = 0;
       add = 0;
    }

   if( trailstop > 0 AND maxprofit[i] < 25 )
    {   
       trailstop = entry[i] * stoplevel1;
       trailARRAY[ i ] = trailstop;
       
    }
    else if ( trailstop > 0 AND maxprofit[i] > 25 )
    {
		
		trailstop = entry[i] * stoplevel2 + add;
		trailARRAY[ i ] = trailstop;
		PlotText(""+WriteVal(maxprofit[i],5.1) + "%",i,H[i]*1.05, colorBrightGreen,colorDefault,30);
		add += Max(C[i]-C[i-1],0);
		addarray[i]= add;
    }

}

PlotShapes(Buy*shapeUpArrow,colorGreen,0,Low);
PlotShapes(Sell*shapeDownArrow,colorRed,0,High);


Plot( trailARRAY,"trailing stop level", colorRed ,styleDashed+styleThick);
Plot( addarray,"Add", colorGreen ,styleDashed+styleThick);```

There is a EXREM for this purpose.
In order to remove excessive amount of signals use it before final arrays (variables).
But since you use full candle cycle you could use some variable like in_position=0;//or 1
and with it allow or disallow your Buy/Sell signal only if you have or have not "in position".

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