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; result[0] = Close[0] * perc; for(int bar = 1; bar < Bars.Count; bar++) { double prev = result[bar - 1]; if( bull ) { if (Close[bar] >= prev) result[bar] = Math.Max(prev, Close[bar] * perc); else { bull = false; result[bar] = Close[bar] * perc2; } } else if (Close[bar] <= prev) result[bar] = Math.Min(prev, Close[bar] * perc2); else { bull = true; result[bar] = Close[bar] * 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, stopLine[bar]); else { if( CrossUnder(bar, Close, stopLine) ) SellAtClose(bar, p); } } else if( CrossOver(bar, Close, stopLine) ) BuyAtClose(bar); } } } }