MQL4 or MQL5: Which Target for a TradingView Script?
Short answer
Choose MQL5 unless the people who will run the script only have MetaTrader 4: it has more drawing styles, a faster and more accurate Strategy Tester, multi-symbol testing, and both netting and hedging accounts. Choose MQL4 when your broker or clients are on MetaTrader 4, since neither runs on the other.
When you move a TradingView script to MetaTrader you have to pick a language: MQL4 for MetaTrader 4 or MQL5 for MetaTrader 5. The two look alike but differ in ways that change how much of a Pine script survives. This guide is for traders and developers deciding which target to use, and for anyone maintaining both.
The short answer
Choose MQL5 unless the people who will run the script only have MetaTrader 4. MQL5 has more drawing styles (filled areas, per-bar colours, candles), a faster and more accurate Strategy Tester, multi-symbol testing, and both netting and hedging accounts. MetaQuotes develops MetaTrader 5 actively. Choose MQL4 when your broker or your clients are on MetaTrader 4, which many retail forex brokers still offer. An MQL4 program does not run on MetaTrader 5 and vice versa; each has to be compiled from its own source in its own MetaEditor.
Indicators: same skeleton, different defaults
Modern MQL4 (build 600 and later, with #property strict) uses the same OnInit()/OnCalculate() structure as MQL5, so a converted indicator looks similar in both. The differences that matter for a Pine conversion:
- Array direction. MQL4's price arrays and indicator buffers are series-indexed by default (index 0 is the newest bar). MQL5's are oldest-first. Pine's
close[length]isclose[i + length]in MQL4 andclose[i - length]in MQL5. - Buffer and style setup. MQL4 binds with
SetIndexBuffer(i, buf)and styles withSetIndexStyle(); MQL5 adds a buffer type (INDICATOR_DATA,INDICATOR_COLOR_INDEX,INDICATOR_CALCULATIONS) and usesindicator_typeNorPlotIndexSetInteger(). - Drawing styles. MQL4 has
DRAW_LINE,DRAW_SECTION,DRAW_HISTOGRAM,DRAW_ARROW,DRAW_ZIGZAGandDRAW_NONE. MQL5 addsDRAW_FILLING(Pine'sfill()), theDRAW_COLOR_*family (a plot whose colour changes per bar),DRAW_CANDLES/DRAW_BARS(Pine'splotcandle()/plotbar()) and more.
The same Pine momentum indicator in both dialects shows the indexing difference:
//@version=6
indicator("Momentum")
length = input.int(10, "Length", minval = 1)
plot(close - close[length], "Momentum", color.blue)#property strict
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 clrDodgerBlue
input int InpLength = 10; // Length
double MomBuf[];
int OnInit()
{
SetIndexBuffer(0, MomBuf);
SetIndexStyle(0, DRAW_LINE);
SetIndexLabel(0, "Momentum");
SetIndexEmptyValue(0, EMPTY_VALUE);
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[])
{
// MQL4: series-indexed by default, index 0 is the NEWEST bar.
int limit = rates_total - prev_calculated;
if(prev_calculated > 0)
limit++; // recompute the live bar
for(int i = limit - 1; i >= 0; i--)
{
if(i + InpLength >= rates_total)
{
MomBuf[i] = EMPTY_VALUE;
continue;
}
MomBuf[i] = close[i] - close[i + InpLength]; // Pine: close - close[length]
}
return rates_total;
}#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_label1 "Momentum"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDodgerBlue
input int InpLength = 10; // Length
double MomBuf[];
int OnInit()
{
SetIndexBuffer(0, MomBuf, INDICATOR_DATA);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
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[])
{
// MQL5: not series-indexed by default, index 0 is the OLDEST bar.
int start = (prev_calculated > 0) ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++)
MomBuf[i] = (i >= InpLength) ? close[i] - close[i - InpLength] : EMPTY_VALUE;
return rates_total;
}Built-in indicators: values vs handles
In MQL4, iMA(NULL, 0, 14, 0, MODE_SMA, PRICE_CLOSE, shift) returns the value for a bar directly. In MQL5, iMA() takes no shift and returns a handle that you create once and read with CopyBuffer(). Pine code that calls ta.rsi() in one line therefore becomes one line in MQL4 and three or four in MQL5. This is a convenience difference, not a capability difference.
Strategies: two order models
A Pine strategy becomes an Expert Advisor, and here the dialects diverge most. MQL4 has one pool of orders identified by tickets: OrderSend() opens, OrderClose() closes, and every open trade is a separate order, so several trades on one symbol are normal. MQL5 separates orders, deals and positions. On a netting account there is one position per symbol and a sell reduces a buy, which is how a Pine strategy with the default pyramiding = 0 behaves; on a hedging account opposite positions can coexist. Most MQL5 code trades through the standard CTrade class, which also handles the broker's filling mode. A minimal "buy when RSI is below 30" EA in each:
#property strict
input double InpLots = 0.10;
input int InpMagic = 1001;
void OnTick()
{
if(OrdersTotal() > 0) return;
double r = iRSI(NULL, 0, 14, PRICE_CLOSE, 1); // value of bar 1, directly
if(r < 30)
{
int ticket = OrderSend(Symbol(), OP_BUY, InpLots, Ask, 3, 0, 0, "long", InpMagic, 0, clrGreen);
if(ticket < 0) Print("OrderSend failed: ", GetLastError());
}
}#include <Trade\Trade.mqh>
input double InpLots = 0.10;
input long InpMagic = 1001;
CTrade trade;
int rsiHandle = INVALID_HANDLE;
int OnInit()
{
rsiHandle = iRSI(_Symbol, _Period, 14, PRICE_CLOSE); // a handle, not a value
if(rsiHandle == INVALID_HANDLE) return INIT_FAILED;
trade.SetExpertMagicNumber(InpMagic);
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason) { IndicatorRelease(rsiHandle); }
void OnTick()
{
if(PositionSelect(_Symbol)) return;
double r[1];
if(CopyBuffer(rsiHandle, 0, 1, 1, r) != 1) return; // value of bar 1
if(r[0] < 30)
if(!trade.Buy(InpLots, _Symbol)) Print("Buy failed: ", trade.ResultRetcode());
}Both read bar 1, the last closed bar, which is the nearest equivalent of a Pine strategy evaluated at bar close. Both run on every tick, so a real conversion also needs a once-per-bar guard and exit logic.
Testing
MetaTrader 5's Strategy Tester runs on several CPU cores (and on remote agents), can test several symbols in one run, and can use real ticks recorded by the broker. MetaTrader 4's tester runs one symbol at a time and models ticks from bar data. If you need to compare a converted strategy's trades against TradingView's list of trades, MQL5 gives you more control over the test conditions.
What changes in Stratlate's output
Stratlate's Pine converter emits both dialects from the same engine. To keep the logic identical, it sets every price array and, in MQL4, every indicator buffer to oldest-first order with ArraySetAsSeries(..., false), and it adds #property strict to MQL4 files. Where MQL4 lacks a feature, the report says so: fill() bands are dropped in MQL4 (the lines they sit between are still drawn), a plotcandle() is drawn as pairs of histogram bars instead of DRAW_CANDLES, and columns or histograms in the main chart window are drawn as lines. A Pine strategy becomes an EA that trades through CTrade in MQL5 and through OrderSend() in MQL4. Either way, compile the output and backtest it before trading.
Pitfalls
- Porting MQL4 indexing to MQL5 unchanged. Symptom: the indicator is drawn back to front, or
array out of rangeappears on the first bar. - Using the MQL4
iMAsignature in MQL5. Symptom: compile errorwrong parameters count. - Assuming hedging behaviour on a netting account. Symptom: a "new" sell closes the open buy instead of opening a second position.
- Omitting
#property strictin MQL4. Symptom: the file compiles under legacy rules, where mistakes such as a function with a missingreturnpath are only warnings instead of errors. - Expecting
fill()or per-bar colours in MQL4. MQL4 has no filled-area or colour-index plots; plan for separate lines or arrows instead.
FAQ
Can MetaTrader 5 run MQL4 indicators or EAs?
No. MetaTrader 5 runs only programs compiled from MQL5 source, and MetaTrader 4 runs only MQL4. The languages are close enough that porting is usually straightforward, but each target needs its own source file.
Is MQL5 harder to write than MQL4?
It is more verbose for indicators, because built-ins return handles instead of values and trading uses orders, deals and positions. In exchange you get more drawing styles, a better tester and support for both netting and hedging accounts.
Which target should I pick for a TradingView strategy?
MQL5 if your broker offers MetaTrader 5, because its netting accounts and tester match a Pine strategy's single-position model more closely. Pick MQL4 only when the strategy must run on MetaTrader 4.
Convert to MQL4 or MQL5
Paste your Pine Script and choose the MetaTrader target. The report lists anything that dialect cannot reproduce.
Open the converter