@jass17 , if you open the formula code editor and use the "Insert Snippet" functionality, you'll get the following two examples of trailing stops.
The simplest one:
amount = 10; // 10% loss (trailing)
ApplyStop( stopTypeTrailing, stopModePercent, amount, True );
Simply adding the above code to your trading system code, you are applying a 10% trailing stop rule (automatically "trailing" the price as it rises).
The function declaration is:
_ApplyStop( type, mode, amount, exitatstop, volatile = False, ReEntryDelay = 0, ValidFrom = 0, ValidTo = -1 ):_
Select the mode 2 to apply an amount expressed in points (stopModePoint) if you want to work with points instead of a percent amount.
If you have not already done it, review also the ApplyStop apply built-in stop documentation page, to better understand all the parameters.
There is also a second sample code using a loop, that shows graphically the trailing stop level:
Buy = 1; // replace with your buy rule
Sell = 0; // replace with your sell rule
StopLevel = 1 - Param("trailing stop %", 3, 0.1, 10, 0.1)/100;
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 );
While waiting for more advanced users' answers/solutions, you may start to play/modify these AmiBroker provided code snippets and see if you can use them in your sample system.
Moreover, a search for "trailing stop" here in the forum will provide you additional material to study.