amibroker

HomeKnowledge Base

How to plot a trailing stop in the Price chart

In this short article we will show how to calculate and plot trailing stop using two different methods.

First method uses looping and it does not use ApplyStop() function as it does not plot stops – it only triggers them in backtest mode. The stop % level can be adjusted via PARAMETERS dalog.



StopLevel Param("trailing stop %"30.1100.1)/100;

Buy CrossMACD(), Signal() );
Sell 0;
trailARRAY Null;
trailstop 0;

for( 
1BarCounti++ )
{

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

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

   if( 
trailstop )
   {   
      
trailstop MaxHigh] * stopleveltrailstop );
      
trailARRAY] = trailstop;
   }

}

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

PlotClose,"Price",colorBlack,styleBar);
PlottrailARRAY,"trailing stop level"colorRed );


 

Trailing stop plot

Alternatively you can use code without looping, but then it requires Equity(1) to evaluate stops as shown in the example code below. Equity( 1 ) is the backtester-in-a-box that runs actual single-security backtest and when parameter 1 is passed it writes back signals (removing excessive ones and writing out all stops to Buy/Sell/Short/Cover arrays).



StopLevel Param("trailing stop %"30.1100.1 );

SetTradeDelays(0,0,0,0);

Buy CrossMACD(), Signal() );
Sell 0;
ApplyStopstopTypeTrailingstopModePercentStopLevelTrue );
 
Equity1); // evaluate stops, all quotes

InTrade FlipBuySell );

SetOption("EveryBarNullCheck"True );
stopline IIfInTradeHighestSinceBuyHigh ) * ( 0.01 StopLevel ), Null );

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

PlotClose,"Price",colorBlack,styleBar);
Plotstopline"trailing stop line"colorRed );

One Response to “How to plot a trailing stop in the Price chart”

  1. Bert Steele
    June 17th, 2007 | 3:48 pm

    Thanks for the looping example. Examples that address issues via looping and also array approach are appreciated.

Leave a reply