Convert a Pine Script Strategy to an MQL5 Expert Advisor
Short answer
By default Pine evaluates a strategy once per bar close and fills market orders at the next bar's open, while an EA is called on every tick and sends real orders. An EA that takes the same trades must reproduce that timing; process_orders_on_close and calc_on_every_tick change it.
A TradingView strategy and a MetaTrader 5 Expert Advisor both trade, but they run on different clocks: Pine evaluates your script once per bar and simulates fills, while an EA is called on every tick and sends real orders to a broker. This guide is for developers who need an EA that takes the same trades as their Pine strategy and want to know exactly where the two can differ.
How each platform runs a strategy
By default a Pine strategy runs once, on the close of each bar. A strategy.entry call does not fill there: TradingView's broker emulator fills the market order at the open of the next bar. Stops and limits attached with strategy.exit are then checked inside later bars using an assumed price path through open, high, low and close. Two declaration arguments change this: process_orders_on_close = true fills at the signal bar's close, and calc_on_every_tick = true recalculates on every realtime tick.
An MQL5 EA has no bar loop. OnTick() fires on every price change, and anything you send with CTrade is executed by the broker immediately, at the current bid or ask. To reproduce the default Pine model you add two things: a new-bar gate so the logic runs once per bar, and reads from shift 1, the bar that has just closed. A market order sent on the first tick of the new bar then fills at (almost) that bar's open, which is the price TradingView used.
The Pine strategy
A long-only moving-average cross with a percentage stop placed at entry:
//@version=6
strategy("SMA cross", overlay = true, default_qty_type = strategy.fixed, default_qty_value = 1)
fastLen = input.int(10, "Fast SMA")
slowLen = input.int(30, "Slow SMA")
stopPct = input.float(2.0, "Stop %")
fast = ta.sma(close, fastLen)
slow = ta.sma(close, slowLen)
if ta.crossover(fast, slow)
strategy.entry("Long", strategy.long)
strategy.exit("Stop", "Long", stop = close * (1 - stopPct / 100))
if ta.crossunder(fast, slow)
strategy.close("Long")The equivalent MQL5 Expert Advisor
#include <Trade/Trade.mqh>
input int InpFastLen = 10; // Fast SMA
input int InpSlowLen = 30; // Slow SMA
input double InpStopPct = 2.0; // Stop %
input double InpLots = 0.10; // Lots
input long InpMagic = 26110801; // Magic number
CTrade trade;
int hFast = INVALID_HANDLE;
int hSlow = INVALID_HANDLE;
int OnInit()
{
hFast = iMA(_Symbol, _Period, InpFastLen, 0, MODE_SMA, PRICE_CLOSE);
hSlow = iMA(_Symbol, _Period, InpSlowLen, 0, MODE_SMA, PRICE_CLOSE);
if(hFast == INVALID_HANDLE || hSlow == INVALID_HANDLE)
return INIT_FAILED;
trade.SetExpertMagicNumber(InpMagic);
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
IndicatorRelease(hFast);
IndicatorRelease(hSlow);
}
// true on the first tick of a new bar
bool IsNewBar()
{
static datetime last = 0;
const datetime t = iTime(_Symbol, _Period, 0);
if(t == 0 || t == last)
return false;
last = t;
return true;
}
// ticket of this EA's long position on this symbol, or 0
ulong LongTicket()
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
const ulong t = PositionGetTicket(i);
if(t == 0)
continue;
if(PositionGetString(POSITION_SYMBOL) == _Symbol
&& PositionGetInteger(POSITION_MAGIC) == InpMagic
&& PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
return t;
}
return 0;
}
void OnTick()
{
if(!IsNewBar())
return;
// bars 1 and 2 are closed; CopyBuffer returns them oldest first
double f[2], s[2];
if(CopyBuffer(hFast, 0, 1, 2, f) != 2 || CopyBuffer(hSlow, 0, 1, 2, s) != 2)
return;
const bool crossUp = f[1] > s[1] && f[0] <= s[0];
const bool crossDown = f[1] < s[1] && f[0] >= s[0];
ulong ticket = LongTicket();
if(ticket != 0 && crossDown)
{
trade.PositionClose(ticket);
ticket = 0;
}
if(ticket == 0 && crossUp)
{
const double signalClose = iClose(_Symbol, _Period, 1);
const double sl = NormalizeDouble(signalClose * (1.0 - InpStopPct / 100.0), _Digits);
trade.Buy(InpLots, _Symbol, 0.0, sl, 0.0, "Long");
}
}What maps to what:
- Indicators.
ta.smabecomes aniMAhandle created once inOnInitand read withCopyBuffer. The copy starts at shift 1 and returns values oldest first, sof[1]is the closed bar andf[0]the one before it. - Crosses.
ta.crossover(a, b)isa > bnow anda[1] <= b[1]one bar earlier;ta.crossunderis the mirror image. Write them out; MQL5 has no built-in. - Stop at entry.
strategy.exit(..., stop = close * 0.98)called together with the entry is a stop-loss computed from the signal bar's close. In MQL5 it is theslargument oftrade.Buy, computed fromiClose(_Symbol, _Period, 1)and normalised to_Digits. - strategy.close. Find this EA's position (symbol plus magic number) and call
trade.PositionClose(ticket). - Inputs.
input.intandinput.floatbecomeinputvariables, plus a lot size and a magic number that Pine never needed.
Mapping the strategy.* calls
| Pine Script v6 | MQL5 | Notes |
|---|---|---|
strategy.entry(id, strategy.long) | trade.Buy(lots, ...) | An entry against an open opposite position reverses it in Pine; see netting and hedging below. |
strategy.entry(..., limit = p) | trade.BuyLimit(lots, p, ...) | A resting order. Pine replaces it when the same id is sent again; in MQL5 you must delete or modify the old one yourself. |
strategy.exit(..., stop = s, limit = l) | trade.PositionModify(ticket, s, l) | Stop-loss and take-profit on the position. |
strategy.exit(..., loss = n, profit = m) | entry price ± ticks × SYMBOL_TRADE_TICK_SIZE | Pine counts these in ticks (syminfo.mintick), not pips. |
strategy.exit(..., trail_points = ...) | your own trailing code in OnTick | The stop moves, so it has to be recomputed and modified as price moves. |
strategy.close(id) / strategy.close_all() | trade.PositionClose(ticket) | Loop over positions filtered by symbol and magic number. |
strategy.position_size | sum of POSITION_VOLUME, signed | In lots, not Pine units; see the helper below. |
strategy.position_avg_price | POSITION_PRICE_OPEN | One averaged position on netting accounts; per position on hedging accounts. |
A helper for strategy.position_size that only counts this EA's own positions:
// strategy.position_size for this EA on this symbol: + long, - short, 0 flat
double PositionSize(const long magic)
{
double size = 0.0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(PositionGetTicket(i) == 0)
continue;
if(PositionGetString(POSITION_SYMBOL) != _Symbol
|| PositionGetInteger(POSITION_MAGIC) != magic)
continue;
const double v = PositionGetDouble(POSITION_VOLUME);
size += PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? v : -v;
}
return size;
}Netting, hedging and reversals
A Pine strategy holds one net position. If you are long 1 and call strategy.entry("Short", strategy.short), Pine closes the long and opens a short in one step. MetaTrader 5 accounts come in two modes, readable from AccountInfoInteger(ACCOUNT_MARGIN_MODE):
- Netting: one position per symbol. Selling twice the held volume reverses it, which matches Pine.
- Hedging (
ACCOUNT_MARGIN_MODE_RETAIL_HEDGING): a sell opens a second, opposite position beside the long. To match Pine, close the long first, then open the short.
pyramiding in the strategy() declaration limits how many entries can stack in one direction (default 1, meaning no stacking). Enforce the same count in the EA, or a second signal opens a second position.
What Stratlate does with a strategy
When you convert a Pine strategy, Stratlate produces an Expert Advisor that places orders, not an indicator. The EA evaluates once per bar on the bar that just closed, so a market order fills at the next bar's open, and it trades through the standard library's CTrade on both netting and hedging accounts. stop=/limit= exits become the position's stop-loss and take-profit, and loss=/profit= tick distances are turned into prices from the trade's own open price. Where the EA cannot reproduce Pine exactly, the report says so: plots are dropped because an EA has no plot buffers, an entry with both limit and stop (a one-cancels-other pair) and a trailing exit are reported as approximations, and pyramiding above 1 is noted. Position sizing has its own guide, linked below. Compile the output in MetaEditor and backtest it before trading it.
Testing it in the MT5 Strategy Tester
- Use the same symbol, timeframe and date range, and set the deposit to the strategy's
initial_capital(Pine's default is 1,000,000 in the account currency, which is rarely what you want). - For a bar-close EA, "Open prices only" is fast and fine for checking signals. When stops and targets matter, use "1 minute OHLC" or "Every tick based on real ticks", because stops are hit inside bars.
- Compare the list of trades first: entry bar, direction, exit bar. Only after those agree compare profit, which also depends on spread, commission and swap.
Pitfalls
- No new-bar gate. The EA re-evaluates on every tick, enters mid-bar and can open several trades per bar. Symptom: far more trades than TradingView.
- Reading shift 0. The forming bar has barely started; on its first tick open, high, low and close are nearly equal. Symptom: signals one bar early, or conditions like
close > openthat never fire. - Treating Pine quantity as lots. A Pine quantity of 1 on a forex symbol is one unit of currency; 1.0 lot is usually 100,000 units. Symptom: positions far larger than intended.
- Ignoring the magic number. The EA closes or counts positions opened by you or by another EA on the same symbol.
- Stops too close or on the wrong side. After a gap the computed stop can be above the current bid, or closer than
SYMBOL_TRADE_STOPS_LEVEL. Symptom: error 10016 (invalid stops) and no trade, where Pine filled. - Expecting identical profit. Pine fills at the bar's open price; MT5 buys at the ask. Every long entry costs the spread.
FAQ
Why does my converted EA enter one bar later or earlier than TradingView?
Usually the EA reads the forming bar (shift 0) instead of the bar that just closed (shift 1), or it has no new-bar gate and trades on any tick. Evaluate once per bar on shift 1 and send market orders immediately; they then fill at the new bar's open, the same bar TradingView uses.
Can an MQL5 Expert Advisor also draw the plots from my Pine strategy?
Not as indicator buffers: an EA has no plot buffers. Either draw chart objects from the EA, or convert the plotting part separately as an indicator and attach both to the chart.
Will the MT5 backtest give the same results as the TradingView Strategy Tester?
Only approximately, even for a correct conversion. Spread, commission, the price feed, the tick model and fill prices differ. Compare the trade list (entry and exit bars and directions) first, then explain the money differences by costs and data.
Convert your strategy to an Expert Advisor
Paste your Pine strategy and get an MQL5 EA that places the orders, with a report of anything it could not reproduce exactly.
Open the converter