Intermediate Trading Tutorial | NinjaTrader 8 | NinjaScript C#
How unusual is the range of the candle that just closed? Dividing its range by a rolling average is one approach, but a single exceptionally large historical candle can distort the average. A percentile rank instead asks how many preceding candles had a range no larger than the candidate. The resulting statistic describes the candidate's position within a recent sample without assuming that the ranges follow a normal distribution. This tutorial implements a closed-bar range rank indicator for NinjaTrader 8 and explains its tie policy, warm-up requirements, and the difference between a historical rank and a probability forecast.
Define the comparison population
The range of a candle is its high minus its low. On a conventional tick-based instrument we divide this range by TickSize and round to the nearest integer tick using midpoint rounding away from zero. This prevents small floating-point representation errors from classifying equal tick ranges differently. The current completed candle is the candidate; the previous N completed candles form the reference population. The candidate is not included in that population.
Count the number K of reference ranges that are less than or equal to the candidate's range. The indicator output is 100 × K / N. With a lookback of 20, its values occur in increments of five percentage points. The possible endpoints are zero when all reference ranges are larger and 100 when every reference range is at or below the candidate. This is an inclusive empirical cumulative-distribution rank, not an interpolated quantile calculation.
Worked example: why ties matter
For a compact example use five preceding candle ranges of 1, 2, 2.5, 3 and 4 price units, and a candidate range of 2.5. Assume a tick size of 0.25, so the ranges correspond to 4, 8, 10, 12 and 16 ticks and the candidate is 10 ticks. Exactly three reference observations are at or below the candidate. The result is 100 × 3 / 5 = 60%. The sorted order in this illustration is for explanation; the program does not sort the historical data.

