I'm simply trying to get a trailing stop that equals the price of an indicator (this could be any indicator).
In other words, if i'm long, i might assign a trailing stop that is equal to a moving average that is currently below the quote.
Below is the sample code of what i'm trying to achieve...can anyone shed some light on what i'm doing wrong - it compiles with no errors, but stop loss doesn't seem to work when i run backtest?
#region Using declarations using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Xml.Serialization; using NinjaTrader.Cbi; using NinjaTrader.Data; using NinjaTrader.Indicator; using NinjaTrader.Gui.Chart; using NinjaTrader.Strategy; #endregion // This namespace holds all strategies and is required. Do not change it. namespace NinjaTrader.Strategy { /// <summary> /// MySampleTrail /// </summary> [Description("MySampleTrail")] public class MySampleTrail : Strategy { #region Variables // Wizard generated variables private int sMA1 = 100; // Default setting for SMA1 private int sMA2 = 200; // Default setting for SMA2 // User defined variables (add any user defined variables below) #endregion /// <summary> /// This method is used to configure the strategy and is called once before any strategy method is called. /// </summary> protected override void Initialize() { Add(SMA(SMA1)); Add(SMA(SMA2)); Add(SMA(SMA1)); CalculateOnBarClose = true; } /// <summary> /// Called on each bar update event (incoming tick) /// </summary> protected override void OnBarUpdate() { // Resets the stop loss to the original value when all positions are closed if (Position.MarketPosition == MarketPosition.Flat) { SetTrailStop(CalculationMode.Ticks, 300); } // If a long position is open, allow for stop loss modification else if (Position.MarketPosition == MarketPosition.Long) { SetTrailStop(CalculationMode.Price, SMA(50)[0]); } // If a short position is open, allow for stop loss modification else if (Position.MarketPosition == MarketPosition.Short) { SetTrailStop(CalculationMode.Price, SMA(50)[0]); } // Condition set 1 if (CrossAbove(SMA(SMA1), SMA(SMA2), 1)) { EnterLong(DefaultQuantity, ""); } // Condition set 2 if (CrossBelow(SMA(SMA1), SMA(SMA2), 1)) { EnterShort(DefaultQuantity, ""); } } #region Properties [Description("SMA1")] [Category("Parameters")] public int SMA1 { get { return sMA1; } set { sMA1 = Math.Max(1, value); } } [Description("SMA2")] [Category("Parameters")] public int SMA2 { get { return sMA2; } set { sMA2 = Math.Max(1, value); } } #endregion } }
Comment