Blog / Code & convert EAs · Pine Script · MQL5 · Backtesting
Pine Script vs MQL5: How the Execution Models Differ
Understand how Pine Script and MQL5 execute trading strategies, process ticks, simulate orders and handle backtests before conversion.
· 5 min read
A strategy can produce convincing results on TradingView but behave differently after conversion into an MT5 Expert Advisor.
The reason isn't always a coding error. Pine Script and MQL5 differ in how they execute calculations, process orders, manage positions and simulate historical prices.
If you translate the trading conditions without accounting for these differences, your MT5 EA may enter trades at different times or produce different backtest results.
Here are the main differences to understand before converting a strategy.
1. When Each Script Executes
By default, a TradingView Pine Script strategy calculates once when each bar closes.
For example:
//@version=6
strategy("Simple Moving Average Strategy", overlay=true)
fastMA = ta.sma(close, 10)
slowMA = ta.sma(close, 20)
buySignal = ta.crossover(fastMA, slowMA)
if buySignal
strategy.entry("Buy", strategy.long)The strategy checks for a moving average crossover at the bar's close.
You can change this behaviour with settings such as:
calc_on_every_tick: Recalculates on updates to the open realtime bar.calc_on_order_fills: Recalculates after simulated order fills.process_orders_on_close: Allows orders to be processed on the signal bar's closing tick.
Be careful with calc_on_every_tick. Historical bars generally don't retain the same complete tick-by-tick information available during realtime execution. This can cause results to change when a chart reloads.
In MQL5, an Expert Advisor typically processes market updates through OnTick():
void OnTick()
{
// EA logic runs when a new tick event is received.
}An EA can evaluate conditions throughout an open candle. However, you can also program it to evaluate signals only once per completed candle.
The important difference: Decide whether the original strategy evaluates signals at bar close, on incoming ticks or after simulated fills. Then reproduce that behaviour in MQL5.
2. When Market Orders Are Filled
Calculation time and order-fill time are not the same thing.
By default, a Pine Script strategy calculates at the closing tick of a bar. A market order it generates is normally filled at the next available tick, typically the following bar's open in historical testing.
Setting process_orders_on_close = true changes this behaviour by allowing orders to be processed on the closing tick.
MQL5 works differently. An EA sends a trade request to the broker's trading server.
For example:
#include <Trade/Trade.mqh>
CTrade trade;
void OpenBuy()
{
bool sent = trade.Buy(0.10, _Symbol);
PrintFormat(
"Method result: %s | Retcode: %u | %s",
sent ? "true" : "false",
trade.ResultRetcode(),
trade.ResultRetcodeDescription()
);
}A true return from trade.Buy() does not automatically mean the position was opened. You must inspect the server return code and resulting trade activity.
The practical takeaway: Match signal timing first, then compare actual entry prices and execution outcomes. Don't assume that TradingView and MT5 will fill market orders at identical prices.
3. How Historical Prices Are Simulated
The two platforms also use different approaches to historical order simulation.
TradingView
TradingView's broker emulator uses available historical price data, including bar OHLC values, to simulate order fills. When the exact intrabar price sequence is unavailable, it makes assumptions about how price moved within the candle.
Its Bar Magnifier feature can use lower-timeframe data to improve intrabar fill simulation where supported.
MetaTrader 5
The MT5 Strategy Tester provides several modelling modes:
| Testing mode | How it works |
|---|---|
| Open prices only | Tests using bar opening prices |
| 1 Minute OHLC | Uses the four OHLC prices of each minute bar |
| Every tick | Generates a more detailed tick sequence from available minute data |
| Every tick based on real ticks | Uses available historical tick data supplied by the broker |
The selected mode can significantly affect results.
For example, an EA using trailing stops or intrabar entry conditions may produce misleading results when tested with Open prices only.
For more detailed testing, use Every tick based on real ticks when suitable broker tick history is available.
Even then, historical testing cannot fully reproduce live liquidity, execution delays or queue conditions.
The practical takeaway: Compare equivalent historical periods and use sufficiently detailed price data on both platforms. Don't compare a detailed intrabar simulation against an MT5 test using Open prices only.
4. Current Candle vs Completed Candle
A strategy that reads the current candle can generate signals before that candle closes.
For example, a moving average crossover may appear during a candle and disappear before its close as prices change.
Pine Script strategies normally wait for the bar to close unless their execution settings are changed. An MQL5 EA running through OnTick() can evaluate the same condition on incoming ticks.
If the original strategy uses confirmed candle signals, the MQL5 version should read completed candles.
double previousClose = iClose(
_Symbol,
PERIOD_CURRENT,
1
);In MQL5:
- Shift
0refers to the current, still-forming candle. - Shift
1refers to the most recently completed candle.
The practical takeaway: Use the same candle-confirmation rules in both implementations. Otherwise, temporary intrabar signals can create different entries.
5. Orders, Deals and Positions
Pine Script strategies track a simulated position using variables such as strategy.position_size.
MQL5 separates trading activity into three concepts:
- Order: A request or instruction to execute a trade.
- Deal: An actual execution recorded by the trading server.
- Position: The resulting market exposure on the account.
Orders vs Positions vs Deals in MT5 explains each one with code.
MT5 also supports two account models:
- Netting: One net position per symbol. Additional trades modify the existing exposure.
- Hedging: Multiple independent positions can exist on the same symbol.
This matters when converting strategies that reverse direction, add to positions or manage multiple entries.
For example, reversing from long to short requires the EA to handle existing exposure correctly. Sending a sell request alone does not guarantee the same result as the original Pine strategy, particularly on a hedging account.
The practical takeaway: Check the account's margin mode and implement the intended closing, opening and position-management behaviour explicitly.
6. Evaluating Signals Once Per Completed Candle in MQL5
If the original strategy evaluates signals once per completed candle, you can use a new-bar check:
datetime lastBarTime = 0;
void OnTick()
{
datetime currentBarTime = iTime(
_Symbol,
PERIOD_CURRENT,
0
);
if(currentBarTime == 0 || currentBarTime == lastBarTime)
return;
lastBarTime = currentBarTime;
double currentClose = iClose(
_Symbol,
PERIOD_CURRENT,
1
);
double previousClose = iClose(
_Symbol,
PERIOD_CURRENT,
2
);
PrintFormat(
"Previous close: %.5f | Earlier close: %.5f",
currentClose,
previousClose
);
// Evaluate completed-candle conditions here.
}This detects the first received tick of a new candle and reads the two most recently completed closes. It demonstrates once-per-bar evaluation; it is not a complete trading strategy.
Before comparing backtests, also align:
- Symbol and timeframe
- Historical testing dates
- Indicator settings and calculations
- Candle confirmation rules
- Entry and exit timing
- Stop Loss and Take Profit calculations
- Position sizing and account assumptions
- Spread, commission and slippage assumptions
Differences in these inputs can produce different results even when the underlying trading conditions are identical.
Conclusion
Pine Script and MQL5 can implement the same trading strategy, but they don't execute it in exactly the same way.
Pine Script strategies generally calculate at bar close by default and use TradingView's broker emulator. MQL5 Expert Advisors respond to terminal events and send trade requests to a broker's trading server.
Before comparing results, match calculation timing, candle references, order handling and position management.
The goal of conversion is not just to translate the code. It is to reproduce the intended trading behaviour. If the backtests still differ, Why Your Pine Backtest and MT5 Backtest Don't Match shows how to find the first trade that diverges, and Converting a Pine Script Strategy to MQL5 walks through a full example.
PositionAlpha's Pine Script to MQL5 converter converts TradingView indicators (Pine Script v4, v5 and v6) into MT5 indicators and reports what it changed or left out. From a strategy() script it converts the calculations and plots, not the order logic. For the trading rules, describe them in the Bot Builder to get an MT5 Expert Advisor. Compile and test either result in MT5 before you rely on it.
Build a bot from your idea
Describe your trading idea and the AI writes MT4 or MT5 code for you to review and test, with a plain-English explanation and setup steps. Your first bot is free.