How to Check a Converted Indicator Matches TradingView

Short answer

Compare values, not charts: on the same input bars, every closed bar after the warm-up must have the same value in both versions within a floating-point tolerance, and the same bars must be empty (na in Pine, EMPTY_VALUE in MQL5).

A converted indicator that compiles and looks right on the chart can still be wrong: off by one bar, seeded differently, or different only at session boundaries. Looking at two charts side by side does not catch that. This guide gives a repeatable check for anyone who has converted a Pine indicator to MQL5, by hand or with a tool, and needs to know whether the numbers agree.

Decide what "matches" means

A useful definition: on the same input bars, every closed bar after the warm-up period has the same value in both versions, within a tolerance for floating-point rounding, and the same bars are empty (na in Pine, EMPTY_VALUE in MQL5). Three parts of that need care:

  • Same input bars. Different prices produce different values, which says nothing about the code.
  • Closed bars. The forming bar changes on every tick on both platforms; compare only bars that are final.
  • After warm-up. Recursive indicators (EMA, RMA, RSI, ATR) depend on where history starts. The two platforms start at different bars, so early values legitimately differ.

Step 1: get the same bars

TradingView data comes from the feed behind the symbol you chart (for example OANDA:EURUSD); MT5 data comes from your broker. They are rarely identical. Where TradingView offers your broker's own symbols, chart those. Then check the alignment of bar times: TradingView exports times in UTC (or the exchange time zone), MT5 uses the broker's server time, often UTC+2 or UTC+3 with a daylight-saving switch. Check a handful of bars by hand: open, high, low and close should agree at the times you think correspond.

Step 2: spot-check in the Data Window

Before exporting anything, open the Data Window on both platforms (Ctrl+D in MetaTrader 5) and hover over the same few bars: one early, one in the middle, one recent, and one where the indicator changes direction. If those disagree in a visible way, fix that first; an export will only confirm it.

Step 3: export both series

On TradingView, export the chart data from the layout menu, with the time format set to UNIX timestamps, if your plan offers it; the file has one column per plot, named by the plot title. In MT5, a small script can dump any indicator buffer for closed bars to MQL5\Files:

#property script_show_inputs

input string InpIndicator = "MyConverted";  // name in MQL5\Indicators, no extension
input int    InpBuffer    = 0;              // buffer index to export
input int    InpBars      = 2000;           // closed bars to export

void OnStart()
  {
   const int h = iCustom(_Symbol, _Period, InpIndicator);  // default inputs
   if(h == INVALID_HANDLE)
     {
      Print("iCustom failed: ", GetLastError());
      return;
     }
   // wait for the indicator to finish its first full calculation
   for(int tries = 0; tries < 50 && BarsCalculated(h) <= 0; tries++)
      Sleep(100);

   double   val[];
   datetime t[];
   // start at shift 1: closed bars only. Both arrays come back oldest first.
   const int n = CopyBuffer(h, InpBuffer, 1, InpBars, val);
   if(n <= 0 || CopyTime(_Symbol, _Period, 1, n, t) != n)
     {
      Print("copy failed: ", GetLastError());
      IndicatorRelease(h);
      return;
     }
   const string name = InpIndicator + "_" + _Symbol + "_" + IntegerToString(PeriodSeconds() / 60) + ".csv";
   const int f = FileOpen(name, FILE_WRITE | FILE_CSV | FILE_ANSI, ',');
   if(f == INVALID_HANDLE)
     {
      Print("FileOpen failed: ", GetLastError());
      IndicatorRelease(h);
      return;
     }
   FileWrite(f, "time_server", "value");
   for(int i = 0; i < n; i++)
      FileWrite(f, (long)t[i], val[i] == EMPTY_VALUE ? "" : DoubleToString(val[i], 8));
   FileClose(f);
   IndicatorRelease(h);
   Print("wrote ", n, " rows to MQL5\\Files\\", name);
  }

It loads the indicator with its default inputs through iCustom, waits for the first calculation, and writes server-time timestamps and values, with empty cells for EMPTY_VALUE. Make sure the inputs match the Pine script's defaults.

Step 4: compare by timestamp

Join the two files on time, skip the warm-up, and compare with a tolerance that combines a relative and an absolute part. Count bars where only one side is empty separately, because a warm-up that is one bar longer on one side is not a wrong value:

import csv

