To convert Pine Script to MQL4, rewrite TradingView's bar-by-bar rollback script into a #property strict MetaTrader 4 indicator (OnCalculate) or Expert Advisor (OnTick), read closed values at shift = 1, and verify signals bar by bar against TradingView on the same feed. The converter above drafts that .mq4 skeleton in your browser from Pine v4, v5 or v6 source without uploading your code anywhere. What no automatic converter can skip is checking broker server time, stop-level rules and bar-close alignment inside MetaEditor 4.
If you are targeting MetaTrader 5 instead of MetaTrader 4, use our Pine Script to MQL5 converter and MT5 port guide, where indicator handles live in OnInit() and CopyBuffer() replaces direct shift calls. If you already have an .mq4 or .ex4 file and want to inspect it or move the opposite way onto TradingView, see how to open .ex4 and .mq4 files and our free MQL4 to Pine Script v6 converter.
How Pine Script's execution loop differs from MetaTrader 4
TradingView executes a Pine script once on every historical bar from oldest (bar_index == 0) to newest, then re-executes on every live price update while rolling back var state between intrabar ticks until the candle closes.
MetaTrader 4 has no automatic intrabar rollback:
- In an MQL4 Custom Indicator (
OnCalculate), MT4 hands yourates_totalandprev_calculated. Series arrays (open[],high[],low[],close[],time[]) index0as the forming candle on the right and count backwards into history (1is the last closed candle,2the candle before that). Yourfor(int shift = limit - 1; shift >= 0; shift--)loop writes directly intoPlotBuf[shift]. - In an MQL4 Expert Advisor (
OnTick), MT4 invokesOnTick()on incoming quote ticks — and skips ticks that arrive whileOnTick()is still running. Any global orstaticcounter increments on every tick unless you gate execution behindif(Time[0] == g_lastBar) return;. - Tickets vs net positions. A Pine
strategy()maintains one net position per chart, sostrategy.entry("Short", strategy.short)automatically closes an open long and flips short. MT4 tracks individual order tickets (OP_BUY,OP_SELL). CallingOrderSend(_Symbol, OP_SELL, ...)while a buy ticket is open leaves both trades open simultaneously (hedged) unless your EA explicitly closes matchingOP_BUYtickets viaOrderClose().
Pine Script v6 to MQL4 function mapping table
Unlike MQL5 — where iMA and iRSI return integer handles in OnInit() — MQL4 built-in technical functions return the double value for a requested shift directly:
| Pine Script (v5 / v6) | MQL4 (#property strict, build 600+) | Critical MT4 porting detail |
|---|---|---|
ta.ema(close, 21) | iMA(_Symbol, _Period, 21, 0, MODE_EMA, PRICE_CLOSE, shift) | Pass shift = 1 in an EA for the closed bar; shift = 0 reads the live tick |
ta.sma(hlc3, 20) | iMA(_Symbol, _Period, 20, 0, MODE_SMA, PRICE_TYPICAL, shift) | hl2 -> PRICE_MEDIAN, hlc3 -> PRICE_TYPICAL, ohlc4 -> PRICE_WEIGHTED |
ta.rma(close, 14) | iMA(_Symbol, _Period, 14, 0, MODE_SMMA, PRICE_CLOSE, shift) | MT4's MODE_SMMA matches Wilder's 1 / length smoothing factor after warmup |
ta.rsi(close, 14) | iRSI(_Symbol, _Period, 14, PRICE_CLOSE, shift) | Match warmup depth (at least 100–250 historical bars) so initial EMA/SMMA seeds converge |
ta.atr(14) | iATR(_Symbol, _Period, 14, shift) | Pine ta.atr(14) uses Wilder's RMA; MetaQuotes' classic ATR averages True Range over 14 bars — check values on 5 closed bars |
[m, s, h] = ta.macd(close, 12, 26, 9) | iMACD(_Symbol, _Period, 12, 26, 9, PRICE_CLOSE, MODE_MAIN, shift) and MODE_SIGNAL | Note MT4's classic iMACD smooths the signal line with SMA, whereas Pine ta.macd defaults to EMA |
[mid, up, dn] = ta.bb(close, 20, 2.0) | iBands(_Symbol, _Period, 20, 2.0, 0, PRICE_CLOSE, MODE_UPPER, shift) | Argument order differs from MQL5: deviation (2.0) comes before bands_shift (0) in MQL4 |
ta.crossover(fast, slow) | (fast_s2 <= slow_s2 && fast_s1 > slow_s1) | Evaluate shift = 2 vs shift = 1 after Time[0] advances to match barstate.isconfirmed |
request.security(syminfo.tickerid, "1D", ta.atr(14)[1], lookahead = barmerge.lookahead_on) | iATR(_Symbol, PERIOD_D1, 14, 1) | shift = 1 on PERIOD_D1 is yesterday's completed broker-server daily bar |
plot(series, "Line") | #property indicator_buffers + SetIndexBuffer(0, Buf0) | Build 600+ supports up to 512 buffers (up from legacy 8), in indicators only |
strategy.entry("L", strategy.long) | Close opposite OP_SELL tickets, then OrderSend(_Symbol, OP_BUY, lots, Ask, slip, sl, tp, ...) | Always filter OrdersTotal() by both OrderSymbol() == _Symbol and OrderMagicNumber() == InpMagic |
Full side-by-side platform differences between MT4 and MT5 — including threading in the Strategy Tester, order types and execution speed — are broken down in MT4 vs MT5.
Worked example: Pine v6 EMA + ATR strategy ported to .mq4
Suppose your TradingView strategy enters on a confirmed 21 / 55 EMA crossover with a 2.0 × ATR(14) protective stop:
//@version=6
strategy("EMA 21/55 ATR Stop", overlay = true)
fastLen = input.int(21, "Fast EMA")
slowLen = input.int(55, "Slow EMA")
atrLen = input.int(14, "ATR Length")
atrMult = input.float(2.0, "Stop Multiplier")
fastEma = ta.ema(close, fastLen)
slowEma = ta.ema(close, slowLen)
atrVal = ta.atr(atrLen)
if ta.crossover(fastEma, slowEma) and barstate.isconfirmed
strategy.entry("Long", strategy.long)
strategy.exit("LX", "Long", stop = close - atrMult * atrVal)
if ta.crossunder(fastEma, slowEma) and barstate.isconfirmed
strategy.entry("Short", strategy.short)
strategy.exit("SX", "Short", stop = close + atrMult * atrVal)
Ported cleanly to MQL4 (#property strict), we gate OnTick() on Time[0], read shift = 1 and shift = 2, enforce the broker's minimum stop distance (MODE_STOPLEVEL) so OrderSend() does not fail with error 130 (ERR_INVALID_STOPS), and close opposite tickets on the same symbol and magic number before reversing:
//+------------------------------------------------------------------+
//| EMA21_55_AtrStop.mq4 — Illustrative MQL4 sketch (compile & test) |
//+------------------------------------------------------------------+
#property strict
input double InpLots = 0.10;
input int InpSlippagePoints = 10;
input int InpMagic = 215514;
input int InpFastLen = 21;
input int InpSlowLen = 55;
input int InpAtrLen = 14;
input double InpAtrMult = 2.0;
datetime g_lastBar = 0;
int CountMagicOrders(const int orderType)
{
int total = 0;
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
if(OrderSymbol() == _Symbol && OrderMagicNumber() == InpMagic && OrderType() == orderType)
total++;
}
return total;
}
void CloseMagicOrders(const int orderType)
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
if(OrderSymbol() != _Symbol || OrderMagicNumber() != InpMagic || OrderType() != orderType) continue;
RefreshRates();
double px = (orderType == OP_BUY) ? Bid : Ask;
if(!OrderClose(OrderTicket(), OrderLots(), px, InpSlippagePoints, clrNONE))
Print("OrderClose error=", GetLastError());
}
}
double ClampStopLoss(const int orderType, const double rawStop)
{
if(rawStop <= 0.0) return 0.0;
double minDist = MarketInfo(_Symbol, MODE_STOPLEVEL) * _Point;
double safeStop = rawStop;
if(orderType == OP_BUY && Bid - safeStop < minDist)
safeStop = Bid - minDist - _Point;
if(orderType == OP_SELL && safeStop - Ask < minDist)
safeStop = Ask + minDist + _Point;
return NormalizeDouble(safeStop, _Digits);
}
void OnTick()
{
if(Time[0] == g_lastBar) return; // Act once when a new bar opens
g_lastBar = Time[0];
double fast1 = iMA(_Symbol, _Period, InpFastLen, 0, MODE_EMA, PRICE_CLOSE, 1);
double fast2 = iMA(_Symbol, _Period, InpFastLen, 0, MODE_EMA, PRICE_CLOSE, 2);
double slow1 = iMA(_Symbol, _Period, InpSlowLen, 0, MODE_EMA, PRICE_CLOSE, 1);
double slow2 = iMA(_Symbol, _Period, InpSlowLen, 0, MODE_EMA, PRICE_CLOSE, 2);
double atr1 = iATR(_Symbol, _Period, InpAtrLen, 1);
double c1 = iClose(_Symbol, _Period, 1);
bool crossUp = (fast2 <= slow2 && fast1 > slow1);
bool crossDn = (fast2 >= slow2 && fast1 < slow1);
if(crossUp)
{
CloseMagicOrders(OP_SELL);
if(CountMagicOrders(OP_BUY) == 0)
{
double sl = ClampStopLoss(OP_BUY, c1 - InpAtrMult * atr1);
int tk = OrderSend(_Symbol, OP_BUY, InpLots, Ask, InpSlippagePoints, sl, 0.0, "EMA_Long", InpMagic, 0, clrDodgerBlue);
if(tk < 0) Print("OrderSend OP_BUY error=", GetLastError());
}
}
else if(crossDn)
{
CloseMagicOrders(OP_BUY);
if(CountMagicOrders(OP_SELL) == 0)
{
double sl = ClampStopLoss(OP_SELL, c1 + InpAtrMult * atr1);
int tk = OrderSend(_Symbol, OP_SELL, InpLots, Bid, InpSlippagePoints, sl, 0.0, "EMA_Short", InpMagic, 0, clrCrimson);
if(tk < 0) Print("OrderSend OP_SELL error=", GetLastError());
}
}
}
Five MT4 porting traps to check before running a demo test
- Error 130 (
ERR_INVALID_STOPS) and 5-digit fractional pips. On a 5-digit EURUSD feed (_Digits == 5),1pip equals10 * _Point, not1 * _Point. Always normalize stop and target prices withNormalizeDouble(price, _Digits)and verifyMarketInfo(_Symbol, MODE_STOPLEVEL). Size lot volume against stop distance first in our forex position size calculator. iMACDsignal-line smoothing mismatch. TradingView'sta.macd(close, 12, 26, 9)smooths the9-bar signal line with an EMA, whereas MetaTrader 4's built-iniMACD(..., MODE_SIGNAL, shift)historically smooths the signal line with a simple moving average (SMA). If your Pine strategy triggers on tight MACD histogram zero-crosses, compute the EMA of the main buffer explicitly withiMAOnArray().- Session clocks and DST gap weeks. Just like MT5, MT4 bar timestamps (
Time[1]) are stamped in your broker's server time zone with no IANA"America/New_York"database. Check your broker's winter and summer UTC offset against our forex market hours clock, and test late March and late October when US and European daylight saving switches sit a week or more apart. - Unmigrated Pine v4 / v5 quirks. If your TradingView script still uses legacy
when =parameters orsecurity()without explicit lookahead rules, upgrade it with our Pine Script v5 to v6 converter and audit repainting patterns in how to tell if an indicator repaints before porting a flawed rule into C-style code. - Countdown loops in custom indicators. When writing an MT4 indicator (
OnCalculate), computeint limit = rates_total - prev_calculated;(adding1whenprev_calculated > 0so the live bar updates) and count downfor(int shift = limit - 1; shift >= 0; shift--). Counting upwards from0breaks any recursive buffer that readsPlotBuf[shift + 1].
.mq4 skeleton in the browser, compile under #property strict in MetaEditor 4, and compare five closed-bar entries timestamp for timestamp against TradingView before trusting any backtest.Frequently asked questions
Can you convert Pine Script to MQL4 automatically?
A browser converter can generate the #property strict .mq4 skeleton, map input variables, rewrite ta.ema or ta.rsi into shift-based iMA and iRSI calls, and wire the Time[0] new-bar gate, but you still have to compile in MetaEditor 4 and verify signals bar by bar. Most bugs between TradingView and MT4 come from tick-vs-bar state, broker server clocks and hedging tickets rather than C-style syntax.
How does MQL4 differ from MQL5 when porting a Pine Script?
MQL4 reads built-in indicators directly per bar with a shift argument such as iMA(_Symbol, _Period, 21, 0, MODE_EMA, PRICE_CLOSE, 1) and manages trades one ticket at a time via OrdersTotal(), OrderSelect() and OrderSend(). MQL5 creates indicator handles once in OnInit(), copies arrays via CopyBuffer() and sends trades asynchronously or through CTrade.
What is the MQL4 equivalent of barstate.isconfirmed in Pine Script?
Track Time[0] in a static or global datetime variable inside OnTick(); when Time[0] changes, a new bar has just opened, so shift 1 is the bar that just closed and shift 2 is the bar before it. Reading shift 0 evaluates the unfinished live candle and causes intrabar signals to fire before the close.
Why does strategy.entry reverse positions in Pine Script but open two trades in MT4?
A Pine strategy holds a single net position per symbol, so calling strategy.entry for a short automatically flattens an open long and reverses. MetaTrader 4 uses ticket-based accounting where OP_BUY and OP_SELL tickets coexist by default; your EA must loop down from OrdersTotal() - 1, match OrderSymbol() and OrderMagicNumber(), and call OrderClose() on opposite tickets before calling OrderSend().
Why does OrderSend fail with error 130 (ERR_INVALID_STOPS) on a ported Pine strategy?
MT4 error 130 means your stop-loss or take-profit price is either on the wrong side of Bid/Ask, unnormalized to _Digits, or closer to the market than the broker's minimum stop distance returned by MarketInfo(_Symbol, MODE_STOPLEVEL).
How many plot buffers can a custom MQL4 indicator use?
Modern MetaTrader 4 builds (build 600 and later) support up to 512 indicator buffers via #property indicator_buffers and SetIndexBuffer(), up from the legacy 8-buffer ceiling in pre-600 builds, though EAs still cannot plot buffers directly on the chart.


![Explainer diagram titled thinkScript to Pine v6, line for line: four side-by-side rows mapping thinkorswim CompoundValue recursive state, AggregationPeriod.DAY[1] higher-timeframe reads, multi-statement plot styling, and AddOrder(OrderType.BUY_AUTO) strategy orders into verified TradingView Pine Script v6.](/_next/image?url=%2Fblog%2Fthinkscript-to-pine-script.jpg&w=3840&q=75&dpl=dpl_BiEhRQzj8TcRZ2HYquKCfA5CnSZb)
