Backtest Trailing Stop Loss in Charts

When I backtest this afl in futures at closing prices (backtest settings)

//Code copied from the KBs
StopLevel = 1 - Param("trailing stop %", 3, 0.1, 10, 0.1)/100;

Buy = Cross( MACD(), Signal() );
Sell = 0;
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 );

http://www.amibroker.com/kb/2007/03/24/how-to-plot-a-trailing-stop-in-the-price-chart/

The following buy signals are generated in Charts
1

But when I backtest It the result is blank.
2

Please guide me where I am getting wrong

You might want to check out ApplyStop() also.
It has many advantages and internally takes care of a lot of things.

2 = stopTypeTrailing - trailing stop,

https://www.amibroker.com/guide/afl/applystop.html

1 Like

Wrong, the code of KB works just fine (here)!

  1. Uncheck Pad & align
  2. (Why have you inserted comma separated list as reference symbols there?)
  3. Check percentage trail stop setting of parameter window in Analysis (it has to be in line with chart setting if you want to have same output!). Your chart does not look like using the default 3% setting but a lower one and if you apply the same AFL to analysis it will use that default one of 3% initially (if not changed to different value by user). So if you use 3% default setting in analysis but chart uses different setting then you do not need to be surprised if you do get different or no output in analysis. :roll_eyes:

Alright?

unnamed

If you still get no output try using low(est) position size setting of one share/contract.

SetPositionSize(1, spsShares);

Besides if you want to know more detailed BT output then check "Detailed Report" in analysis settings and investigate further.
19


Anyway here I am getting SAME result of chart in analysis (if using same percent trail stop setting).

850

958

1 Like