OFFSET = 2 * 3600   # broker server time minus UTC, in seconds (check yours)
WARMUP = 300        # bars to skip at the start of the common range
TV_COLUMN = "HTF EMA"  # the plot title in the TradingView export

def num(s):
    return float(s) if s not in ("", "NaN") else None

tv = {}
with open("tradingview.csv", newline="") as f:
    for row in csv.DictReader(f):
        tv[int(float(row["time"]))] = num(row[TV_COLUMN])

mt = {}
with open("mt5.csv", newline="") as f:
    for row in csv.DictReader(f):
        mt[int(row["time_server"]) - OFFSET] = num(row["value"])

common = sorted(set(tv) & set(mt))[WARMUP:]
diffs, one_sided = [], 0
for t in common:
    a, b = tv[t], mt[t]
    if a is None or b is None:
        one_sided += (a is None) != (b is None)
        continue
    if abs(a - b) > max(1e-9, 1e-6 * max(abs(a), abs(b))):
        diffs.append((t, a, b))

print(f"{len(common)} bars, {len(diffs)} differ, {one_sided} na on one side only")
for t, a, b in diffs[:10]:
    print(t, a, b, b - a)

A relative tolerance of 1e-6 with an absolute floor of 1e-9 is tight enough to catch formula errors and loose enough for double arithmetic. If thousands of bars differ by a little, suspect the input data; if a few bars differ by a lot, suspect the code.

Reading the differences

PatternLikely causeWhere to look
Large early, shrinking to zeroSeeding or warm-upHow the EMA/RMA starts; iMA vs ta.ema
Same shape, shifted one barIndexing direction or shiftArraySetAsSeries, [1] vs i-1
Differs only near session openHigher-timeframe alignmentrequest.security, daily bar boundaries
Zero where Pine is emptyna handlingnz(), EMPTY_VALUE, PLOT_EMPTY_VALUE
Only the newest bar differsForming bar comparedExport closed bars only
Small noise on every barDifferent price dataFeed, symbol, time zone

Strategies: compare trades, not equity

For a converted strategy, compare the list of trades before any profit figure: entry time, direction, exit time, in order. Run the MT5 Strategy Tester on the same symbol, timeframe and range. Spread, commission and the tick model change profit even when every trade matches, so a matching trade list with a different net profit is normal; a missing or extra trade is not.

How Stratlate checks conversions

Every conversion Stratlate makes is checked by a differential verifier that runs the original and the converted script on the same bars and compares their values, which removes data-feed and time-zone differences from the question. It compares a bar only where both sides have a value, counts one-sided empty bars separately, and uses a relative tolerance of 1e-6 with an absolute floor of 1e-9. A script it cannot execute exactly is counted as not verified, never as passing. The measured results are published on the quality page. That check is evidence, not a guarantee: still compile the result in MetaEditor and test it on your own broker's data.

Pitfalls

  • Comparing different inputs. Defaults in the MQL5 inputs that do not match the Pine inputs. Symptom: consistently different values from the first bar.
  • Ignoring daylight saving. A fixed time offset is right for half the year. Symptom: everything matches until a date in March or October, then nothing does.
  • Comparing the live bar. Values differ because one side sampled it a second later.
  • Treating 0 as empty. nz() in Pine turns na into 0, while MQL5 hides EMPTY_VALUE but plots 0. Compare empty cells explicitly.
  • Judging by eye. Two lines a pixel apart can differ by a full bar. Compare numbers.
  • Too short a history. A few hundred bars may never leave the warm-up. Export a few thousand.

FAQ

What tolerance should I use when comparing indicator values?

For the same input bars, a relative difference of about one in a million is a reasonable bar for double arithmetic. Larger but small differences usually mean different input data or a different warm-up, not a wrong formula, so look at where they occur before loosening the tolerance.

Why does my MQL5 indicator match TradingView except for the first few hundred bars?

Recursive calculations such as EMA, RMA, RSI and ATR depend on where history starts and how they are seeded. The two platforms start at different bars, so early values differ and then converge. Skip a warm-up period of several times the longest length.

Can I compare values when my broker's data differs from TradingView's?

Only roughly. With different prices, every value can differ a little, which hides real bugs. Use a TradingView symbol from the same broker if one exists, or check signals and crossings rather than exact values, and rely on same-bar tests for exactness.

Convert and verify

Each Stratlate conversion is run side by side with the original on the same bars. Convert your script and see the result.

Open the converter

Related guides