Beginner Trading Tutorial — Build a Confirmed Candle Shadow Imbalance Indicator in MT4

A candlestick contains more information than its color. Two bullish candles with the same body length may have very different upper and lower shadows. One may have a long lower shadow and a short upper shadow; another may show exactly the opposite structure. A beginner learning to code indicators can use these familiar geometric features to build a simple oscillator without relying on a complicated smoothing algorithm. This tutorial develops a native MQL4 indicator that measures the difference between the lower and upper shadows relative to the entire candle range. It also introduces several important MetaTrader 4 programming concepts, including indicator buffers, historical indexing and closed-bar confirmation.

Identify the four candle prices

Every ordinary candlestick is defined by its open, high, low and close, commonly abbreviated OHLC. Its body extends from the smaller of open and close to the larger of open and close. The upper shadow extends from the top of that body to the high. The lower shadow extends from the low to the bottom of the body. These definitions work equally well for bullish and bearish candles. Simply subtracting the close from the high would be incorrect for a bearish candle, because its open is the top of the body.

Define the upper shadow U as High minus max(Open, Close), and the lower shadow L as min(Open, Close) minus Low. The total candle range R is High minus Low. For a valid candle with positive range, the imbalance is (L minus U) divided by R. A positive result means the lower shadow is longer, a negative result means the upper shadow is longer, and zero means the shadows are equal. Because both shadow lengths are nonnegative and their combined length cannot exceed the entire range, the result stays between −1 and +1 for valid OHLC data.

Confirmed Candle Shadow Imbalance Indicator
Three independent hypothetical bullish candles share the same low of 100, high of 110 and body length of two. Different body locations produce imbalance values of +0.40, −0.40 and zero.

Calculate three candles by hand

For candle A, use open 106, high 110, low 100 and close 108. Its body top is 108 and its body bottom is 106. The upper shadow is two points and the lower shadow is six points. The full range is ten points, so the score is (6−2)/10 = +0.40. For candle B, use open 102, high 110, low 100 and close 104. Its upper shadow is six points and lower shadow is two points, giving −0.40. For candle C, use open 104 and close 106 with the same high and low. Both shadows measure four points, so its score is zero. The examples are independent hypothetical observations rather than historical market data.

Now exchange the open and close of candle A so that it becomes bearish. The body remains between 106 and 108, so the upper and lower shadows and the score remain unchanged. This is intentional: the indicator describes candle geometry, not the direction of the body. A full-body candle with no shadows also scores zero, although its shape is very different from a small candle body centered between two long shadows. Keep this distinction in mind when interpreting the histogram.

Complete native MQL4 source

#property strict
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 clrSteelBlue
#property indicator_width1 2
#property indicator_minimum -1
#property indicator_maximum 1
#property indicator_level1 0

double ShadowScore[];

int OnInit()
{
    SetIndexBuffer(0, ShadowScore);
    ArraySetAsSeries(ShadowScore, true);
    SetIndexStyle(0, DRAW_HISTOGRAM);
    SetIndexEmptyValue(0, EMPTY_VALUE);
    SetIndexLabel(0, "Shadow imbalance");
    IndicatorShortName("Confirmed Shadow Imbalance");
    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[])
{
    // Explicitly use MT4 series indexing.
    ArraySetAsSeries(open, true);
    ArraySetAsSeries(high, true);
    ArraySetAsSeries(low, true);
    ArraySetAsSeries(close, true);

    if(prev_calculated <= 0 || prev_calculated > rates_total)
        ArrayInitialize(ShadowScore, EMPTY_VALUE);

    if(rates_total < 2) return(0);

    int start = rates_total - 1;
    if(prev_calculated > 0 && prev_calculated <= rates_total)
        start = (int)MathMin(start,
                             rates_total - prev_calculated + 1);

    // Bar zero is still forming: do not publish its score.
    ShadowScore[0] = EMPTY_VALUE;

    for(int i = start; i >= 1; --i)
    {
        double range = high[i] - low[i];
        if(range <= 0.0)
        {
            ShadowScore[i] = EMPTY_VALUE;
            continue;
        }

        // Determine both shadows regardless of candle color.
        double bodyTop = MathMax(open[i], close[i]);
        double bodyBottom = MathMin(open[i], close[i]);
        double upper = high[i] - bodyTop;
        double lower = bodyBottom - low[i];

        // Reject inconsistent OHLC data.
        if(upper < 0.0 || lower < 0.0)
            ShadowScore[i] = EMPTY_VALUE;
        else
            ShadowScore[i] = (lower - upper) / range;
    }
    return(rates_total);
}

