Insights ledger

Oransel Research Strategy Engineering

Bands That Breathe: An Adaptive SuperTrend for NinjaTrader 8

SuperTrend asks one question of every trader who loads it: how many ATRs of room does price get before the trend is called over? The classic answer is a...

SuperTrend asks one question of every trader who loads it: how many ATRs of room does price get before the trend is called over? The classic answer is a fixed number, usually 3, chosen once and applied to every kind of market. This note lets the market pick the number instead. A ratio of short-term ATR to long-term ATR scales the multiplier, so the bands pull in when the session goes quiet and open up when price starts running. It is built as a NinjaTrader 8 strategy, with a walkthrough of a hypothetical session showing how a trader might read it. The code is educational and unvalidated.

What the strategy computes

SuperTrend is usually credited to French trader Olivier Seban, and it rests on the Average True Range that J. Welles Wilder introduced in his 1978 book New Concepts in Technical Trading Systems. The classic version works from the bar's median price, (High + Low) / 2:

Upper = Median + Multiplier × ATR

Lower = Median - Multiplier × ATR

Those raw bands then ratchet. In an uptrend the lower band may rise but never fall; in a downtrend the upper band may fall but never rise. A close through the active band flips the trend, and the line jumps to the other side of price. The NinjaTrader 8 versions we looked at keep the multiplier fixed. Adaptive-multiplier variants have appeared as TradingView community scripts, but not, as far as we found, as a NinjaTrader strategy that trades the flips.

This version changes one input. On every bar it computes a volatility regime ratio:

Ratio = ATR(AtrPeriod) / ATR(RegimePeriod)

With the defaults, that is a 10-bar ATR divided by a 100-bar ATR. A ratio of 1.0 means the last ten bars are moving about as much as the last hundred. Below 1.0, the market has gone quiet relative to its own recent history. Above 1.0, it has woken up. The multiplier follows:

Multiplier = clamp(BaseMultiplier × Ratio, MinMultiplier, MaxMultiplier)

The defaults are a base of 3.0, a floor of 2.0 and a ceiling of 4.5. The floor keeps the bands from collapsing onto price in a dead market, and the ceiling stops one violent bar from pushing them out of sight.

The effect compounds. Band distance is the multiplier times the short ATR, and both move in the same direction. When the session goes quiet, the ATR shrinks and the multiplier shrinks with it, so the bands tighten twice. When it speeds up, they widen twice.

The ratchet changes what "widen" means here. In an uptrend, a bigger multiplier does not pull the stop line back down, because the lower band never falls. It slows the line's climb. The line keeps whatever ground it has gained and simply advances more cautiously while the move is fast. When the pace cools, the multiplier drops and the line catches up to price.

A session with the tool

Picture an index futures trader on a 5-minute chart through a full regular session. The numbers below are made up to show how the line and the readout behave, not taken from a real chart.

Loading it. The strategy goes onto the chart from the Strategies window with at least a few days of history loaded, so the 100-bar regime ATR is warmed up before the open. Enable Trading stays off, so the strategy only draws. A dotted line appears under or over price, green in an uptrend and orange-red in a downtrend. The top-right corner of the chart shows the current multiplier and regime ratio, and each flip leaves an arrow labelled with the multiplier that was in force when it happened.

The quiet range. By late morning the market has settled into a band about six points wide. The 10-bar ATR is down to 1.75 points while the 100-bar ATR still remembers the open at 2.50, so the corner reads Multiplier 2.10 Ratio 0.70. The SuperTrend line sits about 3.7 points from the bar's median. A fixed multiplier of 3 would have put it 5.25 points away, outside the whole range, where it would tell the trader nothing.

Near midday, price pokes above the top of the range and the line flips to green with a 2.1x arrow. Two bars later price slips back inside and the line flips orange-red again. The trader reads this for what it is: a tight setting doing its job, because the tight band is what lets the indicator react quickly once a real move begins. The cost of that sensitivity is a flip that goes nowhere, and here it is small because the band was close to price.

The breakout. Early in the afternoon, a bar closes two points above the range high on a burst of activity. The line flips green again, and the arrow reads 2.2x. Because the band was tight, the flip comes on the first close out of the range rather than several points later.

Then the move runs. Over the next eight bars, the 10-bar ATR climbs to 4.00 points while the 100-bar ATR edges up to 2.80. The corner now reads Multiplier 4.29 Ratio 1.43. The trader watches the green line and sees it climbing more slowly than price. It never moves down, but it rises in small steps while the bars are long. When a sharp three-bar pullback retraces nearly half the move, the line is still well below it. A fixed 2.1 setting carried over from the morning would have stood much closer and flipped on that pullback.

