Intermediate Trading Tutorial — Confirmed Adjacent Range Overlap Indicator for NinjaTrader 8
Two candles can have identical ranges yet occupy very different price intervals. One may revisit most of its predecessor's price territory, while another may form entirely outside it. A moving average of candle ranges measures the scale of price movement but cannot distinguish those arrangements. This tutorial builds an ACSIL-independent, native NinjaScript indicator that measures the intersection of adjacent candle price intervals relative to their union, then averages the resulting ratios across a rolling sample. It describes historical range overlap rather than predicting a breakout.
Define the interval comparison
Represent a candle by its low-to-high interval. For two adjacent candles, the intersection length is the smaller high minus the larger low, bounded below by zero. The union length is the sum of the individual interval lengths minus their intersection. This is an interval-based version of the Jaccard similarity measure. When the intervals are identical and have positive width, the ratio equals one. When they are disjoint or touch at only one endpoint, the intersection length is zero and the ratio is zero if the union is positive. A pair of zero-width intervals has no positive union and is marked unavailable.
Multiply the ratio by one hundred to obtain an intuitive scale. A rolling sample of N adjacent pairs requires N+1 candles. Average the individual ratios with equal weights, rather than dividing total intersections by total unions. Those two approaches differ because the latter gives wider unions more influence. This implementation deliberately gives every adjacent pair equal influence. A high average suggests that adjacent sampled intervals tend to revisit similar price territory; it does not establish whether the underlying market is trending or ranging.

Calculate the example by hand
Set Pair count to two. Candle A ranges from 100 to 106 and candle B from 103 to 109. Their intersection is 106 minus 103, or three. Each candle has width six, giving a union length of six plus six minus three, or nine. The pair score is 100 × 3/9 = 33.3333%. Candle C ranges from 110 to 114. B and C do not overlap, so their intersection is zero and their union length is six plus four, or ten. The pair score is zero. Notice that the union excludes the gap between 109 and 110. The rolling average is (33.3333 + 0)/2 = 16.6667%.
For another independent example, compare an interval from 100 to 110 with an interval from 102 to 108. The smaller interval lies entirely inside the larger one, but the score is only 60%, since the shared length is six and the union is ten. A fully contained candle does not automatically receive a perfect overlap score. Identical positive-width intervals receive 100%. These are hypothetical arithmetic examples, not observed market results. Equal weighting is useful when the research question concerns the typical similarity of adjacent ranges rather than the total amount of shared price distance.
Complete NinjaScript source
using System;
using System.ComponentModel.DataAnnotations;
using System.Windows.Media;
using NinjaTrader.NinjaScript;
namespace NinjaTrader.NinjaScript.Indicators
{
public class PSAdjacentRangeOverlap : Indicator
{
[NinjaScriptProperty]
[Range(1, 1000)]
[Display(Name = "Pair count", Order = 1,
GroupName = "Parameters")]
public int Period { get; set; }
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Name = "PSAdjacentRangeOverlap";
Description = "Mean adjacent range overlap";
Calculate = Calculate.OnBarClose;
IsOverlay = false;
Period = 10;
BarsRequiredToPlot = 0;
AddPlot(Brushes.SteelBlue, "Overlap");
AddLine(Brushes.Gray, 50, "Midline");
}
}
protected override void OnBarUpdate()
{
// N adjacent pairs require N+1 bars.
if (CurrentBar < Period)
{
Value.Reset();
return;
}
double sum = 0.0;
int count = 0;
// OnBarClose: index zero is completed.
for (int i = 0; i < Period; i++)
{
double h1 = High[i];
double l1 = Low[i];
double h2 = High[i+1];
double l2 = Low[i+1];
if (h1 < l1 || h2 < l2)
continue;
double intersection = Math.Max(0.0,
Math.Min(h1, h2) - Math.Max(l1, l2));
// Union length excludes any gap between ranges.
double union = (h1-l1) + (h2-l2) - intersection;
if (union <= 0 || double.IsNaN(union) ||
double.IsInfinity(union))
continue;
sum += intersection / union;
count++;
}
// Require every pair to be valid.
if (count != Period)
{
Value.Reset();
return;
}
Value[0] = 100.0 * sum / Period;
}
}
}
Implementation details
The SetDefaults branch configures the indicator's name, calculation mode, separate panel and numerical input. The NinjaScriptProperty and Range attributes expose a bounded positive integer period. AddPlot creates the primary numerical output and AddLine supplies a 50% visual reference. That reference is illustrative and is not a recommended trading threshold.
CurrentBar starts at zero, so the first eligible calculation occurs when CurrentBar equals Period. The loop compares the current completed candle with its predecessor, then moves backward through exactly Period pairs. Because adjacent pairs share candles, the window contains Period plus one prices intervals rather than twice Period distinct candles. The maximum and minimum functions implement the geometric intersection, and the union subtracts the duplicated shared portion. Invalid high-low ordering and nonpositive or nonfinite union lengths are excluded. The implementation requires a complete valid sample; if even one pair is invalid, Value.Reset marks the result unavailable instead of silently averaging a shorter window.
Each evaluation directly scans the requested pairs. This linear cost is easy to audit, and repeating the same calculation with unchanged inputs does not alter the output. A cached rolling average could reduce routine work, but would require careful handling of invalid samples, history resets and repeated calculation events. Establish correctness with the direct implementation before attempting optimization.
Installation and completed-bar timing
Open NinjaTrader 8's NinjaScript Editor and create a new indicator named PSAdjacentRangeOverlap. Replace the user-authored class with the complete source while preserving or allowing the editor to regenerate its standard generated access code. Compile and inspect diagnostics. Add the indicator to a chart, set Pair count to two and compare its Data Box values against independently calculated intervals. The source has not been compiled or executed in NinjaTrader here.
Calculate.OnBarClose evaluates the completed candle, whose index is zero during that event. Its high and low are not used provisionally during formation. The result is aligned with the completed bar, but was not available in confirmed form before that bar ended. In live operation the next incoming event may be needed to recognize bar completion. If the indicator is hosted by another NinjaScript object, configure the host for compatible completed-bar calculation, because its calculation mode can govern embedded indicators. The code assumes a single primary series. It does not reference future observations or intentionally repaint finalized values under unchanged data; historical corrections, session settings or reconstructed bars can nevertheless alter the underlying intervals.
Testing and limitations
Reproduce the examples in a spreadsheet. Test identical intervals, complete containment, partial overlap, endpoint contact, separated intervals, and two zero-width intervals. Verify the first eligible index, Period equal to one, and missing history. Compare historical and replay calculations with identical data. Observe the indicator during live candle formation and confirm that completed scores do not change solely because of active price updates. The study uses highs and lows, not the sequence of trades between them. Overlap does not establish that every price within the intersection traded, and high overlap can occur during a gradual trend. Low overlap may reflect gaps or feed anomalies. The average also discards direction and absolute price width. Research any downstream threshold independently and include realistic spreads, slippage and commissions.
For configurable weighting, range filters, alerts or NinjaScript integration, contact our Custom NinjaTrader indicator Development Services.
Risk disclosure: educational material only. Trading involves risk of loss. Hypothetical calculations do not establish profitability.