Guide · Exits and risk

Trailing stop strategy in NinjaTrader: ATR trail, break-even and NinjaScript

How to design a trailing stop a computer can follow: the four common trail types, how to choose an ATR period and multiple, a NinjaScript outline for the initial stop and break-even move, and how to test it and find out why it did not move.

Trailing stop strategy in NinjaTrader: ATR trail, break-even and NinjaScript: cover illustration

Short answer. A trailing stop in NinjaTrader follows a position as price moves favorably, according to a defined distance or price rule. A fixed-tick trail uses a constant distance; an ATR trailing stop adjusts its proposed distance to recent volatility; and break-even stop automation moves the stop toward the entry price after a specified trigger. In NinjaScript, SetTrailStop() can manage a basic trail, while SetStopLoss() can be updated with custom break-even or ATR logic. They should not be used together for the same entry signal: SetStopLoss() takes precedence. Define the initial stop, trigger, update frequency and rounding rules, then check individual orders in simulation. A stop may fill beyond its trigger price, especially in a fast market.

What a trailing stop does and what it does not

A trailing stop is an exit rule that can move a protective stop in the direction of a favorable price move. For a long position, a typical trail raises the stop as the market rises and leaves it in place when the market falls. For a short position, the direction is reversed. The goal is to change the exit level as a trade develops; the rule does not predict how far the market will move.

A trail needs an initial protective stop, a reference price and an update rule. You might start with a stop 20 ticks from entry, begin trailing after a favorable move of 10 ticks and update the stop at each bar close. Another rule might trail immediately on each incoming tick. Those choices can produce different orders even with the same entry.

A stop-market order generally becomes a market order when triggered, so its fill can differ from the displayed stop price. A gap, a fast move or limited liquidity can make that difference material. A stop also depends on the platform, connection and order arrangement you use. Check where the order resides and what happens if the strategy or connection stops. The bot risk settings guide covers other settings to review alongside an exit.

Compatibility note: the platform terminology and NinjaScript examples in this guide refer to NinjaTrader 8.

Compare four trailing stop rules

Each approach answers a different question about where the stop should go. Write down the details before choosing a distance: a rule described only as “use a trailing stop” leaves too much open to interpretation.

Comparison of trailing stop and break-even rules
RuleHow the stop is proposedMain trade-off
Fixed-tick trailA set number of ticks behind the favorable price reference.Simple to specify, but the distance does not adapt to changing volatility.
ATR trailA multiple of average true range behind a chosen high, low or other reference.Adapts to a volatility measure, but depends on the period, multiple and update rule.
Structure or bar-low trailFor a long, below a defined prior bar low or swing low; reverse the rule for a short.Uses a visible price level, but a loose definition of a swing can make the rule ambiguous.
Break-even, then trailMove to entry or an offset after a trigger, then follow a separately defined trail.Can tighten the stop quickly, but may exit during an ordinary pullback.

For a fixed-tick trail, specify whether the distance is measured from the highest traded price since entry, the current bar or another reference. Also specify whether the stop can move on every tick or only at a bar boundary. A 20-tick trail is not necessarily the same strategy under both update schedules.

For a structure trail, define exactly which bar or swing is eligible. “Below the last swing” is difficult to automate until you state how many bars confirm that swing, whether the current bar counts and what buffer applies. A confirmed swing may be known only after later bars have formed; the strategy must not act as though it knew the level earlier.

Break-even is a stop price, not a guarantee of a zero-cost exit. Entry and exit commissions, fees and slippage can leave a net loss even if the stop is placed at the average entry price. An offset of a few ticks changes the trigger price but cannot guarantee the eventual fill.

How to choose an ATR period and multiple

Average true range, or ATR, summarizes recent price movement using true range, which includes the current bar’s range and gaps relative to the previous close. An ATR trailing stop uses that measure as an input to a distance. It does not indicate direction by itself, and two charts with different bar intervals can produce different ATR values for the same market.

Choose the bar interval and ATR period together. A shorter period can respond more quickly when ranges change, but its readings may fluctuate more. A longer period may be smoother while taking longer to reflect a volatility change. The multiple scales the chosen ATR: a smaller multiple proposes a closer stop, while a larger multiple proposes a wider one. Neither setting is inherently best.

