Using Multiple Donchian Lowerband As StopLoss

I plan to create trading system with stop loss rule as follow:
If buy price less than DonchianLower30 than use DonchianLower30 as stop loss level, unless use DonchianLower20.

DonchianUpper20 =HHV(Ref(H,-1),20);
DonchianLower20 = LLV(Ref(L,-1),20);

DonchianUpper30 =HHV(Ref(H,-1),30);
DonchianLower30 = LLV(Ref(L,-1),30);

Plot(DonchianUpper20,"DU",colorBlue,styleLine);
Plot(DonchianLower20,"DL",colorBlue,styleLine);

Plot(DonchianUpper30,"DU",colorRed,styleLine);
Plot(DonchianLower30,"DL",colorRed,styleLine);
 
Buy = H > DonchianUpper20;
sellpoint = IIf(BuyPrice < DonchianLower30, DonchianLower30, DonchianLower20);
Sell = L < sellpoint;
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
 
  
/* Plot Buy and Sell Signal Arrows */
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorGreen, 0, L, Offset=-15);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorRed, 0, L, Offset=-15);

Amibroker

On picture above, sell signal souldn't occur yet because buy price is less than DonchianLower30.
How to fix the code?

1 Like

Finally, I found the solution.

Buy = H > DonchianUpper20;
BuyPrice = ValueWhen(Buy, C, 1);
Sell = 0;
titikbuy = 0;

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

   if( titikbuy == 0 AND Buy[ i ] ) 
   { 
      titikbuy = BuyPrice[ i ];
   }
   else 
   {
	  Buy[ i ] = 0; // remove excess buy signals
   }

   if( titikbuy > 0 AND titikbuy < DonchianLower30[ i ] )
   {
      if(L[i] < DonchianLower30[ i ])
      {
		  Sell[ i ] = 1;
		  SellPrice[ i ] = C[i];
		  titikbuy = 0;
      }
   }
   else
   {
	  if( titikbuy > 0 AND titikbuy >= DonchianLower30[ i ] )
	  {
		  if(L[i] < DonchianLower20[ i ])
		  {
			 Sell[ i ] = 1;
			 SellPrice[ i ] = C[i];
			 titikbuy = 0;
		  }
	  }
   }
 

}

Case closed. :slightly_smiling_face:

1 Like

I looked at your code yesterday and couldn't see any glaring reason why it did not work.

I would think you shouldn't have to use a for loop in order to get this done. For loops will significantly slow down your code.

Maybe someone can chime in with an even better answer?

@Pinecone, what happens using ValueWhen in the "sellpoint" condition in the OP first formula?
I suggest to add some exploration lines to understand what's going on. What is the BuyPrice at each bar? What should be its value used in that condition?

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