Understand the program structure

The property declarations place the indicator in a separate window and define one output buffer with a blue histogram. The fixed vertical scale makes it easier to compare values across instruments. OnInit binds the ShadowScore array to the indicator buffer and assigns its drawing style. SetIndexEmptyValue specifies which value should be treated as missing rather than drawn. No external indicators, libraries or network connections are needed.

OnCalculate receives price arrays and two important counters. rates_total is the amount of available bar data, while prev_calculated reflects the previous calculation return value. The code explicitly sets the price arrays to series order, where index zero is the newest bar. The buffer is also placed in series order after binding it. This avoids a common beginner error in which the calculation assumes reverse indexing but the actual input array uses chronological indexing.

The first calculation initializes the output to EMPTY_VALUE and evaluates the available completed candles. Subsequent calls recalculate only a small recent section unless additional history or a reset requires more work. The code deliberately leaves index zero empty. Within each iteration it checks the range before dividing and rejects OHLC records whose calculated shadow lengths are negative. A zero-range candle has no meaningful normalized shadow measurement, so the output is missing rather than an invented neutral value. Each evaluated bar requires only a fixed number of arithmetic operations.

Installation in MetaTrader 4

Open MetaEditor from the MT4 terminal. Create a custom indicator called ConfirmedShadowImbalance, replace the generated source with the code above, and save the file under MQL4/Indicators. Compile the source and address any messages reported by your installed compiler. Return to the trading terminal, refresh Navigator if necessary, and attach the indicator to a chart. The histogram appears below the price chart. Open the Data Window to inspect numerical values for individual completed candles. This code has not been compiled or executed in MT4 here, so confirm compilation and behavior before integrating it into another program.

Closed-bar confirmation and repainting

During a live candle, the high, low and close may change with incoming quotes. If a shadow score were displayed on that candle, it could change substantially before the candle completed. This implementation avoids that ambiguity by leaving buffer index zero empty. When a new bar arrives, the former live candle moves to index one and becomes eligible for calculation. Its score is drawn on that completed candle, but it was not available as a confirmed value earlier. An EA reading the indicator with iCustom should use buffer zero at shift one for the latest confirmed observation and explicitly check for EMPTY_VALUE.

The code uses no future data and does not intentionally repaint completed results. Historical data corrections, changes to the data feed and reconstructed offline bars can still change historical OHLC values. Such changes may legitimately alter the calculated result. During a market closure, the most recent candle may remain at index zero until the next bar is recognized.

Testing and limitations

Begin by comparing the histogram with the three numerical examples. Test a bullish candle and a bearish candle with identical body boundaries, a candle with no shadows, a symmetric doji and a zero-range candle. Check that the live bar remains empty even as its geometry changes. Reload the chart and compare results under matching data settings. A score of +0.40 means the lower shadow exceeds the upper shadow by 40 percent of the complete candle range; it is not a probability of a price increase. OHLC data cannot establish the order of trades within the candle or the reason a shadow formed. The measure ignores volume, spread, market context and trading costs. A long lower shadow does not guarantee bullish follow-through. Consider independent trend and volatility measures for research, and validate any proposed trading rules out of sample.

For configurable colors, moving averages of shadow imbalance, alerts or EA integration, contact our Custom MT4 indicator Development Services.

Risk disclosure: educational material only. Trading involves risk of loss. Hypothetical examples are not evidence of profitability.

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.