ta.bb in MQL5: iBands, the multiplier and the tuple

Short answer

Use iBands(..., length, 0, mult, price): buffer 0 is the basis, 1 the upper band and 2 the lower. For a computed source, compute an SMA and a population standard deviation over the same window.

ta.bb(source, length, mult) returns the three Bollinger lines as a tuple: the SMA of the source, and that SMA plus and minus mult standard deviations. MQL5's iBands computes the same three lines for an applied price and exposes them as buffers 0 (base line), 1 (upper) and 2 (lower). For a computed source, or to keep the indicator self-contained, the same values come from an SMA and a population standard deviation over the same window.

What ta.bb computes

basis = ta.sma(source, length)
dev   = mult * ta.stdev(source, length)   // biased = true: divide by length
upper = basis + dev
lower = basis - dev

All three are na until length bars exist. The deviation is the population form (squared deviations divided by length, not length - 1), and it is measured around the same SMA that forms the basis. mult is a float, commonly 2.0. There is no recursion anywhere, so the amount of history loaded does not change the values: the bands on a given bar depend only on that bar and the length - 1 before it. The result is a tuple, so a Pine script destructures it with [basis, upper, lower] = ta.bb(…); the order is middle, upper, lower.

The MQL5 equivalent

//@version=6
indicator("Bollinger Bands", overlay = true)
len  = input.int(20, "Length")
mult = input.float(2.0, "Multiplier", step = 0.1)
[basis, upper, lower] = ta.bb(close, len, mult)
plot(basis, "Basis", color = color.orange)
plot(upper, "Upper", color = color.blue)
plot(lower, "Lower", color = color.blue)

A complete MQL5 indicator with three plotted buffers. Each Pine tuple element becomes one indicator buffer; arrays are oldest-first:

//+------------------------------------------------------------------+
//| ta.bb(source, length, mult) -> [basis, upper, lower]             |
//| basis = SMA, dev = mult * population stdev                        |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots   3
#property indicator_type1   DRAW_LINE
#property indicator_label1  "Basis"
#property indicator_color1  clrOrange
#property indicator_type2   DRAW_LINE
#property indicator_label2  "Upper"
#property indicator_color2  clrDodgerBlue
#property indicator_type3   DRAW_LINE
#property indicator_label3  "Lower"
#property indicator_color3  clrDodgerBlue

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

double BasisBuffer[], UpperBuffer[], LowerBuffer[];

int OnInit()
{
   SetIndexBuffer(0, BasisBuffer, INDICATOR_DATA);
   SetIndexBuffer(1, UpperBuffer, INDICATOR_DATA);
   SetIndexBuffer(2, LowerBuffer, INDICATOR_DATA);
   for(int p = 0; p < 3; p++)
     {
      PlotIndexSetDouble(p, PLOT_EMPTY_VALUE, EMPTY_VALUE);
      PlotIndexSetInteger(p, 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)
        {
         BasisBuffer[i] = UpperBuffer[i] = LowerBuffer[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 dev = InpMult * MathSqrt(acc / InpLength);   // ta.stdev, biased = true
      BasisBuffer[i] = basis;
      UpperBuffer[i] = basis + dev;
      LowerBuffer[i] = basis - dev;
     }
   return rates_total;
}

With a price source, iBands fills the three buffers for you. Its arguments are period, shift, deviation multiplier and applied price, and its buffer numbers follow the Pine tuple order:

// OnInit
bbHandle = iBands(_Symbol, _Period, InpLength, 0, InpMult, PRICE_CLOSE);

// OnCalculate
int toCopy = prev_calculated == 0 ? rates_total : rates_total - prev_calculated + 1;
if(CopyBuffer(bbHandle, 0, 0, toCopy, BasisBuffer) <= 0) return 0;   // BASE_LINE
if(CopyBuffer(bbHandle, 1, 0, toCopy, UpperBuffer) <= 0) return 0;   // UPPER_BAND
if(CopyBuffer(bbHandle, 2, 0, toCopy, LowerBuffer) <= 0) return 0;   // LOWER_BAND

MetaTrader's standard Bollinger Bands also divide by the period, so iBands and ta.bb agree on every bar with a full window, given the same candles.

Where the two differ

TopicPine ScriptMQL5
Return valueTuple [basis, upper, lower]Three buffers: 0 base, 1 upper, 2 lower
Parameter ordersource, length, multiBands: symbol, timeframe, period, shift, deviation, applied price
Deviation formPopulation (divide by length)Same in iBands; your loop must divide by length too
SourceAny seriesiBands: applied prices only; the loop: any buffer
First barsna for length - 1 barsEMPTY_VALUE if you write it; read the built-in only after length bars
Multiplier typefloatdouble input; an int input silently forbids 2.5

What the Stratlate converter emits

The engine does not call iBands. It expands the tuple at the call site into __tup0_basis = pine_sma(close, __pineBar, (int)(len)) and __tup1_dev = (mult * pine_stdev(close, __pineBar, (int)(len))), then binds basis, basis + dev and basis - dev to the three names the script destructures. pine_stdev is the population form, matching ta.bb, and both helpers return na until length bars exist; length and mult default to 20 and 2.0 when omitted. The expansion is reported as exact, and the script above converts CLEAN. Compile and backtest the output and compare the bands against TradingView on recent bars.

Pitfalls

  • Swapping the buffer numbers. Reading iBands buffer 1 as the lower band inverts every touch test; a long entry fires on the upper band.
  • Sample standard deviation. Dividing by length - 1 makes the bands about 2.6 percent wider at length 20, so fewer bars touch them than on TradingView.
  • Deviation around a different average. Using an EMA basis with an SMA-centred deviation, or the reverse, produces bands that look right and never match.
  • Integer multiplier input. input int InpMult = 2 works until someone wants 2.5. Declare it double.
  • Reading the built-in's first bars in an EA. They are not na; check BarsCalculated(bbHandle) and the bar count before using values.

FAQ

Is iBands the same as ta.bb?

Yes, for an applied-price source: SMA basis, population standard deviation around it, bands at plus and minus the multiplier. The values agree bar for bar with the same candles; there is no seed or warm-up difference beyond the first length - 1 bars.

How do I get Bollinger Bands of an RSI or another computed series in MQL5?

iBands only accepts applied prices. Write the series into a calculation buffer and run the SMA and standard deviation loop over that buffer, as the indicator above does over close.

Which iBands buffer is the upper band?

Buffer 1 (UPPER_BAND). Buffer 0 is the base line and buffer 2 the lower band, which is the same order as the Pine tuple [basis, upper, lower].

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