Illustration with made-up round numbers: suppose a long trade’s selected price reference is 1,000 points, the ATR is 10 points and the chosen multiple is 2. The proposed stop is 1,000 − (10 × 2), or 980 points. If the reference later rises to 1,030 while ATR remains 10, the proposed stop becomes 1,010. With a one-way ratchet, the stop can move up to 1,010 but does not move back down if the next proposal is 1,000.

If ATR expands to 20 while the reference remains 1,030, the new formula proposes 990. A one-way rule would keep the existing 1,010 stop instead of widening it to 990. That distinction matters: an ATR-based distance can grow, but many trailing rules deliberately do not increase the existing risk. State whether your rule permits widening; do not assume the formula answers that question.

Translate the resulting distance into valid ticks and check the contract’s tick value before sizing a position. Decide how prices are rounded to valid increments and whether rounding can make a stop too close to the market. The tick value calculator and position size calculator can help with the arithmetic. Initial risk estimates should also allow for costs and the possibility of a fill beyond the stop.

Keep the period and multiple grounded in a written hypothesis. Compare a few reasonable neighboring values across different conditions, rather than selecting the single combination that happens to fit one sample. An ATR trail may behave differently during a sudden volatility change, around a session boundary or when the data contains unusual bars.

NinjaScript outline: initial stop and break-even move

The managed approach offers two relevant methods. SetTrailStop() provides a built-in trailing stop based on a supported offset. SetStopLoss() sets a protective stop and can be called again to change it. For the same entry signal, do not call both expecting one to hand off to the other: SetStopLoss() takes precedence. A break-even-then-ATR trail can instead use one SetStopLoss() order whose price is updated by your own rules.

The following teaching outline shows a long entry with an initial fixed stop and a single break-even move. It is not a finished or tested strategy. The entry condition is deliberately omitted, and the sketch assumes one entry at a time, a single bar series and no position that existed before the strategy started.

private bool movedToBreakEven;
private bool entryCondition; // placeholder: replace with your own entry rule

protected override void OnStateChange()
{
    if (State == State.SetDefaults)
    {
        Calculate = Calculate.OnBarClose;
    }
}

protected override void OnBarUpdate()
{
    if (BarsInProgress != 0 || CurrentBar < BarsRequiredToTrade)
        return;

    if (Position.MarketPosition == MarketPosition.Flat)
    {
        movedToBreakEven = false;

        // Restore the initial offset before a new entry.
        SetStopLoss("LongEntry", CalculationMode.Ticks, 20, false);

        // entryCondition stands in for a separately defined entry rule.
        if (entryCondition)
            EnterLong("LongEntry");
    }
    else if (Position.MarketPosition == MarketPosition.Long
             && !movedToBreakEven)
    {
        double entry = Position.AveragePrice;

        // Example trigger: close at least 12 ticks above entry.
        if (Close[0] >= entry + 12 * TickSize)
        {
            SetStopLoss("LongEntry", CalculationMode.Price, entry, false);
            movedToBreakEven = true;
        }
    }
}

// Alternative for a separate strategy or different entry signal:
// SetTrailStop("TrailEntry", CalculationMode.Ticks, 20, false);
// EnterLong("TrailEntry");

Here the stop is configured before the entry is submitted, and the entry name matches fromEntrySignal. The stop is submitted on an entry execution; setting the rule does not itself create an entry. The example resets the stop offset while flat so the previous break-even price is not carried into the next trade. The alternative SetTrailStop() lines illustrate a different signal; they are not an instruction to place a second stop on LongEntry.

For a static offset, a Set* call can be configured in OnStateChange() when the state is State.Configure. A value that changes during a position belongs in the appropriate event logic, such as OnBarUpdate(). If a strategy has multiple entry signals, use the intended signal names consistently and verify the resulting order quantities. A blank signal and a named signal can have different scope; do not treat names as merely descriptive labels.

The sketch uses Calculate.OnBarClose, so its break-even condition is checked at bar close. A favorable move that occurs and reverses within a bar may never produce a break-even update. Calculate.OnEachTick can give more frequent real-time updates, but historical processing does not automatically reproduce every intrabar event. The built-in trail’s amendment behavior also depends on the strategy’s calculation setting. Check the specific order behavior on the data and settings you intend to use.