If the comparison were strictly less than the candidate, only two observations would count, producing 40%. Both definitions can be useful, but changing the tie convention changes the indicator's meaning. A series of equal-sized range bars can return 100% under the inclusive rule even though its volatility has not expanded. That behavior follows the definition and should not be treated as evidence of an exceptional candle. A midrank convention, counting half of the tied observations, would be a separate implementation.
Complete NinjaScript indicator
// PatternSmart: empirical candle range percentile rank.
// Compare a completed bar against the preceding N bars.
using System;
using System.ComponentModel.DataAnnotations;
using System.Windows.Media;
using NinjaTrader.NinjaScript;
namespace NinjaTrader.NinjaScript.Indicators
{
public class PSClosedRangePercentile : Indicator
{
[NinjaScriptProperty]
[Range(1, 1000)]
[Display(Name = "Lookback", GroupName = "Parameters", Order = 0)]
public int Lookback { get; set; }
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Name = "PSClosedRangePercentile";
Description = "Closed candle range rank against prior bars.";
Calculate = Calculate.OnBarClose;
IsOverlay = false;
BarsRequiredToPlot = 0;
Lookback = 20;
AddPlot(Brushes.RoyalBlue, "RangeRank");
AddLine(Brushes.Gray, 50, "MedianReference");
AddLine(Brushes.IndianRed, 80, "HighRankReference");
}
}
protected override void OnBarUpdate()
{
// Need N earlier bars plus the candidate bar.
if (CurrentBar < Lookback)
{
Value.Reset();
return;
}
// Tick rounding gives consistent ties on tick-based instruments.
double candidate = Math.Round(
(High[0] - Low[0]) / TickSize,
MidpointRounding.AwayFromZero);
if (!IsValidRange(candidate))
{
Value.Reset();
return;
}
int atOrBelow = 0;
for (int i = 1; i <= Lookback; i++)
{
double prior = Math.Round(
(High[i] - Low[i]) / TickSize,
MidpointRounding.AwayFromZero);
if (!IsValidRange(prior))
{
Value.Reset();
return;
}
// Inclusive tie convention; exclude the candidate itself.
if (prior <= candidate)
atOrBelow++;
}
Value[0] = 100.0 * atOrBelow / Lookback;
}
private bool IsValidRange(double value)
{
return !double.IsNaN(value)
&& !double.IsInfinity(value)
&& value >= 0;
}
}
}
Understand the bar index and calculation mode
The indicator sets Calculate.OnBarClose in State.SetDefaults. In its standalone closed-bar configuration, High[0] and Low[0] inside OnBarUpdate represent the candle being processed at its close. High[1] and Low[1] represent the immediately preceding candle. This differs from a script running on each tick where index zero normally refers to a developing candle. Do not mechanically replace the candidate with index one in this example; doing so would shift the closed-bar result back by another candle.
CurrentBar is a zero-based absolute bar index. To compare one candidate with 20 preceding bars, the first eligible CurrentBar is 20, meaning that 21 bars have been processed. Value.Reset leaves an unavailable plot value unset rather than recording a misleading zero. The visual lines at 50 and 80 are fixed reference levels only. They are not independently calculated medians, trading signals, or optimized decision boundaries.
The calculation is single-series and only references the candidate and earlier candles. On standard time-based charts it therefore does not use future data or continuously recalculate the forming candle in its standalone configuration. Historical data corrections, changes in session templates, and bar types that can revise their last bars may change results after a reload. Also, an indicator hosted by a strategy can inherit the parent's Calculate behavior. If the parent uses OnEachTick or OnPriceChange, this code is not a sufficient standalone guard against intrabar evaluation. Keep the calling strategy on OnBarClose or redesign the indicator with an explicit confirmed-bar synchronization mechanism before using it in an intrabar strategy.
Install and inspect the output
- Open the NinjaTrader 8 Control Center, select New and open NinjaScript Editor.
- Create an indicator named PSClosedRangePercentile. Insert the source in the editable indicator section; allow NinjaTrader to manage its generated wrapper code.
- Compile and resolve any diagnostics. Open a conventional time-based chart and add the indicator.
- Begin with the default Lookback of 20 and keep Calculate set to On bar close.
- Use the Data Box to inspect the indicator value on a completed candle and compare its range with the previous 20 ranges.
Choose a window appropriate to the question
| Lookback | Rank step | Practical tradeoff |
|---|---|---|
| 10 | 10 percentage points | Fast adaptation, coarse resolution. |
| 20 | 5 percentage points | Default balance for demonstration. |
| 100 | 1 percentage point | Finer resolution, slower adaptation to regime shifts. |
A longer window does not automatically make a rank more useful. It may mix opening-session behavior with quieter periods or combine different volatility regimes. This simple implementation uses a trailing window without resetting at session boundaries. If a trader needs comparisons only within a particular session, the sample definition and minimum observation policy must be redesigned explicitly.
What to test before integration
- Use a five-bar reference window and reproduce the numerical example manually.
- Test a candidate strictly smaller than all reference ranges and verify a result of zero.
- Test a candidate larger than every reference range and verify 100.
- Check equal-sized candles, confirming that ties count toward K.
- Verify that no value is available before the full prior window exists.
- Observe the chart during the live candle and at its close, then compare after reloading the same data.
The calculation requires O(N) comparisons per completed candle and does not allocate or sort a separate sample array. Very large windows or many hosted instances may still consume resources. Tick rounding assumes conventional, tick-aligned OHLC data; transformed or synthetic bar types can require a different equality policy. Zero-width candles are allowed and can influence the reference distribution. High-minus-low range excludes gaps from the previous close, so the indicator is not a true-range rank.
Interpretation and risk
A rank of 80% means that 80% of the selected preceding ranges are at or below the candidate. It does not imply an 80% probability of a continuation, reversal or profitable trade. A very large candle may occur during either a meaningful directional move or a temporary liquidity shock. Rank also discards magnitude information: a candle slightly larger than the previous maximum and one ten times larger can both score 100. Review price structure and execution conditions independently.
The relevant NinjaScript Calculate, CurrentBar and AddPlot documentation was checked. This source has not been compiled or live-tested for this article. Validate it on your platform before using it in a strategy. Trading involves risk of loss; this tutorial is educational, not investment advice.
If you are interested in this free indicator and would like a custom tie policy, session-aware reference window or strategy integration, contact us through our Custom Trading Software Development Services.