The cool-down. Late in the afternoon the trend stalls. Bars shrink, the ratio drifts back toward 1.0, and the multiplier slides to about 3. The line takes several quick steps up toward price, because the narrower raw band is now above the ratcheted one. The trader sees the stop tighten without having to move anything by hand. When a bar finally closes below it, the line flips orange-red with a 2.9x arrow, and the afternoon's trend is called over.

Using the line. The trader has a few ways to work with this. One is to treat each flip as a signal and the line as a trailing stop. That is what Enable Trading automates: on a flip up it requests a long with a stop at the line, moves that stop each bar as the line ratchets, and reverses on a flip down. Another is to use only the direction as a filter, taking setups from another method only when the line agrees. A third is to watch the corner readout itself. A ratio sitting well under 1.0 for an hour describes compression, and that is a useful thing to know before the next push regardless of what the line is doing.

Reading the multiplier, not just the color. The arrow labels matter. A flip at 2.0x came from a band pinned to its floor in a quiet market and is the easiest kind to trigger. A flip at 4.5x means price closed through a band at its widest setting, which takes a much larger move against the trend. Two flips with the same color can carry very different information, and the label says which kind each one was.

NinjaScript strategy

#region Using declarations
using System;
using System.ComponentModel.DataAnnotations;
using System.Windows.Media;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.NinjaScript;
using NinjaTrader.NinjaScript.DrawingTools;
using NinjaTrader.NinjaScript.Indicators;
#endregion

namespace NinjaTrader.NinjaScript.Strategies.OranselIndustries
{
    public class AdaptiveSuperTrendStrategy : Strategy
    {
        private const string LongSignal = "AstLong";
        private const string ShortSignal = "AstShort";

        private ATR _shortAtr;
        private ATR _regimeAtr;
        private Series<double> _upper;
        private Series<double> _lower;
        private Series<int> _trend;

        protected override void OnStateChange()
        {
            if (State == State.SetDefaults)
            {
                Description = @"SuperTrend whose ATR multiplier scales with the ratio of short to long ATR.";
                Name = "AdaptiveSuperTrendStrategy";
                Calculate = Calculate.OnBarClose;
                EntriesPerDirection = 1;
                EntryHandling = EntryHandling.AllEntries;
                IsExitOnSessionCloseStrategy = true;
                ExitOnSessionCloseSeconds = 30;
                StartBehavior = StartBehavior.WaitUntilFlat;
                TimeInForce = TimeInForce.Gtc;
                RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
                StopTargetHandling = StopTargetHandling.PerEntryExecution;
                BarsRequiredToTrade = 100;
                IsInstantiatedOnEachOptimizationIteration = true;

                AtrPeriod = 10;
                RegimePeriod = 100;
                BaseMultiplier = 3.0;
                MinMultiplier = 2.0;
                MaxMultiplier = 4.5;
                EnableTrading = false;

                AddPlot(new Stroke(Brushes.Gray, 2), PlotStyle.Dot, "SuperTrend");
            }
            else if (State == State.DataLoaded)
            {
                _shortAtr = ATR(AtrPeriod);
                _regimeAtr = ATR(RegimePeriod);
                _upper = new Series<double>(this);
                _lower = new Series<double>(this);
                _trend = new Series<int>(this);
            }
        }

        protected override void OnBarUpdate()
        {
            if (BarsInProgress != 0)
                return;

            double atr = _shortAtr[0];
            double ratio = _regimeAtr[0] > 0 ? atr / _regimeAtr[0] : 1.0;
            double multiplier = Math.Max(MinMultiplier, Math.Min(MaxMultiplier, BaseMultiplier * ratio));
            double median = (High[0] + Low[0]) / 2.0;
            double basicUpper = median + multiplier * atr;
            double basicLower = median - multiplier * atr;

            if (CurrentBar == 0)
            {
                _upper[0] = basicUpper;
                _lower[0] = basicLower;
                _trend[0] = 1;
                Value[0] = basicLower;
                return;
            }

            // The active band may move toward price, never away from it.
            _upper[0] = basicUpper < _upper[1] || Close[1] > _upper[1] ? basicUpper : _upper[1];
            _lower[0] = basicLower > _lower[1] || Close[1] < _lower[1] ? basicLower : _lower[1];

            int trend = _trend[1];
            if (trend == 1 && Close[0] < _lower[0])
                trend = -1;
            else if (trend == -1 && Close[0] > _upper[0])
                trend = 1;
            _trend[0] = trend;

            bool flipped = trend != _trend[1];
            Value[0] = trend == 1 ? _lower[0] : _upper[0];
            PlotBrushes[0][0] = trend == 1 ? Brushes.LimeGreen : Brushes.OrangeRed;

            if (flipped)
                MarkFlip(trend, multiplier);
            if (State == State.Realtime || CurrentBar == Bars.Count - 1)
                Draw.TextFixed(this, "AstState",
                    string.Format("Multiplier {0:0.00}  Ratio {1:0.00}", multiplier, ratio), TextPosition.TopRight);

            if (!EnableTrading || CurrentBar < Math.Max(BarsRequiredToTrade, RegimePeriod))
                return;

            int quantity = Convert.ToInt32(DefaultQuantity);
            if (flipped && trend == 1)
            {
                SetStopLoss(LongSignal, CalculationMode.Price, Value[0], false);
                EnterLong(quantity, LongSignal);
            }
            else if (flipped && trend == -1)
            {
                SetStopLoss(ShortSignal, CalculationMode.Price, Value[0], false);
                EnterShort(quantity, ShortSignal);
            }
            else if (Position.MarketPosition == MarketPosition.Long)
                SetStopLoss(LongSignal, CalculationMode.Price, Value[0], false);
            else if (Position.MarketPosition == MarketPosition.Short)
                SetStopLoss(ShortSignal, CalculationMode.Price, Value[0], false);
        }

