Advanced Trading Tutorial — Directional Range Efficiency in NinjaTrader 8

Two markets can advance by the same number of points while following very different paths. One may climb steadily, while another oscillates violently before reaching the same closing price. A simple momentum reading sees identical displacement. Directional Range Efficiency adds context by comparing that displacement with the total true range accumulated along the way. This tutorial builds a native NinjaScript indicator for investigating that distinction.

Define the ratio

For a window of N completed bars, subtract the close immediately before the window from the latest close. Divide this signed displacement by the sum of true ranges across the N bars. True range is the maximum of high minus low, absolute high minus previous close, and absolute low minus previous close. Unlike a denominator based only on close-to-close changes, this measure also accounts for intrabar excursions and gaps. Valid OHLC data constrain the ratio to the interval from −1 to +1. Zero total range is assigned a neutral value of zero.

Directional Range Efficiency Indicator
Illustrative comparison: a net gain of six points over twelve points of accumulated true range gives +0.50; a net loss of six gives −0.50; no net displacement gives zero.

Worked example

Set N to three for a manual calculation. Suppose the starting close is 100. The next three bars have highs, lows and closes of (103,99,102), (106,102,105), and (108,104,106). Each true range is four, so the total is twelve. The net displacement is six and the score is +0.50. A separate hypothetical window with a net decline of six and the same total range scores −0.50. A window that returns to its initial close scores zero, even if it experienced substantial volatility. A zero score therefore does not necessarily mean a quiet market.

Complete NinjaScript source

The indicator uses a single plot, with green for nonnegative values and red for negative values. The period is exposed as a configurable NinjaScript property. A warm-up guard prevents access to unavailable previous closes. The calculation uses a direct loop rather than a recursive accumulator, making the relationship between the mathematical definition and implementation easy to inspect.

using System;
using System.ComponentModel.DataAnnotations;
using System.Windows.Media;
using NinjaTrader.NinjaScript;
namespace NinjaTrader.NinjaScript.Indicators
{
    public class DirectionalRangeEfficiency : Indicator
    {
        [NinjaScriptProperty]
        [Range(1, 500)]
        [Display(Name="Period", Order=1, GroupName="Parameters")]
        public int Period { get; set; }

        protected override void OnStateChange()
        {
            if (State == State.SetDefaults)
            {
                Name = "DirectionalRangeEfficiency";
                Description = "Signed net displacement divided by total true range.";
                Calculate = Calculate.OnBarClose;
                IsOverlay = false;
                Period = 10;
                BarsRequiredToPlot = 0;
                AddPlot(Brushes.DodgerBlue, "Efficiency");
                AddLine(Brushes.Gray, 0, "Zero");
            }
        }
        protected override void OnBarUpdate()
        {
            // Need one preceding close for each true range.
            if (CurrentBar < Period)
            {
                Value.Reset();
                return;
            }
            double total = 0;
            for (int i = 0; i < Period; i++)
            {
                double previous = Close[i + 1];
                double tr = Math.Max(High[i] - Low[i],
                    Math.Max(Math.Abs(High[i] - previous),
                             Math.Abs(Low[i] - previous)));
                total += tr;
            }
            // Zero total range is treated as neutral.
            double score = total > 0 ?
                (Close[0] - Close[Period]) / total : 0;
            Value[0] = score;
            PlotBrushes[0][0] = score >= 0 ?
                Brushes.SeaGreen : Brushes.IndianRed;
        }
    }
}

Closed-bar execution

Calculate.OnBarClose is the default calculation mode. Under normal standalone use the indicator updates on completed bars, without consulting future prices or using a centered window. Consequently it does not intentionally repaint confirmed values. In a hosting NinjaScript strategy, the parent calculation mode can govern embedded indicators; ensure the host also uses closed-bar calculation or explicitly handles confirmation. Historical data corrections and bar types that reconstruct historical bars may change displayed results. The direct loop requires O(N) work per update, which is acceptable for modest windows but may warrant a rolling sum for large-scale multi-instrument analysis.

Installation

Open the NinjaScript Editor in NinjaTrader 8 and create an indicator named DirectionalRangeEfficiency. Replace the editable indicator class with the implementation above, retaining the platform-generated wrapper region if present. Compile and resolve any environment-specific errors. Add the indicator to a chart through the Indicators dialog. Begin with Period=10, then compare shorter and longer windows without assuming that a particular setting is optimal.

Research and testing

First reproduce the three-bar example manually. Test a flat sequence, a gap, a directional sequence, and an alternating sequence. Compare historical and real-time closed-bar readings using the same instrument, bar type, trading hours template and data source. Verify that the initial warm-up does not display fabricated zero readings. Observe the Data Box during a live bar to confirm that standalone closed-bar values do not update prematurely. This code has not been compiled or run in NinjaTrader here.

For research, compare the distribution of the ratio in trending and ranging periods. A persistent positive ratio may describe efficient upward movement, but a high reading can also occur near exhaustion. Low values may reflect large wicks, reversals or a lack of net movement. The ratio does not measure volume, liquidity, transaction costs or expected returns. Session gaps and synthetic bar construction can affect its meaning. Avoid choosing thresholds solely because they fit historical data; evaluate any proposed trading rule out of sample and account for costs.

For alerts, rolling-sum optimization or integration into a strategy, contact our Custom NinjaTrader indicator Development Services.

Risk disclosure: educational material only. Trading involves risk of loss. Hypothetical examples are not evidence of profitability.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.