Complete Suite: all 12 tools. 6 Premium desks inside.All 12 tools $606.98 one by one

$606.98 one by one $97 once Save $509.98Get the SuiteGet it
ProEA Lab · MT5, TradingView and trading research · Evidence standards

Pine Script to MQL4: Converting a TradingView Indicator or Strategy to MT4 (.mq4)

Paste a Pine Script v4, v5 or v6 indicator or strategy below (or drop a .pine / .zip file) to generate a MetaTrader 4 .mq4 draft locally in your browser and flag MT4 shift, server-clock and OrderSend() traps.

Pine v6 strategy with input.int/float, ta.ema(21/55), ta.atr(14), ta.crossover/crossunder, and strategy.entry.

Expert Advisor draft (.mq4)12 Pine calls mapped2 porting traps flaggedPine v6 → MQL4 (.mq4)
Draft MQL4 (.mq4) skeleton (verify in MetaEditor)

Mapped Pine → MQL4 constructs (12)

  • L2 strategy("EMA Ribbon ATR Trend", overlay=true) → Expert Advisor: #property strict + OnTick() + OrderSend()
  • L3 fastLen = input.int(21) → input int InpFastLen = 21;
  • L4 slowLen = input.int(55) → input int InpSlowLen = 55;
  • L5 atrLen = input.int(14) → input int InpAtrLen = 14;
  • L6 atrMult = input.float(2.0) → input double InpAtrMult = 2.0;
  • L8 fastEma = ta.ema(close, fastLen) → iMA(..., MODE_EMA, ..., shift)
  • L9 slowEma = ta.ema(close, slowLen) → iMA(..., MODE_EMA, ..., shift)
  • L10 atrVal = ta.atr(atrLen) → iATR(_Symbol, _Period, ..., shift)
  • L12 longCond = ta.crossover(fastEma, slowEma) → Closed-bar check: prev(shift 2) <= prev && curr(shift 1) > curr
  • L13 shortCond = ta.crossunder(fastEma, slowEma) → Closed-bar check: prev(shift 2) >= prev && curr(shift 1) < curr
  • L16 strategy.entry("Long", strategy.long) → CloseOrdersByType(OP_SELL) + RefreshRates() + OrderSend(OP_BUY, ...)
  • L18 strategy.entry("Short", strategy.short) → CloseOrdersByType(OP_BUY) + RefreshRates() + OrderSend(OP_SELL, ...)

Execution & clock traps to verify in MetaEditor (2)

  • L10 Pine Wilder RMA / ta.atr() smoothing difference — Pine's ta.atr() smooths True Range with Wilder's RMA (alpha = 1/length), whereas MetaQuotes' built-in ATR example smooths True Range with a simple moving average (SMA). Compare ATR values on 5 bars if exact stop placement matters.
  • L1 Closed-bar execution vs OnTick() + hedging reversal — Pine strategies hold one net position and decide on closed bars; this MQL4 draft gates OnTick() on Time[0], reads shift 1, and closes opposite magic-filtered orders with RefreshRates() before calling OrderSend().

100% browser-local: your source never leaves this tab. Output is an uncompiled starting skeleton — compile in MetaEditor, audit complex state in our Pine to MQL5 port planner, and compare closed-bar signals against TradingView before trading.

PL · 9 min read
Explainer cover titled Pine Script to MQL4, shift by shift: side-by-side mapping comparing TradingView Pine v6 series calls against MetaTrader 4 #property strict iMA/iATR shift 1 calls and OrderClose + OrderSend ticket management.

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:

  1. In an MQL4 Custom Indicator (OnCalculate), MT4 hands you rates_total and prev_calculated. Series arrays (open[], high[], low[], close[], time[]) index 0 as the forming candle on the right and count backwards into history (1 is the last closed candle, 2 the candle before that). Your for(int shift = limit - 1; shift >= 0; shift--) loop writes directly into PlotBuf[shift].
  2. In an MQL4 Expert Advisor (OnTick), MT4 invokes OnTick() on incoming quote ticks — and skips ticks that arrive while OnTick() is still running. Any global or static counter increments on every tick unless you gate execution behind if(Time[0] == g_lastBar) return;.
  3. Tickets vs net positions. A Pine strategy() maintains one net position per chart, so strategy.entry("Short", strategy.short) automatically closes an open long and flips short. MT4 tracks individual order tickets (OP_BUY, OP_SELL). Calling OrderSend(_Symbol, OP_SELL, ...) while a buy ticket is open leaves both trades open simultaneously (hedged) unless your EA explicitly closes matching OP_BUY tickets via OrderClose().

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_SIGNALNote 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

  1. Error 130 (ERR_INVALID_STOPS) and 5-digit fractional pips. On a 5-digit EURUSD feed (_Digits == 5), 1 pip equals 10 * _Point, not 1 * _Point. Always normalize stop and target prices with NormalizeDouble(price, _Digits) and verify MarketInfo(_Symbol, MODE_STOPLEVEL). Size lot volume against stop distance first in our forex position size calculator.
  2. iMACD signal-line smoothing mismatch. TradingView's ta.macd(close, 12, 26, 9) smooths the 9-bar signal line with an EMA, whereas MetaTrader 4's built-in iMACD(..., 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 with iMAOnArray().
  3. 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.
  4. Unmigrated Pine v4 / v5 quirks. If your TradingView script still uses legacy when = parameters or security() 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.
  5. Countdown loops in custom indicators. When writing an MT4 indicator (OnCalculate), compute int limit = rates_total - prev_calculated; (adding 1 when prev_calculated > 0 so the live bar updates) and count down for(int shift = limit - 1; shift >= 0; shift--). Counting upwards from 0 breaks any recursive buffer that reads PlotBuf[shift + 1].
Generate the .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.

Continue reading

SuperTrend Indicator Settings (10,3 vs 7,2, RMA vs SMA & Wicks), Read from Code

Every input in TradingView's top SuperTrend scripts read from the code: how 10 × 3.0 compares against 7 × 2.0, 14 × 2.0, and 22 × 3.0, what Change ATR Calculation Method (RMA vs SMA) and Take Wicks into Account actually alter, an interactive 15-minute candle drill, and a confirmed-bar Pine Script v6 build.

Nov 12 · ProEA Lab

Explainer cover titled SuperTrend settings, read from the code: two simulated 15-minute candle charts side by side comparing 10 x 3.0, RMA, Close (2 flips) against 7 x 2.0, RMA, Close (4 flips and 3 vanished mid-candle breaches).

How to Convert thinkScript to Pine Script v6 (thinkorswim Port Guide)

Port a thinkorswim study or AddOrder strategy to TradingView Pine Script v6 locally in your browser: drop a *STUDY.ts or .zip export, translate recursive def and CompoundValue state, stop AggregationPeriod repaints, and verify closed-bar fills.

Nov 12 · ProEA Lab

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.

Best RSI Divergence Indicators on TradingView (2026), 6 Scripts Code-Read

We read the code of six popular open-source RSI divergence scripts on TradingView line by line: a 20,140-boost script that computes RSI(5) minus RSI(14) with zero price comparison, why offset = -5 hides confirmation lag on historical screenshots, ChartPrime's hidden momentum wrapper, and an honest Pine Script v6 build.

Nov 11 · ProEA Lab

Scorecard cover titled Best RSI divergence indicators, code-read. Comparison table across six popular TradingView RSI divergence scripts checking true price-vs-RSI pivot comparison, closed-bar confirmation, and honest real-time marker placement.