HƯỚNG DẪN

Cách biên dịch hàng loạt tệp MQL5 và đọc log UTF-16 của MetaEditor

Ngày đăng · Cập nhật

Mã

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]")

Vì sao xảy ra

MetaEditor là chương trình giao diện, nên khi biên dịch từ dòng lệnh nó không in gì ra console. Báo cáo duy nhất là tệp log, và MetaEditor ghi tệp này bằng UTF-16. Công cụ đọc log theo UTF-8 hoặc ANSI sẽ thấy một byte null sau mỗi ký tự, nên tìm chuỗi "0 errors" không bao giờ khớp. Mã thoát của MetaEditor không được tài liệu hóa là tín hiệu đạt hay lỗi, nên log là nguồn đáng tin duy nhất.

Các bước

  1. Tìm mọi tệp .mq5 trong thư mục nguồn, kể cả thư mục con.
  2. Đặt cho mỗi tệp một tên log riêng trong _compile_logs, tạo từ đường dẫn tương đối.
  3. Xóa log cũ, rồi chạy MetaEditor với /compile và /log và chờ nó thoát.
  4. Đọc log dạng byte và giải mã theo UTF-16, dùng byte order mark nếu có.
  5. Lấy dòng Result: cuối cùng và đọc số lỗi, số cảnh báo.
  6. Đánh dấu tệp là lỗi nếu thiếu log, không có dòng Result:, hoặc có bất kỳ lỗi nào.
  7. Trả về mã thoát 1 nếu có tệp lỗi, để job CI hoặc tác vụ định kỳ dừng lại.

Lưu ý

  • Thiếu log là lỗi, không phải đạt. Nguyên nhân thường là sai đường dẫn MetaEditor hoặc sai đường dẫn tệp nguồn.
  • Biên dịch từng tệp một. Nhiều tiến trình MetaEditor chạy song song có thể đụng nhau ở tệp include và tệp đầu ra.
  • Nếu mã nguồn nằm ngoài thư mục dữ liệu của terminal, hãy truyền thư mục MQL5 đó làm tham số thứ ba. Thiếu /include thì không tìm thấy các header chuẩn.
  • Tệp .mqh được biên dịch thông qua các tệp .mq5 include chúng. Thêm /s vào lệnh để chỉ kiểm tra cú pháp, không tạo .ex5.
  • Biên dịch không khởi chạy EA nào và không cần tài khoản giao dịch. Không cam kết lợi nhuận. Hãy thử trên tài khoản demo trước.

Thấy trên: Dự án của tôi ·

Dịch vụ liên quan: EA MT5 / MT4