Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(trading): MetaTrader 5 broker connector (Exness-style MT5 brokers)

staniell9a746b9e9515
diff --git a/agent/src/live/registry.py b/agent/src/live/registry.py
index b24e8f96c..81f9ba366 100644
--- a/agent/src/live/registry.py
+++ b/agent/src/live/registry.py
@@ -29,6 +29,7 @@ from src.trading.connectors.dhan.classification import DHAN_TOOL_CLASS
from src.trading.connectors.futu.classification import FUTU_TOOL_CLASS
from src.trading.connectors.ibkr.classification import IBKR_TOOL_CLASS
from src.trading.connectors.longbridge.classification import LONGBRIDGE_TOOL_CLASS
+from src.trading.connectors.mt5.classification import MT5_TOOL_CLASS
from src.trading.connectors.okx.classification import OKX_TOOL_CLASS
from src.trading.connectors.robinhood.classification import ROBINHOOD_TOOL_CLASS
from src.trading.connectors.shoonya.classification import SHOONYA_TOOL_CLASS
@@ -53,6 +54,7 @@ _BROKER_CURATED_MAPS = {
"dhan": DHAN_TOOL_CLASS,
"shoonya": SHOONYA_TOOL_CLASS,
"trading212": TRADING212_TOOL_CLASS,
+ "mt5": MT5_TOOL_CLASS,
}
diff --git a/agent/src/trading/connectors/mt5/__init__.py b/agent/src/trading/connectors/mt5/__init__.py
new file mode 100644
index 000000000..b1a9ff187
--- /dev/null
+++ b/agent/src/trading/connectors/mt5/__init__.py
@@ -0,0 +1,14 @@
+"""MetaTrader 5 connector (Exness-style MT5 brokers) — ``broker_sdk`` transport.
+
+Talks to a locally running MT5 terminal through the official ``MetaTrader5``
+Python package, which is **Windows-only** and an opt-in extra
+(``pip install "vibe-trading-ai[mt5]"``). Credentials live in
+``~/.vibe-trading/mt5.json``.
+
+Paper/live separation: MT5 has no separate paper API — "paper" means the
+broker's DEMO account. Unlike key-scoped connectors the discriminator is
+self-verifying: every session re-reads ``account_info().trade_mode`` and the
+login, and hard-rejects a paper profile attached to a real-money account (and
+vice versa; contest accounts are rejected everywhere, fail-closed). Live order
+placement additionally routes through the mandate gate and kill switch.
+"""
diff --git a/agent/src/trading/connectors/mt5/_client.py b/agent/src/trading/connectors/mt5/_client.py
new file mode 100644
index 000000000..a5babac48
--- /dev/null
+++ b/agent/src/trading/connectors/mt5/_client.py
@@ -0,0 +1,379 @@
+"""MT5 config, session lifecycle, identity guard, and USD sizing helpers.
+
+The ``MetaTrader5`` Python API is process-global and stateful: one
+``initialize()`` per process, module-level functions, ``shutdown()`` to
+detach. Every operation therefore runs inside :func:`_session` — a lock,
+initialize, bidirectional profile/identity verification, work, shutdown —
+so no read or write can ever execute against the wrong account class.
+"""
+
+from __future__ import annotations
+
+import json
+import threading
+from contextlib import contextmanager
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from types import ModuleType
+from typing import Any, Iterator, Mapping
+
+from src.config.paths import get_runtime_root
+from src.trading.connectors.mt5.symbols import normalize_base
+
+CONFIG_FILENAME = "mt5.json"
+
+#: Profiles this connector understands and their account environment.
+PROFILE_ENVIRONMENTS = {
+ "paper": "paper",
+ "live-readonly": "live",
+ "live": "live",
+}
+
+#: Guard marker recorded on every payload: the demo/live discriminator is
+#: re-verified from the terminal on every session (trade_mode) and the login
+#: is pinned against the configured one.
+GUARD_MARKER = "terminal_trade_mode+login_pin"
+
+
+class MT5DependencyError(RuntimeError):
+ """Raised when the optional Windows-only ``MetaTrader5`` package is missing."""
+
+
+class MT5ConfigError(RuntimeError):
+ """Raised when the connector configuration or a symbol is missing/invalid."""
+
+
+class MT5ConnectionError(RuntimeError):
+ """Raised when the local MT5 terminal cannot be attached or queried."""
+
+
+class MT5ProfileMismatchError(RuntimeError):
+ """Raised when the terminal account does not match the selected profile."""
+
+
+@dataclass(frozen=True)
+class MT5Config:
+ """MT5 connector connection settings (persisted in ``~/.vibe-trading/mt5.json``).
+
+ Args:
+ login: Terminal account number; pinned against ``account_info().login``.
+ password: Account password (redacted in every public payload).
+ server: Broker server name, e.g. ``"Exness-MT5Trial8"``.
+ terminal_path: Optional path to ``terminal64.exe`` when several
+ terminals are installed.
+ profile: ``paper``, ``live-readonly`` or ``live``. ``paper`` means the
+ broker's DEMO account.
+ symbol_suffix: Broker account-type suffix appended verbatim to base
+ symbols (Exness: ``"m"`` → ``EURUSDm``).
+ deviation_points: Max market-order slippage in points.
+ max_order_volume: Connector-level per-order lot ceiling (demo AND live).
+ max_order_notional_usd: Connector-level per-order USD ceiling (demo AND
+ live) — defense-in-depth under the live mandate gate.
+ timeout: Terminal attach timeout in seconds.
+ readonly: Interface symmetry with the other SDK connectors.
+ """
+
+ login: int = 0
+ password: str = ""
+ server: str = ""
+ terminal_path: str = ""
+ profile: str = "paper"
+ symbol_suffix: str = ""
+ deviation_points: int = 20
+ max_order_volume: float = 1.0
+ max_order_notional_usd: float = 10_000.0
+ timeout: float = 15.0
+ readonly: bool = True
+
+ @classmethod
+ def from_mapping(cls, data: Mapping[str, Any] | None = None) -> "MT5Config":
+ """Build a config from a JSON-like mapping, normalizing the profile."""
+ payload = dict(data or {})
+ profile = str(payload.get("profile") or "paper").strip().lower()
+ if profile not in PROFILE_ENVIRONMENTS:
+ raise MT5ConfigError("profile must be 'paper', 'live-readonly' or 'live'")
+ return cls(
+ login=int(payload.get("login") or 0),
+ password=str(payload.get("password") or ""),
+ server=str(payload.get("server") or "").strip(),
+ terminal_path=str(payload.get("terminal_path") or "").strip(),
+ profile=profile,
+ symbol_suffix=str(payload.get("symbol_suffix") or "").strip(),
+ deviation_points=int(payload.get("deviation_points") or 20),
+ max_order_volume=float(payload.get("max_order_volume") or 1.0),
+ max_order_notional_usd=float(payload.get("max_order_notional_usd") or 10_000.0),
+ timeout=float(payload.get("timeout") or 15.0),
+ readonly=bool(payload.get("readonly", True)),
+ )
+
+ def with_overrides(self, **overrides: Any) -> "MT5Config":
+ """Return a copy with CLI/tool overrides applied."""
+ payload = asdict(self)
+ for key, value in overrides.items():
+ if value is not None:
+ payload[key] = value
+ return MT5Config.from_mapping(payload)
+
+ @property
+ def environment(self) -> str:
+ """Return ``paper`` or ``live`` for this profile."""
+ return PROFILE_ENVIRONMENTS.get(self.profile, "paper")
+
+ @property
+ def is_demo(self) -> bool:
+ """Return whether this profile targets the broker's demo account."""
+ return self.environment == "paper"
+
+
+_OVERRIDE_KEYS = ("login", "password", "server", "terminal_path", "profile", "symbol_suffix")
+
+
+def build_config(
+ profile_config: Mapping[str, Any] | None = None,
+ overrides: Mapping[str, Any] | None = None,
+) -> "MT5Config":
+ """Resolve config: saved file ← profile defaults ← CLI overrides."""
+ base = asdict(load_config())
+ for key, value in dict(profile_config or {}).items():
+ if value is not None:
+ base[key] = value
+ cfg = MT5Config.from_mapping(base)
+ clean = {k: v for k, v in dict(overrides or {}).items() if k in _OVERRIDE_KEYS and v not in (None, "")}
+ return cfg.with_overrides(**clean) if clean else cfg
+
+
+def config_path() -> Path:
+ """Return the user-level MT5 config path."""
+ return get_runtime_root() / CONFIG_FILENAME
+
+
+def load_config() -> MT5Config:
+ """Load MT5 settings from ``~/.vibe-trading/mt5.json``."""
+ path = config_path()
+ if not path.exists():
+ return MT5Config()
+ try:
+ return MT5Config.from_mapping(json.loads(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
+ raise MT5ConfigError(f"invalid MT5 config at {path}: {exc}") from exc
+
+
+def save_config(config: MT5Config) -> Path:
+ """Persist MT5 settings with owner-only permissions (best-effort on Windows)."""
+ path = config_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(asdict(config), indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ try:
+ path.chmod(0o600)
+ except OSError:
+ pass
+ return path
+
+
+def mt5_available() -> bool:
+ """Return whether the optional ``MetaTrader5`` package can be imported."""
+ try:
+ _require_mt5()
+ return True
+ except MT5DependencyError:
+ return False
+
+
+def _require_mt5() -> ModuleType:
+ """Import the Windows-only ``MetaTrader5`` package or fail with an install hint."""
+ try:
+ import MetaTrader5 # type: ignore[import-not-found]
+ except ImportError as exc:
+ raise MT5DependencyError(
+ "MetaTrader5 is not installed (Windows-only). Install the extra with "
+ '`pip install "vibe-trading-ai[mt5]"` and run a local MT5 terminal.'
+ ) from exc
+ return MetaTrader5
+
+
+def _missing_fields(cfg: MT5Config) -> list[str]:
+ """Fields the connector cannot operate without (login pin is mandatory)."""
+ missing = []
+ if not cfg.login:
+ missing.append("login")
+ if not cfg.password:
+ missing.append("password")
+ if not cfg.server:
+ missing.append("server")
+ return missing
+
+
+def _public_config(cfg: MT5Config) -> dict[str, Any]:
+ """Redacted config for health/error payloads (never leaks secrets)."""
+ login_text = str(cfg.login) if cfg.login else ""
+ return {
+ "login": (login_text[:2] + "***") if login_text else "",
+ "password": "***redacted***" if cfg.password else "",
+ "server": cfg.server,
+ "terminal_path": cfg.terminal_path,
+ "profile": cfg.profile,
+ "environment": cfg.environment,
+ "is_demo": cfg.is_demo,
+ "symbol_suffix": cfg.symbol_suffix,
+ "deviation_points": cfg.deviation_points,
+ "max_order_volume": cfg.max_order_volume,
+ "max_order_notional_usd": cfg.max_order_notional_usd,
+ "paper_guard": GUARD_MARKER,
+ }
+
+
+#: The MetaTrader5 API is process-global; sessions must never interleave.
+_MT5_LOCK = threading.Lock()
+
+
+def _last_error(mt5: Any) -> str:
+ """Best-effort ``last_error()`` text for diagnostics."""
+ try:
+ return str(mt5.last_error())
+ except Exception: # noqa: BLE001 - diagnostics must never mask the real error
+ return "unknown"
+
+
+@contextmanager
+def _session(cfg: MT5Config) -> Iterator[Any]:
+ """Attach to the terminal, verify identity, yield the module, detach.
+
+ Raises:
+ MT5DependencyError: The ``MetaTrader5`` package is not installed.
+ MT5ConnectionError: The terminal is not running/reachable or the
+ account cannot be read.
+ MT5ProfileMismatchError: The terminal account's trade mode or login
+ does not match the selected profile (fail-closed, bidirectional).
+ """
+ mt5 = _require_mt5()
+ with _MT5_LOCK:
+ kwargs: dict[str, Any] = {
+ "login": cfg.login,
+ "password": cfg.password,
+ "server": cfg.server,
+ "timeout": int(cfg.timeout * 1000),
+ }
+ args = (cfg.terminal_path,) if cfg.terminal_path else ()
+ if not mt5.initialize(*args, **kwargs):
+ raise MT5ConnectionError(
+ f"MT5 initialize failed ({_last_error(mt5)}); is the MT5 terminal "
+ "installed, running, and logged in to the configured server?"
+ )
+ try:
+ account = mt5.account_info()
+ if account is None:
+ raise MT5ConnectionError(f"MT5 account_info unavailable ({_last_error(mt5)})")
+ _assert_profile(cfg, account, mt5)
+ yield mt5
+ finally:
+ try:
+ mt5.shutdown()
+ except Exception: # noqa: BLE001 - detach must never mask the result
+ pass
+
+
+def _assert_profile(cfg: MT5Config, account: Any, mt5: Any) -> None:
+ """Hard bidirectional identity guard, run inside every session.
+
+ Paper profiles require a DEMO account; live profiles require a REAL
+ account; contest accounts are rejected everywhere (fail-closed). The
+ configured login is pinned against the terminal's actual login.
+ """
+ trade_mode = getattr(account, "trade_mode", None)
+ demo_mode = getattr(mt5, "ACCOUNT_TRADE_MODE_DEMO", 0)
+ real_mode = getattr(mt5, "ACCOUNT_TRADE_MODE_REAL", 2)
+ if cfg.environment == "paper" and trade_mode != demo_mode:
+ raise MT5ProfileMismatchError(
+ f"paper profile {cfg.profile!r} requires a DEMO account, but the terminal "
+ f"is logged in to trade_mode={trade_mode!r} — refusing (fail-closed)."
+ )
+ if cfg.environment == "live" and trade_mode != real_mode:
+ raise MT5ProfileMismatchError(
+ f"live profile {cfg.profile!r} requires a REAL account, but the terminal "
+ f"is logged in to trade_mode={trade_mode!r} — refusing (fail-closed)."
+ )
+ terminal_login = getattr(account, "login", None)
+ if cfg.login and terminal_login is not None and int(terminal_login) != cfg.login:
+ raise MT5ProfileMismatchError(
+ f"login pin mismatch: profile is configured for a different account than "
+ f"the terminal's — refusing (fail-closed)."
+ )
+
+
+def _resolve_symbol(mt5: Any, cfg: MT5Config, symbol: str) -> str:
+ """Resolve a project symbol to the broker's Market Watch name.
+
+ Tries the configured suffix first, then the bare base, then discovers
+ suffixed variants via ``symbols_get`` (shortest match wins, which picks
+ ``EURUSDm`` over ``EURUSDz`` deterministically on Exness).
+ """
+ base = normalize_base(symbol)
+ if not base:
+ raise MT5ConfigError("symbol is required")
+ candidates = []
+ if cfg.symbol_suffix:
+ candidates.append(base + cfg.symbol_suffix)
+ candidates.append(base)
+ name = next((c for c in candidates if mt5.symbol_info(c) is not None), None)
+ if name is None:
+ matches = sorted(
+ (getattr(info, "name", "") for info in (mt5.symbols_get(group=f"{base}*") or ())),
+ key=len,
+ )
+ matches = [m for m in matches if m]
+ if not matches:
+ raise MT5ConfigError(
+ f"symbol {symbol!r} not offered by this broker (no match for {base}*)"
+ )
+ name = matches[0]
+ if not mt5.symbol_select(name, True):
+ raise MT5ConfigError(f"symbol {name!r} could not be selected in Market Watch")
+ return name
+
+
+def _tick_mid(mt5: Any, name: str) -> float | None:
+ """Mid price from the current tick, ``None`` when unpriceable."""
+ tick = mt5.symbol_info_tick(name)
+ if tick is None:
+ return None
+ bid = float(getattr(tick, "bid", 0.0) or 0.0)
+ ask = float(getattr(tick, "ask", 0.0) or 0.0)
+ if bid > 0 and ask > 0:
+ return (bid + ask) / 2.0
+ last = float(getattr(tick, "last", 0.0) or 0.0)
+ return last if last > 0 else None
+
+
+def _usd_contract_value(mt5: Any, cfg: MT5Config, name: str, lots: float) -> float | None:
+ """USD value of ``lots`` of broker symbol ``name``, ``None`` on any failure.
+
+ 1 lot == ``trade_contract_size`` units of the base currency. Quote-USD
+ pairs price via the tick mid; base-USD pairs are exact; crosses convert
+ the base through its ``<BASE>USD``/``USD<BASE>`` pair when the broker
+ offers one (suffix-aware). Unresolvable → ``None`` (fail-closed).
+ """
+ info = mt5.symbol_info(name)
+ if info is None:
+ return None
+ size = float(getattr(info, "trade_contract_size", 0.0) or 0.0)
+ if size <= 0 or lots <= 0:
+ return None
+ base = str(getattr(info, "currency_base", "") or "").upper()
+ profit = str(getattr(info, "currency_profit", "") or "").upper()
+ if base == "USD":
+ return lots * size
+ if profit == "USD":
+ mid = _tick_mid(mt5, name)
+ return lots * size * mid if mid is not None else None
+ # Cross: convert the base currency through a USD pair.
+ direct_candidates = [base + "USD" + cfg.symbol_suffix, base + "USD"] if cfg.symbol_suffix else [base + "USD"]
+ for conv in direct_candidates:
+ if mt5.symbol_info(conv) is not None:
+ mid = _tick_mid(mt5, conv)
+ return lots * size * mid if mid is not None else None
+ inverse_candidates = ["USD" + base + cfg.symbol_suffix, "USD" + base] if cfg.symbol_suffix else ["USD" + base]
+ for conv in inverse_candidates:
+ if mt5.symbol_info(conv) is not None:
+ mid = _tick_mid(mt5, conv)
+ return lots * size / mid if mid else None
+ return None
diff --git a/agent/src/trading/connectors/mt5/classification.py b/agent/src/trading/connectors/mt5/classification.py
new file mode 100644
index 000000000..3738e7b4e
--- /dev/null
+++ b/agent/src/trading/connectors/mt5/classification.py
@@ -0,0 +1,32 @@
+"""Curated read/write classification for MT5 SDK operations.
+
+Keys are the MetaTrader5 module functions the connector touches plus the
+connector's own public order methods. Anything not listed and not a known
+read resolves to WRITE (fail-closed) when the live gate consults this map.
+"""
+
+from __future__ import annotations
+
+from src.live.classification import ToolClass
+
+#: MT5 operation read/write catalog. ``order_check`` is pinned WRITE
+#: conservatively — it is only ever used inside the write path.
+MT5_TOOL_CLASS: dict[str, ToolClass] = {
+ # READ
+ "account_info": ToolClass.READ,
+ "positions_get": ToolClass.READ,
+ "orders_get": ToolClass.READ,
+ "history_deals_get": ToolClass.READ,
+ "symbol_info": ToolClass.READ,
+ "symbol_info_tick": ToolClass.READ,
+ "symbols_get": ToolClass.READ,
+ "copy_rates_from_pos": ToolClass.READ,
+ "copy_rates_range": ToolClass.READ,
+ # WRITE
+ "order_send": ToolClass.WRITE,
+ "order_check": ToolClass.WRITE,
+ "place_order": ToolClass.WRITE,
+ "cancel_order": ToolClass.WRITE,
+ "close_position": ToolClass.WRITE,
+ "modify_position": ToolClass.WRITE,
+}
diff --git a/agent/src/trading/connectors/mt5/orders.py b/agent/src/trading/connectors/mt5/orders.py
new file mode 100644
index 000000000..96f6a46d8
--- /dev/null
+++ b/agent/src/trading/connectors/mt5/orders.py
@@ -0,0 +1,407 @@
+"""MT5 order operations: sizing hook, place, cancel/close (risk-reducing).
+
+Validation runs before any SDK touch and every failure returns a fail-closed
+``{"status": "error", ...}`` payload. Connector-level size guards
+(``max_order_volume`` / ``max_order_notional_usd``) apply to demo AND live —
+defense-in-depth underneath the live mandate gate.
+
+Hedging note: MT5 accounts (Exness default) are usually HEDGING accounts — an
+opposite-side ``place_order`` OPENS a hedge, it does not close the existing
+position. Closing goes through :func:`cancel_order`/:func:`close_position`
+with the position ticket, which pins the deal to ``position=`` so it can only
+ever reduce exposure. ``src.live.runtime.flatten`` submits via the generic
+``place_order`` and therefore hedges rather than closes on MT5 — acceptable
+(net exposure to price moves is neutralized) but a ticket-pinned flatten is a
+documented follow-up.
+"""
+
+from __future__ import annotations
+
+import math
+from typing import Any
+
+from src.trading.connectors.mt5 import _client
+from src.trading.connectors.mt5._client import (
+ GUARD_MARKER,
+ MT5Config,
+ MT5ConfigError,
+ MT5ConnectionError,
+ MT5DependencyError,
+ MT5ProfileMismatchError,
+ _missing_fields,
+ _resolve_symbol,
+ _usd_contract_value,
+)
+
+_MT5_ERRORS = (MT5DependencyError, MT5ConfigError, MT5ConnectionError, MT5ProfileMismatchError)
+
+_ORDER_COMMENT = "vibe-trading"
+_ORDER_MAGIC = 862_001
+
+
+def quantity_notional_usd(config: MT5Config | None, symbol: str, quantity: float) -> float | None:
+ """USD notional of ``quantity`` LOTS of ``symbol`` — the live gate's sizing hook.
+
+ The gate (``src.live.sdk_order_gate._implied_notional``) treats this as
+ AUTHORITATIVE: MT5 quantities are lots (1 lot EURUSD == 100,000 EUR), so
+ ``quantity x quote`` would under-state notional ~contract-size-fold.
+ Returns ``None`` on any failure (→ fail-closed DENY upstream).
+ """
+ cfg = config or _client.load_config()
+ try:
+ with _client._session(cfg) as mt5:
+ name = _resolve_symbol(mt5, cfg, symbol)
+ return _usd_contract_value(mt5, cfg, name, float(quantity))
+ except Exception: # noqa: BLE001 - sizing must fail closed, never raise
+ return None
+
+
+def place_order(
+ config: MT5Config | None = None,
+ *,
+ symbol: str,
+ side: str,
+ quantity: float | str | None = None,
+ notional: float | str | None = None,
+ order_type: str = "market",
+ limit_price: float | str | None = None,
+ time_in_force: str = "day",
+) -> dict[str, Any]:
+ """Place a market or pending-limit order on the configured MT5 account.
+
+ Args:
+ config: Resolved connector config; loaded from disk when ``None``.
+ symbol: Project or broker symbol (``EUR/USD``, ``EURUSD``, ``EURUSDm``).
+ side: ``"buy"`` or ``"sell"``.
+ quantity: Size in LOTS. Exactly one of ``quantity``/``notional``.
+ notional: USD amount, converted to lots and floored to the symbol's
+ ``volume_step`` (never rounded up).
+ order_type: ``"market"`` or ``"limit"`` (limit → pending order).
+ limit_price: Required for limit orders.
+ time_in_force: ``"day"`` (default) or ``"gtc"`` — pending orders only.
+
+ Returns:
+ ``{"status": "ok", "order_id", ...}`` on ``TRADE_RETCODE_DONE``; a
+ fail-closed ``{"status": "error", "error": ...}`` payload otherwise.
+ """
+ cfg = config or _client.load_config()
+
+ clean_side = str(side or "").strip().lower()
+ if clean_side not in ("buy", "sell"):
+ return _order_error(cfg, "side must be 'buy' or 'sell'", symbol=symbol, side=side)
+
+ clean_type = str(order_type or "").strip().lower()
+ if clean_type not in ("market", "limit"):
+ return _order_error(cfg, "order_type must be 'market' or 'limit'", symbol=symbol, side=clean_side)
+
+ clean_symbol = str(symbol or "").strip().upper()
+ if not clean_symbol:
+ return _order_error(cfg, "symbol is required", symbol=symbol, side=clean_side)
+
+ has_qty = quantity is not None
+ has_notional = notional is not None
+ if has_qty == has_notional:
+ return _order_error(
+ cfg, "exactly one of quantity or notional is required", symbol=clean_symbol, side=clean_side
+ )
+ if clean_type == "limit" and limit_price is None:
+ return _order_error(cfg, "limit order requires limit_price", symbol=clean_symbol, side=clean_side)
+
+ missing = _missing_fields(cfg)
+ if missing:
+ return _order_error(
+ cfg, f"MT5 connector not configured: missing {', '.join(missing)}.", symbol=clean_symbol, side=clean_side
+ )
+
+ try:
+ with _client._session(cfg) as mt5:
+ name = _resolve_symbol(mt5, cfg, symbol)
+ info = mt5.symbol_info(name)
+ if info is None:
+ return _order_error(cfg, f"no symbol info for {name!r}", symbol=clean_symbol, side=clean_side)
+
+ volume = _sized_volume(mt5, cfg, name, info, quantity, notional)
+ if isinstance(volume, str): # sizing error message
+ return _order_error(cfg, volume, symbol=clean_symbol, side=clean_side)
+
+ guard_error = _size_guards(mt5, cfg, name, volume)
+ if guard_error is not None:
+ return _order_error(cfg, guard_error, symbol=clean_symbol, side=clean_side)
+
+ request = _build_request(
+ mt5, cfg, name, info,
+ side=clean_side, order_type=clean_type,
+ volume=volume, limit_price=limit_price, time_in_force=time_in_force,
+ )
+ if isinstance(request, str):
+ return _order_error(cfg, request, symbol=clean_symbol, side=clean_side)
+
+ check = mt5.order_check(request)
+ done = getattr(mt5, "TRADE_RETCODE_DONE", 10009)
+ check_code = getattr(check, "retcode", None)
+ if check is None or check_code not in (0, done):
+ comment = getattr(check, "comment", "no response") if check is not None else "no response"
+ return _order_error(
+ cfg,
+ f"MT5 order_check rejected the order (retcode={check_code}): {comment}",
+ symbol=clean_symbol, side=clean_side,
+ )
+
+ result = mt5.order_send(request)
+ return _order_result(
+ cfg, mt5, result,
+ symbol=clean_symbol, resolved_symbol=name, side=clean_side,
+ order_type=clean_type, volume=volume,
+ )
+ except _MT5_ERRORS as exc:
+ return _order_error(cfg, str(exc), symbol=clean_symbol, side=clean_side)
+
+
+def cancel_order(
+ config: MT5Config | None = None,
+ order_id: str = "",
+ *,
+ symbol: str | None = None,
+) -> dict[str, Any]:
+ """Cancel a pending order OR close an open position by ticket (risk-reducing).
+
+ MT5 separates pending orders from open positions; a single "cancel" ticket
+ id may name either. Both branches strictly reduce risk — removing a
+ resting order, or sending an opposite deal pinned to ``position=`` capped
+ at the position's own volume — which is why this path stays un-gated (but
+ live-audited) like every other connector's cancel.
+ """
+ cfg = config or _client.load_config()
+ try:
+ ticket = int(str(order_id).strip())
+ except (TypeError, ValueError):
+ return _order_error(cfg, f"MT5 cancel requires a numeric ticket, got {order_id!r}", symbol=symbol)
+
+ try:
+ with _client._session(cfg) as mt5:
+ pending = mt5.orders_get(ticket=ticket) or ()
+ if pending:
+ request = {
+ "action": getattr(mt5, "TRADE_ACTION_REMOVE", 8),
+ "order": ticket,
+ "comment": _ORDER_COMMENT,
+ }
+ result = mt5.order_send(request)
+ return _order_result(cfg, mt5, result, action="order_cancelled", order_ticket=ticket)
+
+ positions = mt5.positions_get(ticket=ticket) or ()
+ if positions:
+ return _close(mt5, cfg, positions[0], requested_volume=None)
+
+ return _order_error(cfg, f"no pending order or open position with ticket {ticket}")
+ except _MT5_ERRORS as exc:
+ return _order_error(cfg, str(exc), order_id=str(ticket))
+
+
+def close_position(
+ config: MT5Config | None = None,
+ position_id: int = 0,
+ *,
+ volume: float | None = None,
+) -> dict[str, Any]:
+ """Close (fully or partially) an open position by ticket."""
+ cfg = config or _client.load_config()
+ try:
+ ticket = int(position_id)
+ except (TypeError, ValueError):
+ return _order_error(cfg, f"close_position requires a numeric ticket, got {position_id!r}")
+ try:
+ with _client._session(cfg) as mt5:
+ positions = mt5.positions_get(ticket=ticket) or ()
+ if not positions:
+ return _order_error(cfg, f"no open position with ticket {ticket}")
+ return _close(mt5, cfg, positions[0], requested_volume=volume)
+ except _MT5_ERRORS as exc:
+ return _order_error(cfg, str(exc), position_id=str(ticket))
+
+
+# --------------------------------------------------------------------------- #
+# Internals #
+# --------------------------------------------------------------------------- #
+
+
+def _sized_volume(
+ mt5: Any, cfg: MT5Config, name: str, info: Any,
+ quantity: float | str | None, notional: float | str | None,
+) -> float | str:
+ """Resolve the order volume in lots, or return an error message string."""
+ volume_min = float(getattr(info, "volume_min", 0.01) or 0.01)
+ volume_max = float(getattr(info, "volume_max", 100.0) or 100.0)
+ step = float(getattr(info, "volume_step", 0.01) or 0.01)
+
+ if quantity is not None:
+ volume = float(quantity)
+ else:
+ unit_usd = _usd_contract_value(mt5, cfg, name, 1.0)
+ if unit_usd is None or unit_usd <= 0:
+ return f"cannot size {name!r} by notional: USD contract value unavailable (fail-closed)"
+ raw = float(notional) / unit_usd
+ # Floor to the volume step — a notional budget must never round UP.
+ volume = math.floor(raw / step + 1e-9) * step
+ volume = round(volume, 8)
+ if volume > volume_max:
+ volume = volume_max
+ if volume < volume_min:
+ return (
+ f"order volume {volume} lots is below the symbol minimum {volume_min} "
+ f"for {name!r}"
+ )
+ return volume
+
+
+def _size_guards(mt5: Any, cfg: MT5Config, name: str, volume: float) -> str | None:
+ """Connector-level per-order guards (demo AND live), fail-closed."""
+ if volume > cfg.max_order_volume:
+ return (
+ f"order volume {volume} lots exceeds the connector max_order_volume "
+ f"guard ({cfg.max_order_volume}); raise it in mt5.json if intended"
+ )
+ usd = _usd_contract_value(mt5, cfg, name, volume)
+ if usd is None:
+ return (
+ f"order for {name!r} could not be priced in USD, so the "
+ "max_order_notional_usd guard is unenforceable (fail-closed)"
+ )
+ if usd > cfg.max_order_notional_usd:
+ return (
+ f"order notional ~${usd:,.0f} exceeds the connector max_order_notional_usd "
+ f"guard (${cfg.max_order_notional_usd:,.0f}); raise it in mt5.json if intended"
+ )
+ return None
+
+
+def _build_request(
+ mt5: Any, cfg: MT5Config, name: str, info: Any,
+ *, side: str, order_type: str, volume: float,
+ limit_price: float | str | None, time_in_force: str,
+) -> dict[str, Any] | str:
+ """Build the ``order_send`` request dict, or return an error message string."""
+ request: dict[str, Any] = {
+ "symbol": name,
+ "volume": volume,
+ "magic": _ORDER_MAGIC,
+ "comment": _ORDER_COMMENT,
+ }
+ if order_type == "market":
+ tick = mt5.symbol_info_tick(name)
+ if tick is None:
+ return f"no tick data for {name!r}; cannot price a market order"
+ price = getattr(tick, "ask", None) if side == "buy" else getattr(tick, "bid", None)
+ if not price or float(price) <= 0:
+ return f"no {'ask' if side == 'buy' else 'bid'} price for {name!r}"
+ request.update(
+ {
+ "action": getattr(mt5, "TRADE_ACTION_DEAL", 1),
+ "type": getattr(mt5, "ORDER_TYPE_BUY", 0) if side == "buy" else getattr(mt5, "ORDER_TYPE_SELL", 1),
+ "price": float(price),
+ "deviation": cfg.deviation_points,
+ "type_filling": _filling_mode(mt5, info, pending=False),
+ }
+ )
+ else:
+ tif = str(time_in_force or "").strip().lower()
+ request.update(
+ {
+ "action": getattr(mt5, "TRADE_ACTION_PENDING", 5),
+ "type": (
+ getattr(mt5, "ORDER_TYPE_BUY_LIMIT", 2)
+ if side == "buy"
+ else getattr(mt5, "ORDER_TYPE_SELL_LIMIT", 3)
+ ),
+ "price": float(limit_price),
+ "type_time": getattr(mt5, "ORDER_TIME_GTC", 0) if tif == "gtc" else getattr(mt5, "ORDER_TIME_DAY", 1),
+ "type_filling": _filling_mode(mt5, info, pending=True),
+ }
+ )
+ return request
+
+
+def _filling_mode(mt5: Any, info: Any, *, pending: bool) -> int:
+ """Negotiate a filling mode from the symbol's allowed-modes bitmask."""
+ if pending:
+ return getattr(mt5, "ORDER_FILLING_RETURN", 2)
+ mask = int(getattr(info, "filling_mode", 0) or 0)
+ if mask & int(getattr(mt5, "SYMBOL_FILLING_IOC", 2)):
+ return getattr(mt5, "ORDER_FILLING_IOC", 1)
+ if mask & int(getattr(mt5, "SYMBOL_FILLING_FOK", 1)):
+ return getattr(mt5, "ORDER_FILLING_FOK", 0)
+ return getattr(mt5, "ORDER_FILLING_RETURN", 2)
+
+
+def _close(mt5: Any, cfg: MT5Config, position: Any, *, requested_volume: float | None) -> dict[str, Any]:
+ """Send an opposite deal pinned to the position ticket (risk-reducing only)."""
+ name = getattr(position, "symbol", "")
+ ticket = int(getattr(position, "ticket", 0) or 0)
+ position_volume = float(getattr(position, "volume", 0.0) or 0.0)
+ volume = position_volume if requested_volume is None else min(float(requested_volume), position_volume)
+ sell_type = getattr(mt5, "POSITION_TYPE_SELL", 1)
+ is_short = getattr(position, "type", 0) == sell_type
+ tick = mt5.symbol_info_tick(name)
+ if tick is None:
+ return _order_error(cfg, f"no tick data for {name!r}; cannot close position {ticket}")
+ price = getattr(tick, "ask", None) if is_short else getattr(tick, "bid", None)
+ if not price or float(price) <= 0:
+ return _order_error(cfg, f"no close price for {name!r} (position {ticket})")
+ request = {
+ "action": getattr(mt5, "TRADE_ACTION_DEAL", 1),
+ "symbol": name,
+ "position": ticket,
+ "volume": volume,
+ "type": getattr(mt5, "ORDER_TYPE_BUY", 0) if is_short else getattr(mt5, "ORDER_TYPE_SELL", 1),
+ "price": float(price),
+ "deviation": cfg.deviation_points,
+ "type_filling": _filling_mode(mt5, mt5.symbol_info(name), pending=False),
+ "magic": _ORDER_MAGIC,
+ "comment": _ORDER_COMMENT,
+ }
+ result = mt5.order_send(request)
+ return _order_result(cfg, mt5, result, action="position_closed", position=ticket, volume=volume)
+
+
+def _order_result(cfg: MT5Config, mt5: Any, result: Any, **extra: Any) -> dict[str, Any]:
+ """Interpret an ``order_send`` response, failing closed on any non-DONE retcode."""
+ if result is None:
+ return _order_error(cfg, f"MT5 order_send returned no result ({_client._last_error(mt5)})", **extra)
+ retcode = getattr(result, "retcode", None)
+ done = getattr(mt5, "TRADE_RETCODE_DONE", 10009)
+ partial = getattr(mt5, "TRADE_RETCODE_DONE_PARTIAL", 10010)
+ if retcode not in (done, partial):
+ comment = getattr(result, "comment", "")
+ return _order_error(cfg, f"MT5 rejected order (retcode={retcode}): {comment}", **extra)
+ payload: dict[str, Any] = {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_demo": cfg.is_demo,
+ "paper_guard": GUARD_MARKER,
+ "order_id": str(getattr(result, "order", "")),
+ "deal_id": str(getattr(result, "deal", "")),
+ "filled_volume": getattr(result, "volume", None),
+ "filled_price": getattr(result, "price", None),
+ "retcode": retcode,
+ }
+ if retcode == partial:
+ payload["partial"] = True
+ for key, value in extra.items():
+ if value is not None:
+ payload[key] = value
+ return payload
+
+
+def _order_error(cfg: MT5Config, message: str, **extra: Any) -> dict[str, Any]:
+ """Build a fail-closed error payload carrying profile/guard context."""
+ payload: dict[str, Any] = {
+ "status": "error",
+ "error": message,
+ "profile": cfg.profile,
+ "is_demo": cfg.is_demo,
+ "paper_guard": GUARD_MARKER,
+ }
+ for key, value in extra.items():
+ if value is not None:
+ payload[key] = value
+ return payload
diff --git a/agent/src/trading/connectors/mt5/profiles.py b/agent/src/trading/connectors/mt5/profiles.py
new file mode 100644
index 000000000..6aa1fc6ce
--- /dev/null
+++ b/agent/src/trading/connectors/mt5/profiles.py
@@ -0,0 +1,78 @@
+"""Built-in MetaTrader 5 connector profiles.
+
+"Paper" is the broker's DEMO MT5 account (e.g. an Exness demo) — MT5 has no
+separate sandbox API. Unlike key-scoped connectors the discriminator is hard:
+every session re-reads ``account_info().trade_mode`` from the terminal and
+rejects a paper profile attached to a real-money account (and vice versa;
+contest accounts are rejected everywhere). The order-placing profiles add
+``orders.place``; the live one is gated behind a mandate + kill switch.
+Requires Windows, the ``MetaTrader5`` extra, and a running logged-in terminal.
+"""
+
+from __future__ import annotations
+
+from src.trading.types import READ_CAPABILITIES, TradingProfile
+
+MT5_PROFILES: tuple[TradingProfile, ...] = (
+ TradingProfile(
+ id="mt5-paper-sdk",
+ connector="mt5",
+ label="MetaTrader 5 Demo · local terminal",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "paper"},
+ notes=(
+ "Reads a DEMO MT5 account through the local terminal (Windows-only "
+ "MetaTrader5 package). The terminal's trade_mode and login are "
+ "re-verified on every call; a real-money account is hard-rejected."
+ ),
+ ),
+ TradingProfile(
+ id="mt5-live-sdk-readonly",
+ connector="mt5",
+ label="MetaTrader 5 Live · Read-Only",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "live-readonly"},
+ notes=(
+ "Reads a REAL MT5 account only. Order placement is not exposed in "
+ "this profile; a demo account is hard-rejected (identity guard)."
+ ),
+ ),
+ TradingProfile(
+ id="mt5-paper-trade",
+ connector="mt5",
+ label="MetaTrader 5 Demo · Trading",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES + ("orders.place",),
+ readonly=False,
+ config={"profile": "paper"},
+ notes=(
+ "Places orders on a DEMO MT5 account (e.g. Exness demo). Connector "
+ "size guards (max_order_volume / max_order_notional_usd in mt5.json) "
+ "apply even on demo. Note: MT5 hedging accounts OPEN a hedge on an "
+ "opposite-side order; close positions by ticket via cancel."
+ ),
+ ),
+ TradingProfile(
+ id="mt5-live-trade",
+ connector="mt5",
+ label="MetaTrader 5 Live · Trading",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES + ("orders.place.requires_mandate",),
+ readonly=False,
+ config={"profile": "live"},
+ notes=(
+ "Places orders on a REAL MT5 account. Live order placement is gated "
+ "behind a user-defined mandate (forex/cfd instrument allowances, "
+ "lot-aware USD notional caps) and the kill switch, plus the "
+ "connector's own size guards."
+ ),
+ ),
+)
diff --git a/agent/src/trading/connectors/mt5/reads.py b/agent/src/trading/connectors/mt5/reads.py
new file mode 100644
index 000000000..524b3cbc1
--- /dev/null
+++ b/agent/src/trading/connectors/mt5/reads.py
@@ -0,0 +1,281 @@
+"""MT5 read operations: status, account, positions, orders, quote, history.
+
+Every read runs through :func:`_client._session` (identity guard included)
+and returns a fail-closed ``{"status": "error", ...}`` envelope instead of
+raising, so tools and CLI degrade cleanly when the SDK/terminal is absent.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+from typing import Any
+
+from src.trading.connectors.mt5 import _client
+from src.trading.connectors.mt5._client import (
+ GUARD_MARKER,
+ MT5Config,
+ MT5ConfigError,
+ MT5ConnectionError,
+ MT5DependencyError,
+ MT5ProfileMismatchError,
+ _missing_fields,
+ _public_config,
+ _resolve_symbol,
+ _usd_contract_value,
+)
+
+_MT5_ERRORS = (MT5DependencyError, MT5ConfigError, MT5ConnectionError, MT5ProfileMismatchError)
+
+#: Canonical period token → MetaTrader5 timeframe constant name. Resolved via
+#: ``getattr`` on the module so fakes only need the integers. NOTE ``1m``
+#: (minute) and ``1M`` (month) differ by case, matching the other connectors.
+_TIMEFRAME_MAP = {
+ "1m": "TIMEFRAME_M1", "5m": "TIMEFRAME_M5", "15m": "TIMEFRAME_M15",
+ "30m": "TIMEFRAME_M30", "1h": "TIMEFRAME_H1", "4h": "TIMEFRAME_H4",
+ "1d": "TIMEFRAME_D1", "1w": "TIMEFRAME_W1", "1M": "TIMEFRAME_MN1",
+}
+
+
+def _envelope(cfg: MT5Config, **extra: Any) -> dict[str, Any]:
+ """Common payload header stamped on every read result."""
+ payload: dict[str, Any] = {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_demo": cfg.is_demo,
+ "paper_guard": GUARD_MARKER,
+ }
+ payload.update(extra)
+ return payload
+
+
+def _error(cfg: MT5Config, message: str, **extra: Any) -> dict[str, Any]:
+ """Fail-closed error payload carrying profile/guard context."""
+ payload = _envelope(cfg, **extra)
+ payload["status"] = "error"
+ payload["error"] = message
+ return payload
+
+
+def check_status(config: MT5Config | None = None) -> dict[str, Any]:
+ """Check SDK readiness, config completeness, and terminal/account identity."""
+ cfg = config or _client.load_config()
+ report: dict[str, Any] = {
+ "status": "ok",
+ "config": _public_config(cfg),
+ "sdk": {"package": "MetaTrader5", "installed": _client.mt5_available()},
+ "paper_guard": GUARD_MARKER,
+ }
+ missing = _missing_fields(cfg)
+ if missing:
+ report["status"] = "error"
+ report["error"] = f"MT5 connector not configured: missing {', '.join(missing)}."
+ return report
+ if not report["sdk"]["installed"]:
+ report["status"] = "error"
+ report["error"] = (
+ "Optional dependency missing: install with `pip install \"vibe-trading-ai[mt5]\"` "
+ "(Windows-only; requires a local MT5 terminal)."
+ )
+ return report
+ try:
+ with _client._session(cfg) as mt5:
+ account = mt5.account_info()
+ report["account"] = {
+ "login": int(getattr(account, "login", 0) or 0),
+ "server": getattr(account, "server", ""),
+ "currency": getattr(account, "currency", ""),
+ "leverage": getattr(account, "leverage", None),
+ "balance": getattr(account, "balance", None),
+ "equity": getattr(account, "equity", None),
+ "trade_mode": getattr(account, "trade_mode", None),
+ "is_demo": cfg.is_demo,
+ }
+ except _MT5_ERRORS as exc:
+ report["status"] = "error"
+ report["error"] = str(exc)
+ return report
+
+
+def get_account_snapshot(config: MT5Config | None = None) -> dict[str, Any]:
+ """Fetch account balance/equity/margin for the configured account."""
+ cfg = config or _client.load_config()
+ try:
+ with _client._session(cfg) as mt5:
+ account = mt5.account_info()
+ payload = {
+ "login": int(getattr(account, "login", 0) or 0),
+ "name": getattr(account, "name", ""),
+ "server": getattr(account, "server", ""),
+ "currency": getattr(account, "currency", ""),
+ "balance": getattr(account, "balance", None),
+ "equity": getattr(account, "equity", None),
+ "margin": getattr(account, "margin", None),
+ "margin_free": getattr(account, "margin_free", None),
+ "margin_level": getattr(account, "margin_level", None),
+ "leverage": getattr(account, "leverage", None),
+ "trade_mode": getattr(account, "trade_mode", None),
+ "is_demo": cfg.is_demo,
+ }
+ except _MT5_ERRORS as exc:
+ return _error(cfg, str(exc))
+ return _envelope(cfg, account=payload)
+
+
+def get_positions(config: MT5Config | None = None) -> dict[str, Any]:
+ """Fetch open positions with a USD ``market_value`` per row.
+
+ ``market_value`` is ``None`` when the position cannot be priced in USD —
+ the live gate's exposure math treats that as unparseable and fails closed
+ rather than under-counting exposure.
+ """
+ cfg = config or _client.load_config()
+ try:
+ with _client._session(cfg) as mt5:
+ sell_type = getattr(mt5, "POSITION_TYPE_SELL", 1)
+ rows = []
+ for pos in mt5.positions_get() or ():
+ symbol = getattr(pos, "symbol", "")
+ rows.append(
+ {
+ "ticket": getattr(pos, "ticket", None),
+ "symbol": symbol,
+ "side": "sell" if getattr(pos, "type", 0) == sell_type else "buy",
+ "volume": getattr(pos, "volume", None),
+ "price_open": getattr(pos, "price_open", None),
+ "price_current": getattr(pos, "price_current", None),
+ "sl": getattr(pos, "sl", None),
+ "tp": getattr(pos, "tp", None),
+ "swap": getattr(pos, "swap", None),
+ "profit": getattr(pos, "profit", None),
+ "time": getattr(pos, "time", None),
+ "market_value": _usd_contract_value(
+ mt5, cfg, symbol, float(getattr(pos, "volume", 0.0) or 0.0)
+ ),
+ }
+ )
+ except _MT5_ERRORS as exc:
+ return _error(cfg, str(exc))
+ return _envelope(cfg, positions=rows)
+
+
+def get_open_orders(config: MT5Config | None = None, *, include_executions: bool = False) -> dict[str, Any]:
+ """Fetch pending orders (open positions are a separate read) and, optionally, recent deals."""
+ cfg = config or _client.load_config()
+ try:
+ with _client._session(cfg) as mt5:
+ rows = []
+ for order in mt5.orders_get() or ():
+ rows.append(
+ {
+ "order_id": str(getattr(order, "ticket", "")),
+ "symbol": getattr(order, "symbol", ""),
+ "order_type": getattr(order, "type", None),
+ "volume": getattr(order, "volume_initial", None),
+ "volume_current": getattr(order, "volume_current", None),
+ "price_open": getattr(order, "price_open", None),
+ "sl": getattr(order, "sl", None),
+ "tp": getattr(order, "tp", None),
+ "time_setup": getattr(order, "time_setup", None),
+ "state": getattr(order, "state", None),
+ }
+ )
+ executions = None
+ if include_executions:
+ now = datetime.now(timezone.utc)
+ deals = mt5.history_deals_get(now - timedelta(days=7), now) or ()
+ executions = [
+ {
+ "deal_id": str(getattr(deal, "ticket", "")),
+ "order_id": str(getattr(deal, "order", "")),
+ "symbol": getattr(deal, "symbol", ""),
+ "volume": getattr(deal, "volume", None),
+ "price": getattr(deal, "price", None),
+ "profit": getattr(deal, "profit", None),
+ "time": getattr(deal, "time", None),
+ }
+ for deal in deals
+ ]
+ except _MT5_ERRORS as exc:
+ return _error(cfg, str(exc))
+ result = _envelope(cfg, open_orders=rows)
+ if include_executions:
+ result["executions"] = executions
+ return result
+
+
+def get_quote(symbol: str, *, config: MT5Config | None = None, **_: Any) -> dict[str, Any]:
+ """Fetch the current tick for ``symbol`` (suffix-aware broker resolution).
+
+ ``last`` is omitted when the terminal reports 0 (common on forex ticks) so
+ the live gate's quote parser falls through to bid/ask instead of a zero.
+ """
+ cfg = config or _client.load_config()
+ clean = str(symbol or "").strip().upper()
+ try:
+ with _client._session(cfg) as mt5:
+ name = _resolve_symbol(mt5, cfg, symbol)
+ tick = mt5.symbol_info_tick(name)
+ if tick is None:
+ return _error(cfg, f"no tick data for {name!r}", symbol=clean)
+ quote: dict[str, Any] = {
+ "bid": getattr(tick, "bid", None),
+ "ask": getattr(tick, "ask", None),
+ "time": getattr(tick, "time", None),
+ }
+ last = float(getattr(tick, "last", 0.0) or 0.0)
+ if last > 0:
+ quote["last"] = last
+ info = mt5.symbol_info(name)
+ if info is not None:
+ quote["spread"] = getattr(info, "spread", None)
+ except _MT5_ERRORS as exc:
+ return _error(cfg, str(exc), symbol=clean)
+ return _envelope(cfg, symbol=clean, resolved_symbol=name, quote=quote)
+
+
+def get_historical_bars(
+ symbol: str,
+ *,
+ config: MT5Config | None = None,
+ period: str = "1d",
+ limit: int = 90,
+ **_: Any,
+) -> dict[str, Any]:
+ """Fetch recent OHLCV bars from the terminal's local history."""
+ cfg = config or _client.load_config()
+ clean = str(symbol or "").strip().upper()
+ timeframe_name = _TIMEFRAME_MAP.get(period.strip(), "TIMEFRAME_D1")
+ try:
+ with _client._session(cfg) as mt5:
+ name = _resolve_symbol(mt5, cfg, symbol)
+ timeframe = getattr(mt5, timeframe_name)
+ rates = mt5.copy_rates_from_pos(name, timeframe, 0, int(limit))
+ bars = [_rate_to_dict(rate) for rate in (rates if rates is not None else ())]
+ except _MT5_ERRORS as exc:
+ return _error(cfg, str(exc), symbol=clean)
+ return _envelope(
+ cfg, symbol=clean, resolved_symbol=name, period=period,
+ timeframe=timeframe_name, bars=bars,
+ )
+
+
+def _rate_to_dict(rate: Any) -> dict[str, Any]:
+ """Map one rates row (numpy structured row, mapping, or object) defensively."""
+
+ def _get(key: str) -> Any:
+ try:
+ return rate[key] # numpy structured rows and mappings
+ except (TypeError, KeyError, IndexError, ValueError):
+ return getattr(rate, key, None)
+
+ volume = _get("tick_volume")
+ return {
+ "time": _get("time"),
+ "open": _get("open"),
+ "high": _get("high"),
+ "low": _get("low"),
+ "close": _get("close"),
+ "volume": volume,
+ "spread": _get("spread"),
+ "real_volume": _get("real_volume"),
+ }
diff --git a/agent/src/trading/connectors/mt5/sdk.py b/agent/src/trading/connectors/mt5/sdk.py
new file mode 100644
index 000000000..11e9b4599
--- /dev/null
+++ b/agent/src/trading/connectors/mt5/sdk.py
@@ -0,0 +1,65 @@
+"""MT5 connector facade — the module ``service._sdk_module("mt5")`` imports.
+
+Re-exports the full duck-typed ``broker_sdk`` surface from the split
+implementation modules (kept under the repo's file-size ceiling). Tests
+monkeypatch one seam — ``_client._require_mt5`` — and the whole connector
+runs against the injected fake.
+"""
+
+from __future__ import annotations
+
+from src.trading.connectors.mt5._client import (
+ CONFIG_FILENAME,
+ GUARD_MARKER,
+ PROFILE_ENVIRONMENTS,
+ MT5Config,
+ MT5ConfigError,
+ MT5ConnectionError,
+ MT5DependencyError,
+ MT5ProfileMismatchError,
+ build_config,
+ config_path,
+ load_config,
+ mt5_available,
+ save_config,
+)
+from src.trading.connectors.mt5.orders import (
+ cancel_order,
+ close_position,
+ place_order,
+ quantity_notional_usd,
+)
+from src.trading.connectors.mt5.reads import (
+ check_status,
+ get_account_snapshot,
+ get_historical_bars,
+ get_open_orders,
+ get_positions,
+ get_quote,
+)
+
+__all__ = [
+ "CONFIG_FILENAME",
+ "GUARD_MARKER",
+ "PROFILE_ENVIRONMENTS",
+ "MT5Config",
+ "MT5ConfigError",
+ "MT5ConnectionError",
+ "MT5DependencyError",
+ "MT5ProfileMismatchError",
+ "build_config",
+ "config_path",
+ "load_config",
+ "mt5_available",
+ "save_config",
+ "cancel_order",
+ "close_position",
+ "place_order",
+ "quantity_notional_usd",
+ "check_status",
+ "get_account_snapshot",
+ "get_historical_bars",
+ "get_open_orders",
+ "get_positions",
+ "get_quote",
+]
diff --git a/agent/src/trading/connectors/mt5/symbols.py b/agent/src/trading/connectors/mt5/symbols.py
new file mode 100644
index 000000000..172d76f70
--- /dev/null
+++ b/agent/src/trading/connectors/mt5/symbols.py
@@ -0,0 +1,76 @@
+"""Pure MT5 symbol normalization + mandate classification (no SDK import).
+
+Broker symbol resolution (suffix discovery against a live terminal) lives in
+``_client``; this module is the terminal-free half the order gate uses, so it
+must stay importable and correct on any platform.
+"""
+
+from __future__ import annotations
+
+from src.live.mandate.model import AssetClass, InstrumentType
+
+#: ISO-4217 codes accepted as halves of a spot forex pair. Deliberately
+#: EXCLUDES metals (XAU/XAG/XPT/XPD): metal symbols classify as CFD so the
+#: mandate admits them only via an explicit ``"cfd"`` instrument allowance.
+_CURRENCIES: frozenset[str] = frozenset(
+ {
+ "USD", "EUR", "GBP", "JPY", "CHF", "AUD", "NZD", "CAD",
+ "SEK", "NOK", "DKK", "PLN", "CZK", "HUF", "TRY", "ZAR",
+ "MXN", "SGD", "HKD", "CNH", "CNY", "THB", "ILS", "RON",
+ "INR", "IDR", "KRW", "BRL", "CLP", "COP", "AED", "SAR",
+ }
+)
+
+#: Longest broker account-type suffix still treated as a suffix ("m", "z",
+#: "c", "raw", ".r", "micro" is NOT — 5 chars means a different instrument).
+_MAX_SUFFIX_LEN = 4
+
+
+def normalize_base(symbol: str) -> str:
+ """Collapse ``EUR/USD`` / ``eur-usd`` / ``EURUSD.FX`` to ``EURUSD``.
+
+ Uppercases and strips separators plus the project's ``.FX`` market tag.
+ Broker suffixes are preserved (``EURUSDm`` → ``EURUSDM``); stripping them
+ is :func:`split_suffix`'s job.
+ """
+ token = symbol.strip().upper()
+ if token.endswith(".FX"):
+ token = token[: -len(".FX")]
+ for separator in ("/", "-", "_", " "):
+ token = token.replace(separator, "")
+ return token
+
+
+def split_suffix(token: str) -> tuple[str, str]:
+ """Split a broker account-type suffix off a normalized token.
+
+ ``EURUSDM`` → ``("EURUSD", "M")`` when the first six characters form a
+ currency pair and the remainder is short enough to be a suffix; anything
+ else returns ``(token, "")`` unchanged.
+ """
+ if len(token) <= 6 or len(token) > 6 + _MAX_SUFFIX_LEN:
+ return token, ""
+ base, tail = token[:6], token[6:]
+ if base[:3] in _CURRENCIES and base[3:] in _CURRENCIES:
+ return base, tail
+ return token, ""
+
+
+def is_forex_pair(token: str) -> bool:
+ """True when ``token`` (optionally broker-suffixed) is a currency pair."""
+ base, _ = split_suffix(token)
+ return len(base) == 6 and base[:3] in _CURRENCIES and base[3:] in _CURRENCIES
+
+
+def classify_mt5_symbol(symbol: str) -> tuple[InstrumentType, AssetClass | None]:
+ """Map an MT5 symbol to its mandate ``(InstrumentType, AssetClass)``.
+
+ Currency pairs (including Exness-style suffixed forms) classify as
+ ``(FOREX, FOREX)``. Everything else — metals, index/energy/crypto CFDs,
+ stock CFDs, unrecognized strings — classifies as ``(CFD, None)``:
+ fail-safe, because CFD has no asset-class bucket and is admitted only when
+ the mandate explicitly lists ``"cfd"`` in ``allowed_instruments``.
+ """
+ if is_forex_pair(normalize_base(symbol)):
+ return InstrumentType.FOREX, AssetClass.FOREX
+ return InstrumentType.CFD, None
diff --git a/agent/src/trading/profiles.py b/agent/src/trading/profiles.py
index 5aa795209..10a3faf19 100644
--- a/agent/src/trading/profiles.py
+++ b/agent/src/trading/profiles.py
@@ -12,6 +12,7 @@ from src.trading.connectors.dhan.profiles import DHAN_PROFILES
from src.trading.connectors.futu.profiles import FUTU_PROFILES
from src.trading.connectors.ibkr.profiles import IBKR_PROFILES
from src.trading.connectors.longbridge.profiles import LONGBRIDGE_PROFILES
+from src.trading.connectors.mt5.profiles import MT5_PROFILES
from src.trading.connectors.okx.profiles import OKX_PROFILES
from src.trading.connectors.robinhood.profiles import ROBINHOOD_PROFILES
from src.trading.connectors.shoonya.profiles import SHOONYA_PROFILES
@@ -34,6 +35,7 @@ BUILTIN_PROFILES: tuple[TradingProfile, ...] = (
*DHAN_PROFILES,
*SHOONYA_PROFILES,
*TRADING212_PROFILES,
+ *MT5_PROFILES,
)
diff --git a/agent/src/trading/service.py b/agent/src/trading/service.py
index 3cc7ef873..8795b3dc6 100644
--- a/agent/src/trading/service.py
+++ b/agent/src/trading/service.py
@@ -23,6 +23,7 @@ _SDK_CONNECTOR_MODULES = {
"dhan": "src.trading.connectors.dhan.sdk",
"shoonya": "src.trading.connectors.shoonya.sdk",
"trading212": "src.trading.connectors.trading212.sdk",
+ "mt5": "src.trading.connectors.mt5.sdk",
}
@@ -200,6 +201,9 @@ def get_history(
#: Connector → (instrument type, fixed asset class | None). ``None`` asset class
#: means "infer from the symbol's market" (multi-market equity connectors).
+#: ``mt5`` is deliberately absent: its symbols split into forex pairs vs CFDs,
+#: so classification is per-symbol via ``classify_mt5_symbol`` (see
+#: ``_order_classification``).
_CONNECTOR_INSTRUMENT = {
"okx": ("crypto", "crypto"),
"binance": ("crypto", "crypto"),
@@ -223,6 +227,13 @@ def _order_classification(connector: str, symbol: str):
"""
from src.live.mandate.model import AssetClass, InstrumentType
+ if connector == "mt5":
+ from src.trading.connectors.mt5.symbols import classify_mt5_symbol
+
+ # Forex pairs → (FOREX, FOREX); metals/indices/anything else → (CFD,
+ # None), which the mandate admits only via an explicit "cfd" allowance.
+ return classify_mt5_symbol(symbol)
+
instrument_name, asset_name = _CONNECTOR_INSTRUMENT.get(connector, ("equity", None))
instrument = InstrumentType(instrument_name)
if asset_name is not None:
diff --git a/agent/tests/test_mt5_connector.py b/agent/tests/test_mt5_connector.py
new file mode 100644
index 000000000..c9dc86346
--- /dev/null
+++ b/agent/tests/test_mt5_connector.py
@@ -0,0 +1,812 @@
+"""MetaTrader 5 connector tests (Exness-style brokers, Windows-only SDK).
+
+Mirrors ``test_sdk_connectors.py`` conventions: the real ``MetaTrader5``
+package is never imported (it does not install on CI's ubuntu runner) — every
+test drives the connector through a ``FakeMT5`` namespace injected at the
+single ``_client._require_mt5`` seam. Symbol classification is pure and needs
+no fake at all.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from src.live.mandate.model import AssetClass, InstrumentType
+from src.trading.connectors.mt5.symbols import (
+ classify_mt5_symbol,
+ is_forex_pair,
+ normalize_base,
+ split_suffix,
+)
+
+pytestmark = pytest.mark.unit
+
+
+# --------------------------------------------------------------------------- #
+# FakeMT5 — stands in for the Windows-only MetaTrader5 package #
+# --------------------------------------------------------------------------- #
+
+
+def _symbol(
+ name: str,
+ *,
+ base: str,
+ profit: str,
+ contract_size: float = 100_000.0,
+ volume_min: float = 0.01,
+ volume_max: float = 100.0,
+ volume_step: float = 0.01,
+ filling_mode: int = 3, # FOK|IOC bitmask
+ spread: int = 6,
+) -> SimpleNamespace:
+ return SimpleNamespace(
+ name=name,
+ currency_base=base,
+ currency_profit=profit,
+ trade_contract_size=contract_size,
+ volume_min=volume_min,
+ volume_max=volume_max,
+ volume_step=volume_step,
+ filling_mode=filling_mode,
+ spread=spread,
+ )
+
+
+class FakeMT5:
+ """Configurable in-memory stand-in exposing the MetaTrader5 module surface."""
+
+ ACCOUNT_TRADE_MODE_DEMO = 0
+ ACCOUNT_TRADE_MODE_CONTEST = 1
+ ACCOUNT_TRADE_MODE_REAL = 2
+ TRADE_ACTION_DEAL = 1
+ TRADE_ACTION_PENDING = 5
+ TRADE_ACTION_SLTP = 6
+ TRADE_ACTION_REMOVE = 8
+ ORDER_TYPE_BUY = 0
+ ORDER_TYPE_SELL = 1
+ ORDER_TYPE_BUY_LIMIT = 2
+ ORDER_TYPE_SELL_LIMIT = 3
+ POSITION_TYPE_BUY = 0
+ POSITION_TYPE_SELL = 1
+ ORDER_TIME_GTC = 0
+ ORDER_TIME_DAY = 1
+ ORDER_FILLING_FOK = 0
+ ORDER_FILLING_IOC = 1
+ ORDER_FILLING_RETURN = 2
+ SYMBOL_FILLING_FOK = 1
+ SYMBOL_FILLING_IOC = 2
+ TRADE_RETCODE_DONE = 10009
+ TRADE_RETCODE_DONE_PARTIAL = 10010
+ TIMEFRAME_M1 = 1
+ TIMEFRAME_M5 = 5
+ TIMEFRAME_M15 = 15
+ TIMEFRAME_M30 = 30
+ TIMEFRAME_H1 = 16385
+ TIMEFRAME_H4 = 16388
+ TIMEFRAME_D1 = 16408
+ TIMEFRAME_W1 = 32769
+ TIMEFRAME_MN1 = 49153
+
+ def __init__(self) -> None:
+ self.initialize_result = True
+ self.initialize_calls: list[dict[str, Any]] = []
+ self.shutdown_calls = 0
+ self.account = SimpleNamespace(
+ login=12345,
+ trade_mode=self.ACCOUNT_TRADE_MODE_DEMO,
+ balance=10_000.0,
+ equity=10_050.0,
+ margin=120.0,
+ margin_free=9_930.0,
+ margin_level=8375.0,
+ leverage=200,
+ currency="USD",
+ server="Exness-MT5Trial8",
+ name="Demo User",
+ )
+ self.symbols: dict[str, SimpleNamespace] = {
+ "EURUSDm": _symbol("EURUSDm", base="EUR", profit="USD"),
+ "USDJPYm": _symbol("USDJPYm", base="USD", profit="JPY"),
+ "EURJPYm": _symbol("EURJPYm", base="EUR", profit="JPY"),
+ "XAUUSDm": _symbol("XAUUSDm", base="XAU", profit="USD", contract_size=100.0),
+ }
+ self.ticks: dict[str, SimpleNamespace] = {
+ "EURUSDm": SimpleNamespace(bid=1.0799, ask=1.0801, last=0.0, time=1_750_000_000),
+ "USDJPYm": SimpleNamespace(bid=156.10, ask=156.14, last=0.0, time=1_750_000_000),
+ "XAUUSDm": SimpleNamespace(bid=2399.5, ask=2400.5, last=0.0, time=1_750_000_000),
+ }
+ self.positions: list[SimpleNamespace] = []
+ self.pending_orders: list[SimpleNamespace] = []
+ self.deals: list[SimpleNamespace] = []
+ self.rates: dict[str, list[dict[str, Any]]] = {}
+ self.rates_calls: list[tuple[str, int, int, int]] = []
+ self.order_check_requests: list[dict[str, Any]] = []
+ self.order_check_result: Any = SimpleNamespace(retcode=0, comment="ok")
+ self.order_send_requests: list[dict[str, Any]] = []
+ self.order_send_result: Any = SimpleNamespace(
+ retcode=self.TRADE_RETCODE_DONE,
+ order=424242,
+ deal=515151,
+ volume=0.05,
+ price=1.0801,
+ comment="done",
+ )
+ self.last_error_value: tuple[int, str] = (1, "Success")
+
+ # -- lifecycle ----------------------------------------------------------
+ def initialize(self, *args: Any, **kwargs: Any) -> bool:
+ self.initialize_calls.append({"args": args, "kwargs": kwargs})
+ return self.initialize_result
+
+ def shutdown(self) -> None:
+ self.shutdown_calls += 1
+
+ def last_error(self) -> tuple[int, str]:
+ return self.last_error_value
+
+ # -- account/reads ------------------------------------------------------
+ def account_info(self) -> Any:
+ return self.account
+
+ def positions_get(self, ticket: int | None = None, **_: Any) -> tuple | None:
+ rows = self.positions
+ if ticket is not None:
+ rows = [p for p in rows if p.ticket == ticket]
+ return tuple(rows)
+
+ def orders_get(self, ticket: int | None = None, **_: Any) -> tuple | None:
+ rows = self.pending_orders
+ if ticket is not None:
+ rows = [o for o in rows if o.ticket == ticket]
+ return tuple(rows)
+
+ def history_deals_get(self, *_args: Any, **_kwargs: Any) -> tuple:
+ return tuple(self.deals)
+
+ def symbol_info(self, name: str) -> Any:
+ return self.symbols.get(name)
+
+ def symbol_info_tick(self, name: str) -> Any:
+ return self.ticks.get(name)
+
+ def symbol_select(self, name: str, enable: bool = True) -> bool:
+ return name in self.symbols
+
+ def symbols_get(self, group: str | None = None) -> tuple:
+ if not group:
+ return tuple(self.symbols.values())
+ prefix = group.strip("*")
+ return tuple(info for name, info in self.symbols.items() if name.upper().startswith(prefix.upper()))
+
+ def copy_rates_from_pos(self, name: str, timeframe: int, start: int, count: int):
+ self.rates_calls.append((name, timeframe, start, count))
+ return self.rates.get(name)
+
+ # -- orders --------------------------------------------------------------
+ def order_check(self, request: dict[str, Any]) -> Any:
+ self.order_check_requests.append(dict(request))
+ return self.order_check_result
+
+ def order_send(self, request: dict[str, Any]) -> Any:
+ self.order_send_requests.append(dict(request))
+ return self.order_send_result
+
+
+def fake_mt5(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> FakeMT5:
+ from src.trading.connectors.mt5 import _client
+
+ fake = FakeMT5()
+ monkeypatch.setattr(_client, "_require_mt5", lambda: fake)
+ monkeypatch.setattr(_client, "get_runtime_root", lambda: tmp_path)
+ return fake
+
+
+def _paper_config(**extra: Any):
+ from src.trading.connectors.mt5._client import MT5Config
+
+ payload: dict[str, Any] = {
+ "login": 12345,
+ "password": "hunter2secret",
+ "server": "Exness-MT5Trial8",
+ "symbol_suffix": "m",
+ "profile": "paper",
+ }
+ payload.update(extra)
+ return MT5Config.from_mapping(payload)
+
+
+# --------------------------------------------------------------------------- #
+# Pure symbol classification (no SDK) #
+# --------------------------------------------------------------------------- #
+
+
+class TestNormalizeBase:
+ @pytest.mark.parametrize(
+ ("raw", "expected"),
+ [
+ ("EUR/USD", "EURUSD"),
+ ("eur-usd", "EURUSD"),
+ ("EUR USD", "EURUSD"),
+ ("EURUSD.FX", "EURUSD"),
+ ("eurusd", "EURUSD"),
+ ("XAU/USD", "XAUUSD"),
+ ("EURUSDm", "EURUSDM"),
+ ],
+ )
+ def test_normalizes(self, raw: str, expected: str) -> None:
+ assert normalize_base(raw) == expected
+
+ def test_blank_stays_blank(self) -> None:
+ assert normalize_base(" ") == ""
+
+
+class TestSplitSuffix:
+ def test_splits_broker_suffix(self) -> None:
+ assert split_suffix("EURUSDM") == ("EURUSD", "M")
+
+ def test_no_suffix(self) -> None:
+ assert split_suffix("EURUSD") == ("EURUSD", "")
+
+ def test_long_tail_not_a_suffix(self) -> None:
+ # More than 4 trailing chars is a different instrument, not a suffix.
+ assert split_suffix("EURUSDMICRO") == ("EURUSDMICRO", "")
+
+ def test_metal_prefix_never_splits(self) -> None:
+ # XAU is not an ISO currency here, so XAUUSDM must not be treated as
+ # a suffixed forex pair.
+ assert split_suffix("XAUUSDM") == ("XAUUSDM", "")
+
+
+class TestIsForexPair:
+ @pytest.mark.parametrize("token", ["EURUSD", "USDJPY", "GBPAUD", "EURUSDM"])
+ def test_true_for_currency_pairs(self, token: str) -> None:
+ assert is_forex_pair(token)
+
+ @pytest.mark.parametrize("token", ["XAUUSD", "US30", "USTEC", "BTCUSD", "", "AAPL"])
+ def test_false_for_everything_else(self, token: str) -> None:
+ assert not is_forex_pair(token)
+
+
+class TestClassifyMt5Symbol:
+ @pytest.mark.parametrize("symbol", ["EUR/USD", "EURUSD", "EURUSDm", "eurusd", "USDJPY"])
+ def test_forex_pairs(self, symbol: str) -> None:
+ assert classify_mt5_symbol(symbol) == (InstrumentType.FOREX, AssetClass.FOREX)
+
+ @pytest.mark.parametrize("symbol", ["XAUUSD", "XAUUSDm", "US30", "USTEC", "BTCUSD", "DE40"])
+ def test_everything_else_is_cfd(self, symbol: str) -> None:
+ # Fail-safe: unrecognized symbols classify as CFD, which the mandate
+ # admits only when "cfd" is explicitly allowed.
+ assert classify_mt5_symbol(symbol) == (InstrumentType.CFD, None)
+
+ def test_blank_is_cfd(self) -> None:
+ assert classify_mt5_symbol("") == (InstrumentType.CFD, None)
+
+
+# --------------------------------------------------------------------------- #
+# Config + availability + redaction #
+# --------------------------------------------------------------------------- #
+
+
+class TestConfig:
+ def test_from_mapping_defaults(self) -> None:
+ from src.trading.connectors.mt5._client import MT5Config
+
+ cfg = MT5Config.from_mapping({})
+ assert cfg.profile == "paper"
+ assert cfg.environment == "paper"
+ assert cfg.is_demo is True
+ assert cfg.login == 0
+ assert cfg.deviation_points == 20
+ assert cfg.max_order_volume == pytest.approx(1.0)
+ assert cfg.max_order_notional_usd == pytest.approx(10_000.0)
+
+ def test_from_mapping_rejects_unknown_profile(self) -> None:
+ from src.trading.connectors.mt5._client import MT5Config, MT5ConfigError
+
+ with pytest.raises(MT5ConfigError):
+ MT5Config.from_mapping({"profile": "yolo"})
+
+ def test_live_profiles_map_to_live_environment(self) -> None:
+ from src.trading.connectors.mt5._client import MT5Config
+
+ assert MT5Config.from_mapping({"profile": "live"}).environment == "live"
+ assert MT5Config.from_mapping({"profile": "live-readonly"}).environment == "live"
+ assert MT5Config.from_mapping({"profile": "live"}).is_demo is False
+
+ def test_build_config_precedence(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import _client
+
+ _client.save_config(_paper_config())
+ cfg = _client.build_config({"profile": "live-readonly"}, {"server": "Exness-MT5Real2"})
+ assert cfg.login == 12345 # from saved file
+ assert cfg.profile == "live-readonly" # profile default overrides file
+ assert cfg.server == "Exness-MT5Real2" # explicit override wins
+
+ def test_save_and_load_round_trip(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import _client
+
+ path = _client.save_config(_paper_config())
+ assert path.name == "mt5.json"
+ loaded = _client.load_config()
+ assert loaded.login == 12345
+ assert loaded.server == "Exness-MT5Trial8"
+ assert loaded.symbol_suffix == "m"
+
+ def test_public_config_redacts_secrets(self) -> None:
+ from src.trading.connectors.mt5._client import _public_config
+
+ public = _public_config(_paper_config())
+ text = str(public)
+ assert "hunter2secret" not in text
+ assert public["password"] == "***redacted***"
+ assert "12345" not in str(public.get("login", ""))
+
+
+class TestAvailability:
+ def test_mt5_available_false_when_import_fails(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ from src.trading.connectors.mt5 import _client
+
+ def _missing() -> Any:
+ raise _client.MT5DependencyError("MetaTrader5 is not installed")
+
+ monkeypatch.setattr(_client, "_require_mt5", _missing)
+ assert _client.mt5_available() is False
+
+ def test_reads_return_error_envelope_when_sdk_missing(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ from src.trading.connectors.mt5 import _client, sdk
+
+ def _missing() -> Any:
+ raise _client.MT5DependencyError("MetaTrader5 is not installed (Windows-only)")
+
+ monkeypatch.setattr(_client, "_require_mt5", _missing)
+ monkeypatch.setattr(_client, "get_runtime_root", lambda: tmp_path)
+ result = sdk.get_positions(_paper_config())
+ assert result["status"] == "error"
+ assert "MetaTrader5" in result["error"]
+
+ def test_check_status_reports_unconfigured(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ report = sdk.check_status(sdk.build_config({"profile": "paper"}))
+ assert report["status"] == "error"
+ assert "not configured" in report["error"]
+
+ def test_check_status_happy_path(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ report = sdk.check_status(_paper_config())
+ assert report["status"] == "ok"
+ assert report["account"]["is_demo"] is True
+ assert report["account"]["server"] == "Exness-MT5Trial8"
+ assert fake_mt5.shutdown_calls >= 1
+
+
+# --------------------------------------------------------------------------- #
+# Identity guard (bidirectional, fail-closed) #
+# --------------------------------------------------------------------------- #
+
+
+class TestIdentityGuard:
+ def _positions_via(self, cfg) -> dict[str, Any]:
+ from src.trading.connectors.mt5 import sdk
+
+ return sdk.get_positions(cfg)
+
+ def test_paper_profile_rejects_real_account(self, fake_mt5: FakeMT5) -> None:
+ fake_mt5.account.trade_mode = FakeMT5.ACCOUNT_TRADE_MODE_REAL
+ result = self._positions_via(_paper_config())
+ assert result["status"] == "error"
+ assert "demo" in result["error"].lower()
+
+ def test_paper_profile_rejects_contest_account(self, fake_mt5: FakeMT5) -> None:
+ fake_mt5.account.trade_mode = FakeMT5.ACCOUNT_TRADE_MODE_CONTEST
+ result = self._positions_via(_paper_config())
+ assert result["status"] == "error"
+
+ def test_live_profile_rejects_demo_account(self, fake_mt5: FakeMT5) -> None:
+ result = self._positions_via(_paper_config(profile="live-readonly"))
+ assert result["status"] == "error"
+ assert "real" in result["error"].lower() or "live" in result["error"].lower()
+
+ def test_login_pin_mismatch_rejected(self, fake_mt5: FakeMT5) -> None:
+ result = self._positions_via(_paper_config(login=99999))
+ assert result["status"] == "error"
+ assert "login" in result["error"].lower()
+
+ def test_matching_demo_account_passes(self, fake_mt5: FakeMT5) -> None:
+ result = self._positions_via(_paper_config())
+ assert result["status"] == "ok"
+ assert fake_mt5.shutdown_calls == 1 # every op passes through _session
+
+
+# --------------------------------------------------------------------------- #
+# USD sizing (the lot-semantics fix) #
+# --------------------------------------------------------------------------- #
+
+
+class TestQuantityNotionalUsd:
+ def _size(self, symbol: str, lots: float) -> float | None:
+ from src.trading.connectors.mt5 import sdk
+
+ return sdk.quantity_notional_usd(_paper_config(), symbol, lots)
+
+ def test_quote_usd_pair(self, fake_mt5: FakeMT5) -> None:
+ # 0.1 lots EURUSD = 10,000 EUR ~= 10,800 USD at mid 1.08.
+ assert self._size("EURUSD", 0.1) == pytest.approx(10_800.0)
+
+ def test_base_usd_pair(self, fake_mt5: FakeMT5) -> None:
+ # 0.1 lots USDJPY = 10,000 USD exactly.
+ assert self._size("USDJPY", 0.1) == pytest.approx(10_000.0)
+
+ def test_metal_cfd(self, fake_mt5: FakeMT5) -> None:
+ # 0.1 lots XAUUSD = 10 oz * 2400 mid = 24,000 USD.
+ assert self._size("XAUUSD", 0.1) == pytest.approx(24_000.0)
+
+ def test_cross_pair_via_base_usd_conversion(self, fake_mt5: FakeMT5) -> None:
+ # EURJPY: 0.1 lots = 10,000 EUR, converted through EURUSDm mid 1.08.
+ assert self._size("EURJPY", 0.1) == pytest.approx(10_800.0)
+
+ def test_unresolvable_cross_fails_closed(self, fake_mt5: FakeMT5) -> None:
+ fake_mt5.symbols["GBPJPYm"] = _symbol("GBPJPYm", base="GBP", profit="JPY")
+ assert self._size("GBPJPY", 0.1) is None
+
+ def test_missing_tick_fails_closed(self, fake_mt5: FakeMT5) -> None:
+ del fake_mt5.ticks["EURUSDm"]
+ assert self._size("EURUSD", 0.1) is None
+
+
+# --------------------------------------------------------------------------- #
+# Reads #
+# --------------------------------------------------------------------------- #
+
+
+class TestReads:
+ def test_account_snapshot_fields(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ result = sdk.get_account_snapshot(_paper_config())
+ assert result["status"] == "ok"
+ account = result["account"]
+ assert account["login"] == 12345
+ assert account["balance"] == pytest.approx(10_000.0)
+ assert account["equity"] == pytest.approx(10_050.0)
+ assert account["leverage"] == 200
+ assert account["is_demo"] is True
+
+ def test_positions_carry_usd_market_value(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ fake_mt5.positions = [
+ SimpleNamespace(
+ ticket=777, symbol="EURUSDm", type=FakeMT5.POSITION_TYPE_BUY,
+ volume=0.1, price_open=1.0750, price_current=1.0800,
+ sl=1.0700, tp=1.0900, swap=-0.5, profit=50.0, time=1_750_000_000,
+ )
+ ]
+ result = sdk.get_positions(_paper_config())
+ assert result["status"] == "ok"
+ row = result["positions"][0]
+ assert row["ticket"] == 777
+ assert row["side"] == "buy"
+ assert row["market_value"] == pytest.approx(10_800.0)
+
+ def test_position_market_value_none_when_unpriceable(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ fake_mt5.positions = [
+ SimpleNamespace(
+ ticket=778, symbol="EURUSDm", type=FakeMT5.POSITION_TYPE_SELL,
+ volume=0.1, price_open=1.0750, price_current=1.0800,
+ sl=0.0, tp=0.0, swap=0.0, profit=-10.0, time=1_750_000_000,
+ )
+ ]
+ del fake_mt5.ticks["EURUSDm"]
+ result = sdk.get_positions(_paper_config())
+ # Row present, value None → gate exposure math fails closed downstream.
+ assert result["positions"][0]["market_value"] is None
+
+ def test_quote_omits_zero_last(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ result = sdk.get_quote("EUR/USD", config=_paper_config())
+ assert result["status"] == "ok"
+ assert result["resolved_symbol"] == "EURUSDm"
+ quote = result["quote"]
+ assert quote["bid"] == pytest.approx(1.0799)
+ assert quote["ask"] == pytest.approx(1.0801)
+ assert "last" not in quote
+
+ def test_history_maps_rows_and_timeframes(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ fake_mt5.rates["EURUSDm"] = [
+ {"time": 1_750_000_000, "open": 1.07, "high": 1.09, "low": 1.06,
+ "close": 1.08, "tick_volume": 1200, "spread": 6, "real_volume": 0},
+ ]
+ result = sdk.get_historical_bars("EURUSD", config=_paper_config(), period="1h", limit=10)
+ assert result["status"] == "ok"
+ bar = result["bars"][0]
+ assert bar["close"] == pytest.approx(1.08)
+ assert bar["volume"] == 1200
+ assert fake_mt5.rates_calls[-1][1] == FakeMT5.TIMEFRAME_H1
+
+ def test_minute_and_month_periods_differ(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ fake_mt5.rates["EURUSDm"] = []
+ sdk.get_historical_bars("EURUSD", config=_paper_config(), period="1m", limit=5)
+ sdk.get_historical_bars("EURUSD", config=_paper_config(), period="1M", limit=5)
+ assert fake_mt5.rates_calls[-2][1] == FakeMT5.TIMEFRAME_M1
+ assert fake_mt5.rates_calls[-1][1] == FakeMT5.TIMEFRAME_MN1
+
+ def test_pending_orders_read(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ fake_mt5.pending_orders = [
+ SimpleNamespace(
+ ticket=888, symbol="EURUSDm", type=FakeMT5.ORDER_TYPE_BUY_LIMIT,
+ volume_initial=0.05, volume_current=0.05, price_open=1.0500,
+ sl=0.0, tp=0.0, time_setup=1_750_000_000, state=1,
+ )
+ ]
+ result = sdk.get_open_orders(_paper_config())
+ assert result["status"] == "ok"
+ assert result["open_orders"][0]["order_id"] == "888"
+
+
+# --------------------------------------------------------------------------- #
+# place_order #
+# --------------------------------------------------------------------------- #
+
+
+class TestPlaceOrder:
+ def _place(self, fake: FakeMT5, **kwargs: Any) -> dict[str, Any]:
+ from src.trading.connectors.mt5 import sdk
+
+ defaults: dict[str, Any] = {
+ "symbol": "EURUSD", "side": "buy", "quantity": 0.05,
+ "notional": None, "order_type": "market",
+ "limit_price": None, "time_in_force": "day",
+ }
+ defaults.update(kwargs)
+ return sdk.place_order(_paper_config(), **defaults)
+
+ def test_market_buy_request_shape(self, fake_mt5: FakeMT5) -> None:
+ result = self._place(fake_mt5)
+ assert result["status"] == "ok"
+ assert result["order_id"] == "424242"
+ request = fake_mt5.order_send_requests[-1]
+ assert request["action"] == FakeMT5.TRADE_ACTION_DEAL
+ assert request["type"] == FakeMT5.ORDER_TYPE_BUY
+ assert request["symbol"] == "EURUSDm"
+ assert request["volume"] == pytest.approx(0.05)
+ assert request["price"] == pytest.approx(1.0801) # buy at ask
+ assert request["deviation"] == 20
+ assert request["type_filling"] == FakeMT5.ORDER_FILLING_IOC
+
+ def test_market_sell_priced_at_bid(self, fake_mt5: FakeMT5) -> None:
+ self._place(fake_mt5, side="sell")
+ assert fake_mt5.order_send_requests[-1]["price"] == pytest.approx(1.0799)
+ assert fake_mt5.order_send_requests[-1]["type"] == FakeMT5.ORDER_TYPE_SELL
+
+ def test_limit_order_is_pending_with_tif(self, fake_mt5: FakeMT5) -> None:
+ self._place(fake_mt5, order_type="limit", limit_price=1.05, time_in_force="gtc")
+ request = fake_mt5.order_send_requests[-1]
+ assert request["action"] == FakeMT5.TRADE_ACTION_PENDING
+ assert request["type"] == FakeMT5.ORDER_TYPE_BUY_LIMIT
+ assert request["price"] == pytest.approx(1.05)
+ assert request["type_time"] == FakeMT5.ORDER_TIME_GTC
+
+ def test_rejected_retcode_surfaces_error(self, fake_mt5: FakeMT5) -> None:
+ fake_mt5.order_send_result = SimpleNamespace(
+ retcode=10018, order=0, deal=0, volume=0.0, price=0.0, comment="Market closed"
+ )
+ result = self._place(fake_mt5)
+ assert result["status"] == "error"
+ assert "10018" in result["error"]
+ assert "Market closed" in result["error"]
+
+ def test_order_check_failure_blocks_send(self, fake_mt5: FakeMT5) -> None:
+ fake_mt5.order_check_result = SimpleNamespace(retcode=10019, comment="No money")
+ result = self._place(fake_mt5)
+ assert result["status"] == "error"
+ assert fake_mt5.order_send_requests == []
+
+ def test_volume_guard_blocks_before_sdk(self, fake_mt5: FakeMT5) -> None:
+ result = self._place(fake_mt5, quantity=1.5) # max_order_volume = 1.0
+ assert result["status"] == "error"
+ assert "max_order_volume" in result["error"]
+ assert fake_mt5.order_send_requests == []
+
+ def test_notional_guard_blocks_before_sdk(self, fake_mt5: FakeMT5) -> None:
+ # 0.5 lots EURUSD ~= 54,000 USD > default 10,000 cap.
+ result = self._place(fake_mt5, quantity=0.5)
+ assert result["status"] == "error"
+ assert "max_order_notional_usd" in result["error"]
+ assert fake_mt5.order_send_requests == []
+
+ def test_notional_sizing_floors_to_volume_step(self, fake_mt5: FakeMT5) -> None:
+ # 5000 USD / (100k * 1.08 per lot) = 0.0463 lots → floors to 0.04.
+ result = self._place(fake_mt5, quantity=None, notional=5000.0)
+ assert result["status"] == "ok"
+ assert fake_mt5.order_send_requests[-1]["volume"] == pytest.approx(0.04)
+
+ def test_notional_below_min_volume_errors(self, fake_mt5: FakeMT5) -> None:
+ result = self._place(fake_mt5, quantity=None, notional=500.0) # < 0.01 lots
+ assert result["status"] == "error"
+ assert fake_mt5.order_send_requests == []
+
+ def test_exactly_one_size_required(self, fake_mt5: FakeMT5) -> None:
+ assert self._place(fake_mt5, quantity=None, notional=None)["status"] == "error"
+ assert self._place(fake_mt5, quantity=0.05, notional=1000.0)["status"] == "error"
+
+ def test_unconfigured_errors_before_sdk(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ result = sdk.place_order(
+ sdk.build_config({"profile": "paper"}),
+ symbol="EURUSD", side="buy", quantity=0.05, notional=None,
+ order_type="market", limit_price=None, time_in_force="day",
+ )
+ assert result["status"] == "error"
+ assert "not configured" in result["error"]
+ assert fake_mt5.order_send_requests == []
+
+ def test_unknown_symbol_lists_candidates(self, fake_mt5: FakeMT5) -> None:
+ result = self._place(fake_mt5, symbol="NZDCAD")
+ assert result["status"] == "error"
+ assert fake_mt5.order_send_requests == []
+
+
+# --------------------------------------------------------------------------- #
+# cancel_order / close_position (risk-reducing dual semantics) #
+# --------------------------------------------------------------------------- #
+
+
+class TestCancelOrder:
+ def test_pending_ticket_removed(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ fake_mt5.pending_orders = [
+ SimpleNamespace(
+ ticket=888, symbol="EURUSDm", type=FakeMT5.ORDER_TYPE_BUY_LIMIT,
+ volume_initial=0.05, volume_current=0.05, price_open=1.05,
+ sl=0.0, tp=0.0, time_setup=0, state=1,
+ )
+ ]
+ result = sdk.cancel_order(_paper_config(), "888")
+ assert result["status"] == "ok"
+ assert result["action"] == "order_cancelled"
+ request = fake_mt5.order_send_requests[-1]
+ assert request["action"] == FakeMT5.TRADE_ACTION_REMOVE
+ assert request["order"] == 888
+
+ def test_position_ticket_closed_with_opposite_deal(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ fake_mt5.positions = [
+ SimpleNamespace(
+ ticket=777, symbol="EURUSDm", type=FakeMT5.POSITION_TYPE_BUY,
+ volume=0.1, price_open=1.0750, price_current=1.0800,
+ sl=0.0, tp=0.0, swap=0.0, profit=0.0, time=0,
+ )
+ ]
+ result = sdk.cancel_order(_paper_config(), "777")
+ assert result["status"] == "ok"
+ assert result["action"] == "position_closed"
+ request = fake_mt5.order_send_requests[-1]
+ assert request["action"] == FakeMT5.TRADE_ACTION_DEAL
+ assert request["type"] == FakeMT5.ORDER_TYPE_SELL # opposite of long
+ assert request["position"] == 777
+ assert request["volume"] == pytest.approx(0.1)
+
+ def test_close_volume_capped_at_position(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ fake_mt5.positions = [
+ SimpleNamespace(
+ ticket=777, symbol="EURUSDm", type=FakeMT5.POSITION_TYPE_SELL,
+ volume=0.1, price_open=1.08, price_current=1.07,
+ sl=0.0, tp=0.0, swap=0.0, profit=0.0, time=0,
+ )
+ ]
+ result = sdk.close_position(_paper_config(), 777, volume=5.0)
+ assert result["status"] == "ok"
+ request = fake_mt5.order_send_requests[-1]
+ assert request["volume"] == pytest.approx(0.1) # never more than the position
+ assert request["type"] == FakeMT5.ORDER_TYPE_BUY # opposite of short
+
+ def test_unknown_ticket_errors(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ result = sdk.cancel_order(_paper_config(), "31337")
+ assert result["status"] == "error"
+ assert fake_mt5.order_send_requests == []
+
+ def test_non_integer_ticket_errors(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ result = sdk.cancel_order(_paper_config(), "abc")
+ assert result["status"] == "error"
+ assert fake_mt5.order_send_requests == []
+
+
+# --------------------------------------------------------------------------- #
+# Profiles, classification, service registration #
+# --------------------------------------------------------------------------- #
+
+
+class TestProfilesAndRegistration:
+ def test_four_profiles_registered(self) -> None:
+ from src.trading.profiles import list_profiles
+ from src.trading.types import READ_CAPABILITIES
+
+ profiles = {p.id: p for p in list_profiles()}
+ for pid in ("mt5-paper-sdk", "mt5-live-sdk-readonly", "mt5-paper-trade", "mt5-live-trade"):
+ assert pid in profiles, f"{pid} missing from BUILTIN_PROFILES"
+ assert profiles[pid].connector == "mt5"
+ assert profiles[pid].transport == "broker_sdk"
+
+ assert profiles["mt5-paper-sdk"].readonly is True
+ assert profiles["mt5-paper-sdk"].capabilities == READ_CAPABILITIES
+ assert profiles["mt5-live-sdk-readonly"].environment == "live"
+ assert profiles["mt5-live-sdk-readonly"].readonly is True
+ assert profiles["mt5-paper-trade"].readonly is False
+ assert "orders.place" in profiles["mt5-paper-trade"].capabilities
+ assert profiles["mt5-live-trade"].readonly is False
+ assert "orders.place.requires_mandate" in profiles["mt5-live-trade"].capabilities
+
+ def test_check_connection_unconfigured_degrades(self, fake_mt5: FakeMT5) -> None:
+ from src.trading import service
+
+ report = service.check_connection("mt5-paper-sdk")
+ assert report["status"] == "error"
+ assert "not configured" in report["error"]
+ assert report["connector"] == "mt5"
+ assert report["transport"] == "broker_sdk"
+
+ def test_order_classification_forex_and_cfd(self) -> None:
+ from src.trading.service import _order_classification
+
+ assert _order_classification("mt5", "EURUSDm") == (InstrumentType.FOREX, AssetClass.FOREX)
+ assert _order_classification("mt5", "EUR/USD") == (InstrumentType.FOREX, AssetClass.FOREX)
+ assert _order_classification("mt5", "XAUUSD") == (InstrumentType.CFD, None)
+
+ def test_classification_map_fail_closed(self) -> None:
+ from src.live import registry
+ from src.live.classification import ToolClass, classify_tool
+ from src.trading.connectors.mt5.classification import MT5_TOOL_CLASS
+
+ assert registry._BROKER_CURATED_MAPS["mt5"] is MT5_TOOL_CLASS
+ for op in ("order_send", "order_check", "place_order", "cancel_order", "close_position"):
+ assert MT5_TOOL_CLASS[op] is ToolClass.WRITE
+ assert classify_tool("order_send", None, MT5_TOOL_CLASS) is ToolClass.WRITE
+ # Unknown ops must never resolve READ (fail-closed).
+ assert classify_tool("mystery_op", None, MT5_TOOL_CLASS) is not ToolClass.READ
+
+ def test_paper_place_via_service(self, fake_mt5: FakeMT5) -> None:
+ from src.trading import service
+ from src.trading.connectors.mt5 import _client
+
+ _client.save_config(_paper_config())
+ result = service.place_order("EURUSD", "mt5-paper-trade", side="buy", quantity=0.05)
+ assert result["status"] == "ok"
+ assert result["environment"] == "paper"
+ assert len(fake_mt5.order_send_requests) == 1
+
+ def test_live_place_blocked_without_mandate(self, fake_mt5: FakeMT5, monkeypatch: pytest.MonkeyPatch) -> None:
+ from src.trading import service
+ from src.trading.connectors.mt5 import _client
+
+ _client.save_config(_paper_config(profile="live"))
+ monkeypatch.setattr("src.live.sdk_order_gate.load_mandate", lambda broker: None)
+ result = service.place_order("EURUSD", "mt5-live-trade", side="buy", quantity=0.05)
+ assert result["status"] == "blocked"
+ assert fake_mt5.order_send_requests == [] # gate blocks before any SDK call
diff --git a/agent/tests/test_sdk_order_gate.py b/agent/tests/test_sdk_order_gate.py
index 01c828cfb..0c7baee68 100644
--- a/agent/tests/test_sdk_order_gate.py
+++ b/agent/tests/test_sdk_order_gate.py
@@ -311,7 +311,7 @@ def test_longbridge_place_order_paper_only_guard() -> None:
assert out2["status"] == "error" and "paper" in out2["error"].lower()
[email protected]("connector", ["tiger", "alpaca", "okx", "binance", "futu", "longbridge"])
[email protected]("connector", ["tiger", "alpaca", "okx", "binance", "futu", "longbridge", "mt5"])
def test_connector_place_order_rejects_bad_side(connector) -> None:
import importlib
@@ -321,7 +321,7 @@ def test_connector_place_order_rejects_bad_side(connector) -> None:
assert out["status"] == "error"
[email protected]("connector", ["tiger", "alpaca", "okx", "binance", "futu", "longbridge"])
[email protected]("connector", ["tiger", "alpaca", "okx", "binance", "futu", "longbridge", "mt5"])
def test_connector_place_order_rejects_both_qty_and_notional(connector) -> None:
import importlib