For an ATR version, calculate a candidate stop from a clearly specified reference and ATR value, round it to a valid tick and update only when it improves on the existing intended stop. For a short, reverse the comparisons. Define what happens if the candidate is already on the wrong side of the current market: a stop change can be rejected or behave differently from the intended exit. Include rejection handling and inspect actual order updates before relying on the rule.

Partial fills add another layer. Depending on the strategy’s stop-and-target handling, NinjaTrader can create protection for individual partial fills or combine fills. The average entry price and protected quantity can change as executions arrive. The short outline does not resolve those cases, manage pending entry orders or confirm that every requested change was accepted. Test those cases explicitly, and use execution and order updates where more precise handling is needed. The NinjaTrader automation guide covers the broader development workflow.

Check the official NinjaTrader references for SetTrailStop() and SetStopLoss(). Neither method may be called during State.SetDefaults. SetTrailStop() does not support CalculationMode.Price or CalculationMode.Currency; use a suitable SetStopLoss() design for absolute-price stop updates.

ATM Strategy trail or strategy-coded trail?

An ATM Strategy is configured through the platform’s order-entry workflow and can apply predefined stop and target behavior to eligible orders. A NinjaScript strategy has its own entry and order-management logic. Choose the owner of the position and stop deliberately: an ATM trail and a strategy-coded trail are not interchangeable settings on one shared piece of logic.

An ATM setup may suit a manually initiated trade with predefined management rules. A coded trail may suit a rule that depends on an indicator, a custom reference or other strategy state. Availability and behavior depend on the setup, so inspect the actual working orders instead of assuming that selecting an ATM template automatically changes the exits of a NinjaScript strategy.

Before using either approach, identify the initial stop, the activation trigger, the update frequency and the response to a rejected change. Avoid placing competing exits for the same position without a deliberate design. Check what happens if you manually adjust an order, disable the strategy or close the position through another interface.

Test the stop under the conditions it will encounter

Start with a chart and a written example. For several individual trades, note the entry, initial stop, trigger, proposed new stop and actual order update. Include a trade that moves favorably and reverses before the bar closes, one where volatility expands, and one with a partial fill if your setup can produce it. The purpose is to verify the sequence, not just the final exit.

  1. Compare the same setup with the trail on and off. Keep the entry rules, initial protection, position size, costs and test period consistent. Define the alternative exit in advance so the comparison isolates the trail as far as practical.
  2. Include costs and slippage. Commissions and fees affect net results, and a stop-market fill can occur beyond its trigger. Try more than one plausible slippage assumption, particularly for fast conditions.
  3. Inspect intrabar ordering. If a bar contains both a favorable move that would tighten the stop and an adverse move that would hit it, ordinary bar data may not establish which happened first. A historical fill is an approximation when the underlying sequence is unavailable.
  4. Understand Tick Replay and fill settings. Tick Replay can provide historical tick-by-tick data to supported scripts when configured with suitable data, but it is not a guarantee of live-equivalent order fills. Review its limitations separately from historical order-fill resolution, and check whether your combination of settings is supported.
  5. Check sensitivity and simulation. Vary the ATR period, multiple and trigger by modest amounts, then observe the same rules with live data in simulation. Watch order submissions, changes, fills and connection behavior as well as the reported outcomes.

Differences between historical and simulated results can arise from data, event timing, fill assumptions and execution behavior. Keep notes on which setting produced each run. The strategy testing guide explains the wider process; the goal here is to understand what the trailing stop changed and whether that behavior matches the written rule.

Why a trailing stop is not working or exits too early

  • The stop never moves. The activation condition may not have been reached on the data used by the strategy. Check whether the trigger uses a bar close, a high or low, bid or ask, or another price. Confirm that the strategy is enabled and receiving updates.
  • The trail appears to be ignored. A SetStopLoss() call may take precedence over SetTrailStop() for the same entry signal. Search the strategy for both calls and inspect the actual entry-signal names.
  • The stop starts at an unexpected price. A dynamic stop value may have been left over from the prior position, or the entry may have filled at a different price than expected. Reset the intended initial setting while flat and check the executions.
  • A change is rejected. The proposed price may be invalid, off the tick grid or on the wrong side of the market when the change reaches the order system. Review the order log and error handling; a requested price is not proof of an accepted order.
  • The stop moves only once per bar. Check Calculate, the bar interval and whether the observed run is historical or real time. A bar-close rule can lag a fast move even when its arithmetic is correct.
  • The trade exits on a small pullback. The initial distance, break-even trigger or trail may be tight relative to ordinary movement. Check the reference price and ATR units, then compare the rule with nearby settings without tuning solely to one trade.
  • The wrong quantity is protected. Review entry signals, partial executions and the stop-and-target handling setting. Compare the position quantity with each working stop, especially while an entry is still filling.
  • No expected order appears. Confirm that the entry actually executed and that the intended strategy is running on the right instrument and account. The strategy troubleshooting guide can help locate a strategy that is missing or not enabled.

