ta.sma, ta.ema and ta.rma in MQL5: seeding and warm-up
Short answer
They differ in two places: the first bars, where each platform starts the average differently, and the smoothing constant, where Wilder's average gets swapped for an ordinary EMA. Write out the exact recursion behind ta.sma, ta.ema and ta.rma to match bar for bar, and use iMA only where it is a safe substitute.
A converted moving average rarely goes wrong in the middle of the chart. It goes wrong in two places: the first bars, where each platform starts the average differently, and the smoothing constant, where Wilder's average gets swapped for an ordinary EMA. This guide gives the exact recursion behind Pine's three base averages, an MQL5 version that reproduces them bar for bar, and the cases where MetaTrader's built-in iMA is a safe substitute.
The three formulas
ta.sma(src, len): the arithmetic mean of the lastlenvalues. It isnauntillenbars exist.ta.ema(src, len):alpha = 2 / (len + 1), thenema = alpha * src + (1 - alpha) * ema[1]. The equivalent function in TradingView's reference starts from the first source value.ta.rma(src, len): Wilder's smoothing,alpha = 1 / len. Its first value is the SMA of the firstlenvalues, and it isnabefore that.ta.rsiandta.atrare built on it.
Written out in Pine, the recursions look like this. my_ema and my_rma follow the reference definitions; plotting them next to the built-ins is the quickest way to see the warm-up behaviour on your own symbol.
//@version=6
indicator("Reference averages", overlay = true)
len = input.int(14, "Length", minval = 1)
my_ema(float src, int length) =>
alpha = 2.0 / (length + 1)
float sum = na
sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * sum[1]
my_rma(float src, int length) =>
alpha = 1.0 / length
seed = ta.sma(src, length) // called on every bar, see the note below
float sum = na
sum := na(sum[1]) ? seed : alpha * src + (1 - alpha) * sum[1]
plot(ta.sma(close, len), "SMA")
plot(my_ema(close, len), "EMA, same recursion as ta.ema")
plot(my_rma(close, len), "RMA, same recursion as ta.rma")The seed line sits outside the ternary on purpose. A ta.* call inside a ternary arm only runs on the bars where that arm is chosen, and it keeps its own history from those bars alone. Here it would still produce the right seed, but hoisting it avoids the compiler warning and the doubt. The conditional ta.* calls guide explains why.
The same averages in MQL5
The indicator below computes all three over close on oldest-first arrays (index 0 is the oldest bar). EMPTY_VALUE plays the role of na, and the previous value of each recursion is read from its own buffer, so recalculating the forming bar on every tick does not compound the update.
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots 3
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDodgerBlue
#property indicator_label1 "SMA"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrOrange
#property indicator_label2 "EMA"
#property indicator_type3 DRAW_LINE
#property indicator_color3 clrMagenta
#property indicator_label3 "RMA"
input int InpLength = 14; // Length
double SmaBuf[], EmaBuf[], RmaBuf[];
int OnInit()
{
if(InpLength < 1)
return INIT_PARAMETERS_INCORRECT;
SetIndexBuffer(0, SmaBuf, INDICATOR_DATA);
SetIndexBuffer(1, EmaBuf, INDICATOR_DATA);
SetIndexBuffer(2, RmaBuf, INDICATOR_DATA);
for(int p = 0; p < 3; p++)
PlotIndexSetDouble(p, PLOT_EMPTY_VALUE, EMPTY_VALUE);
return INIT_SUCCEEDED;
}
double SmaAt(const double &src[], const int i, const int len)
{
double sum = 0.0;
for(int k = 0; k < len; k++)
sum += src[i - k];
return sum / len;
}
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 int len = InpLength;
const double aEma = 2.0 / (len + 1.0);
const double aRma = 1.0 / len;
int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++)
{
// ta.sma: na until len bars exist
SmaBuf[i] = (i >= len - 1) ? SmaAt(close, i, len) : EMPTY_VALUE;
// ta.ema: starts from the first value, then recurses
EmaBuf[i] = (i == 0) ? close[0]
: aEma * close[i] + (1.0 - aEma) * EmaBuf[i - 1];
// ta.rma: na until len bars, seeded with the SMA, then Wilder smoothing
if(i < len - 1)
RmaBuf[i] = EMPTY_VALUE;
else if(i == len - 1)
RmaBuf[i] = SmaAt(close, i, len);
else
RmaBuf[i] = aRma * close[i] + (1.0 - aRma) * RmaBuf[i - 1];
}
return rates_total;
}Note 2.0 and 1.0 in the alphas. In MQL5, 2 / (len + 1) with an int length is integer division and evaluates to 0, which turns the EMA into a flat line at the first close. The code assumes close, which is never missing. If you average a computed series that can be na, decide what each average does on those bars and compare the result with TradingView.
Seeding and warm-up: why the first bars differ
An EMA or RMA value contains a fraction of its starting point forever, but that fraction shrinks by a factor of (1 - alpha) every bar:
| Average | Weight of the start after 5 × length bars | After 10 × length bars |
|---|---|---|
EMA, alpha = 2 / (len + 1) | about e-10, 0.005% | about e-20, negligible |
RMA, alpha = 1 / len | about e-5, 0.7% | about e-10, 0.005% |
Two practical rules follow. First, RMA-based indicators such as RSI and ATR need roughly twice as much history as an EMA of the same length before the start stops mattering. Second, TradingView and MetaTrader start the recursion on whatever bar their history begins, and those bars are almost never the same: TradingView's depends on your plan and the symbol, MT5's on the broker's data and the "Max bars in chart" setting. Even a perfect conversion therefore disagrees on the first bars and converges later. Compare recent bars, not the left edge of the chart.
The SMA has no memory beyond its window, so once both platforms have len bars it matches exactly. If an SMA differs in the middle of the chart, the inputs differ: different candles, a different session, or a different source price.
Using iMA instead
For averages of a price, MetaTrader's built-in moving average is an option. The modes line up with Pine like this:
| Pine | iMA mode | Notes |
|---|---|---|
ta.sma | MODE_SMA | Same definition |
ta.ema | MODE_EMA | Same recursion; early values depend on the start |
ta.rma | MODE_SMMA | Smoothed MA: (prev * (len - 1) + price) / len, which is Wilder's alpha 1 / len |
ta.wma | MODE_LWMA | Linear weights, newest bar weighted most |
The applied price maps too: hl2 is PRICE_MEDIAN, hlc3 is PRICE_TYPICAL, hlcc4 is PRICE_WEIGHTED. To average another indicator's output, pass that indicator's handle as the applied_price argument of iMA; for a series you compute yourself, write the recursion as shown above. The built-in's warm-up handling is not documented in detail, so when exact early values matter, compute the average yourself. A minimal iMA indicator for ta.rma(close, 14):
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrMagenta
#property indicator_label1 "SMMA (ta.rma)"
input int InpLength = 14; // Length
double MaBuf[];
int maHandle = INVALID_HANDLE;
int OnInit()
{
SetIndexBuffer(0, MaBuf, INDICATOR_DATA);
maHandle = iMA(_Symbol, _Period, InpLength, 0, MODE_SMMA, PRICE_CLOSE);
return maHandle == INVALID_HANDLE ? INIT_FAILED : INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
IndicatorRelease(maHandle);
}
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(maHandle) < rates_total)
return prev_calculated; // iMA not ready yet; try next tick
int toCopy = (prev_calculated > 0) ? rates_total - prev_calculated + 1 : rates_total;
// The newest toCopy values land at the end of MaBuf, aligned with close[].
if(CopyBuffer(maHandle, 0, 0, toCopy, MaBuf) <= 0)
return prev_calculated;
return rates_total;
}RSI and ATR: the averages inside other indicators
ta.rsi smooths gains and losses with ta.rma, and MetaTrader's standard RSI also uses Wilder smoothing, so after warm-up they agree. ATR is different: ta.atr smooths the true range with ta.rma, while MetaTrader's standard ATR averages it with a simple moving average. iATR is therefore not a drop-in replacement for ta.atr; compute the true range (MathMax(high[i], close[i - 1]) - MathMin(low[i], close[i - 1])) and apply the RMA recursion to it.
What Stratlate's converter does
The Pine to MQL5 converter does not map these calls to iMA. It implements them in its runtime library: ta.sma as a windowed mean that is na until the window is full, ta.ema starting from the first non-na value, and ta.rma seeded with the SMA of its first len values. Each call site gets its own state array, so two ta.ema calls never share a recursion. Compile and backtest the result, and compare values on recent bars against TradingView.
Pitfalls
- EMA alpha for an RMA. Using
MODE_EMAor2 / (len + 1)where Pine usesta.rmamakes RSI- and ATR-style lines react too fast; the gap never closes. - iATR for ta.atr. The values have the same scale but a different shape, especially after volatility spikes.
- Judging by the first bars. Differences on the first few dozen bars are usually the seed, not a bug. Look at bars after 5 to 10 times the length.
- Integer division.
2 / (len + 1)withint lenis 0 in MQL5. - Recursion from a scalar. Keeping the previous EMA in a
static doublecompounds the update on every tick of the forming bar. Read the previous bar's slot instead. - Different candles. The averages can only match if the inputs do. MT5 charts are usually built from the broker's bid prices, while TradingView's candles come from the data feed you selected, so a small constant difference often comes from the data rather than the code.
FAQ
Which MQL5 moving average matches ta.rma?
MODE_SMMA, the smoothed moving average. It uses the same recursion as Wilder's RMA, with alpha = 1 / length. Using MODE_EMA instead makes RSI- and ATR-style values react too fast.
Why does my EMA differ from TradingView on the first bars?
Each platform starts the EMA on the first bar of its own history, and every later value still carries part of that starting point. The effect shrinks every bar and is negligible after about five times the length, so compare recent bars, not the first ones.
Is iATR the same as ta.atr?
No. MetaTrader's standard ATR averages the true range with a simple moving average, while ta.atr uses Wilder smoothing (ta.rma). Compute the true range yourself and smooth it with an RMA to match TradingView.
Convert indicators with their averages intact
Stratlate converts ta.sma, ta.ema, ta.rma and the indicators built on them to MQL5 with the same recursions. Compile the output and backtest it before trading on it.