Trailing stop when condition 1 occurs

Hi I am trying to set a trailing stop when condition 1 occurs; if it does not occur the initial stop is 20%.

condition1 =Close>Ref(High,-1)
if condition 1 is true I want the trailig stop to be:
stop1 = Ref(Low,-1);

I have followed this guide but I must be doing something wrong:

Here is the code, I don't understand why the trailing is not updated when I am bought and condition 1 occurs:

_SECTION_BEGIN("Test1");


SetOption( "CommissionAmount", 5 );
SetOption("MaxOpenPositions", 4); 
SetOption( "InitialEquity", 100000 );                     
PositionSize = -20;
SetOption( "AllowPositionShrinking", True );             
SetOption( "AllowSameBarExit", True );                   
SetOption("ExtraColumnsLocation", 1 );
RoundLotSize = 1;
SetTradeDelays (0, 0, 0, 0 );


Buy = Cross( MACD(), Signal() );
Sell = 0;
trailARRAY = Null;
trailstop = 0;
Sell=0;
Short = Cover = False;


StopLevel = 1 - Param("trailing stop %", 0, 0.1, 20, 0.1)/100;
condition1 = 0;
stop1 = 0

trailARRAY = Null;
trailstop = 0;

for( i = 1; i < BarCount; i++ )
{
   if(Buy[i])
   {
	 trailstop = BuyPrice[i]*0.8;
	 condition1 =Close[i]>Ref(High[i],-1);
	 if(condition1[i] > 0)
	 {
	    stop1 = Ref(Low[i],-1);
		trailstop = stop1[ i ] * stoplevel;
	 }	 	 
   }
   
   else Buy[ i ] = 0; // remove excess buy signals

   if( trailstop > 0 AND Low[ i ] < trailstop )
   {
      Sell[ i ] = 1;
      SellPrice[ i ] = trailstop;
      condition1 = 0;
      stop1 = 0;
      trailstop = 0;
   }

   if( trailstop > 0 )
   {
      trailstop = Max( stop1[ i ] * stoplevel, trailstop );
      trailARRAY[ i ] = trailstop;
   }

}


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

Plot( Close,"Price",colorBlack,styleBar);
Plot( trailARRAY,"trailing stop level", colorRed );


_SECTION_END();

Greetings.

That is not trailing stop. It is just exit condition with two parts.

But then the condition is impossible because you DO NOT know the TODAY'S CLOSE to evaluate condition1 before the end of the session, so you can't exit when today prices hit yesterday low, because the session has ended at the time you can evaluate condition1.

1 Like

I understand you but I don't know how to fix it, if I take condition1 out of the loop it doesn't work either.

No, you don't understand it. It is pointless to fix the code if the IDEA is flawed. Please re-read my previous answer. You physically can't evaluate Close>Ref(High,-1) before end of the session, because you don't know what the CLOSE price is, before market closes.

1 Like

Thanks, but I don't know how to solve it, if I put Ref(Close,-1)>Ref(High,-2) it doesn't work either.

          condition1 =Close[i]>High[i-1];
	 
          if(condition1 > 0)

Not sure , but you are mixing scalar with array, fix it and test.

1 Like

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