Trailing stoploss not working at all

I know there are many threads on trailing stoploss and i incorporated some of the codes into my analysis but none seem to work.

what i am trying to test is to Buy when the close crosses above the 200 SMA and SPY's close is also above 200 SMA. the sell comes if it hits the 10% trailing stop loss. the trailing stoploss code is obtained from this forum but does not seem to work. the backtest result is just 1 stock that buys and sell at end of the testing period.

can anyone help me?

code is below

SetPositionSize(20, spsPercentOfEquity ); //set 20% as max equity for each position. so total can have 5 concurrent positions
sp500 = Foreign( "SPY", "C", True );
sp500ma= MA(sp500, 200);

SlowMA = MA( C, 200 );
Buy = Cross( C, SlowMA) AND sp500>sp500ma;

Sell = 0;
SellPrice = LastValue(C);
//Trailing StopLoss//
pctStop = 10; // 10% trailing stop loss.
pctStepSize = 10; // 10% trailing stop loss to Move further.
InLong = Flip(Buy, Sell);
InTrade = InLong;
entryPrice = ValueWhen(Buy, BuyPrice);
maxPctChange = 100 * (HighestSince(Buy,High) / entryPrice -1);
numSteps = floor(maxPctChange/pctStepSize );
highestStep = entryPrice * (1 + numSteps * pctStepSize/100);
StopLevel = iif( intrade , highestStep *(1- pctStop/100),Null);
Sell = Cover = 0; // 0 or False means exit only by ApplyStop

Maybe you need

ApplyStop(stopTypeTrailing, ...
3 Likes

Read the amibroker Knowledge base.

It has all you need to know

Here is the formula with working TSL (To change the percentage of your stop loss go in parameters)

code:

///////////////////////////////////////////// To plot basic price chart //////////////////////////////////////////////////////////////////
SystemName = "Dummy name";   
SysVer ="v0.0";   
SetFormulaName( SystemName );   
  
paraCounter = 1;   
_N(paraParam = "" + paraCounter + "." +  NumToStr(GetChartID(),1,false) + ".");   
   
_SECTION_BEGIN("Price");   
SetChartOptions(0,chartShowArrows|chartShowDates);   
_N(Title = StrFormat(SystemName + " " + SysVer + "    |    {{NAME}}    -    {{INTERVAL}}    {{DATE}}          Open: %.2f          High: %.2f          Low: %.2f          Close: %.2f (%.2f%%)          Volume: %.0f          {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ), V ));   
Plot( C, "Close", colorDefault, styleNoTitle | GetPriceStyle() );    
_SECTION_END();  

////////////////////////////////////////////////// your code  ////////////////////////////////////////////////////////////////////////////////////////

SetPositionSize(20, spsPercentOfEquity ); //set 20% as max equity for each position. so total can have 5 concurrent positions
sp500 = Foreign( "SPY", "C", True ); 
sp500ma= MA(sp500, 200);

SlowMA = MA( C, 200 );
Buy = Cross( C, SlowMA) AND sp500>sp500ma;

Sell = 0;
SellPrice = LastValue(C);
 

/////////////////////////////////////////Basic trailling stoploss in percentage ///////////////////////////////////////////////

StopLevel = 1 - Param("trailing stop %", 3, 0.1, 10, 0.1)/100;  //can modify percentage from here


trailARRAY = Null;
trailstop = 0;

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

   if( trailstop == 0 AND Buy[ i ] ) 
   { 
      trailstop = High[ i ] * stoplevel;
   }
   else Buy[ i ] = 0; // remove excess buy signals

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

   if( trailstop > 0 )
   {
      trailstop = Max( High[ 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 );

//////////////////////////////////////////////////////////////////////////////////////////////

NOTE: I plotted a basic price chart and signals of your indicator with stoploss.

1 Like

thanks so much ! it worked

what does 3, 0.1, 10, 0.1 means? i looked up the following page but it also does not state what the figures mean.

http://www.amibroker.com/guide/afl/param.html

It should be well noted that ApplyStop is a way to go, and the code from Knowledge Base is solely for DRAWING the stop line. The original poster code did not incluyde any drawing so ApplyStop is ONE-LINE SOLUTION that he should use.

well, i used the following code
Sell=ApplyStop(stopTypeTrailing, stopModePercent, 15, True, True );

but it always sell 2 bars after, regardless i put it as 15% or 80%. wonder why.

Your code is wrong.
You should not assign Sell variable the way you do.

ApplyStop is NOT a function that returns anything. ApplyStop returns nothing. It is a switch that tells backtester to perform stops DURING BACKTESTING.

Correct code is

Sell = 0 ; // DO NOT exit normally

// APPLY STOP DURING BACKTESTING !  
ApplyStop(stopTypeTrailing, stopModePercent, 15, True, True );
// you need to RUN BACKTEST to see the result!
1 Like

thanks so much for pointing me in the right direction