HOW-TO

How to batch compile MQL5 files and read MetaEditor UTF-16 logs

Published · Updated

Code

python
r"""Batch compile MQL5 files with MetaEditor and check each UTF-16 log.

Usage:
  python compile_all.py "C:\Program Files\MetaTrader 5\MetaEditor64.exe" "C:\YOUR_SOURCE_DIR"
  Optional third argument: an MQL5 folder to pass as /include.
"""
import re
import subprocess
import sys
from pathlib import Path

RESULT_RE = re.compile(r"Result:?\s*(\d+)\s+error\S*\s*,\s*(\d+)\s+warning", re.I)
ERROR_RE = re.compile(r"\)\s*:\s*error\s+\d+", re.I)
TIMEOUT_SECONDS = 300


def read_log(path):
    raw = Path(path).read_bytes()
    if raw[:2] in (b"\xff\xfe", b"\xfe\xff"):  # UTF-16 byte order mark
        return raw.decode("utf-16", errors="replace")
    encoding = "utf-16-le" if b"\x00" in raw[:64] else "utf-8"
    return raw.decode(encoding, errors="replace")


def parse_log(text):
    """Return (errors, warnings, error_lines). errors is None without a Result line."""
    error_lines = [ln.strip() for ln in text.splitlines() if ERROR_RE.search(ln)]
    matches = RESULT_RE.findall(text)
    if not matches:
        return None, None, error_lines
    errors, warnings = (int(n) for n in matches[-1])
    return errors, warnings, error_lines


def compile_one(metaeditor, src, log, include=None):
    log = Path(log)
    log.parent.mkdir(parents=True, exist_ok=True)
    log.unlink(missing_ok=True)  # a stale log must never count as a pass
    cmd = f'"{metaeditor}" /compile:"{src}" /log:"{log}"'
    if include:
        cmd += f' /include:"{include}"'
    result = {"file": str(src), "ok": False, "lines": []}
    try:
        subprocess.run(cmd, timeout=TIMEOUT_SECONDS)  # exit code ignored on purpose
    except subprocess.TimeoutExpired:
        return {**result, "reason": "timeout"}
    if not log.is_file():
        return {**result, "reason": "no log written"}
    errors, warnings, lines = parse_log(read_log(log))
    if errors is None:
        return {**result, "reason": "no Result line in log", "lines": lines}
    ok = errors == 0 and not lines
    return {**result, "ok": ok, "lines": lines,
            "reason": f"{errors} errors, {warnings} warnings"}


def main(metaeditor, source_dir, include=None):
    root = Path(source_dir).resolve()
    log_dir = root / "_compile_logs"
    sources = sorted(root.rglob("*.mq5"))
    failed = 0
    for src in sources:
        log = log_dir / ("__".join(src.relative_to(root).parts) + ".log")
        result = compile_one(metaeditor, src, log, include)
        print("PASS" if result["ok"] else "FAIL", result["file"], "-", result["reason"])
        for line in result["lines"]:
            print("   ", line)
        failed += not result["ok"]
    print(f"{len(sources) - failed}/{len(sources)} files compiled with 0 errors")
    return 1 if failed or not sources else 0


if __name__ == "__main__":
    if len(sys.argv) in (3, 4):
        sys.exit(main(*sys.argv[1:]))
    print("usage: python compile_all.py <MetaEditor64.exe> <source_dir> [include_dir]")

Why it happens

MetaEditor is a desktop program, so a compile started from the command line prints nothing to the console. The only report is the log file, and MetaEditor writes it as UTF-16. A tool that reads it as UTF-8 or ANSI sees a null byte after every character, so a plain search for "0 errors" never matches. The exit code is not documented as a pass or fail signal, so the log is the only reliable source.

Steps

  1. Find every .mq5 file under the source folder, including subfolders.
  2. Give each file its own log name in _compile_logs, built from its relative path.
  3. Delete the old log, then start MetaEditor with /compile and /log and wait for it to exit.
  4. Read the log as bytes and decode it as UTF-16, using the byte order mark when present.
  5. Take the last Result: line and read the error and warning counts.
  6. Mark the file as failed if the log is missing, has no Result: line, or reports any error.
  7. Return exit code 1 if any file failed, so a CI job or scheduled task stops.

Pitfalls

  • A missing log is a failure, not a pass. It usually means a wrong MetaEditor path or a wrong source path.
  • Compile one file at a time. Parallel MetaEditor processes can collide on shared include files and output files.
  • If the sources live outside the terminal data folder, pass that MQL5 folder as the third argument. Without /include, standard headers are not found.
  • .mqh files are compiled through the .mq5 files that include them. Add /s to the command for a syntax check that writes no .ex5.
  • Compiling does not start any EA and needs no trading account. No profit is promised. Test on a demo account first.

Seen on: Own project ·

Related service: MT5 / MT4 Expert Advisor