Trading Tips — Prior Range Breakout Distance in MetaTrader 4
A close just one tick above resistance and a close far above resistance both satisfy a conventional Boolean breakout condition. Yet these two events describe very different relationships between price and its earlier trading range. A useful indicator coding technique is to measure the signed distance beyond the earlier range and normalize it by the width of that range. This tutorial implements that idea as a closed-bar MQL4 histogram. It is a descriptive tool for studying breakouts, not an automated entry system.
Define the reference without including the candidate
For each completed candidate candle, find the highest high and lowest low of the N candles immediately preceding it. Call these U and L. Their difference W = U − L is the reference width. If the candidate close C exceeds U, the score is (C − U)/W. If C falls below L, the score is (C − L)/W. If the close remains within the interval, the score is zero. A nonpositive reference width is treated as unavailable data rather than zero, because division would not be meaningful.
The candidate must be excluded from the reference calculation. Otherwise a new high established by the candidate could immediately lift the reference high and suppress the very breakout being measured. The earlier high and low remain fixed while that candidate develops. Using the prior range width instead of a fixed number of broker points also avoids an unnecessary dependency on the number of decimal places in a quote.

Numerical examples
Set the reference high to 110 and the reference low to 100. The width is ten price units. A completed close at 113 exceeds the upper boundary by three units, giving +0.30. An independent candidate closing at 105 remains inside the range and scores zero. A third candidate closing at 98 falls two units below the lower boundary, giving −0.20. A close exactly at either boundary is zero because the conditions use strict comparisons. The three cases are separate examples against the same hypothetical reference, not consecutive bars updating a rolling range.
Suppose another instrument has a reference interval from 200 to 240 and closes at 252. The upper excursion is twelve units and the width is forty, so it also scores +0.30. The normalized readings match despite different absolute price scales. This does not mean the two instruments have identical volatility distributions or trading costs. Normalization only expresses a specific relationship between each close and its own reference width.
Complete MQL4 indicator source
#property strict
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 clrSteelBlue
#property indicator_width1 2
input int Lookback = 20;
double Score[];
int OnInit()
{
if(Lookback < 1 || Lookback > 5000)
return(INIT_PARAMETERS_INCORRECT);
SetIndexBuffer(0, Score);
ArraySetAsSeries(Score, true);
SetIndexStyle(0, DRAW_HISTOGRAM);
SetIndexEmptyValue(0, EMPTY_VALUE);
SetIndexLabel(0, "Breakout distance");
IndicatorShortName("Prior Range Breakout Distance");
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);
ArraySetAsSeries(close, true);
if(prev_calculated == 0 || prev_calculated > rates_total)
ArrayInitialize(Score, EMPTY_VALUE);
if(rates_total < Lookback + 2) return(0);
// Candidate i needs earlier bars i+1 through i+Lookback.
int oldest = rates_total - Lookback - 1;
int start = oldest;
if(prev_calculated > 0 && prev_calculated <= rates_total)
start = (int)MathMin(oldest, rates_total-prev_calculated+1);
// Keep the live candle empty.
Score[0] = EMPTY_VALUE;
for(int i = start; i >= 1; --i)
{
double upper = high[i+1];
double lower = low[i+1];
for(int j = i+2; j <= i+Lookback; ++j)
{
upper = MathMax(upper, high[j]);
lower = MathMin(lower, low[j]);
}
double width = upper-lower;
if(width <= 0.0)
Score[i] = EMPTY_VALUE;
else if(close[i] > upper)
Score[i] = (close[i]-upper)/width;
else if(close[i] < lower)
Score[i] = (close[i]-lower)/width;
else
Score[i] = 0.0;
}
return(rates_total);
}
Implementation and buffer management
The indicator uses the modern OnInit and OnCalculate event handlers supported by current MT4 builds. SetIndexBuffer binds the output array to the indicator, after which ArraySetAsSeries explicitly makes index zero the newest bar. The input high, low and close arrays are also explicitly configured in series order. This prevents the algorithm from depending on implicit array direction.
In the calculation loop, candidate i begins at one because the candle at zero is still forming. The reference starts at i+1 and ends at i+Lookback. The oldest eligible candidate is rates_total minus Lookback minus one, ensuring the final reference index is no larger than rates_total minus one. The initial calculation clears the entire output buffer, leaving the oldest bars empty until enough history exists. Subsequent calls recalculate recent values using prev_calculated; when the terminal resets that argument to zero, the indicator rebuilds its available history. The direct search uses O(N) work per evaluated candle, making the reference logic transparent. A deque-based rolling maximum and minimum could reduce work for very large histories, but would require additional state and careful reset handling.
Installation and chart configuration
Open MetaEditor from MetaTrader 4 and create a custom indicator called PriorRangeBreakoutDistance. Replace the generated source with the code, save it in the MQL4/Indicators folder and compile. Return to MT4 and attach the indicator from Navigator. The histogram appears in a separate chart window. Begin with Lookback=20, then use a small value such as three for manual comparisons. Check compilation and behavior in your installed terminal before deployment; the source has not been compiled or executed here.
Closed-bar behavior and EA integration
The histogram at index zero is always empty. Once a new bar starts, the former live bar moves to index one and its completed close can be evaluated. The output is placed on that candidate's historical bar, even though the value was unavailable before that bar closed. An EA using the MQL4 iCustom interface should read buffer mode zero at shift one for the latest confirmed observation, and check for EMPTY_VALUE before applying any comparison. The study has one output buffer and contains no trading functions.
Because the calculation uses only the candidate's completed close and earlier highs and lows, it does not intentionally repaint confirmed values. A rolling reference naturally changes for each new candidate, but that is not the same as revising the earlier candidate's reference after future prices arrive. History corrections, feed changes and reconstructed offline charts can nevertheless alter historical values. During a weekend or trading halt, the last bar may remain at index zero until a new bar is recognized.
Practical validation checklist
Manually identify a small reference window and verify its upper and lower boundaries in the Data Window. Test positive, negative and inside-range outcomes, exact equality with each boundary and a zero-width reference. Confirm that the live candle remains empty even if its price temporarily crosses the earlier high. After a new bar appears, compare the confirmed result with a manual calculation. Change the lookback and reload the chart to check initialization. If studying signals through an EA, log the candidate timestamp and returned buffer value so that chart and program observations can be aligned correctly.
Interpretation and limitations
A reading of +0.30 means the close is above the earlier range by 30 percent of its width, not that price has risen 30 percent. The score is unbounded, so unusually narrow reference windows can produce extreme values. A zero score means the close is inside or on the reference boundaries, not necessarily that volatility is low. The indicator ignores intrabar excursions beyond the boundary when the candle ultimately closes inside. It also does not incorporate volume, spread, commissions or order-flow information. Large values can result from news gaps or temporary liquidity disturbances rather than durable trends. Research any proposed threshold on independent data and account for realistic costs.
For alerts, minimum-width filters, optimized rolling windows or EA integration, contact our Custom MT4 indicator Development Services.
Risk disclosure: educational material only. Trading involves risk of loss. Hypothetical examples do not establish profitability.