Intermediate Trading Tutorial | MT4 | MQL4 Custom Indicator
When Bollinger Bands move closer together, traders often describe the market as entering a squeeze. But visual inspection alone is an unreliable way to compare volatility across charts. A four-dollar separation may be substantial for a low-priced instrument and negligible for an expensive one. Bollinger Bandwidth expresses the distance between the upper and lower bands as a percentage of the middle band, making the calculation easier to interpret across different price scales. In this tutorial we build an MT4 custom indicator that plots the normalized width of completed candles and displays an adjustable reference threshold. The indicator does not send orders, forecast direction or promise that a narrow range will produce a profitable breakout.
Define the measurement before writing code
For a given completed bar, let U be the upper Bollinger Band, L the lower band, and M the middle band. The bandwidth in percent is 100 × (U − L) / M. We use the standard MetaTrader Bollinger Bands calculation with a 20-period lookback, a deviation multiplier of 2.0, close prices and zero horizontal displacement. The middle band must be positive for this definition. If it is not positive, the indicator displays no value rather than silently changing the formula. The output is measured in percentage points; a value of 4.0 means that the full band separation is four percent of the middle band, not four pips or a four percent change in price.
With the usual symmetric bands, the numerator reflects twice the deviation multiplier times the standard deviation. The normalized width therefore combines information about dispersion and price level. It is important to distinguish width from the position of price inside the bands. Price can touch the upper band while bandwidth is either large or small. A narrow reading also does not say whether the next candle will rise or fall.
Two hypothetical observations
Suppose observation A has a middle band of 100, an upper band of 102 and a lower band of 98. Its bandwidth is 100 × 4 / 100 = 4%. Observation B has the same middle band, but its upper and lower bands are 101 and 99. Its width is 2%. If the reference threshold is 3%, A is above the threshold and B is at or below it. These are illustrative band snapshots, not quotations from a live market or claims about future performance.

