Quick Answer
A Pine Script strategy can give different results on MQL5 because the platforms handle bar and tick execution, unconfirmed and higher-timeframe data, indicator values, and order fills differently. Compare signals on matching, confirmed bars first; then check indicator buffers, execution timing, spread, commission, and slippage before comparing backtest performance.
Key Facts
| Area | Pine Script | MQL5 |
|---|---|---|
| Execution | Evaluates chart bars; realtime behavior depends on strategy settings | Event-driven EA commonly evaluates on each OnTick() event |
| Current candle | Realtime values may change until the bar is confirmed | Shift 0 is forming; shift 1 is the last closed bar |
| RSI access | ta.rsi() returns a series value | iRSI() creates a handle; CopyBuffer() reads its values |
| Higher timeframe | request.security() has lookahead and confirmation behavior | Read the selected timeframe's series/indicator and align by bar time |
| Backtest results | Depend on TradingView data and broker-emulator settings | Depend on MT5 history, Strategy Tester settings, and execution assumptions |
Why Pine Script and MQL5 Can Disagree
Pine runs in TradingView’s chart and broker emulator; an MQL5 EA runs in MetaTrader using terminal events and broker data. Match symbol, timeframe, dates, signal timing, and sizing, then compare signals before evaluating spread, commissions, slippage, and fills.
Bar-by-Bar Pine Logic vs. MQL5 OnTick()
Pine evaluates a script across chart bars. Historical bars are evaluated using their available data; a realtime bar can be recalculated as new ticks arrive. Strategies normally calculate at bar close, unless options such as calc_on_every_tick change realtime calculation behavior. Under the default historical broker-emulator behavior, a market order created at a bar's close is generally filled on the next available tick, which is typically the next bar's open. Settings such as process_orders_on_close, intrabar recalculation, and Bar Magnifier can change the modeled timing or available intrabar detail; they do not make simulated fills identical to live broker execution. See TradingView's strategy execution and order-fill documentation.
An MQL5 EA is event-driven. OnTick() runs when the terminal receives a tick for the chart symbol. If the EA evaluates an entry condition on every tick, it may see an intrabar condition that Pine’s default bar-close strategy would not act on. Conversely, a new-bar-only check can miss behavior the Pine strategy was configured to evaluate intrabar.
To imitate a bar-close rule, many EAs detect the first tick of a new bar and read the last completed candle. Make the bar choice explicit: in MQL5, shift 0 is the forming bar, while shift 1 is the most recently closed bar. Use the same completed candle in both systems before investigating order execution.
Repainting and request.security() Can Create False Parity
Realtime values are not always final. A signal based on the current candle can appear and disappear before that candle closes. Higher-timeframe data introduces another risk: request.security() may return values from an unconfirmed higher-timeframe candle that later change. A script using lookahead incorrectly can also expose future higher-timeframe values on historical bars, creating signals that could not have been known live.
For a confirmed higher-timeframe value in Pine, a common pattern is to request the prior completed higher-timeframe bar:
confirmedHtfClose = request.security(
syminfo.tickerid,
"60",
close[1],
lookahead = barmerge.lookahead_on
)
Do not translate this into “use the latest H1 close” without checking when that value becomes available. In MT5, higher-timeframe data is typically read using the appropriate symbol/timeframe series or indicator handle, then aligned to the chart bars by time. Differences in bar boundaries, missing history, sessions, and data feeds can shift the apparent signal. Compare timestamps and confirm whether both versions use completed or still-forming higher-timeframe bars.
ta.rsi() vs. iRSI() and CopyBuffer()
Pine’s ta.rsi(source, length) returns an RSI series that can be used directly in expressions. MQL5’s iRSI() creates an indicator handle; the EA then requests calculated values with CopyBuffer(). The handle must be valid, and the buffer may not be ready immediately, so check the number of values copied rather than assuming the request succeeded.
The paired examples below calculate RSI and detect a cross above 30 using completed candles. They illustrate signal logic, not a complete trading system: risk sizing, existing positions, and order handling must be implemented separately.
Pine Script (v6):
//@version=6
strategy("RSI signal example", overlay = false)
rsiValue = ta.rsi(close, 14)
longSignal = ta.crossover(rsiValue, 30)
if longSignal
strategy.entry("Long", strategy.long)
MQL5 (EA signal check):
int rsiHandle = INVALID_HANDLE;
datetime lastBarTime = 0;
int OnInit()
{
rsiHandle = iRSI(_Symbol, _Period, 14, PRICE_CLOSE);
return rsiHandle == INVALID_HANDLE ? INIT_FAILED : INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
if (rsiHandle != INVALID_HANDLE)
IndicatorRelease(rsiHandle);
}
void OnTick()
{
datetime barTime = iTime(_Symbol, _Period, 0);
if (barTime == 0 || barTime == lastBarTime)
return;
double rsiValues[];
ArraySetAsSeries(rsiValues, true);
if (CopyBuffer(rsiHandle, 0, 0, 3, rsiValues) != 3)
return;
lastBarTime = barTime;
bool longSignal = rsiValues[2] <= 30.0 && rsiValues[1] > 30.0;
if (longSignal)
Print("RSI crossed above 30 on the last closed bar.");
}
With ArraySetAsSeries() enabled, this example reads index 1 as the last closed bar and index 2 as the closed bar before it; it deliberately avoids using the still-forming bar at index 0 for the crossover. If CopyBuffer() has not returned all requested values, the EA waits for a later tick. When adapting the example, check the indicator’s symbol, timeframe, warm-up history, and the exact bar shifts. A valid handle or a successful compile alone does not prove the values match Pine.
A Practical Backtest-Parity Checklist
- Match the inputs: symbol, timeframe, date range, indicator lengths, price source, and strategy settings.
- Compare signals first: log each signal’s bar time and direction in both platforms. Investigate the first bar where they differ.
- Confirm candle state: determine whether each condition uses a forming candle, a closed candle, or a confirmed higher-timeframe value.
- Review fills and costs: align order timing where possible, then account for spread, commissions, slippage, and each platform’s fill model.
- Check account behavior: lot-size rounding, minimum volume, netting versus hedging, and position-closing rules can change results even when entries match.
- Test out of sample: use additional market periods and a demo/forward test. Historical parity cannot guarantee future performance or live fills.
For prop firm traders, also verify the EA’s volume limits and any account-specific daily loss or drawdown controls independently. A signal match does not establish that a system complies with a firm’s rules.
Related Guides
- MT5 every tick vs real ticks: what the tester models
- Pine Script close[1] in MQL5: bar indexing explained
- Pine Script ta.rsi and ta.ema vs MQL5: why indicator values differ
- Pine Script var and varip in MQL5: keep state between bars
- Pine Script to MQL5 converter: paste a strategy and get an MQL5 draft
- Pine Script function should be called on each calculation: the CW10003 warning for history functions inside conditions.
- Pine Script memory limits exceeded: the RE10139 runtime error and how to reduce memory use.
- Pine Script maximum number of orders (9000): the strategy order limit and date filters.
Frequently Asked Questions
Convert, Then Verify
Different results are easier to diagnose when signal logic and execution are compared separately. Record the first mismatching bar, its time and indicator values, and the order creation and fill times in both platforms. This prevents tuning parameters to hide a data or timing mismatch.
CodeFlowOS can produce an MQL5 draft with an optional platform check; the check does not prove behavioral parity. Try the converter, read the verification notes, conversion guide, and pricing, then compare signals and test fills with matching settings. For more detail, see CopyBuffer indexing, Pine/MQL5 backtesting, and position sizing.