{"id":52,"date":"2007-03-24T11:06:34","date_gmt":"2007-03-24T16:06:34","guid":{"rendered":"http:\/\/www.amibroker.com\/kb\/2007\/03\/24\/how-to-plot-a-trailing-stop-in-the-price-chart\/"},"modified":"2014-12-04T08:23:03","modified_gmt":"2014-12-04T13:23:03","slug":"how-to-plot-a-trailing-stop-in-the-price-chart","status":"publish","type":"post","link":"https:\/\/www.amibroker.com\/wordpress\/kb\/2007\/03\/24\/how-to-plot-a-trailing-stop-in-the-price-chart\/","title":{"rendered":"How to plot a trailing stop in the Price chart"},"content":{"rendered":"
In this short article we will show how to calculate and plot trailing stop using two different methods. <\/p>
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.<\/p>
StopLevel <\/span>= <\/span>1 <\/span>- <\/span>Param<\/span>(<\/span>"trailing stop %"<\/span>, <\/span>3<\/span>, <\/span>0.1<\/span>, <\/span>10<\/span>, <\/span>0.1<\/span>)\/<\/span>100<\/span>;
<\/span>Buy <\/span>= <\/span>Cross<\/span>( <\/span>MACD<\/span>(), <\/span>Signal<\/span>() );
<\/span>Sell <\/span>= <\/span>0<\/span>;
<\/span>trailARRAY <\/span>= <\/span>Null<\/span>;
<\/span>trailstop <\/span>= <\/span>0<\/span>;
for( <\/span>i <\/span>= <\/span>1<\/span>; <\/span>i <\/span>< <\/span>BarCount<\/span>; <\/span>i<\/span>++ )
{
if( <\/span>trailstop <\/span>== <\/span>0 <\/span>AND <\/span>Buy<\/span>[ <\/span>i <\/span>] )
{
<\/span>trailstop <\/span>= <\/span>High<\/span>[ <\/span>i <\/span>] * <\/span>stoplevel<\/span>;
}
else <\/span>Buy<\/span>[ <\/span>i <\/span>] = <\/span>0<\/span>; <\/span>\/\/ remove excess buy signals
<\/span>if( <\/span>trailstop <\/span>> <\/span>0 <\/span>AND <\/span>Low<\/span>[ <\/span>i <\/span>] < <\/span>trailstop <\/span>)
{
<\/span>Sell<\/span>[ <\/span>i <\/span>] = <\/span>1<\/span>;
<\/span>SellPrice<\/span>[ <\/span>i <\/span>] = <\/span>trailstop<\/span>;
<\/span>trailstop <\/span>= <\/span>0<\/span>;
}
if( <\/span>trailstop <\/span>> <\/span>0 <\/span>)
{
<\/span>trailstop <\/span>= <\/span>Max<\/span>( <\/span>High<\/span>[ <\/span>i <\/span>] * <\/span>stoplevel<\/span>, <\/span>trailstop <\/span>);
<\/span>trailARRAY<\/span>[ <\/span>i <\/span>] = <\/span>trailstop<\/span>;
}
}
<\/span>PlotShapes<\/span>(<\/span>Buy<\/span>*<\/span>shapeUpArrow<\/span>,<\/span>colorGreen<\/span>,<\/span>0<\/span>,<\/span>Low<\/span>);
<\/span>PlotShapes<\/span>(<\/span>Sell<\/span>*<\/span>shapeDownArrow<\/span>,<\/span>colorRed<\/span>,<\/span>0<\/span>,<\/span>High<\/span>);
<\/span>Plot<\/span>( <\/span>Close<\/span>,<\/span>"Price"<\/span>,<\/span>colorBlack<\/span>,<\/span>styleBar<\/span>);
<\/span>Plot<\/span>( <\/span>trailARRAY<\/span>,<\/span>"trailing stop level"<\/span>, <\/span>colorRed <\/span>)<\/code>\u00a0<\/p>