Normalization also helps with a change of price scale. If all three bands in observation A were multiplied by ten, their separation would rise from 4 to 40 while their midpoint would rise to 1,000. Bandwidth would remain 4%. This property does not imply that a universal 3% threshold is appropriate for every market. Different timeframes, trading sessions and volatility regimes produce different distributions.
Complete MQL4 indicator
// PatternSmart: closed-bar Bollinger Bandwidth (%)
#property strict
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 clrRoyalBlue
#property indicator_width1 2
#property indicator_level1 3.0
input int BandsPeriod = 20;
input double Deviation = 2.0;
input double SqueezePercent = 3.0;
double WidthBuffer[];
int OnInit()
{
if(BandsPeriod < 2 || Deviation <= 0.0 ||
SqueezePercent <= 0.0)
return(INIT_PARAMETERS_INCORRECT);
if(!SetIndexBuffer(0, WidthBuffer, INDICATOR_DATA))
return(INIT_FAILED);
// Set series indexing AFTER binding the buffer.
ArraySetAsSeries(WidthBuffer, true);
SetIndexStyle(0, DRAW_LINE);
SetIndexLabel(0, "Bandwidth (%)");
SetIndexEmptyValue(0, EMPTY_VALUE);
SetIndexDrawBegin(0, BandsPeriod - 1);
SetLevelValue(0, SqueezePercent);
SetLevelStyle(STYLE_DASH, 1, clrIndianRed);
IndicatorDigits(3);
IndicatorShortName("Closed BB Width (%)");
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[])
{
if(prev_calculated <= 0 || prev_calculated > rates_total)
ArrayInitialize(WidthBuffer, EMPTY_VALUE);
if(rates_total < BandsPeriod + 1)
return(0);
// The oldest bar with a complete trailing window.
int oldest = rates_total - BandsPeriod;
int start = oldest;
if(prev_calculated > 0 && prev_calculated <= rates_total)
start = (int)MathMin(oldest,
rates_total - prev_calculated + 1);
// Shift zero stays blank; evaluate completed candles only.
WidthBuffer[0] = EMPTY_VALUE;
for(int i = start; i >= 1; --i)
{
double mid = iBands(NULL, 0, BandsPeriod, Deviation,
0, PRICE_CLOSE, MODE_MAIN, i);
double upper = iBands(NULL, 0, BandsPeriod, Deviation,
0, PRICE_CLOSE, MODE_UPPER, i);
double lower = iBands(NULL, 0, BandsPeriod, Deviation,
0, PRICE_CLOSE, MODE_LOWER, i);
WidthBuffer[i] = EMPTY_VALUE;
if(!MathIsValidNumber(mid) || !MathIsValidNumber(upper) ||
!MathIsValidNumber(lower))
continue;
if(mid == EMPTY_VALUE || upper == EMPTY_VALUE ||
lower == EMPTY_VALUE || mid <= 0.0 ||
upper < mid || lower > mid)
continue;
WidthBuffer[i] = 100.0 * (upper - lower) / mid;
}
return(rates_total);
}
The three calls to iBands use the same symbol, timeframe, period, deviation, applied price and bar shift. MODE_MAIN requests the middle line, MODE_UPPER the upper line and MODE_LOWER the lower line. A zero bands-shift argument prevents horizontal displacement, while the final argument i selects the historical bar. These two shift concepts should not be confused. Changing the bands displacement instead of the bar index would change the interpretation of the plotted data.
Buffer zero stores the percentage width. The buffer is explicitly set to series indexing after SetIndexBuffer because binding can change the indexing order. In this convention index zero is the live bar and index one is the latest completed bar. The loop works backward from the oldest eligible shift to one and deliberately leaves index zero empty. This avoids displaying a live value that can expand or contract with every tick.
Calculation window and incremental updates
A 20-period band requires 20 observations. The first historical output is placed only where a complete trailing window exists. At least 21 chart bars are needed to display the newest completed value, because shift zero is excluded. On initial calculation, or when the platform resets prev_calculated after history changes, the buffer is initialized to EMPTY_VALUE. During ordinary updates, the indicator revisits recent bars rather than recalculating the entire chart on every quote. It recalculates shift one even when the total number of chart bars does not increase, which is useful when a new bar arrives and the chart has reached its configured history limit. The code uses no future prices.
Installation and practical configuration
- Open MT4, select File → Open Data Folder, and navigate to MQL4/Indicators.
- Create a file named PS_Closed_BB_Width.mq4 in MetaEditor and replace its contents with the complete code.
- Compile it, review any diagnostics, refresh the Navigator if needed, and attach the indicator to a chart.
- Attach the built-in Bollinger Bands with matching period, deviation, zero shift and close-price settings.
- Use the Data Window to compare a completed bar's three band values with the custom percentage output.
The red reference level is a visual threshold, not an automatic alert or a signal buffer. For example, a reading of exactly 3.000% satisfies an inclusive condition of width less than or equal to three percent if you implement that comparison elsewhere. Rounding the Data Window to three decimal places can conceal tiny differences around the boundary, so use unrounded buffer values for programmatic conditions.
Parameter tradeoffs
| Input | Default | Interpretation |
|---|---|---|
| BandsPeriod | 20 | Longer windows smooth the volatility estimate; shorter windows respond faster but may fluctuate more. |
| Deviation | 2.0 | A larger multiplier widens the bands, changing the percentage scale even on identical data. |
| SqueezePercent | 3.0 | Changes only the visual reference level; it does not alter the underlying bandwidth values. |
Calibrate the threshold using representative historical data, then evaluate it on a separate period. A threshold selected solely because it identifies a few attractive historical examples may be overfit. A rolling percentile of historical bandwidth is a possible extension, but it is not part of this indicator and would require an explicit reference-window definition.
Edge cases and verification
The script rejects invalid numeric values, missing indicator values, nonpositive middle bands and inconsistent band ordering. A legitimate flat window with identical positive upper, middle and lower values has a bandwidth of zero. Near-zero positive midlines can produce very large percentages, so this formula is unsuitable without further safeguards for some synthetic spreads or instruments around zero. Missing or revised price history can also affect past results. Closed-bar calculations prevent ordinary intrabar fluctuation, not all historical data revisions.
- Verify observations A and B manually: 4% and 2% respectively.
- Check that the newest live candle has an empty buffer value.
- Verify the first completed output has sufficient lookback data.
- Change only the threshold and confirm that the width readings remain unchanged.
- Compare matching historical shifts after changing timeframe or refreshing history.
- Use a positive constant-price test series to check that a zero-width observation is retained.
The implementation uses the MQL4 Reference definitions of iBands, SetIndexBuffer, series indexing and OnCalculate. It has not been compiled or tested in a live MT4 installation for this article. Always validate the indicator with your terminal's build and data before integrating it into an EA. Bandwidth identifies relative dispersion, not trade direction, fill quality or expected returns. Trading involves risk of loss; this example is educational and not investment advice.
If you are interested in this free indicator and want percentile-based thresholds, closed-bar alerts or EA integration, please contact us through our Custom Trading Software Development Services.