Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(data): MetaTrader 5 as a market-data source (mt5 loader)

staniell84c57e882931
diff --git a/agent/backtest/loaders/akshare_loader.py b/agent/backtest/loaders/akshare_loader.py
index 216af3d7e..8116c755c 100644
--- a/agent/backtest/loaders/akshare_loader.py
+++ b/agent/backtest/loaders/akshare_loader.py
@@ -49,7 +49,9 @@ def _is_forex(code: str) -> bool:
Issue #54 — forex symbols (EURUSD, GBPUSD, etc.) have no exchange suffix
and previously fell through to the A-share endpoint.
"""
- upper = code.upper().removesuffix(".FX")
+ # Accept the canonical slash form (EUR/USD) too, so the forex fallback
+ # chain (mt5 → akshare) actually engages for project-style codes.
+ upper = code.upper().removesuffix(".FX").replace("/", "")
try:
from akshare.forex.cons import symbol_market_map
except Exception:
@@ -198,7 +200,7 @@ class DataLoader:
— note ``最新价`` (latest) plays the role of close. Volume isn't reported,
so we synthesize a zero column to satisfy the OHLCV contract.
"""
- symbol = code.upper().removesuffix(".FX")
+ symbol = code.upper().removesuffix(".FX").replace("/", "")
df = ak.forex_hist_em(symbol=symbol)
if df is None or df.empty:
return None
diff --git a/agent/backtest/loaders/mt5_loader.py b/agent/backtest/loaders/mt5_loader.py
new file mode 100644
index 000000000..1d277ba53
--- /dev/null
+++ b/agent/backtest/loaders/mt5_loader.py
@@ -0,0 +1,243 @@
+"""MetaTrader 5 data loader — forex/metals history from a local MT5 terminal.
+
+Feeds backtests and ``get_market_data`` from the user's own broker feed
+(e.g. Exness), with the broker's exact symbols and session times. Requires
+Windows, the optional ``MetaTrader5`` package (``pip install
+"vibe-trading-ai[mt5]"``), and a running, logged-in MT5 terminal — when any of
+those are missing :meth:`DataLoader.is_available` is ``False`` and the forex
+fallback chain degrades to akshare/yfinance/local.
+
+Config is shared with the MT5 trading connector via ``~/.vibe-trading/mt5.json``
+(read directly — this module deliberately does not import the connector).
+With no config file, ``mt5.initialize()`` attaches to the last-used, already
+logged-in terminal, which is the primary read-only path.
+
+History depth is bounded by the terminal's "Max bars in chart" setting.
+Broker account-type suffixes (Exness ``EURUSDm``) are discovered via
+``symbols_get`` and memoized; results are keyed by the caller's ORIGINAL
+code so the runner's coverage check (``set(codes) - set(data_map)``) holds.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from types import ModuleType
+from typing import Any
+
+import pandas as pd
+
+from backtest.loaders.base import cached_loader_fetch, validate_date_range, validate_ohlc
+from backtest.loaders.registry import register
+
+logger = logging.getLogger(__name__)
+
+#: Shared file contract with the MT5 trading connector (extra keys tolerated).
+_MT5_CONFIG_PATH = Path.home() / ".vibe-trading" / "mt5.json"
+
+#: Canonical interval token → MetaTrader5 timeframe constant name.
+_INTERVAL_MAP = {
+ "1m": "TIMEFRAME_M1", "5m": "TIMEFRAME_M5", "15m": "TIMEFRAME_M15",
+ "30m": "TIMEFRAME_M30", "1H": "TIMEFRAME_H1", "4H": "TIMEFRAME_H4",
+ "1D": "TIMEFRAME_D1",
+}
+
+#: Process-lifetime attach cache: ``initialize`` can take seconds (it may even
+#: launch the terminal), and chain resolution probes ``is_available`` often.
+_init_state: bool | None = None
+
+#: base symbol → resolved broker symbol memo.
+_symbol_cache: dict[str, str] = {}
+
+
+def _import_mt5() -> ModuleType | None:
+ """Lazy-import the Windows-only SDK; ``None`` when absent."""
+ try:
+ import MetaTrader5 # type: ignore[import-not-found]
+ except ImportError:
+ return None
+ return MetaTrader5
+
+
+def _read_mt5_config() -> dict[str, Any]:
+ """Best-effort read of the shared mt5.json ({} on missing/corrupt)."""
+ try:
+ raw = json.loads(_MT5_CONFIG_PATH.read_text(encoding="utf-8"))
+ return raw if isinstance(raw, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+
+def _ensure_initialized() -> bool:
+ """Attach to the terminal once per process (result cached, even negative)."""
+ global _init_state
+ if _init_state is not None:
+ return _init_state
+ mt5 = _import_mt5()
+ if mt5 is None:
+ _init_state = False
+ return False
+ config = _read_mt5_config()
+ kwargs: dict[str, Any] = {}
+ if config.get("login"):
+ kwargs["login"] = int(config["login"])
+ kwargs["password"] = str(config.get("password") or "")
+ kwargs["server"] = str(config.get("server") or "")
+ if config.get("timeout"):
+ kwargs["timeout"] = int(float(config["timeout"]) * 1000)
+ args = (str(config["terminal_path"]),) if config.get("terminal_path") else ()
+ try:
+ ok = bool(mt5.initialize(*args, **kwargs))
+ except Exception as exc: # noqa: BLE001 - availability probe must not raise
+ logger.warning("mt5: initialize raised: %s", exc)
+ ok = False
+ if not ok:
+ try:
+ logger.warning("mt5: terminal attach failed: %s", mt5.last_error())
+ except Exception: # noqa: BLE001
+ pass
+ _init_state = ok
+ return ok
+
+
+def _to_query_base(code: str) -> str:
+ """``EUR/USD`` / ``EURUSD.FX`` → ``EURUSD`` (upper, separators stripped)."""
+ token = code.strip().upper()
+ if token.endswith(".FX"):
+ token = token[: -len(".FX")]
+ for separator in ("/", "-", "_", " "):
+ token = token.replace(separator, "")
+ return token
+
+
+def _resolve_broker_symbol(mt5: ModuleType, code: str) -> str | None:
+ """Resolve a project code to the broker's symbol name (memoized).
+
+ Order: the raw token exactly (case-sensitive broker names pass through),
+ the normalized base, then suffix discovery via ``symbols_get(f"{base}*")``
+ — shortest name first, then alphabetical, which deterministically picks
+ ``EURUSDm`` over ``EURUSDz`` on Exness-style brokers.
+ """
+ base = _to_query_base(code)
+ cached = _symbol_cache.get(base)
+ if cached is not None:
+ return cached
+ raw = code.strip()
+ for candidate in dict.fromkeys((raw, base)): # ordered, deduped
+ if candidate and mt5.symbol_info(candidate) is not None:
+ _symbol_cache[base] = candidate
+ return candidate
+ matches = sorted(
+ (getattr(info, "name", "") for info in (mt5.symbols_get(group=f"{base}*") or ())),
+ key=lambda name: (len(name), name),
+ )
+ matches = [m for m in matches if m]
+ if not matches:
+ logger.warning("mt5: symbol %r not offered by this broker (no match for %s*)", code, base)
+ return None
+ _symbol_cache[base] = matches[0]
+ return matches[0]
+
+
+def _rates_to_frame(rates: Any, start_date: str, end_date: str) -> pd.DataFrame | None:
+ """Map a ``copy_rates_range`` structured array to the loader frame contract."""
+ if rates is None or len(rates) == 0:
+ return None
+ frame = pd.DataFrame(rates)
+ if "time" not in frame.columns or "close" not in frame.columns:
+ return None
+ frame["trade_date"] = pd.to_datetime(frame["time"], unit="s")
+ frame = frame.set_index("trade_date").sort_index()
+ # Forex real_volume is zero on most brokers; tick_volume is the standard proxy.
+ frame["volume"] = frame.get("tick_volume", 0)
+ # Bars carry intraday timestamps; the end date is inclusive of its whole day.
+ start = pd.Timestamp(start_date)
+ end = pd.Timestamp(end_date) + pd.Timedelta(days=1)
+ frame = frame[(frame.index >= start) & (frame.index < end)]
+ frame = frame[["open", "high", "low", "close", "volume"]].dropna()
+ frame = validate_ohlc(frame)
+ return frame if not frame.empty else None
+
+
+@register
+class DataLoader:
+ """Forex/metals OHLCV from the local MT5 terminal (Windows, opt-in extra)."""
+
+ name = "mt5"
+ markets = {"forex"}
+ #: A running, logged-in terminal is the auth surface (futu precedent).
+ requires_auth = True
+
+ def __init__(self) -> None: # never raises — registry availability contract
+ pass
+
+ def is_available(self) -> bool:
+ """SDK importable AND the terminal attach succeeded (cached)."""
+ return _import_mt5() is not None and _ensure_initialized()
+
+ def fetch(
+ self,
+ codes: list[str],
+ start_date: str,
+ end_date: str,
+ *,
+ interval: str = "1D",
+ fields: list[str] | None = None,
+ ) -> dict[str, pd.DataFrame]:
+ """Fetch OHLCV frames keyed by the original input codes.
+
+ Per-symbol failures log and skip (never raise) so the runner's
+ runtime fallback can engage for the missing symbols.
+ """
+ validate_date_range(start_date, end_date)
+ timeframe_name = _INTERVAL_MAP.get(interval)
+ if timeframe_name is None:
+ logger.warning("unsupported MT5 interval %s, using 1D", interval)
+ interval, timeframe_name = "1D", "TIMEFRAME_D1"
+
+ result: dict[str, pd.DataFrame] = {}
+ for code in codes:
+ clean = code.strip()
+ if not clean:
+ continue
+ try:
+ frame = cached_loader_fetch(
+ source=self.name,
+ symbol=_to_query_base(clean),
+ timeframe=interval,
+ start_date=start_date,
+ end_date=end_date,
+ fields=None,
+ fetch=lambda c=clean: self._fetch_one(c, start_date, end_date, timeframe_name),
+ )
+ except Exception as exc: # noqa: BLE001 - one symbol never poisons the batch
+ logger.warning("mt5: fetch failed for %s: %s", clean, exc)
+ continue
+ if frame is not None and not frame.empty:
+ result[code] = frame
+ return result
+
+ def _fetch_one(
+ self, code: str, start_date: str, end_date: str, timeframe_name: str
+ ) -> pd.DataFrame | None:
+ """Fetch one symbol from the terminal (``None`` on any failure)."""
+ mt5 = _import_mt5()
+ if mt5 is None or not _ensure_initialized():
+ return None
+ name = _resolve_broker_symbol(mt5, code)
+ if name is None:
+ return None
+ try:
+ mt5.symbol_select(name, True)
+ timeframe = getattr(mt5, timeframe_name)
+ # tz-aware UTC is mandatory: the MT5 API shifts naive datetimes by
+ # the local timezone, silently offsetting the requested range.
+ date_from = datetime.fromisoformat(start_date).replace(tzinfo=timezone.utc)
+ date_to = datetime.fromisoformat(end_date).replace(tzinfo=timezone.utc) + timedelta(days=1)
+ rates = mt5.copy_rates_range(name, timeframe, date_from, date_to)
+ except Exception as exc: # noqa: BLE001 - terminal hiccups degrade, not raise
+ logger.warning("mt5: rates fetch failed for %s (%s): %s", code, name, exc)
+ return None
+ return _rates_to_frame(rates, start_date, end_date)
diff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.py
index f2c987a66..a0d93752b 100644
--- a/agent/backtest/loaders/registry.py
+++ b/agent/backtest/loaders/registry.py
@@ -50,6 +50,7 @@ VALID_SOURCES: set[str] = {
"fmp",
"qveris", # QVERIS-INTEGRATION
"india_broker",
+ "mt5",
"local",
"auto",
}
@@ -96,6 +97,7 @@ def _ensure_registered() -> None:
"backtest.loaders.fmp_loader",
"backtest.loaders.qveris_loader", # QVERIS-INTEGRATION
"backtest.loaders.india_broker_loader",
+ "backtest.loaders.mt5_loader",
"backtest.loaders.local_loader",
]
import importlib
@@ -134,7 +136,9 @@ FALLBACK_CHAINS: dict[str, list[str]] = {
"futures": ["tushare", "akshare", "local"],
"fund": ["tushare", "akshare", "local"],
"macro": ["akshare", "tushare", "local"],
- "forex": ["akshare", "yfinance", "local"],
+ # mt5 leads when a local MetaTrader 5 terminal is attached (Windows-only,
+ # broker feed); otherwise it reports unavailable and the chain proceeds.
+ "forex": ["mt5", "akshare", "yfinance", "local"],
}
diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.py
index e1cdb7caf..12d3e04b2 100644
--- a/agent/backtest/metrics.py
+++ b/agent/backtest/metrics.py
@@ -19,15 +19,16 @@ from backtest.models import TradeRecord
# sessions are marginally longer (~330 min) — an approximation in line with the
# rest of this annualisation table; the key fix is that intraday mootdx/futu no
# longer fall back to the bars_per_day=1 default, which mis-annualised vol/Sharpe.
-_TRADING_DAYS = {"tushare": 252, "yfinance": 252, "okx": 365, "akshare": 252, "ccxt": 365, "mootdx": 252, "futu": 252}
+_TRADING_DAYS = {"tushare": 252, "yfinance": 252, "okx": 365, "akshare": 252, "ccxt": 365, "mootdx": 252, "futu": 252, "mt5": 260}
+# mt5 is a forex/CFD feed: 24x5 sessions → 260 trading days, 24h intraday bars.
_BARS_PER_DAY = {
- "1m": {"tushare": 240, "okx": 1440, "yfinance": 390, "akshare": 240, "ccxt": 1440, "mootdx": 240, "futu": 240},
- "5m": {"tushare": 48, "okx": 288, "yfinance": 78, "akshare": 48, "ccxt": 288, "mootdx": 48, "futu": 48},
- "15m": {"tushare": 16, "okx": 96, "yfinance": 26, "akshare": 16, "ccxt": 96, "mootdx": 16, "futu": 16},
- "30m": {"tushare": 8, "okx": 48, "yfinance": 13, "akshare": 8, "ccxt": 48, "mootdx": 8, "futu": 8},
- "1H": {"tushare": 4, "okx": 24, "yfinance": 7, "akshare": 4, "ccxt": 24, "mootdx": 4, "futu": 4},
- "4H": {"tushare": 1, "okx": 6, "yfinance": 2, "akshare": 1, "ccxt": 6, "mootdx": 1, "futu": 1},
- "1D": {"tushare": 1, "okx": 1, "yfinance": 1, "akshare": 1, "ccxt": 1, "mootdx": 1, "futu": 1},
+ "1m": {"tushare": 240, "okx": 1440, "yfinance": 390, "akshare": 240, "ccxt": 1440, "mootdx": 240, "futu": 240, "mt5": 1440},
+ "5m": {"tushare": 48, "okx": 288, "yfinance": 78, "akshare": 48, "ccxt": 288, "mootdx": 48, "futu": 48, "mt5": 288},
+ "15m": {"tushare": 16, "okx": 96, "yfinance": 26, "akshare": 16, "ccxt": 96, "mootdx": 16, "futu": 16, "mt5": 96},
+ "30m": {"tushare": 8, "okx": 48, "yfinance": 13, "akshare": 8, "ccxt": 48, "mootdx": 8, "futu": 8, "mt5": 48},
+ "1H": {"tushare": 4, "okx": 24, "yfinance": 7, "akshare": 4, "ccxt": 24, "mootdx": 4, "futu": 4, "mt5": 24},
+ "4H": {"tushare": 1, "okx": 6, "yfinance": 2, "akshare": 1, "ccxt": 6, "mootdx": 1, "futu": 1, "mt5": 6},
+ "1D": {"tushare": 1, "okx": 1, "yfinance": 1, "akshare": 1, "ccxt": 1, "mootdx": 1, "futu": 1, "mt5": 1},
}
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index 7befdb1da..9006691a1 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -1055,6 +1055,7 @@ def get_market_data(
- "tencent": China A-shares via Tencent Finance API (e.g. 000001.SZ, 601595.SH)
- "akshare": A-shares, US, HK, futures, forex (free, e.g. 000001.SZ, AAPL.US)
- "ccxt": crypto from 100+ exchanges (free, e.g. BTC/USDT)
+ - "mt5": forex/metals from a local MetaTrader 5 terminal (Windows; e.g. EUR/USD, XAUUSD.FX)
- "auto": auto-detect based on symbol format (with fallback)
Args:
diff --git a/agent/src/market_data.py b/agent/src/market_data.py
index 9538b25a9..db90087d3 100644
--- a/agent/src/market_data.py
+++ b/agent/src/market_data.py
@@ -28,6 +28,12 @@ _SOURCE_PATTERNS = [
(re.compile(r"^[A-Z0-9&.\-]+\.(NS|BO)$", re.I), "yahoo"),
(re.compile(r"^[A-Z]+-USDT$", re.I), "okx"),
(re.compile(r"^[A-Z]+/USDT$", re.I), "ccxt"),
+ # Forex pairs and metals (EUR/USD, XAU/USD, EURUSD.FX). mt5 is the head of
+ # the forex chain and degrades to akshare/yfinance via the registry when no
+ # local MT5 terminal is attached. The 3-letter quote cannot collide with
+ # the 4-letter /USDT crypto rule above.
+ (re.compile(r"^[A-Z]{3}/[A-Z]{3}$", re.I), "mt5"),
+ (re.compile(r"^[A-Z]{6}\.FX$", re.I), "mt5"),
]
diff --git a/agent/src/tools/market_data_tool.py b/agent/src/tools/market_data_tool.py
index 62611ed6c..d5af428cb 100644
--- a/agent/src/tools/market_data_tool.py
+++ b/agent/src/tools/market_data_tool.py
@@ -53,13 +53,16 @@ class MarketDataTool(BaseTool):
"alphavantage",
"tiingo",
"fmp",
+ "mt5",
],
"description": (
"Data source. 'auto' detects from symbol format with fallback. "
"Free, no key: yfinance/yahoo (US/HK equities), okx/ccxt "
"(crypto), baostock/tencent/eastmoney/sina/akshare/mootdx "
"(China A-shares), stooq (global EOD). Key-gated REST: tushare "
- "(China A-shares), finnhub/alphavantage/tiingo/fmp (US/global)."
+ "(China A-shares), finnhub/alphavantage/tiingo/fmp (US/global). "
+ "mt5: forex/metals from a local MetaTrader 5 terminal (Windows; "
+ "e.g. EUR/USD, XAUUSD.FX)."
),
"default": "auto",
},
diff --git a/agent/tests/test_akshare_loader.py b/agent/tests/test_akshare_loader.py
index d24f71a3c..98ae27e9f 100644
--- a/agent/tests/test_akshare_loader.py
+++ b/agent/tests/test_akshare_loader.py
@@ -63,6 +63,10 @@ class TestIsForex:
def test_fx_suffix_matches(self) -> None:
assert _is_forex("EURUSD.FX")
+ def test_slash_form_matches(self) -> None:
+ # Canonical project form — required for the mt5 → akshare fallback.
+ assert _is_forex("EUR/USD")
+
def test_a_share_does_not_match(self) -> None:
assert not _is_forex("600519.SH")
diff --git a/agent/tests/test_market_data.py b/agent/tests/test_market_data.py
index f22c8a0f3..5e157475d 100644
--- a/agent/tests/test_market_data.py
+++ b/agent/tests/test_market_data.py
@@ -46,6 +46,10 @@ from src.market_data import (
("500325.BO", "yahoo"), # India BSE (numeric scrip code)
("BTC-USDT", "okx"),
("ETH/USDT", "ccxt"),
+ ("EUR/USD", "mt5"), # forex pair → mt5 chain head (registry fallback)
+ ("XAU/USD", "mt5"), # metals share the forex route
+ ("EURUSD.FX", "mt5"),
+ ("XAUUSD.FX", "mt5"),
("local:my_file", "local"),
("something_weird", "tushare"), # documented fallback
],
diff --git a/agent/tests/test_mt5_loader.py b/agent/tests/test_mt5_loader.py
new file mode 100644
index 000000000..d58bc0890
--- /dev/null
+++ b/agent/tests/test_mt5_loader.py
@@ -0,0 +1,270 @@
+"""MT5 backtest data loader tests (Windows-only SDK, faked here).
+
+The real ``MetaTrader5`` package never installs on CI's ubuntu runner; the
+loader lazy-imports it, so tests inject a fake module via ``sys.modules`` and
+exercise symbol resolution, interval mapping, the frame contract, config
+plumbing, and graceful degradation (init failure → unavailable → registry
+fallback engages).
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import numpy as np
+import pytest
+
+import backtest.loaders.mt5_loader as mt5_loader
+from backtest.loaders.mt5_loader import DataLoader, _to_query_base
+
+pytestmark = pytest.mark.unit
+
+
+_RATES_DTYPE = [
+ ("time", "<i8"), ("open", "<f8"), ("high", "<f8"), ("low", "<f8"),
+ ("close", "<f8"), ("tick_volume", "<i8"), ("spread", "<i4"), ("real_volume", "<i8"),
+]
+
+#: 2026-06-02 00:00 UTC and the next two days, hourly-ish spacing irrelevant.
+_T0 = 1_780_358_400
+
+
+def _rates(*rows: tuple) -> np.ndarray:
+ return np.array(list(rows), dtype=_RATES_DTYPE)
+
+
+def _default_rates() -> np.ndarray:
+ return _rates(
+ (_T0, 1.07, 1.09, 1.06, 1.08, 1200, 6, 0),
+ (_T0 + 86_400, 1.08, 1.10, 1.07, 1.09, 1300, 6, 0),
+ (_T0 + 2 * 86_400, 1.09, 1.11, 1.08, 1.10, 1400, 6, 0),
+ )
+
+
+class _FakeMT5Module:
+ TIMEFRAME_M1 = 1
+ TIMEFRAME_M5 = 5
+ TIMEFRAME_M15 = 15
+ TIMEFRAME_M30 = 30
+ TIMEFRAME_H1 = 16385
+ TIMEFRAME_H4 = 16388
+ TIMEFRAME_D1 = 16408
+
+ def __init__(self) -> None:
+ self.initialize_result = True
+ self.initialize_calls: list[dict[str, Any]] = []
+ self.symbol_names = ["EURUSDm", "EURUSDz", "XAUUSDm", "USDJPYm"]
+ self.rates: dict[str, np.ndarray | None] = {}
+ self.rates_calls: list[tuple[str, int, Any, Any]] = []
+
+ def initialize(self, *args: Any, **kwargs: Any) -> bool:
+ self.initialize_calls.append({"args": args, "kwargs": kwargs})
+ return self.initialize_result
+
+ def shutdown(self) -> None: # pragma: no cover - not called by the loader
+ pass
+
+ def last_error(self) -> tuple[int, str]:
+ return (-6, "Terminal: Authorization failed") if not self.initialize_result else (1, "Success")
+
+ def symbol_info(self, name: str) -> Any:
+ return SimpleNamespace(name=name) if name in self.symbol_names else None
+
+ def symbol_select(self, name: str, enable: bool = True) -> bool:
+ return name in self.symbol_names
+
+ def symbols_get(self, group: str | None = None) -> tuple:
+ if not group:
+ return tuple(SimpleNamespace(name=n) for n in self.symbol_names)
+ prefix = group.strip("*").upper()
+ return tuple(SimpleNamespace(name=n) for n in self.symbol_names if n.upper().startswith(prefix))
+
+ def copy_rates_range(self, name: str, timeframe: int, date_from: Any, date_to: Any):
+ self.rates_calls.append((name, timeframe, date_from, date_to))
+ return self.rates.get(name)
+
+
+def fake_mod(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> _FakeMT5Module:
+ fake = _FakeMT5Module()
+ fake.rates["EURUSDm"] = _default_rates()
+ monkeypatch.setitem(sys.modules, "MetaTrader5", fake)
+ monkeypatch.setattr(mt5_loader, "_MT5_CONFIG_PATH", tmp_path / "mt5.json")
+ monkeypatch.setattr(mt5_loader, "_init_state", None)
+ monkeypatch.setattr(mt5_loader, "_symbol_cache", {})
+ return fake
+
+
+# --------------------------------------------------------------------------- #
+# Symbol normalization + resolution #
+# --------------------------------------------------------------------------- #
+
+
+class TestQueryBase:
+ @pytest.mark.parametrize(
+ ("raw", "expected"),
+ [
+ ("EUR/USD", "EURUSD"),
+ ("EURUSD.FX", "EURUSD"),
+ ("XAU/USD", "XAUUSD"),
+ ("eurusd", "EURUSD"),
+ ("EURUSDm", "EURUSDM"),
+ ],
+ )
+ def test_normalizes(self, raw: str, expected: str) -> None:
+ assert _to_query_base(raw) == expected
+
+
+class TestResolution:
+ def test_suffix_discovery_prefers_shortest_then_alpha(self, fake_mod: _FakeMT5Module) -> None:
+ loader = DataLoader()
+ frames = loader.fetch(["EUR/USD"], "2026-06-01", "2026-06-10")
+ # EURUSDm and EURUSDz both match EURUSD*; deterministic pick is EURUSDm.
+ assert fake_mod.rates_calls[0][0] == "EURUSDm"
+ assert "EUR/USD" in frames
+
+ def test_exact_symbol_wins_over_suffix(self, fake_mod: _FakeMT5Module) -> None:
+ fake_mod.symbol_names.append("EURUSD")
+ fake_mod.rates["EURUSD"] = _default_rates()
+ loader = DataLoader()
+ loader.fetch(["EUR/USD"], "2026-06-01", "2026-06-10")
+ assert fake_mod.rates_calls[0][0] == "EURUSD"
+
+ def test_raw_broker_symbol_passes_through(self, fake_mod: _FakeMT5Module) -> None:
+ loader = DataLoader()
+ loader.fetch(["EURUSDm"], "2026-06-01", "2026-06-10")
+ assert fake_mod.rates_calls[0][0] == "EURUSDm"
+
+ def test_unresolvable_symbol_skipped_without_raise(self, fake_mod: _FakeMT5Module) -> None:
+ loader = DataLoader()
+ frames = loader.fetch(["NZD/CAD", "EUR/USD"], "2026-06-01", "2026-06-10")
+ assert "NZD/CAD" not in frames
+ assert "EUR/USD" in frames # one bad symbol never poisons the batch
+
+
+# --------------------------------------------------------------------------- #
+# Intervals + frame contract #
+# --------------------------------------------------------------------------- #
+
+
+class TestIntervalsAndFrames:
+ def test_interval_mapping(self, fake_mod: _FakeMT5Module) -> None:
+ loader = DataLoader()
+ loader.fetch(["EUR/USD"], "2026-06-01", "2026-06-10", interval="1H")
+ assert fake_mod.rates_calls[-1][1] == _FakeMT5Module.TIMEFRAME_H1
+
+ def test_unknown_interval_defaults_to_daily(self, fake_mod: _FakeMT5Module) -> None:
+ loader = DataLoader()
+ loader.fetch(["EUR/USD"], "2026-06-01", "2026-06-10", interval="7z")
+ assert fake_mod.rates_calls[-1][1] == _FakeMT5Module.TIMEFRAME_D1
+
+ def test_frame_contract(self, fake_mod: _FakeMT5Module) -> None:
+ loader = DataLoader()
+ frames = loader.fetch(["EUR/USD"], "2026-06-01", "2026-06-10")
+ frame = frames["EUR/USD"] # keyed by the ORIGINAL input code
+ assert list(frame.columns) == ["open", "high", "low", "close", "volume"]
+ assert frame.index.name == "trade_date"
+ assert frame["volume"].tolist() == [1200, 1300, 1400] # tick_volume
+ assert frame["close"].iloc[-1] == pytest.approx(1.10)
+
+ def test_range_clipped(self, fake_mod: _FakeMT5Module) -> None:
+ loader = DataLoader()
+ frames = loader.fetch(["EUR/USD"], "2026-06-02", "2026-06-03")
+ # Third bar (2026-06-04) falls outside the requested end date.
+ assert len(frames["EUR/USD"]) == 2
+
+ def test_tz_aware_range_passed_to_terminal(self, fake_mod: _FakeMT5Module) -> None:
+ loader = DataLoader()
+ loader.fetch(["EUR/USD"], "2026-06-01", "2026-06-10")
+ _, _, date_from, date_to = fake_mod.rates_calls[-1]
+ # Naive datetimes get shifted by local tz inside the MT5 API.
+ assert date_from.tzinfo is not None
+ assert date_to.tzinfo is not None
+ assert date_to > date_from
+
+
+# --------------------------------------------------------------------------- #
+# Availability + config #
+# --------------------------------------------------------------------------- #
+
+
+class TestAvailability:
+ def test_available_when_initialized(self, fake_mod: _FakeMT5Module) -> None:
+ assert DataLoader().is_available() is True
+
+ def test_init_failure_negative_cached(self, fake_mod: _FakeMT5Module) -> None:
+ fake_mod.initialize_result = False
+ loader = DataLoader()
+ assert loader.is_available() is False
+ assert loader.fetch(["EUR/USD"], "2026-06-01", "2026-06-10") == {}
+ assert loader.is_available() is False
+ assert len(fake_mod.initialize_calls) == 1 # one attempt per process
+
+ def test_missing_package_unavailable(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setitem(sys.modules, "MetaTrader5", None)
+ monkeypatch.setattr(mt5_loader, "_init_state", None)
+ assert DataLoader().is_available() is False
+
+ def test_config_file_feeds_initialize(
+ self, fake_mod: _FakeMT5Module, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ config = tmp_path / "mt5.json"
+ config.write_text(
+ json.dumps({"login": 12345, "password": "pw", "server": "Exness-MT5Trial8"}),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(mt5_loader, "_MT5_CONFIG_PATH", config)
+ DataLoader().is_available()
+ kwargs = fake_mod.initialize_calls[0]["kwargs"]
+ assert kwargs["login"] == 12345
+ assert kwargs["server"] == "Exness-MT5Trial8"
+
+ def test_no_config_attaches_bare(self, fake_mod: _FakeMT5Module) -> None:
+ DataLoader().is_available()
+ call = fake_mod.initialize_calls[0]
+ assert call["args"] == ()
+ assert "login" not in call["kwargs"]
+
+
+# --------------------------------------------------------------------------- #
+# Registry + routing #
+# --------------------------------------------------------------------------- #
+
+
+class TestRegistryWiring:
+ def test_mt5_in_valid_sources(self) -> None:
+ from backtest.loaders.registry import VALID_SOURCES
+
+ assert "mt5" in VALID_SOURCES
+
+ def test_mt5_registered(self) -> None:
+ from backtest.loaders.registry import LOADER_REGISTRY, _ensure_registered
+
+ _ensure_registered()
+ assert "mt5" in LOADER_REGISTRY
+
+ def test_mt5_heads_forex_chain(self) -> None:
+ from backtest.loaders.registry import FALLBACK_CHAINS
+
+ assert FALLBACK_CHAINS["forex"][0] == "mt5"
+ assert "akshare" in FALLBACK_CHAINS["forex"] # degradation path intact
+
+ @pytest.mark.parametrize(
+ ("code", "expected"),
+ [
+ ("EUR/USD", "mt5"),
+ ("XAU/USD", "mt5"),
+ ("EURUSD.FX", "mt5"),
+ ("XAUUSD.FX", "mt5"),
+ ("BTC-USDT", "okx"), # unchanged
+ ("ETH/USDT", "ccxt"), # 4-letter quote must not match the forex rule
+ ],
+ )
+ def test_detect_source_forex(self, code: str, expected: str) -> None:
+ from src.market_data import detect_source
+
+ assert detect_source(code) == expected
diff --git a/agent/tests/test_registry.py b/agent/tests/test_registry.py
index 98b95129d..42ec3183a 100644
--- a/agent/tests/test_registry.py
+++ b/agent/tests/test_registry.py
@@ -178,7 +178,9 @@ class TestFallbackChains:
assert FALLBACK_CHAINS["futures"] == ["tushare", "akshare", "local"]
assert FALLBACK_CHAINS["fund"] == ["tushare", "akshare", "local"]
assert FALLBACK_CHAINS["macro"] == ["akshare", "tushare", "local"]
- assert FALLBACK_CHAINS["forex"] == ["akshare", "yfinance", "local"]
+ # mt5 heads the forex chain (terminal feed when attached), degrading to
+ # the previous chain unchanged.
+ assert FALLBACK_CHAINS["forex"] == ["mt5", "akshare", "yfinance", "local"]
# ---------------------------------------------------------------------------