Separate a weakening trend from a one-bar interruption
A trend-following system that exits immediately on a close below a moving average can be sensitive to brief pullbacks. Requiring two consecutive completed closes below a reference EMA changes the exit from a single observation into a persistence test. The trade-off is explicit: fewer isolated exit signals, but potentially greater loss when a trend reverses abruptly.
Entry, confirmation and protection
For a reproducible research baseline, enter one unit long when the 20-period EMA crosses above the 50-period EMA while flat. During the position, increment a counter after every completed close strictly below the current 20-period EMA. Reset it to zero when the close is equal to or above that EMA. At two consecutive violations, submit a market exit linked to the long entry. Independently maintain a 40-tick protective stop from entry; the close confirmation must never delay that stop. The stop size is illustrative and not optimized.
Worked example
Assume the EMA is approximately 100 for five illustrative observations. Closes of 102, 99, 101, 99 and 98 produce counters of 0, 1, 0, 1 and 2. The recovery to 101 cancels the first warning. Only the last observation triggers the confirmed exit, assuming the protective stop has not already closed the position. The actual EMA changes each bar.

Figure: a recovery resets the counter; two subsequent violations trigger the exit.
NinjaScript 8 implementation fragment
// Members of a single-series managed NinjaScript strategy.
private int belowCount;
private bool exitPending;
// In State.SetDefaults: Calculate = Calculate.OnBarClose;
// EntriesPerDirection = 1;
// In State.Configure:
// SetStopLoss("TrendLE", CalculationMode.Ticks, 40, false);
protected override void OnBarUpdate()
{
if (CurrentBar < 50) return;
if (Position.MarketPosition == MarketPosition.Flat)
{
belowCount = 0;
exitPending = false;
if (CrossAbove(EMA(20), EMA(50), 1))
EnterLong(1, "TrendLE");
return;
}
if (Position.MarketPosition != MarketPosition.Long)
return;
belowCount = Close[0] < EMA(20)[0]
? Math.Min(belowCount + 1, 2) : 0;
if (belowCount >= 2 && !exitPending)
{
exitPending = true;
ExitLong("ConfirmLX", "TrendLE");
}
}
Integrate these members into a Strategy class with the standard NinjaTrader namespaces and the indicated configuration. The sample assumes a single primary series, one entry and no scale-ins or reversals. Calculate.OnBarClose prevents repeated tick-level increments. The exitPending latch suppresses repeated exit submissions until the position is flat. In production, also track working entry orders and reconcile rejected or cancelled exits through OnOrderUpdate and fills through OnExecutionUpdate. If an exit fails, do not blindly clear the latch: verify the remaining position and outstanding orders, then recover or disable according to a defined policy. Reconcile the competing protective stop and market exit, including partial fills and reconnections. Reset state on each new trade; if the strategy can flatten and re-enter between bar updates, explicitly reset on execution transitions rather than relying solely on the flat observation.
Backtest and risk
Compare one, two and three consecutive closes with identical entries, initial stops, quantity and costs. Track exit delay, maximum adverse excursion, net returns and drawdown. Test equality with the EMA, a single violation followed by recovery, gaps through the protective stop and rejected exits. Historical bar-close fills may differ from live fills; use suitable intrabar fill resolution and simulation before deployment. No compilation or backtest was performed for this fragment. Futures and leveraged products can cause substantial losses, and a stop does not guarantee a maximum loss.
For custom order-state and exit management, see Custom NinjaTrader strategy Development Services.