Intermediate Trading Tutorial | MQL4 custom indicators

Two candles can have the same closing price but very different intrabar ranges. One might finish near its high after a broad move, while another finishes near its low despite closing at exactly the same price. A conventional close-to-close momentum measurement does not capture that distinction. This tutorial develops a free MT4 custom indicator that measures where each completed candle closes within its own range and averages those normalized observations. The result is a bounded, price-independent view of closing pressure that can complement, but not replace, trend and volatility analysis.

Define the measurement before writing the code

For each bar with a positive high-low range, calculate a close location value as (2 × Close − High − Low) / (High − Low). A close at the high produces +1, a close at the low produces −1, and a midpoint close produces zero. The same calculation can be expressed as twice the proportion of the range below the close, minus one. It measures the final location, not the actual sequence of trades inside a candle.

Next calculate a simple arithmetic mean of these values over five completed bars. The default period of five is deliberately short enough to illustrate the behavior. Under valid OHLC data, the resulting line remains between −1 and +1. A positive value means the average normalized closing location lies above the midpoint; a negative value means it lies below. Neither value reveals whether the absolute price has risen or fallen across the window.

Five-bar calculation by hand

Consider five hypothetical candles, each with a high of 110 and a low of 100, but with different closing prices. The equal ranges make the arithmetic especially transparent; actual trading ranges need not be equal.

Bar Close Close location
1 109 0.8
2 107 0.4
3 102 −0.6
4 106 0.2
5 108 0.6
Build a Closed-Bar Close Location Pressure Indicator in MQL4
Figure 1. Five hypothetical completed bars produce a sum of 1.4 and a mean of 0.28.

The average is 1.4 / 5 = 0.28. Although the third candle closes near its low, the remaining observations tilt the mean above zero. When a sixth candle closes, the oldest observation leaves the window. For example, if that new value is −0.8, the new sum is 1.4 − 0.8 − 0.8 = −0.2 and the average becomes −0.04. A single change can therefore move a short window across its midpoint without proving a market reversal.

Complete MQL4 indicator source

// PatternSmart: closed-bar close location pressure (MT4)
#property strict
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 DodgerBlue
#property indicator_width1 2
#property indicator_minimum -1
#property indicator_maximum 1
#property indicator_level1 0
input int Period = 5;
double Pressure[];

int OnInit()
{
    if(Period < 1) return(INIT_PARAMETERS_INCORRECT);
    SetIndexBuffer(0, Pressure);
    ArraySetAsSeries(Pressure, true);
    SetIndexStyle(0, DRAW_LINE);
    SetIndexLabel(0, "Close Location Pressure");
    SetIndexEmptyValue(0, EMPTY_VALUE);
    SetIndexDrawBegin(0, Period - 1);
    IndicatorShortName("Close Location Pressure (" + 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(high, true);
    ArraySetAsSeries(low, true);
    ArraySetAsSeries(close, true);
    if(prev_calculated == 0) ArrayInitialize(Pressure, EMPTY_VALUE);
    Pressure[0] = EMPTY_VALUE; // Never publish a forming-bar value
    if(rates_total <= Period) return(0);

    int oldest = rates_total - Period;
    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 sum = 0.0;
        for(int j = i; j < i + Period; j++)
        {
            double range = high[j] - low[j];
            // Flat bars contribute zero; keep a fixed denominator
            if(range > 0.0)
                sum += (2.0 * close[j] - high[j] - low[j]) / range;
        }
        Pressure[i] = sum / Period;
    }
    return(rates_total);
}

Buffer design and calculation boundaries

The indicator uses one data buffer in a separate window, with a zero reference level. ArraySetAsSeries explicitly establishes the indexing convention: index zero is the forming bar, index one is the most recently completed bar, and larger indices refer to older bars. For an output at index i, the inner loop includes i through i + Period − 1. All those observations are at or before the output bar; none come from a later time. The oldest calculable index is rates_total − Period, because larger starting indices would run beyond the available history.

The forming bar is assigned EMPTY_VALUE, not zero. Zero would represent a genuine balanced reading and could be mistaken for a signal. Empty values also distinguish insufficient history from valid observations. When the terminal first loads the indicator, it initializes the buffer and computes the full valid range. Subsequent calls use prev_calculated to recalculate the newest relevant closed bars. If history is refreshed and the terminal resets prev_calculated, the buffer is rebuilt. This simple bounded loop favors clarity; for very large periods, an incremental rolling sum may be more efficient.

Install and use it on MetaTrader 4

  1. Open MetaEditor from MT4 and create a new custom indicator source file named CloseLocationPressure.mq4 under MQL4/Indicators.
  2. Replace the generated source with the full code above, save, and compile in your terminal.
  3. Refresh Navigator if necessary, then attach the indicator to a chart. Keep Period at five for the initial check.
  4. Use the Data Window to inspect the most recently completed bar, then compare it with a manual calculation using the same chart history.
  5. Observe the chart during a live candle. The indicator should leave the active candle blank and update the newly completed observation when the next bar becomes available.

The code follows the MQL4 OnCalculate and indicator-buffer interfaces. It has not been compiled or executed in a live terminal for this article; local compiler and data verification remain necessary.

Choosing the period and treating flat bars

Short windows react quickly to shifts in candle geometry, but can cross zero frequently in sideways markets. Longer windows, such as 14 or 20, damp isolated extremes and may respond more slowly when conditions change. Compare several periods on the same instrument and aggregation without optimizing on a small sample. Because the calculation gives every candle equal weight, a one-point candle at its high contributes the same value as a ten-point candle at its high. That is an explicit design choice. If activity matters, a separate volatility filter or a range-weighted variant is a different model and should be evaluated independently.

A flat candle has no meaningful normalized close location. Here it contributes zero while the denominator stays fixed. Excluding flat observations instead would alter the effective sample size; either convention can be reasonable, but they must not be mixed silently. In illiquid instruments, many flat bars can pull the average toward zero. Treat that as a data-quality and activity consideration rather than evidence of balanced buying and selling.

Validation checklist and interpretation

Test closes at both extremes and at the midpoint. Check that five identical +1 observations produce +1, five −1 observations produce −1, and a flat observation never causes division by zero. Test Period = 1, insufficient history, a new bar, and a terminal history refresh. Compare the Data Window with the hand-worked example. If integrating the indicator into an EA using iCustom, read buffer zero at shift one, check for EMPTY_VALUE, and remember that a newly completed bar becomes available when the terminal recognizes the next bar. Do not use shift zero as though it contained a confirmed reading.

Positive pressure may coexist with falling prices: a series of downward gaps followed by closes near each intrabar high can generate positive values despite a declining price sequence. Conversely, an upward trend can contain repeated closes in the lower halves of candles. This is neither volume delta nor a money-flow measure, and it does not measure actual order imbalance. Combine it with clearly defined market context and test any decision rule separately, including transaction costs and out-of-sample data.

If you would like range weighting, alerts, multi-timeframe confirmation, or integration into an Expert Advisor, contact us for Custom MT4 indicator Development Services.

Risk disclosure: This tutorial is educational. Hypothetical values are not market results or evidence of profitability. Trading involves risk of loss.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.