Intermediate Trading Tutorial | MQL5 custom indicators
Opening gaps do not always point in the same direction. A market can open above its previous close several times, yet a few large downward gaps may offset all those upward moves. Counting the number of positive gaps alone misses that difference. This tutorial builds a free MT5 indicator that compares the signed sum of recent opening gaps with their combined absolute size. The resulting directional gap share oscillator distinguishes persistent directional gaps from mixed gap activity while remaining bounded between −100 and +100.
Define a gap precisely
For each candle, subtract the immediately preceding candle's closing price from the current candle's opening price. This is an open-to-prior-close difference, not a comparison between the current low and the previous high. The latter would identify a different type of chart gap. Our definition can produce a nonzero observation even if the two candles overlap. Positive values represent openings above the preceding close; negative values represent openings below it.
Over a window of N completed bars, add the signed differences to obtain the net gap. Separately add their absolute values to obtain gross gap activity. Divide the net by the gross and multiply by 100. Because the absolute value of the sum cannot exceed the sum of the absolute values, the result is bounded. If every measurable gap is positive, the result is +100; if every gap is negative, it is −100. When opposing gaps balance exactly, the result is zero. If there are no nonzero gaps at all, the denominator is zero; the implementation returns zero as an explicit neutral convention.
A five-bar worked example
Suppose the following hypothetical observations are measured in price units. Each row compares the opening price of a completed candle with the preceding candle's close. These are illustrative values, not historical market data.
| Bar | Previous close | Open | Gap | Absolute gap |
|---|---|---|---|---|
| 1 | 100 | 102 | +2 | 2 |
| 2 | 105 | 104 | −1 | 1 |
| 3 | 103 | 103 | 0 | 0 |
| 4 | 101 | 104 | +3 | 3 |
| 5 | 106 | 104 | −2 | 2 |

The signed sum is 2 − 1 + 0 + 3 − 2 = 2, whereas the absolute sum is 2 + 1 + 0 + 3 + 2 = 8. The oscillator reads +25. The two positive and two negative observations have equal counts, but positive gaps are larger in aggregate. If the next completed gap is −4 and the oldest +2 leaves the window, net becomes −4 and gross becomes 10, producing −40. This change illustrates how rolling-window replacement can shift the reading sharply without necessarily indicating a reversal in the underlying price.
Complete MQL5 indicator source
// PatternSmart: directional opening gap share (MT5)
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDodgerBlue
#property indicator_width1 2
#property indicator_label1 "Gap Share"
#property indicator_minimum -100
#property indicator_maximum 100
#property indicator_level1 0
input int Period = 5;
double GapShare[];
int OnInit()
{
if(Period < 1) return(INIT_PARAMETERS_INCORRECT);
if(!SetIndexBuffer(0, GapShare, INDICATOR_DATA))
return(INIT_FAILED);
ArraySetAsSeries(GapShare, true);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, Period);
IndicatorSetString(INDICATOR_SHORTNAME,
"Directional Gap Share (" + IntegerToString(Period) + ")");
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(close, true);
if(prev_calculated <= 0 || prev_calculated > rates_total)
ArrayInitialize(GapShare, EMPTY_VALUE);
if(rates_total < 1) return(0);
GapShare[0] = EMPTY_VALUE;
// N gaps need N+1 closed bars.
if(rates_total < Period + 2) return(0);
int oldest = rates_total - Period - 1;
int start = oldest;
if(prev_calculated > 0 && prev_calculated <= rates_total)
start = MathMin(oldest, rates_total - prev_calculated + 1);
for(int i = start; i >= 1; --i)
{
double net = 0.0, gross = 0.0;
for(int j = i; j < i + Period; ++j)
{
double gap = open[j] - close[j + 1];
net += gap;
gross += MathAbs(gap);
}
// No measurable gaps: report neutral by convention.
GapShare[i] = gross > 0.0 ? 100.0 * net / gross : 0.0;
}
return(rates_total);
}
Buffer and indexing design
The program creates one data buffer in a separate window. SetIndexBuffer binds the array to the indicator's output, and ArraySetAsSeries establishes the newest-first indexing convention after that binding. The incoming open and close arrays are explicitly set to the same direction. Index zero is intentionally blank; index one contains the latest completed-bar result. For a result at index i, the loop reads opens from i through i + Period − 1 and corresponding previous closes from i + 1 through i + Period. Because the final observation needs an additional earlier close, N gap observations require N + 1 completed candles.
The oldest valid output is rates_total − Period − 1. The initial calculation fills the valid range and initializes unavailable values to EMPTY_VALUE. Later calls use prev_calculated to refresh the newest relevant completed bars. A history reload that resets prev_calculated triggers a full rebuild. This straightforward nested loop is appropriate for ordinary lookbacks, although a rolling numerator and denominator would reduce the cost for extremely long windows.
Install in MetaTrader 5
- Open MetaEditor from MT5 and create a custom indicator named DirectionalGapShare.mq5 under MQL5/Indicators.
- Replace the generated source with the complete code above, save it and compile in your terminal.
- Attach the indicator to a chart using Navigator. Begin with the default Period of five and examine a daily chart and an intraday chart separately.
- Open the Data Window and inspect the most recent completed reading. Calculate the five differences manually using the same broker's price history.
- Observe behavior across a new bar and compare the updated output with the hand calculation.
The implementation uses the native MQL5 indicator interface. Compilation and live execution have not been performed for this article. Verify the source in your installed platform before using it in a production workflow.
Parameter choices and data limitations
A five-bar period makes individual openings influential, as the example shows. A period of twenty smooths the impact of one large observation but may retain old gaps long after market conditions have changed. Increasing the period does not guarantee a more useful signal. On many continuous intraday markets, opens frequently equal the prior close, making the indicator predominantly zero or highly sensitive to rare discontinuities. Daily charts on session-based instruments may provide richer variation, but session definitions differ between data providers.
Also distinguish directional concentration from magnitude. A window containing only one tiny positive gap and four zero gaps produces +100, just as a window of five very large positive gaps does. This is not a bug; the ratio deliberately discards the absolute scale. Traders interested in material gaps should additionally inspect gross activity, possibly normalized by a volatility measure, and test that separate filter. Do not interpret +100 as a probability of a profitable long trade.
Verification and EA integration
Check all-positive, all-negative, balanced and all-zero test windows. Verify that insufficient history leaves an empty output rather than a false neutral signal. Confirm the result for Period = 1: a single nonzero gap produces either +100 or −100. Observe that the current bar remains blank even though its opening price is known. This conservative publication convention provides a consistent completed-bar interface and avoids treating a forming bar as a historical sample.
An EA can create an iCustom handle for the indicator and call CopyBuffer with buffer number zero, start position one and count one. Confirm that the handle is valid and the copy returns one element before reading it; EMPTY_VALUE means unavailable. Release the handle when no longer needed. Do not treat the handle itself as an indicator value or confuse MQL5's interface with the direct-value iCustom call in MQL4.
Interpretation and risk
Opening gaps may reflect session boundaries, news, liquidity, contract rollover or data adjustments. They do not measure buying and selling volume, and a positive reading can coexist with a declining trend if intrabar losses outweigh opening gains. The indicator is a descriptive feature, not an entry or exit system. Test any trading rule independently, accounting for execution costs, gaps through stops and out-of-sample performance.
If you would like session-only filtering, gross gap activity as a second buffer, or integration into an Expert Advisor, contact us for Custom MT5 indicator Development Services.
Risk disclosure: This tutorial is educational and does not constitute investment advice. Hypothetical calculations do not demonstrate profitability. Trading can result in significant losses.