ta.bbw in MQL5: Bollinger Band Width without a built-in

Short answer

MQL5 has no built-in Bollinger Band Width. Compute 2 * mult * stdev / sma over the window, or (upper - lower) / base from the three iBands buffers.

ta.bbw(source, length, mult) is the Bollinger Band Width: the distance between the upper and lower band divided by the middle band. It measures how wide the bands are relative to price, which is what squeeze setups watch. MQL5 has no built-in for it. You compute it from the same SMA and standard deviation that make the bands, either in a loop or from the three iBands buffers.

What ta.bbw computes

basis = ta.sma(source, length)
dev   = mult * ta.stdev(source, length)     // population form
bbw   = ((basis + dev) - (basis - dev)) / basis
      = 2 * mult * ta.stdev(source, length) / ta.sma(source, length)

The result is a ratio, not a price distance, so it is comparable across symbols and price levels. It is na until length bars exist, and na if the basis is zero, because Pine's division by zero yields na. In Pine v6 the value is a plain ratio (0.04 for bands 4 percent of price apart); it is not multiplied by 100. Some third-party scripts and MetaTrader indicators show the width in percent, so check which scale your thresholds assume before porting a squeeze condition like bbw < 0.02. There is no recursion, so history depth does not affect the values.

The MQL5 equivalent

//@version=6
indicator("Bollinger Band Width", overlay = false)
len  = input.int(20, "Length")
mult = input.float(2.0, "Multiplier", step = 0.1)
plot(ta.bbw(close, len, mult), "BBW")

A complete MQL5 indicator in a separate window. It computes the mean and population deviation over the same window and guards the division:

//+------------------------------------------------------------------+
//| ta.bbw(source, length, mult) = (upper - lower) / basis           |
//|                              = 2 * mult * stdev / sma            |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_label1  "BBW (ta.bbw)"

input int    InpLength = 20;   // length
input double InpMult   = 2.0;  // mult

double BbwBuffer[];

int OnInit()
{
   SetIndexBuffer(0, BbwBuffer, INDICATOR_DATA);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpLength - 1);
   return InpLength > 0 ? INIT_SUCCEEDED : INIT_PARAMETERS_INCORRECT;
}

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[])
{
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
     {
      if(i < InpLength - 1)
        {
         BbwBuffer[i] = EMPTY_VALUE;
         continue;
        }
      double sum = 0.0;
      for(int k = 0; k < InpLength; k++)
         sum += close[i - k];
      const double basis = sum / InpLength;
      double acc = 0.0;
      for(int k = 0; k < InpLength; k++)
        {
         const double d = close[i - k] - basis;
         acc += d * d;
        }
      const double stdev = MathSqrt(acc / InpLength);
      // Pine: division by zero is na; a basis of 0 only happens on synthetic data
      BbwBuffer[i] = basis != 0.0 ? 2.0 * InpMult * stdev / basis : EMPTY_VALUE;
     }
   return rates_total;
}

If the chart already uses iBands, the width follows from its buffers without a second loop:

// after copying iBands buffers 0 (base), 1 (upper) and 2 (lower) for bar i
BbwBuffer[i] = base[i] != 0.0 ? (upper[i] - lower[i]) / base[i] : EMPTY_VALUE;

Both forms give the same number because iBands uses the population deviation around an SMA, exactly as ta.bb and ta.bbw do.

Where the two differ

TopicPine ScriptMQL5
Native functionta.bbwNone; loop or iBands arithmetic
ScaleRatio (0.04 = 4 percent)Whatever you write; keep it a ratio to reuse Pine thresholds
Zero basisnaDivision by zero stops the indicator; guard it
Deviation formPopulationPopulation in iBands; your loop must divide by length
First barsna for length - 1 barsEMPTY_VALUE written by you
SourceAny seriesiBands: applied prices; the loop: any buffer

What the Stratlate converter emits

The engine writes ta.bbw inline as pine_div((2.0 * (mult) * pine_stdev(close, __pineBar, (int)(len))), pine_sma(close, __pineBar, (int)(len))), defaulting length to 20 and mult to 2 when omitted. pine_stdev is the population form, and pine_div returns na on a zero denominator as Pine does, so the output is a ratio on the same scale as TradingView's. The source must be a named series: ta.bbw of a computed expression is reported as unsupported, and the workaround is to assign the expression to a variable first. The script above converts CLEAN and the call is reported as exact. Compile and backtest the output.

Pitfalls

  • Percent versus ratio. Porting a threshold from a script that multiplies by 100 into code that does not (or the reverse) makes a squeeze filter always true or never true.
  • Dividing by the standard deviation instead of the basis. The result is the constant 2 * mult; a flat line is the symptom.
  • Sample deviation. A constant 2.6 percent excess at length 20, enough to shift which bars pass a tight threshold.
  • Unguarded division. Synthetic or spread symbols can have a zero or negative basis; guard it, or the indicator stops with a runtime error.
  • Different candles. The width uses the same prices as the bands, so a feed difference shows up here too.

FAQ

Does MetaTrader 5 have a Bollinger Band Width indicator?

Not among the standard indicators. Compute it from the band buffers as (upper - lower) / base, or directly as 2 * mult * stdev / sma; the two are algebraically identical.

Is ta.bbw in percent?

No. ta.bbw returns a ratio of the band distance to the basis, so 0.05 means the bands are 5 percent of price apart. Multiply by 100 only if the thresholds you port were written for a percent scale.

Can I compute ta.bbw on a computed series with the converter?

Assign the expression to a variable and pass the variable. The engine needs a named series for ta.bbw and reports a computed expression in that position as unsupported.

Convert the whole script

Paste a Pine Script indicator or strategy and get MQL5 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.

Open the converter

Related