I'm a newbie so the solution to my problem is probably obvious to everyone 
(except me).  I've tried to run a single-stock backtest with code by TJ, 
published in the May 09 issue of Stocks & Commodities (please see below).  It 
should generate a graph of a trailing stop loss line, by either fixed-% or 
ATR-chandelier methods, by looping rather than the ApplyStop command. 

When I try to run the code my chart shows "Empty" for the trailing stop loss 
line.  Likewise, in an exploration AddColumn produces values for sup and res 
for each i, but trailARRAY is empty. (The graphics for the exploration do 
generate a line in the chart for the  trailstop line!?)

Any suggestions on how I can get this code to output a backtest?
   ============================   

// "Using Initial and Trailing Stops" (part 1), by Sylvain Vervoort, 
// p36, Stocks & Commodities, May 09, programmed by T. Janeczko

Version(5.20);
SetBarsRequired(sbrAll);

// get start date
Start = Cross( DateNum(), ParamDate("Start date", "2008-12-04") );
Started = Flip( Start, 0);

StopMode = ParamToggle( "Stop Mode", "Fixed | Chandelier" );
StopLevel = Param( "Fixed perc %", 14, 0.1, 50, 0.1)/100;
StopATRFactor = Param( "Chandelier ATR Multiple", 4, 0.5, 10, 0.1 );
StopATRPeriod = Param( "Chandelier ATR period", 14, 3, 50 );

// calculate support and resistance levels
if( StopMode == 0 ) // fixed percentage trailing stop
{
sup = C * (1 - stoplevel);
res = C * (1 + stoplevel);
}
else  // Chandelier ATR-based stop
{
sup = C - StopATRFactor * ATR( StopATRPeriod );
res = C + StopATRFactor * ATR( StopATRPeriod );
}

// calculate trailing stop line
trailARRAY = Null;
trailstop = 0;
for( i=1; i<BarCount; i++)
{
if( Started[i] ==0 ) continue;

if( C[i] > trailstop AND C[i-1] > trailstop )
   trailstop = Max( trailstop, sup[i] );
else
if( C[i] < trailstop AND C[i-1] < trailstop )
   trailstop = Min( trailstop, res[i] );

else
   trailstop = IIf( C[i] > trailstop, sup[i], res[i] );

trailARRAY[i] = trailstop;
}

//  generate buy/sell signals based on crossover with trail stop line 
Buy = Start OR Cross( C, trailArray );
Sell =  Cross( trailArray, C);

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

Plot( Close, "Price", colorBlack, styleBar);
Plot( trailARRAY, "trailing stop level", colorRed);

Reply via email to