        private void MarkFlip(int trend, double multiplier)
        {
            string tag = "AstFlip" + CurrentBar;
            string label = multiplier.ToString("0.0") + "x";
            if (trend == 1)
            {
                Draw.ArrowUp(this, tag, false, 0, Low[0] - 2 * TickSize, Brushes.LimeGreen);
                Draw.Text(this, tag + "Label", label, 0, Low[0] - 6 * TickSize, Brushes.LimeGreen);
            }
            else
            {
                Draw.ArrowDown(this, tag, false, 0, High[0] + 2 * TickSize, Brushes.OrangeRed);
                Draw.Text(this, tag + "Label", label, 0, High[0] + 6 * TickSize, Brushes.OrangeRed);
            }
        }

        #region Properties
        [NinjaScriptProperty]
        [Range(1, int.MaxValue)]
        [Display(Name = "ATR Period", Description = "ATR used for band distance and the top of the regime ratio", Order = 1, GroupName = "SuperTrend")]
        public int AtrPeriod { get; set; }

        [NinjaScriptProperty]
        [Range(2, int.MaxValue)]
        [Display(Name = "Regime Period", Description = "Long ATR used as the bottom of the regime ratio", Order = 2, GroupName = "SuperTrend")]
        public int RegimePeriod { get; set; }

        [NinjaScriptProperty]
        [Range(0.1, double.MaxValue)]
        [Display(Name = "Base Multiplier", Description = "Multiplier when the regime ratio is 1.0", Order = 3, GroupName = "SuperTrend")]
        public double BaseMultiplier { get; set; }

        [NinjaScriptProperty]
        [Range(0.1, double.MaxValue)]
        [Display(Name = "Min Multiplier", Description = "Floor for the adaptive multiplier", Order = 4, GroupName = "SuperTrend")]
        public double MinMultiplier { get; set; }

        [NinjaScriptProperty]
        [Range(0.1, double.MaxValue)]
        [Display(Name = "Max Multiplier", Description = "Ceiling for the adaptive multiplier", Order = 5, GroupName = "SuperTrend")]
        public double MaxMultiplier { get; set; }

        [NinjaScriptProperty]
        [Display(Name = "Enable Trading", Description = "Trade the flips with the line as a stop; off = chart only", Order = 1, GroupName = "Orders")]
        public bool EnableTrading { get; set; }
        #endregion
    }
}

Parameter ledger

ParameterDefaultWhat it controls
ATR Period10ATR for band distance and the top of the regime ratio
Regime Period100Long ATR the short ATR is compared against
Base Multiplier3.0Multiplier when the ratio is exactly 1.0
Min Multiplier2.0Floor in quiet markets
Max Multiplier4.5Ceiling in fast markets
Enable TradingOffChart line and arrows only until switched on
CalculateOn bar closeThe line, ratio and flips update once per completed bar

Base, floor and ceiling should be set together. With a base of 3.0, the floor is reached when the ratio falls to about 0.67 and the ceiling at 1.5, so most bars land in the adaptive zone between them. Narrowing that zone turns the strategy back into a fixed-multiplier SuperTrend, and widening it lets the regime ratio do more of the work. The regime period sets what "normal" means: 100 five-minute bars is a little over one regular trading session, while 100 daily bars is close to five months.

Taking it further

The regime ratio is useful beyond the multiplier. Plotting it in its own panel would show compression and expansion directly, and a horizontal line at 1.0 makes the regime changes easy to see. Making RegimePeriod session-aware, by restarting the long ATR each session or comparing against the same time of day on previous sessions, would stop the open's volatility from skewing the midday ratio. Each of these is a small change to OnBarUpdate(), because the strategy already computes the ratio on every bar.