ta.rsi in MQL5: iRSI vs an RSI that matches TradingView
Short answer
For a price source use iRSI: it has the same Wilder smoothing and seed, so the two agree once the first length bars are behind you. Write the RSI yourself only when the Pine source is not a price, such as an EMA or another indicator.
ta.rsi(source, length) is the Relative Strength Index: Wilder's smoothed average of the up moves of source divided by the smoothed average of its down moves, scaled to 0..100. MetaTrader 5 computes the same thing in iRSI, with the same smoothing and the same seed, so for a price source the two agree bar for bar once the first length bars are behind you. The only time you need to write the RSI yourself is when the Pine source is not a price: an EMA, a spread, another indicator.
What ta.rsi computes
On every bar Pine takes the one-bar change of the source, splits it into a gain (change > 0 ? change : 0) and a loss (change < 0 ? -change : 0), and smooths both with ta.rma(x, length). RSI is 100 - 100 / (1 + avgGain / avgLoss); when the average loss is zero the result is 100. ta.rma is Wilder's smoothing, alpha = 1 / length, and its first value is the plain mean of the first length inputs. Because the first change exists only on bar 1, the first RSI value appears on bar index length; before that ta.rsi is na. The RSI reads the source on the current bar, so on the realtime bar it moves with every tick and settles when the bar closes.
The MQL5 equivalent
Pine first. The input is deliberately a plain input.int so the MQL5 version has the same single parameter.
//@version=6
indicator("RSI ref", overlay=false)
len = input.int(14, "Length", minval=1)
r = ta.rsi(close, len)
plot(r, "RSI")
hline(70)
hline(30)The MQL5 indicator below computes the same values without a handle. It uses the short form of OnCalculate, which gives the indicator an "Apply to" drop-down in MetaTrader: that drop-down is the counterpart of Pine's source argument, as long as the source is a price. The buffers are indexed oldest-first, so price[i - 1] is the previous bar, the same direction as Pine's source[1] once you remember that MQL5 arrays start at the left edge of the chart.
//+------------------------------------------------------------------+
//| RSI that matches ta.rsi(source, length) bar for bar |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_plots 1
#property indicator_label1 "RSI"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDodgerBlue
#property indicator_minimum 0
#property indicator_maximum 100
#property indicator_level1 30
#property indicator_level2 70
input int InpLength = 14; // Length
double RsiBuf[], GainBuf[], LossBuf[];
int OnInit()
{
SetIndexBuffer(0, RsiBuf, INDICATOR_DATA);
SetIndexBuffer(1, GainBuf, INDICATOR_CALCULATIONS);
SetIndexBuffer(2, LossBuf, INDICATOR_CALCULATIONS);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpLength);
IndicatorSetString(INDICATOR_SHORTNAME, "RSI(" + (string)InpLength + ")");
return INIT_SUCCEEDED;
}
// The short OnCalculate form: price[] is the "Apply to" source, the
// counterpart of Pine's `source` argument. Arrays are oldest-first.
int OnCalculate(const int rates_total, const int prev_calculated,
const int begin, const double &price[])
{
const int len = InpLength;
if(rates_total <= len) return 0;
int start = prev_calculated > 1 ? prev_calculated - 1 : 1;
if(start == 1) { RsiBuf[0] = EMPTY_VALUE; GainBuf[0] = 0.0; LossBuf[0] = 0.0; }
for(int i = start; i < rates_total; i++)
{
const double d = price[i] - price[i - 1];
const double gain = d > 0.0 ? d : 0.0;
const double loss = d < 0.0 ? -d : 0.0;
if(i < len) // ta.rsi is na until `len` changes exist
{
GainBuf[i] = 0.0; LossBuf[i] = 0.0; RsiBuf[i] = EMPTY_VALUE;
continue;
}
if(i == len) // seed: plain mean of the first len changes
{
double sg = 0.0, sl = 0.0;
for(int k = 1; k <= len; k++)
{
const double dk = price[k] - price[k - 1];
sg += dk > 0.0 ? dk : 0.0;
sl += dk < 0.0 ? -dk : 0.0;
}
GainBuf[i] = sg / len;
LossBuf[i] = sl / len;
}
else // Wilder: alpha = 1 / len, same as ta.rma
{
GainBuf[i] = (GainBuf[i - 1] * (len - 1) + gain) / len;
LossBuf[i] = (LossBuf[i - 1] * (len - 1) + loss) / len;
}
RsiBuf[i] = LossBuf[i] == 0.0 ? 100.0
: 100.0 - 100.0 / (1.0 + GainBuf[i] / LossBuf[i]);
}
return rates_total;
}If the source is a price, you can skip all of that and read the built-in indicator. iRSI seeds its averages with a simple mean of the first length changes and then applies Wilder's recursion, so it reproduces ta.rsi on every bar from index length on.
// When the Pine source is a plain price (close, open, hl2, hlc3, ...),
// the built-in iRSI gives the same numbers after the warm-up bars.
int rsiHandle = iRSI(_Symbol, _Period, 14, PRICE_CLOSE); // in OnInit
// in OnCalculate: fetch the whole history once, then only the newest bar
int toCopy = prev_calculated == 0 ? rates_total : rates_total - prev_calculated + 1;
if(CopyBuffer(rsiHandle, 0, 0, toCopy, RsiBuf) != toCopy) return 0;For a computed source (ta.rsi(ta.ema(close, 9), 14), ta.rsi(close - open, 14), an RSI of an RSI) there is no applied-price constant to pass, so use the hand-written version and feed it your own buffer.
Where the two differ
| Aspect | Pine ta.rsi | MQL5 iRSI |
|---|---|---|
| Smoothing | ta.rma, alpha = 1 / length | Wilder: (prev * (len - 1) + x) / len, the same recursion |
| Seed | Mean of the first length changes | Mean of the first length changes |
| First value | Bar index length; na before | Bar index length; 0 written before, hidden by PLOT_DRAW_BEGIN |
| Source | Any series | One of the ENUM_APPLIED_PRICE constants |
| No movement at all | 100 when the average loss is 0 | 100 when only the loss is 0, 50 when both are 0 |
| Missing values | na propagates; an na source restarts the warm-up | No na; the buffer always holds a number |
| Access | Direct value | Handle in OnInit, CopyBuffer in OnCalculate |
The "both are zero" row matters only on synthetic data where length consecutive closes are identical. The warm-up rows matter more than they look: because the recursion keeps a fraction of its seed forever, two RSIs started on different first bars disagree slightly for a long time. With alpha = 1 / 14 the seed still carries about 0.7% of the weight after 70 bars. Compare values well inside the chart, not at its left edge, and give the MT5 chart at least as much history as TradingView has.
What the Stratlate converter emits
The converter does not route ta.rsi through iRSI. It emits a call to its runtime helper pine_rsi(src, gainState, lossState, bar, length), which allocates two state arrays per call site, seeds Wilder's averages with the mean of the first length changes, restarts the warm-up if the source turns na, and returns 100 when the average loss is zero. That works for any source expression, not only prices, and it is reported as an exact mapping. The one place iRSI does appear is inside request.security(...): an RSI of a price on another timeframe becomes an iRSI handle with the matching PRICE_* constant, and the report flags the higher-timeframe read itself as an approximation because session boundaries differ between the two platforms. Compile the output and backtest it; the differential verifier on the quality page compares it with the original on the same bars.
Pitfalls
- Using
MODE_EMA-style smoothing (alpha = 2 / (len + 1)) for the gain and loss averages. The RSI reacts too fast, overshoots TradingView's by several points at turns, and the gap never closes. - Writing
1 / InpLengthwith an integer input. Integer division gives 0, the averages never update, and the RSI sits at its seed value. - Keeping the previous averages in a
static double. On the realtime bar the update runs on every tick and compounds; the RSI drifts within the bar and differs from TradingView by the time the bar closes. ReadGainBuf[i - 1]instead. - Passing
PRICE_CLOSEtoiRSIwhen the Pine source ishlc3or an input that the user changed. The lines look alike but cross 70 and 30 on different bars. Maphl2,hlc3,ohlc4toPRICE_MEDIAN,PRICE_TYPICAL,PRICE_WEIGHTED. - Comparing the first few dozen bars. They carry each platform's seed; the lines converge later.
- Declaring the indicator buffers as series (
ArraySetAsSeries(RsiBuf, true)) in a loop written for oldest-first indexing.price[i - 1]then points to the next bar, and the RSI is mirrored in time.
FAQ
Is iRSI identical to ta.rsi?
For a price source, yes from bar index length onward: both use Wilder smoothing seeded with the simple mean of the first changes. Before that bar Pine shows na and MT5 writes zeros that are hidden from the plot. The two can still differ by a few hundredths if the charts start on different bars, because the seed decays slowly.
How do I convert ta.rsi of a computed series, such as ta.rsi(ta.ema(close, 9), 14)?
Compute the inner series into an INDICATOR_CALCULATIONS buffer and run the hand-written RSI from this page over that buffer instead of price[]. iRSI cannot take a buffer as its source, only an applied-price constant.
Why does my converted RSI show 50 on flat bars where TradingView shows 100?
The two platforms handle the case where neither gains nor losses occurred over the whole window differently: ta.rsi returns 100 whenever the average loss is 0, while iRSI returns 50 when both averages are 0. It only occurs on data with length identical closes in a row, such as a halted symbol or a weekend gap in a filled series.
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