Intermediate Trading Tutorial | NinjaTrader 8 custom indicators
A large candle is not necessarily exploring new territory. It may simply travel across a price interval that the preceding candle has already covered. Conversely, a comparatively small candle can form entirely beyond the preceding range. This tutorial builds a free NinjaTrader 8 indicator that measures the proportion of each completed candle's high-low interval outside the previous candle's interval, then averages those proportions across a configurable window. The result describes range displacement independently of whether the market moved upward or downward. It is intended as a descriptive feature for technical analysis and NinjaScript development, not a standalone trade trigger.
Measure interval overlap rather than candle size
Represent the current candle as an interval from its low to its high, and represent the preceding candle in the same way. Their common interval begins at the larger of the two lows and ends at the smaller of the two highs. The overlap length is the difference between those boundaries, floored at zero. This last step is essential: two disjoint intervals have zero overlap, not negative overlap. Divide the overlap by the current candle's width, subtract the result from one, and multiply by 100 to express the escape fraction as a percentage.
Notice that the denominator is the current range rather than the union or the preceding range. This makes the statistic asymmetric. It asks how much of this candle lies outside the prior candle, not how similar the two candles are in a symmetric mathematical sense. If the current candle is fully contained by the preceding one, its escape fraction is zero. If the two intervals are completely disjoint, it is 100. A candle that surrounds the preceding interval can have an intermediate or high value even if its closing price remains within the preceding range.
Calculate the indicator manually
Suppose the previous candle spans 100 to 110, while the current candle spans 104 to 114. Their overlap is 104 to 110, or six price units. The current range is ten units. The uncovered portion is four units, all above the previous high, so the escape fraction is 40%. The direction is not encoded in the percentage itself. A different candle spanning 96 to 106 would also produce 40%, this time with the uncovered portion below the previous low.

The rolling indicator uses an equally weighted arithmetic mean rather than a ratio of total uncovered width to total candle width. The distinction matters because a wide candle and a narrow candle each contribute one normalized observation. The following hypothetical sequence illustrates five successive comparisons, starting with an initial reference candle spanning 100 to 110.
| Current interval | Prior interval | Overlap | Escape |
|---|---|---|---|
| 104–114 | 100–110 | 6 | 40% |
| 106–111 | 104–114 | 5 | 0% |
| 112–116 | 106–111 | 0 | 100% |
| 110–115 | 112–116 | 3 | 40% |
| 111–115 | 110–115 | 4 | 0% |
The mean is (40 + 0 + 100 + 40 + 0) / 5 = 36%. Even though one interval is entirely outside the previous one, the two contained intervals substantially reduce the average. This is more informative about repeated range exploration than simply highlighting the largest candle.
Complete NinjaScript source
// PatternSmart: Range Escape Fraction for NinjaTrader 8
using System;
using System.ComponentModel.DataAnnotations;
using System.Windows.Media;
using NinjaTrader.NinjaScript;
namespace NinjaTrader.NinjaScript.Indicators
{
public class PSRangeEscapeFraction : 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 = "PSRangeEscapeFraction";
Description = "Mean fraction of each bar outside the prior range.";
Calculate = Calculate.OnBarClose;
IsOverlay = false;
BarsRequiredToPlot = 0;
Period = 5;
AddPlot(Brushes.RoyalBlue, "EscapePercent");
AddLine(Brushes.Gray, 50, "Midpoint");
}
}
protected override void OnBarUpdate()
{
// N comparisons require N+1 bars.
if (CurrentBar < Period)
{
Value.Reset();
return;
}
double sum = 0.0;
for (int j = 0; j < Period; j++)
{
double width = High[j] - Low[j];
if (width <= 0.0)
continue; // Neutral contribution, fixed denominator.
double overlap = Math.Max(0.0,
Math.Min(High[j], High[j + 1])
- Math.Max(Low[j], Low[j + 1]));
double fraction = 1.0 - overlap / width;
sum += Math.Max(0.0, Math.Min(1.0, fraction));
}
Value[0] = 100.0 * sum / Period;
}
}
}
Lifecycle and bar indexing
State.SetDefaults defines the indicator's name, parameter default, plotting behavior and calculation mode. AddPlot creates the output series; AddLine supplies a visual reference at 50. The reference is not an optimized entry threshold. Calculate.OnBarClose makes OnBarUpdate evaluate completed bars under ordinary standalone indicator use. Within that callback, High[0] and Low[0] refer to the bar being evaluated, rather than a future bar. Each comparison uses j and j + 1, so the final comparison reads the bar Period positions back. CurrentBar is zero-based; the condition CurrentBar less than Period therefore protects the additional preceding observation. Until sufficient bars exist, Value.Reset marks the plot value invalid rather than presenting a genuine zero reading.
Inside the loop, a zero-width bar contributes zero and the denominator remains Period. This is an explicit convention, not a claim that the price actually explored a measurable fraction. The clamp limits numerical rounding effects near zero and one. The straightforward loop costs O(Period) per completed bar and requires no auxiliary rolling series. With the permitted range of one through 500, it is useful for experimenting with the calculation. A high-throughput multi-instrument deployment could maintain a rolling sum of separately computed per-bar fractions instead, but should validate equivalence before replacing this implementation.
Installation in NinjaTrader 8
- Open New → NinjaScript Editor and create an indicator named PSRangeEscapeFraction.
- Replace the editable indicator class and necessary imports with the code above. Leave any platform-generated wrapper region to NinjaTrader; do not paste duplicate generated wrappers.
- Compile in the editor. The source is written for NT8, but this article has not executed a NinjaTrader compiler or live market test.
- Open a chart, select Indicators, add PSRangeEscapeFraction, and set Period to five initially. Confirm the calculation mode is On bar close.
- Compare the Data Box value for a completed bar with a manual calculation from six consecutive OHLC intervals.
Parameter choices and practical limitations
Period = 1 gives the escape percentage of a single completed candle. A shorter average responds promptly to range changes but can alternate sharply when consecutive candles overlap and separate. A longer window smooths isolated changes while retaining older conditions. The same numeric output on a one-minute chart and a daily chart does not imply equal market behavior: aggregation changes the intervals and the frequency of price discontinuities. Tick, range, and other non-time-based bars also construct price intervals differently. Evaluate settings on the exact bar type and trading-hours template used in your intended workflow.
A disjoint candle can yield 100 even if the skipped distance is enormous or very small. The metric only describes the current interval outside its predecessor; it does not count the empty gap between them. It also cannot distinguish upside and downside escape, and a high reading can occur during alternating two-way volatility. A directional extension or an absolute range filter would answer different questions and should be tested independently.
Validation checklist
Test identical ranges, full containment, disjoint intervals, touching boundaries, partial overlap, and flat bars. Check the worked example and confirm the first valid point follows Period + 1 loaded bars. Inspect completed historical values during playback and after a reload. Session boundaries and feed corrections may alter the input data; ordinary historical stability is conditional on unchanged bars. A parent NinjaScript strategy can control the effective calculation frequency of hosted indicators, so when integrating this feature, ensure the calling strategy uses completed-bar timing or deliberately handles the intrabar distinction. Do not assume that every live callback represents a closed bar when changing Calculate settings.
If you would like separate upside and downside plots, alerts, a rolling-sum optimization or integration with a custom NinjaScript strategy, contact us for Custom NinjaTrader indicator Development Services.
Risk disclosure: This educational indicator is not investment advice. Examples are hypothetical. Trading involves risk of loss, and a range statistic does not establish profitability.