Intermediate Trading Tutorial — Closed-Bar Range Percentile Rank in MT4
Raw candle ranges can be difficult to compare across instruments and market conditions. A range of twenty points may be unusually large during one session and routine during another. Rather than divide the current range by an average, this tutorial ranks a completed candle against a fixed sample of earlier candles. The resulting percentile describes the relative position of its range in the observed historical distribution, without requiring a normal distribution or estimating its parameters. It is a descriptive volatility tool, not a forecast of the next candle.
Definition and tie handling
Define candle range as High minus Low, expressed in integer quote points. Select N earlier completed candles as the reference sample, excluding the signal candle itself. Count the number L of reference ranges strictly smaller than the signal range, and the number E equal to it. The midrank percentile is 100 × (L + 0.5 × E) / N. Values are bounded between zero and one hundred. A signal larger than every reference observation receives 100; one smaller than all observations receives zero. When every reference range equals the signal range, the result is 50. Unlike a strict-less-than rank, this convention does not classify identical values as unusually small.

Worked examples
Set Period to four and use reference ranges of 2, 4, 4 and 8 quote points. For a signal range of four, L equals one and E equals two. The score is 100 × (1+0.5×2)/4 = 50. For a signal of five against the same sample, L is three and E is zero, giving 75. A range of nine gives 100, while a range of one gives zero. These are separate hypothetical comparisons against the same reference, not a sequence in which the reference remains fixed as new bars arrive.
In live use, the sample advances one bar at a time. When a new candle completes, it becomes the signal and the preceding N completed candles become its reference. The oldest observation drops out. A score can change because the signal range changes or because the reference distribution changes. Neither effect by itself demonstrates a change in future trading opportunities.
Complete native MQL4 source
#property strict
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 clrSteelBlue
#property indicator_minimum 0
#property indicator_maximum 100
input int Period = 20;
double RankBuffer[];
int OnInit()
{
if(Period < 1 || Period > 10000 || _Point <= 0)
return(INIT_PARAMETERS_INCORRECT);
SetIndexBuffer(0, RankBuffer);
ArraySetAsSeries(RankBuffer, true);
SetIndexStyle(0, DRAW_LINE);
SetIndexLabel(0, "Range rank");
SetIndexEmptyValue(0, EMPTY_VALUE);
IndicatorShortName("PS Closed Range Percentile");
return(INIT_SUCCEEDED);
}
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
ArraySetAsSeries(high, true);
ArraySetAsSeries(low, true);
// Clear the buffer on full recalculation.
if(prev_calculated <= 0 || prev_calculated > rates_total)
ArrayInitialize(RankBuffer, EMPTY_VALUE);
// The forming candle never receives a value.
RankBuffer[0] = EMPTY_VALUE;
int oldest = rates_total - Period - 1;
if(oldest < 1)
return(rates_total);
int start = oldest;
if(prev_calculated > 0 && prev_calculated <= rates_total)
start = MathMin(oldest,
MathMax(1, rates_total-prev_calculated+1));
for(int i=start; i>=1; --i)
{
// Convert ranges to integer quote-point units.
long target = (long)MathRound((high[i]-low[i])/_Point);
int lower = 0, ties = 0;
bool valid = high[i] >= low[i];
for(int j=1; j<=Period; ++j)
{
if(high[i+j] < low[i+j])
valid = false;
long prior = (long)MathRound(
(high[i+j]-low[i+j])/_Point);
if(prior < target) ++lower;
else if(prior == target) ++ties;
}
RankBuffer[i] = valid
? 100.0*(lower+0.5*ties)/Period
: EMPTY_VALUE;
}
return(rates_total);
}
Implementation and indexing
OnInit binds the output buffer and explicitly enables time-series indexing after binding. OnCalculate applies the same indexing direction to high and low. In this convention index zero is the forming candle, index one is the latest completed candle, and larger indices refer to older observations. The inner loop begins at i+1, so the signal is never included in its own reference. The oldest eligible index is rates_total minus Period minus one. A minimum of N+2 chart bars is needed to calculate index one while leaving index zero blank.
Quote-point conversion uses the symbol's _Point value and rounds each observed range to the nearest integer. This provides a reproducible equality rule rather than comparing floating-point price differences directly. Quote points are not necessarily exchange trade ticks or pips. For symbols whose price increments differ from the quote precision, consider adapting the rounding convention to the actual instrument specification. Zero ranges are valid observations, whereas a high below its low invalidates the calculation. EMPTY_VALUE identifies missing output rather than an ordinary rank of zero.
The source uses prev_calculated to avoid recomputing all historical bars on each update. When the terminal reports a full recalculation, the output is cleared and all eligible indices are rebuilt. On ordinary calls it refreshes a small recent portion of the series. Each computed observation uses a direct scan of N earlier ranges. This O(N) approach is transparent and suitable as a reference implementation; a sorted rolling data structure can reduce computation for very large windows, but adds complexity to insertion, removal, duplicate handling and terminal resets.
Install and inspect the indicator
Open MetaEditor from MetaTrader 4, create a custom indicator named PSClosedRangePercentile, and replace the generated source with the complete example. Compile the MQ4 file and inspect any diagnostics in your installed build. Attach the indicator to a chart and set Period to four for manual validation. The separate panel uses a fixed zero-to-one-hundred scale. Use the Data Window to compare completed-bar readings with independently computed ranges. This code has not been compiled or executed in MT4 here.
Closed-bar behavior
The current bar is explicitly assigned EMPTY_VALUE. Therefore changing intrabar highs and lows do not generate a provisional percentile. Once the terminal recognizes a new bar, the former active candle can receive its completed score at index one. Although plotted at the completed candle, that score was not available as a confirmed value before the close. A consuming Expert Advisor should normally read shift one and reject EMPTY_VALUE. Historical corrections, changes to the chart timeframe and data reloads can change the underlying observations. The formula itself uses no future bars and does not intentionally repaint finalized values under unchanged data.
Testing and interpretation
Reproduce the worked comparisons in a spreadsheet, then test identical ranges, zero-range candles, a signal outside the entire reference distribution, insufficient history and Period equal to one. Verify that the active bar remains blank during incoming ticks. Compare results after a full reload using the same data. Check point conversion on symbols with different quote precision. A short reference sample produces coarse rank steps; longer samples can mix observations from different volatility regimes. Overlapping windows are dependent, and a rank of 90 does not mean a 90% probability of a profitable trade. The statistic ignores directional price movement, gaps between candles, volume and execution costs. Use independent samples when evaluating any downstream filter.
For additional true-range options, configurable alerts, or Expert Advisor integration, contact our Custom MT4 indicator Development Services.
Risk disclosure: educational material only. Trading involves risk of loss; hypothetical calculations do not establish profitability.