The following is a simple backtester code for illustrative purposes which is
meant to enter on the close being greater than the 20 period moving average and
exiting on a trailing stop based on the high minus 3.0 times ATR. Basically I'm
trying to test the effectiveness of an ATR stop which I've embedded in the
backtester code. I've plotted the trailing stop as an indicator over the price
chart but when I run a backtest of the code below, the exits don't match up
with the trailing stop indicator. In fact I'm getting exits one and two bars
after entry. I really don't understand what is going on as I'm not that
experienced at writing AFL code. Can someone with coding experience please help?
Thanks
Maurice
Code:
SetBarsRequired(10000,10000);
SetFormulaName("Weekly SMA System with ATR stop");
SetTradeDelays( 1, 1, 1, 1 );
SetOption( "initialequity", 100000 );
SetOption( "PriceBoundChecking", 1 );
SetOption( "CommissionMode", 2 );
SetOption( "CommissionAmount", 32.95 );
SetOption( "UsePrevBarEquityForPosSizing", True );
SetOption("MaxOpenPositions", 20); //
SetOption( "AllowPositionShrinking", False);
SetOption("AllowSameBarExit", False);
ATRLevel = 3*ATR(20);
Buy = C>MA(C,30);
PositionSize=-10;// invest 10% of portfolio equity in single trade
Sell = 0;
trailARRAY = Null;
trailstop = 0;
for( i = 1; i < BarCount; i++ )
{
if( trailstop == 0 AND Buy[ i ] )
{
trailstop = H[ i ]- ATRLevel[ i ];
}
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( H[ i ]- ATRLevel[ i ], trailstop );
trailARRAY[ i ] = trailstop;
}
}
Sell = trailARRAY;
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);