Traders' Tip text
Generally, when I think of setting a trailing stop, I immediately reach for Wealth-Lab’s ExitAtTrailingStop function. That method differs from the trailing stop method presented in the article, which exits a position if the closing price is beyond the stop trigger price. The ExitAtTrailingStop method, on the other hand, immediately exits a position if the stop price is “touched” by any intraday excursion. The WealthScript code presented adds two “slider” parameters so that you can easily switch between the two different stop methods as well as the stop percentage in order to make on-the-fly comparisons.
Figure 1. In our raw profit backtest, the article’s “stop on close” method had a significantly higher profit than the touch stop method.
WealthScript Code (C#)
using System;
using System.Drawing;
using WealthLab;
using WealthLab.Indicators;
namespace WealthLab.Strategies
{
public class SAC_FixedPctTrailingStop : WealthScript
{
private StrategyParameter _pctTrail = null;
private StrategyParameter _touchStop = null;
public SAC_FixedPctTrailingStop()
{
_pctTrail = CreateParameter("Pct Trail", 14d, 5d, 30d, 1d);
_touchStop = CreateParameter("Touch Stop=1", 0, 0, 1, 1);
}
// Custom indicator
public DataSeries PercentLine(double pct)
{
double perc = 1 - pct/100;
double perc2 = 1 + pct/100;
DataSeries result = new DataSeries(Bars, "PercentLine(" + pct + ")");
// Create the trailing stop series
bool bull = true;
result0 = Close0 * perc;
for(int bar = 1; bar < Bars.Count; bar++)
{
double prev = resultbar - 1;
if( bull )
{
if (Closebar >= prev)
resultbar = Math.Max(prev, Closebar * perc);
else
{
bull = false;
resultbar = Closebar * perc2;
}
}
else if (Closebar <= prev)
resultbar = Math.Min(prev, Closebar * perc2);
else
{
bull = true;
resultbar = Closebar * perc;
}
}
return result;
}
// Execute the strategy
protected override void Execute()
{
DataSeries stopLine = PercentLine(_pctTrail.Value);
PlotSeries(PricePane, stopLine, Color.Blue, LineStyle.Dashed, 1);
for(int bar = 1; bar < Bars.Count; bar++)
{
if (IsLastPositionActive)
{
Position p = LastPosition;
if ( _touchStop.ValueInt == 1 )
ExitAtTrailingStop(bar + 1, p, stopLinebar);
else
{
if( CrossUnder(bar, Close, stopLine) )
SellAtClose(bar, p);
}
}
else if( CrossOver(bar, Close, stopLine) )
BuyAtClose(bar);
}
}
}
}