Intermediate Trading Tutorial — Confirmed Opening Gap Fill Ratio in MT4
An opening price can differ substantially from the preceding candle's close. Simply recording the size of that difference does not reveal whether the market subsequently moved back toward the earlier close. This tutorial builds a native MQL4 indicator that measures how much of an opening gap was retraced within the same completed candle. It distinguishes upward and downward gaps using two colored output buffers and reports the extent of retracement on a bounded percentage scale. The measurement is descriptive: it is neither a forecast of future gap closure nor a simulation of an executable order.
Define a gap and its retracement
Let P be the immediately preceding candle's closing price, O the evaluated candle's opening price, H its high, and L its low. Define the signed opening gap G as O minus P. A positive value is an upward gap; a negative value is a downward gap. For an upward gap, measure retracement toward P using O minus L and divide by G. For a downward gap, use H minus O and divide by the absolute gap. Multiply the fraction by one hundred after clamping it between zero and one. Thus zero means no observed excursion toward the previous close, and one hundred means the candle reached or passed that reference level. The result does not measure how far price traveled beyond the reference.
A minimum gap size prevents extremely small opening differences from dominating the ratio. The source expresses that filter in integer quote points, using the symbol's _Point and rounding to the nearest point. The actual unrounded price difference is retained in the retracement calculation. This is a close-to-open definition: it is not the classical price gap between two nonoverlapping high-low ranges. A qualifying event can occur even if the two candles' ranges overlap.

