ta.stdev in MQL5: iStdDev and the biased flag
Short answer
With the default biased = true, use iStdDev with MODE_SMA: both divide by length, the population form. For biased = false Pine divides by length - 1, which MetaTrader has no built-in for, so loop by hand.
ta.stdev(source, length, biased) is the standard deviation of the last length values around their simple mean. With the default biased = true it divides the squared deviations by length, the population form, and that is exactly what MetaTrader's iStdDev computes when its averaging method is MODE_SMA. With biased = false Pine divides by length - 1, the sample form, which MetaTrader has no built-in for. Both are a short loop in MQL5.
What ta.stdev computes
mean = ta.sma(source, length)
acc = sum((source[k] - mean)^2, k = 0 … length - 1)
stdev = sqrt(acc / length) // biased = true (default)
stdev = sqrt(acc / (length - 1)) // biased = falseThe result is na until length bars exist. The mean is always the SMA over the same window; there is no option to centre it on another average. The two forms differ by the constant factor sqrt(length / (length - 1)): about 2.6 percent for length 20 and 0.5 percent for length 100. That is small enough to go unnoticed on a chart and large enough to move a Bollinger band and change which bars touch it. biased must be a simple bool, so a script fixes it once. There is no recursion, so history depth does not matter.
The MQL5 equivalent
//@version=6
indicator("Standard deviation", overlay = false)
len = input.int(20, "Length")
biased = input.bool(true, "Population (biased) estimate")
plot(ta.stdev(close, len, biased), "Stdev")A complete MQL5 indicator with both forms selectable. Arrays are oldest-first; the mean and the deviations use the same length values:
//+------------------------------------------------------------------+
//| ta.stdev(source, length, biased): population (biased = true, |
//| divide by n) or sample (biased = false, divide by n - 1) |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_type1 DRAW_LINE
#property indicator_label1 "Stdev (ta.stdev)"
input int InpLength = 20; // length
input bool InpBiased = true; // biased: true = population (Pine default), false = sample
double StdevBuffer[];
int OnInit()
{
SetIndexBuffer(0, StdevBuffer, INDICATOR_DATA);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpLength - 1);
if(InpLength <= 0 || (!InpBiased && InpLength < 2))
return INIT_PARAMETERS_INCORRECT;
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[])
{
const double divisor = InpBiased ? InpLength : InpLength - 1;
int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++)
{
if(i < InpLength - 1)
{
StdevBuffer[i] = EMPTY_VALUE;
continue;
}
double sum = 0.0;
for(int k = 0; k < InpLength; k++)
sum += close[i - k];
const double mean = sum / InpLength; // the SMA over the same window
double acc = 0.0;
for(int k = 0; k < InpLength; k++)
{
const double d = close[i - k] - mean;
acc += d * d;
}
StdevBuffer[i] = MathSqrt(acc / divisor);
}
return rates_total;
}For a price source and the default biased form, the built-in does the same work:
// OnInit: period, shift 0, mean = SMA, applied price
sdHandle = iStdDev(_Symbol, _Period, InpLength, 0, MODE_SMA, PRICE_CLOSE);
// OnCalculate
int toCopy = prev_calculated == 0 ? rates_total : rates_total - prev_calculated + 1;
if(CopyBuffer(sdHandle, 0, 0, toCopy, StdevBuffer) <= 0)
return 0;iStdDev takes an averaging method because MetaTrader lets the deviation be measured around an EMA or LWMA instead of the SMA. Pine has no such option, so MODE_SMA is the only setting that corresponds to ta.stdev.
Where the two differ
| Topic | Pine Script | MQL5 |
|---|---|---|
| Divisor | length (biased, default) or length - 1 | iStdDev: length only; the loop: your choice |
| Mean | Always the SMA | iStdDev: any ma_method; use MODE_SMA to match |
| Source | Any series | iStdDev: applied prices; the loop: any buffer |
| First bars | na for length - 1 bars | EMPTY_VALUE if you write it; read the built-in only after length bars |
| Shift | Via [n] or plot offset | ma_shift argument of iStdDev |
| length = 1 with biased = false | Division by zero gives na | Runtime error; reject in OnInit |
What the Stratlate converter emits
The engine maps ta.stdev to the windowed helper pine_stdev(close, __pineBar, (int)(len)), which computes the SMA over the window and returns sqrt(acc / length), the population form, with na until length bars exist. A computed source is recorded in a per-call-site window array and read back through pine_stdev_step. The third argument is not carried into the output: ta.stdev(src, len, false) is emitted identically to the default and no note is written, so a script that uses the sample form converts to the population form and its values come out smaller by the factor sqrt((length - 1) / length). For the default biased = true the mapping is exact; the test script above converts CLEAN. Compile and backtest the output, and if the script sets biased = false, change the divisor by hand.
Pitfalls
- Sample where population was meant. A Bollinger band built on
length - 1is 2.6 percent wider at length 20 and touches price less often than TradingView's. Check the flag before comparing. iStdDevwithMODE_EMA. The deviations are measured around a different centre; the result is close but never equal tota.stdev.- Two different windows. Computing the mean over
lengthbars but the deviations over a different count (an off-by-one in the loop) gives a biased number that does not match either form. - Integer divisor.
acc / InpLengthis fine becauseaccis a double;acc / (InpLength - 1)withInpLength = 1divides by zero. - Reading the first
length - 1bars from the built-in. There is no full window yet and the values are notna; a band built from them is meaningless. Skip them.
FAQ
Is iStdDev the same as ta.stdev?
With MODE_SMA and an applied-price source, yes: both are the population standard deviation around the simple mean of the last length values. It does not match ta.stdev with biased = false, which divides by length - 1; for that form use the loop.
Which form does Bollinger Bands use?
Pine's ta.bb and TradingView's built-in Bollinger Bands use ta.stdev with the default biased = true, and MetaTrader's iBands also divides by the period. So the two platforms' standard bands agree; only a hand-written script that passes false differs.
How large is the difference between the two forms?
The ratio is sqrt(length / (length - 1)): about 1.026 at length 20, 1.005 at 100. It is a constant factor, so a line that is uniformly a few percent off along the whole chart is almost always this flag.
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