Intermediate Trading Tutorial — Range-Weighted Wick Imbalance in MT5

Candlestick shadows provide a compact description of the distance between the body and the extremes of a bar. Comparing upper and lower shadows can help characterize the geometry of recent price action, but a single candle is often noisy. This tutorial builds a native MQL5 indicator that aggregates shadow lengths across a configurable window of completed candles and normalizes the difference by the combined high-low ranges. The purpose is to describe asymmetry, not to predict a reversal.

Define the statistic

For each candle, upper wick equals high minus the larger of open and close. Lower wick equals the smaller of open and close minus low. Range equals high minus low. Sum upper minus lower across the selected window and divide by the sum of ranges, multiplying by 100. The resulting score lies between minus 100 and plus 100 for valid OHLC data. Positive values indicate more upper shadow length; negative values indicate more lower shadow length. Zero indicates equal aggregate lengths, not necessarily an absence of shadows.

Range-Weighted Wick Imbalance Indicator
Three hypothetical candles, each with high 110 and low 100. The first opens at 104 and closes at 106, the second opens at 102 and closes at 108, and the third opens at 104 and closes at 102. Individual scores are 0%, 0% and 40%.

Worked example

The first candle has upper and lower shadows of four each. The second has two each. The third has upper shadow six and lower shadow two. Their combined difference is four and combined range is thirty. The three-bar indicator is therefore 13.33%. With Period set to one, the third candle instead gives 40%. If the next candle has upper shadow one, lower shadow five and range eight, the next three-bar window has net difference zero and total range twenty-eight, producing zero. This demonstrates that the statistic can return to balance without requiring the newest candle to have equal shadows.

Consider a different pair of candles with ranges two and ten and individual scores 100% and minus 20%. The unweighted average of percentages is 40%, but the range-weighted score is zero because the signed shadow lengths are plus two and minus two. This is a deliberate choice: larger price intervals receive greater weight. It is not volume weighting and should not be described as a measure of actual buying or selling pressure.

Complete native MQL5 indicator

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_color1 clrSteelBlue
#property indicator_label1 "Wick imbalance"
#property indicator_level1 0
#property indicator_minimum -100
#property indicator_maximum 100
input int Period=3;
double Result[];

int OnInit()
{
    if(Period<1) return INIT_PARAMETERS_INCORRECT;
    if(!SetIndexBuffer(0,Result,INDICATOR_DATA))
        return INIT_FAILED;
    ArraySetAsSeries(Result,true);
    PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,EMPTY_VALUE);
    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);
    // Reset after history changes.
    bool reset=prev_calculated<=0 || prev_calculated>rates_total;
    if(reset || rates_total<=Period)
        ArrayInitialize(Result,EMPTY_VALUE);
    if(rates_total<=Period) return 0;
    Result[0]=EMPTY_VALUE;
    int oldest=rates_total-Period;
    int start=reset ? oldest :
        (int)MathMin(oldest,rates_total-prev_calculated+1);
    for(int i=start;i>=1;--i)
    {
        double numerator=0,denominator=0;
        bool valid=true;
        // Aggregate lengths before dividing.
        for(int j=i;j<i+Period;++j)
        {
            double upper=high[j]-MathMax(open[j],close[j]);
            double lower=MathMin(open[j],close[j])-low[j];
            double range=high[j]-low[j];
            if(!MathIsValidNumber(range) || !MathIsValidNumber(upper)
                || !MathIsValidNumber(lower) || upper<0 || lower<0 || range<0)
            { valid=false; break; }
            numerator+=upper-lower;
            denominator+=range;
        }
        Result[i]=(valid && denominator>0)
            ? 100.0*numerator/denominator : EMPTY_VALUE;
    }
    return rates_total;
}

Implementation and indexing

The indicator uses one data buffer and a histogram in a separate window. The fixed vertical scale allows readings to be compared visually across charts. OnInit validates the period, binds the output buffer, and configures EMPTY_VALUE for unavailable observations. The buffer is set to reverse series indexing after binding, since binding can reset its indexing direction. The input price arrays are also explicitly configured as series arrays in OnCalculate. Index zero is the forming bar and index one is the latest completed bar.

For each eligible output index i, the inner loop reads i through i plus Period minus one. These indices refer to the evaluated candle and its older neighbors. The oldest eligible index is rates_total minus Period. The code never accesses a newer candle than the evaluated one. It validates shadow lengths and range, and skips a window if any constituent observation has invalid geometry. A flat candle with zero range contributes zero to both sums. A window composed entirely of flat candles has an undefined denominator and is marked empty. A genuine zero score remains valid.

On a full recalculation, the buffer is cleared and all eligible observations are evaluated. Subsequent calls use prev_calculated to limit work to the affected recent bars. The extra recalculated bar makes the logic straightforward when the chart advances. The direct implementation has complexity proportional to the period for each evaluated observation. For unusually large windows, a rolling sum could reduce computation, but would require careful handling of history resets, invalid observations and repeated calls. This version prioritizes transparent indexing over that optimization.

Closed-bar behavior and repainting

While a candle is forming, its high, low and close can all change. The program leaves index zero empty, so the most recent confirmed reading appears at index one after a new bar is recognized. The value is drawn at the historical position of the evaluated candle, not at the instant of its confirmation. An automated consumer must not assume that the final score was known earlier in that candle. The formula does not use future prices or intentionally revise completed values. Broker corrections, history reloads and chart construction changes can legitimately change historical results.

Installation and integration

Open MetaEditor, create a custom indicator named PSRangeWeightedWickImbalance, replace the generated source with the example and save under MQL5/Indicators. Compile and inspect diagnostics in your installed version. Attach the indicator to a standard candle chart and set Period to three. Use the Data Window to inspect values rather than estimating histogram heights. An EA can use iCustom to obtain a handle and CopyBuffer to read buffer zero at shift one. Verify the returned count and reject EMPTY_VALUE; release the handle when finished. The source has not been compiled or run in MT5 here.

Testing and limitations

Test the three-candle sequence, a doji, a candle without shadows, a flat window and a window with unequal ranges. Check Period equal to one and insufficient history. Observe the first tick of a new bar and confirm that index zero stays empty. Compare a spreadsheet calculation with the Data Window and repeat after reloading identical history. A long upper wick can occur in many different intrabar paths; OHLC data cannot reveal which path occurred or how much volume traded at each price. The score ignores gaps, spread, liquidity and transaction costs. A threshold is not evidence of profitable trading. Test proposed applications on independent samples across different market regimes.

For configurable weighting, multi-timeframe filters or EA integration, contact our Custom MT5 indicator Development Services.

Risk disclosure: educational content only. Trading involves risk of loss; hypothetical examples do not establish 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.