How to Convert an MQL4 or MQL5 Indicator to Pine Script
Short answer
Mostly by deleting code: the bar loop, buffer bookkeeping and handle management disappear, because Pine runs the script once per bar. The loop body becomes the Pine script, i becomes the current bar, and every array read becomes a series reference.
Converting from MetaTrader to TradingView is mostly a matter of deleting code: the bar loop, the buffer bookkeeping and the handle management all disappear, because Pine does them for you. What remains is getting the indexing and the built-in indicators exactly right. This guide is for MQL4 or MQL5 developers who need their indicator or Expert Advisor on TradingView. Here the MQL source comes first and the Pine result second.
The core idea: delete the loop
An MQL indicator's OnCalculate() walks over bars with an index i. Pine runs your script once per bar, so the loop body is the Pine script and i becomes "the current bar". Every array read turns into a series reference:
- MQL5 (default, oldest-first arrays):
close[i - k]becomesclose[k]. - MQL4, or MQL5 after
ArraySetAsSeries(arr, true)(newest-first):Close[i + k]becomesclose[k]. iClose(_Symbol, _Period, shift)and similar accessors are always newest-first:shiftbecomes the history offset.
Before converting a single line, find every ArraySetAsSeries call and note which arrays are series-indexed. Getting this wrong mirrors the indicator in time, and the result can still look plausible.
Step 1: Buffers become plots or plain variables
Read the #property indicator_plots count and each SetIndexBuffer() call. A buffer bound with INDICATOR_DATA that has a drawing style becomes a plot() (or plotshape() for DRAW_ARROW, or a style argument for DRAW_HISTOGRAM). A buffer bound with INDICATOR_CALCULATIONS becomes an ordinary variable: it existed only to keep history, and every Pine variable has history already. A DRAW_COLOR_* plot's colour-index buffer becomes the color argument of the plot, written as an expression.
Inputs map directly: input int InpPeriod = 20; // Period becomes input.int(20, "Period"), and an enum input becomes input.string with options.
Step 2: Handles become ta.* calls
MQL5 creates indicator handles in OnInit() and copies values in OnCalculate(); MQL4 calls iMA(NULL, 0, period, ma_shift, method, price, shift) and gets a number back. In Pine both become a single function call evaluated on every bar. The usual mapping:
iMAwithMODE_SMA,MODE_EMA,MODE_SMMA,MODE_LWMA:ta.sma,ta.ema,ta.rma,ta.wma. A non-zeroma_shiftmoves the line, which is theoffsetargument ofplot().iRSI:ta.rsi.iCCI:ta.cci.iStdDevwithMODE_SMA:ta.stdev(both use the population formula by default).iATR: notta.atr. MetaTrader's ATR is a simple average of the true range, Pine'sta.atris Wilder's smoothing. Useta.sma(ta.tr, length)to reproduce MetaTrader's values.- Applied prices:
PRICE_CLOSE/OPEN/HIGH/LOWareclose/open/high/low;PRICE_MEDIANishl2;PRICE_TYPICALishlc3;PRICE_WEIGHTEDis(high + low + 2 * close) / 4, which ishlcc4, notohlc4.
Expect small differences in the first bars after the warm-up period: each platform seeds its averages in its own way, and the values converge afterwards (exactly or to within rounding, depending on the indicator).
Step 3: A complete example
An MQL5 moving-average envelope built on an iMA handle:
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots 3
#property indicator_label1 "Mid"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrGray
#property indicator_label2 "Upper"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrGreen
#property indicator_label3 "Lower"
#property indicator_type3 DRAW_LINE
#property indicator_color3 clrRed
input int InpPeriod = 20; // Period
input double InpPercent = 1.0; // Percent
double MidBuf[], UpBuf[], DnBuf[];
int maHandle = INVALID_HANDLE;
int OnInit()
{
SetIndexBuffer(0, MidBuf, INDICATOR_DATA);
SetIndexBuffer(1, UpBuf, INDICATOR_DATA);
SetIndexBuffer(2, DnBuf, INDICATOR_DATA);
for(int p = 0; p < 3; p++)
PlotIndexSetInteger(p, PLOT_DRAW_BEGIN, InpPeriod - 1);
maHandle = iMA(_Symbol, _Period, InpPeriod, 0, MODE_SMA, PRICE_CLOSE);
if(maHandle == INVALID_HANDLE)
return INIT_FAILED;
return 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 0; // MA not ready yet; retry next tick
int toCopy = (prev_calculated > 0) ? rates_total - prev_calculated + 1 : rates_total;
if(CopyBuffer(maHandle, 0, 0, toCopy, MidBuf) <= 0)
return 0;
int start = (prev_calculated > 0) ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++)
{
UpBuf[i] = MidBuf[i] * (1.0 + InpPercent / 100.0);
DnBuf[i] = MidBuf[i] * (1.0 - InpPercent / 100.0);
}
return rates_total;
}The same indicator in Pine Script v6. The handle, BarsCalculated(), CopyBuffer(), prev_calculated and OnDeinit() have no counterpart and simply disappear:
//@version=6
indicator("MA Envelope", overlay = true)
period = input.int(20, "Period", minval = 1)
percent = input.float(1.0, "Percent")
mid = ta.sma(close, period)
plot(mid, "Mid", color.gray)
plot(mid * (1 + percent / 100), "Upper", color.green)
plot(mid * (1 - percent / 100), "Lower", color.red)Step 4: MQL4 specifics
Older MQL4 code uses start() instead of OnCalculate(), IndicatorCounted() instead of prev_calculated, and the predefined series arrays Close[], High[] and so on. All of these are newest-first, and loops usually run backwards from limit to 0. The translation rule is the same: drop the loop and turn [i + k] into [k].
// MQL4: series indexing, i counts back from the newest bar (0)
for(int i = limit - 1; i >= 0; i--)
DiffBuf[i] = Close[i] - Close[i + 1];diff = close - close[1]
plot(diff, "Diff")An iMA(NULL, 0, 14, 0, MODE_SMA, PRICE_CLOSE, 1) call with a shift of 1 becomes ta.sma(close, 14)[1]. Call the function on every bar and take the history afterwards; calling it inside an if gives it a different history in Pine.
Step 5: Expert Advisors become strategies
An EA's OnTick() that opens and closes trades maps to a Pine strategy() script. OrderSend() or CTrade::Buy() becomes strategy.entry(), closing becomes strategy.close(), and stop-loss/take-profit levels become strategy.exit() with stop and limit prices (or loss and profit in ticks). A typical "buy when RSI is below 30 and flat" EA becomes:
//@version=6
strategy("RSI dip", overlay = true)
r = ta.rsi(close, 14)
if r < 30 and strategy.position_size == 0
strategy.entry("Long", strategy.long)Three behaviours change. Pine evaluates a strategy once per bar at the close by default and fills the order at the next bar's open, while an EA reacts to every tick. Position size is in contracts, cash or percent of equity, not lots. And a TradingView strategy is a backtest and alert source, not a live trading robot: live execution goes through TradingView's broker integrations or alerts sent to a bridge.
What Pine cannot express
Some MetaTrader features have no Pine equivalent and must be redesigned or dropped: DLL imports, file reading and writing, OnTimer(), OnChartEvent() and other events, the order book, global variables of the terminal, and reading other indicators' buffers with iCustom() (in Pine, a published script's output is only reachable through input.source, or by reimplementing it). Chart objects map to line.new(), label.new() and box.new(), which are capped per script (500 of each type at most). Calls for other symbols or timeframes become request.security(), which has a per-script limit on the number of requests.
Stratlate's MQL-to-Pine direction accepts both MQL4 and MQL5, emits Pine Script v6, turns an EA whose OnTick() places orders into a strategy(), and lists anything it could not translate as a source-located warning in the report. Review that list and backtest the result before relying on it.
Pitfalls
- Ignoring
ArraySetAsSeries. Symptom: the Pine output looks like the original reflected in time, or crosses happen on the wrong bars. - Using
ta.atrforiATR. Symptom: ATR bands that are close to MetaTrader's but never identical. - Translating
EMPTY_VALUEliterally. Symptom: a plot that jumps to about 1.8e308. Usena. - Calling
ta.*inside a conditional branch. Symptom: averages that "skip" bars. Compute the value on every bar at top level, then use it in the condition. - Integer division that the MQL code relied on. Symptom: values off by a fraction. MQL5 truncates
int / int; Pine v6 does not, so wrap withint()ormath.floor()where truncation was intended. - Comparing against a different data feed. Your broker's MetaTrader prices and TradingView's feed can differ; compare on bars whose OHLC values match.
FAQ
Can TradingView run MQL4 or MQL5 code directly?
No. TradingView only runs Pine Script, so an MQL indicator or Expert Advisor has to be rewritten in Pine, either by hand or with a converter, and then checked against the original.
Can an MQL5 Expert Advisor trade live on TradingView after conversion?
It becomes a Pine strategy, which TradingView backtests and can use to send alerts. Live orders go through TradingView's supported broker integrations or through alerts forwarded to an execution bridge; the script itself does not run inside a broker terminal the way an EA does.
Why do the first values of my converted indicator differ from MetaTrader?
Moving averages and oscillators are seeded differently during warm-up, and the two platforms may load different amounts of history. Compare values after the warm-up period on bars where both platforms show the same prices.
Convert MQL4 or MQL5 to Pine Script
Paste your MetaTrader indicator or Expert Advisor and get Pine Script v6, with a report of every construct that needs your attention.
Open the converter