iBands in Pine Script: ta.bb with deviation as the multiplier

Short answer

Use [basis, upper, lower] = ta.bb(source, length, mult), with MetaTrader's deviation as the multiplier. The standard deviation definition is the same, so the values match; bands_shift becomes plot's offset.

iBands creates a handle to MetaTrader's Bollinger Bands indicator with three buffers: BASE_LINE (0), UPPER_BAND (1) and LOWER_BAND (2). Pine Script returns the same three series as a tuple from ta.bb(source, length, mult), where mult is MetaTrader's deviation. The standard deviation definition is the same on both platforms, so the values match; only the display shift and the warm-up cells need attention.

What iBands computes

The signature is iBands(symbol, timeframe, bands_period, bands_shift, deviation, applied_price). Note the argument order: in MQL5 the shift comes before the deviation, the reverse of MQL4's iBands. The stock indicator (Indicators\Examples\BB.mq5) computes, for each bar i ≥ n−1, the simple average m of the last n applied prices, then the population standard deviation σ = sqrt(Σ(p − m)² / n) over the same window, and sets upper = m + d·σ, lower = m − d·σ. Bars before the window is full hold 0.0 and are hidden by PLOT_DRAW_BEGIN. bands_shift is a PLOT_SHIFT on the indicator's own plots: it moves the drawing, not the buffer values you read with CopyBuffer.

The Pine Script equivalent

ta.bb(source, length, mult) returns [basis, upper, lower] with basis = ta.sma(source, length) and upper/lower = basis ± mult · ta.stdev(source, length). ta.stdev divides by n by default (its biased parameter is true), which is exactly MetaTrader's divisor. The applied price is the source argument and the shift becomes offset on each plot().

//@version=6
indicator("iBands port", overlay = true)
len   = input.int(20, "Period", minval = 1)
shift = input.int(0, "Bands shift")
dev   = input.float(2.0, "Deviation", step = 0.1)
src   = input.source(close, "Applied price")

[basis, upper, lower] = ta.bb(src, len, dev)

plot(basis, "Base line", color.gray, offset = shift)
plot(upper, "Upper band", color.rgb(30, 144, 255), offset = shift)
plot(lower, "Lower band", color.rgb(30, 144, 255), offset = shift)

The MQL5 indicator being replaced, reading all three buffers from the handle:

#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots   3
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrGray
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrDodgerBlue
#property indicator_type3   DRAW_LINE
#property indicator_color3  clrDodgerBlue

input int                InpPeriod = 20;          // bands_period
input int                InpShift  = 0;           // bands_shift (display only)
input double             InpDev    = 2.0;         // deviation
input ENUM_APPLIED_PRICE InpPrice  = PRICE_CLOSE; // applied_price

double BaseBuffer[];
double UpperBuffer[];
double LowerBuffer[];
int    bbHandle;

int OnInit()
  {
   SetIndexBuffer(0, BaseBuffer,  INDICATOR_DATA);
   SetIndexBuffer(1, UpperBuffer, INDICATOR_DATA);
   SetIndexBuffer(2, LowerBuffer, INDICATOR_DATA);
   for(int p = 0; p < 3; p++)
      PlotIndexSetInteger(p, PLOT_SHIFT, InpShift);
   bbHandle = iBands(_Symbol, _Period, InpPeriod, 0, InpDev, InpPrice);
   if(bbHandle == INVALID_HANDLE)
      return(INIT_FAILED);
   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(BarsCalculated(bbHandle) < rates_total)
      return(0);
   int to_copy = (prev_calculated == 0) ? rates_total : rates_total - prev_calculated + 1;
   if(CopyBuffer(bbHandle, BASE_LINE,  0, to_copy, BaseBuffer)  <= 0) return(0);
   if(CopyBuffer(bbHandle, UPPER_BAND, 0, to_copy, UpperBuffer) <= 0) return(0);
   if(CopyBuffer(bbHandle, LOWER_BAND, 0, to_copy, LowerBuffer) <= 0) return(0);
   return(rates_total);
  }

Where the two differ

TopicMQL5 iBandsPine ta.bb
Standard deviationPopulation (divide by n)Population by default (biased = true)
Argument orderperiod, shift, deviation, pricesource, length, mult; shift is a plot property
OutputsThree buffers by index 0, 1, 2One tuple [basis, upper, lower]
Warm-up0.0 for the first n−1 barsna for the first n−1 bars
Deviation typedoublesimple float; input.float is fine, a series value is not
ShiftDisplay only; buffer values are unshiftedoffset in plot(), series unshifted
Middle line typeSMA onlySMA only in ta.bb; build with ta.ema and ta.stdev for other bases

What the Stratlate converter emits

The MQL5 → Pine engine dispatches iBands to three prelude helpers, f_bb_main, f_bb_upper and f_bb_lower, defined as ta.sma(src, len) and that average plus or minus mult · ta.stdev(src, len); the lowering swaps the MQL5 argument order so the deviation, not the shift, becomes the multiplier (ExprLowering, the iBands dialect note). In the handle form the band is chosen from the CopyBuffer buffer index; our probe emitted B0 := f_bb_main(close, 20, 2.0), B1 := f_bb_upper(…), B2 := f_bb_lower(…) with MQLW0501 approximation warnings for the mode resolution. bands_shift is dropped rather than turned into a plot offset, so add offset by hand if the original used it, and compile and compare the output.

Pitfalls

  • Passing biased = false to ta.stdev when hand-rolling the bands. The sample deviation divides by n−1 and widens the bands by about 2.5% at n = 20, so touches happen on different bars.
  • Confusing MQL4 and MQL5 argument order. In MQL4 iBands takes deviation then bands_shift; MQL5 takes bands_shift then deviation. A shift of 0 passed as the deviation gives three identical lines.
  • Indexing the series with the shift (upper[shift]) instead of using offset. Signals move when only the drawing should.
  • Reading buffer 3. iBands has exactly three buffers; a fourth CopyBuffer fails and the indicator stays empty.
  • Comparing the first n−1 bars: MetaTrader shows 0.0 there, which looks like the price collapsing to zero if you export the buffer.

FAQ

Do iBands and ta.bb give identical values?

Yes, for the same source, period and deviation. Both use a simple moving average and the population standard deviation of the same window, and neither has a seed effect, so the lines agree from bar n−1 onwards.

How do I port bands_shift?

Give the same value as offset to each of the three plot() calls. The band values themselves stay aligned with the bar they were computed on, as they are in MetaTrader's buffers.

What is bands_shift useful for if it does not change the values?

Only for display, for example to project the bands a few bars forward. Code that trades on the bands should read the unshifted values on both platforms.

Convert the whole program

Paste an MQL4 or MQL5 indicator or Expert Advisor and get Pine Script v6 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