Worked numerical examples
Assume a previous close of 100 and an open of 110. The gap is ten price units. If the signal candle's low is 108, its excursion toward the reference is two units, and the ratio is 20%. If the low is 104, the excursion is six units and the ratio is 60%. If the low reaches 98, the unbounded ratio is 120%, but the displayed value is 100%. These are independent hypothetical cases, each with a high of 112 and a close of 111. The high and close do not change the upward-gap retracement formula.
For a downward example, take the previous close as 100 and the open as 90. A candle with high 96, low 88 and close 91 has retraced six of the ten gap units, so its downward-gap fill ratio is 60%. It is displayed in the downward-gap buffer. If the high remains at 90, the ratio is zero. A high of 101 yields a capped result of 100%. Neither the sign nor the percentage describes the candle's closing direction. Assume for all examples that the minimum gap threshold is satisfied.
Complete native MQL4 indicator source
#property strict
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_color1 clrSeaGreen
#property indicator_color2 clrIndianRed
#property indicator_minimum 0
#property indicator_maximum 100
input int MinGapPoints = 10;
double UpFill[], DownFill[];
int OnInit()
{
if(MinGapPoints < 1 || _Point <= 0)
return(INIT_PARAMETERS_INCORRECT);
SetIndexBuffer(0, UpFill);
SetIndexBuffer(1, DownFill);
ArraySetAsSeries(UpFill, true);
ArraySetAsSeries(DownFill, true);
SetIndexStyle(0, DRAW_HISTOGRAM, STYLE_SOLID, 3);
SetIndexStyle(1, DRAW_HISTOGRAM, STYLE_SOLID, 3);
SetIndexEmptyValue(0, EMPTY_VALUE);
SetIndexEmptyValue(1, EMPTY_VALUE);
SetIndexLabel(0, "Up gap fill %");
SetIndexLabel(1, "Down gap fill %");
IndicatorShortName("PS Confirmed Gap Fill");
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(open, true);
ArraySetAsSeries(high, true);
ArraySetAsSeries(low, true);
ArraySetAsSeries(close, true);
bool full = prev_calculated <= 0 ||
prev_calculated > rates_total;
if(full)
{
ArrayInitialize(UpFill, EMPTY_VALUE);
ArrayInitialize(DownFill, EMPTY_VALUE);
}
// Never publish a provisional live-bar value.
UpFill[0] = EMPTY_VALUE;
DownFill[0] = EMPTY_VALUE;
UpFill[rates_total-1] = EMPTY_VALUE;
DownFill[rates_total-1] = EMPTY_VALUE;
int start = rates_total - 2;
if(!full)
start = (int)MathMin(start,
MathMax(1, rates_total-prev_calculated+1));
for(int i=start; i>=1; --i)
{
UpFill[i] = EMPTY_VALUE;
DownFill[i] = EMPTY_VALUE;
if(high[i] < open[i] || low[i] > open[i] ||
high[i] < low[i])
continue;
double gap = open[i] - close[i+1];
long gapPoints = (long)MathRound(gap/_Point);
if(MathAbs((double)gapPoints) < MinGapPoints ||
gap == 0.0)
continue;
// Use the extreme toward the previous close.
double fraction;
if(gap > 0.0)
fraction = (open[i]-low[i])/gap;
else
fraction = (high[i]-open[i])/(-gap);
double fill = 100.0 * MathMax(0.0,
MathMin(1.0, fraction));
if(gap > 0.0) UpFill[i] = fill;
else DownFill[i] = fill;
}
return(rates_total);
}
Buffers and historical indexing
The initialization function binds two indicator buffers and enables series indexing after binding. Both buffers use histogram drawing styles and the same zero-to-one-hundred scale. An upward gap populates only UpFill, and a downward gap populates only DownFill. EMPTY_VALUE distinguishes a nonqualifying observation from a valid zero retracement. A zero-height histogram may not be visible, so inspect the Data Window or read the buffers programmatically when distinguishing those cases.
OnCalculate explicitly sets the input price arrays to series order. Index zero is the active candle; index one is the latest completed candle. For an evaluated index i, the preceding close is at i+1. The oldest calculable index is rates_total minus two, since the oldest loaded candle has no preceding observation. The code clears both the live and oldest positions, initializes the buffers on full recalculation, and refreshes recent history using prev_calculated. Each observation requires a constant number of arithmetic operations. There is no rolling accumulator or recursive dependency.
The threshold uses rounded quote points rather than pips or necessarily the exchange's minimum trade tick. For example, on a five-decimal FX quote where _Point equals 0.00001, a minimum of ten points corresponds to 0.00010. Always check the symbol specification before interpreting the input. The code rejects obvious inconsistencies between the open and observed extremes, and checks for zero gap before dividing. It assumes normal finite OHLC prices supplied by the terminal.
Installation and closed-bar timing
Open MetaEditor from MT4, create a custom indicator named PSConfirmedGapFill, replace its source with the example, and compile the MQ4 file. Attach the compiled indicator to a chart and configure MinGapPoints for the instrument's quote precision. Use the Data Window to inspect individual completed candles. An Expert Advisor can use iCustom with the upward or downward buffer index and shift one, rejecting EMPTY_VALUE before applying any condition. The code has not been compiled or executed in MT4 here.
The active candle's high and low can change continuously, but the implementation deliberately publishes no value at index zero. Only when a subsequent candle is recognized can the previous candle's final retracement appear at index one. Although the result is drawn on the evaluated candle, it was not confirmed at its opening time. The formula accesses no future observations and does not intentionally repaint completed values under unchanged data. Historical corrections, session changes and reconstructed candles can legitimately alter results.
Testing and limitations
Reproduce both directional examples in a spreadsheet. Test a gap below the minimum, a zero gap, exactly the minimum threshold, zero retracement, partial retracement and a full overshoot. Check that only one buffer is populated for each qualifying bar. Compare completed values after reloading identical data and observe that the active bar remains empty. A candle extreme crossing the reference does not establish that every intermediate price traded, or that a particular order would have been filled. Chart prices may omit the relevant executable bid or ask; spreads, slippage and liquidity matter. The indicator does not track unfilled gaps across later candles. Broker sessions, weekend gaps, feed differences and timeframe selection can materially change the observations. Evaluate any downstream hypothesis on independent data with realistic costs.
For multi-bar gap tracking, session filters or Expert Advisor integration, contact our Custom MT4 indicator Development Services.
Risk disclosure: educational material only. Trading involves risk of loss. Hypothetical examples do not demonstrate profitability.