Trailing stop checklist

  • Initial stop distance and position size defined before entry.
  • Trail type, activation trigger and price reference written down.
  • ATR period, chart interval and multiple specified if using an ATR trail.
  • One-way ratchet or permitted widening stated explicitly.
  • Break-even trigger and any offset defined, including expected costs.
  • Entry signals matched to their intended managed stop calls.
  • SetStopLoss() and SetTrailStop() not competing for the same signal.
  • Dynamic stop settings reset before the next entry.
  • Tick rounding, invalid prices, rejected changes and partial fills considered.
  • Bar-close versus intrabar behavior checked on the intended data.
  • Trail-on and trail-off comparisons use the same setup and cost assumptions.
  • Individual order updates reviewed in simulation before any decision to trade with real money.

Using a ready-made bot

If you are considering a ready-made strategy, review its published entry and exit rules and verify which settings are available before assuming it uses a particular trailing stop. Ask how the initial stop, any break-even trigger and any trailing rule interact, and whether the strategy manages its own orders. The bots page is a starting point for reviewing the available options.

Use the same checks you would apply to custom code: confirm the instrument and contract, estimate risk from the initial stop, inspect working orders in simulation and understand how the strategy handles interruptions. A trailing stop is one part of a risk plan; a daily limit or session-close rule may address a different concern. See the guides to daily loss limits and exit on session close for those settings.

Related guides

Bots mentioned in this guide

Futures trading involves substantial risk of loss. Stop orders, historical tests and simulated results cannot guarantee an outcome. This guide is educational and is not investment advice. Risk disclosure.

FAQ

Common questions

What is a trailing stop in NinjaTrader?

It is a protective stop that follows the position in the favorable direction by a set distance or price rule, and stays in place when price moves against you. In NinjaScript the managed approach offers SetTrailStop for a simple trail and SetStopLoss for stops you update yourself.

Can I use SetTrailStop and SetStopLoss together?

Not for the same entry signal. NinjaTrader documents that if both are called for the same position, SetStopLoss takes precedence, so the trail may appear to be ignored. Use different signal names or build the trail from SetStopLoss updates.

How do I set an ATR trailing stop?

Pick an ATR period and a multiple, calculate a candidate stop from a defined reference price minus or plus ATR times the multiple, round it to a valid tick, and only move the stop when the new level improves on the current one. Test neighboring settings rather than one best fit.

Why is my trailing stop not moving?

Common causes are an activation trigger that was never reached, a SetStopLoss call overriding the trail, a Calculate setting that updates only at bar close, a rejected stop change, or the strategy not being enabled. Check the order log for each change.

Does a break-even stop guarantee no loss?

No. Commissions, fees and slippage can leave a net loss even when the stop sits at the entry price, and a stop-market order can fill beyond its trigger. Futures trading involves substantial risk of loss.

Founding Lifetime offer

Lifetime access at $1,297 for the first 50 buyers

FuturesBotLab is a lineup of 9 NinjaScript strategies for gold and US index futures, each with its risk rules written into the code. Founding Lifetime is one payment for every current and future bot. Licensing uses your NinjaTrader account email. The $1,297 founding price is for the first 50 Lifetime buyers only. Prefer to start small? Weekly is $49, Monthly $97 and Yearly $597.

Futures trading involves substantial risk of loss and is not suitable for every investor. No bot guarantees any result. Risk disclosure.

How checkout works

  1. Choose your membership on the purchase page.
  2. Enter your email.
  3. Complete payment using the secure Stripe Checkout link sent to your email. Your account is set up after payment.

Choose a plan

Compare all plans

Questions first? Email support@futuresbotlab.com.

Founding price · first 50 buyers

Let the bot follow the rules, so you don't have to.

Every bot, every update, one membership.