"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(sandbox): let backtests attach to the running MT5 terminal, credential-free
Yufeng He2838a75a5cb3
diff --git a/agent/backtest/loaders/mt5_loader.py b/agent/backtest/loaders/mt5_loader.pyindex 196eb12c2..b97eda0da 100644--- a/agent/backtest/loaders/mt5_loader.py+++ b/agent/backtest/loaders/mt5_loader.py@@ -94,6 +94,13 @@ def _ensure_initialized() -> bool:if config.get("timeout"):kwargs["timeout"] = int(float(config["timeout"]) * 1000)args = (str(config["terminal_path"]),) if config.get("terminal_path") else ()+ if not args:+ logger.warning(+ "mt5: no terminal_path configured, so the SDK picks a terminal "+ "itself; on hosts with several MT5 installations that can be a "+ "different installation logged into a different account. Set "+ "terminal_path in mt5.json to pin the attach (#1589)."+ )try:ok = bool(mt5.initialize(*args, **kwargs))except Exception as exc: # noqa: BLE001 - availability probe must not raisediff --git a/agent/src/core/runner.py b/agent/src/core/runner.pyindex 74b01a7fb..22a54157e 100644--- a/agent/src/core/runner.py+++ b/agent/src/core/runner.py@@ -144,6 +144,33 @@ def _rlimit_bootstrap_argv() -> list[str] | None:]+def _reexpose_mt5_config(src_root: Path, dst_root: Path) -> None:+ """Write a credential-free subset of the host's ``mt5.json`` into the sandbox.++ The full connector config carries broker ``login``/``password``/``server``,+ which strategy code must never see (VT-001), so the file can never join the+ generic re-expose list. A backtest still has to attach to the+ already-running, already-logged-in terminal, so it gets only+ ``terminal_path`` and ``timeout`` (#1589).+ """+ src = src_root / "mt5.json"+ if not src.exists():+ return+ try:+ config = json.loads(src.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return+ if not isinstance(config, dict):+ return+ subset = {key: config[key] for key in ("terminal_path", "timeout") if key in config}+ if not subset:+ return+ try:+ (dst_root / "mt5.json").write_text(json.dumps(subset), encoding="utf-8")+ except OSError:+ pass++def _prepare_sandbox_home(real_home: Path | None) -> Path:"""Create an ephemeral HOME and symlink in only the loader-owned paths.@@ -184,6 +211,7 @@ def _prepare_sandbox_home(real_home: Path | None) -> Path:# falls back to a live fetch / disabled cache — never a# hard break.pass+ _reexpose_mt5_config(src_root, dst_root)try:os.chmod(dst_root, 0o755)except OSError:diff --git a/agent/tests/test_mt5_loader.py b/agent/tests/test_mt5_loader.pyindex ca3c0aa45..91ec51df2 100644--- a/agent/tests/test_mt5_loader.py+++ b/agent/tests/test_mt5_loader.py@@ -238,6 +238,29 @@ class TestAvailability:assert call["args"] == ()assert "login" not in call["kwargs"]+ def test_bare_attach_warns_about_terminal_picking(+ self, fake_mod: _FakeMT5Module, caplog: pytest.LogCaptureFixture+ ) -> None:+ # A path-less initialize() lets the SDK pick any terminal on the host,+ # which can be a different installation on a different account (#1589).+ # The attach itself is the documented primary path; the warning is the+ # hint that pins it down for multi-install users.+ with caplog.at_level("WARNING", logger="backtest.loaders.mt5_loader"):+ DataLoader().is_available()+ assert any("terminal_path" in r.message for r in caplog.records)++ def test_terminal_path_attaches_without_the_warning(+ self, fake_mod: _FakeMT5Module, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture+ ) -> None:+ config = tmp_path / "mt5.json"+ config.write_text(json.dumps({"terminal_path": "C:/MT5/terminal64.exe"}), encoding="utf-8")+ monkeypatch.setattr(mt5_loader, "_MT5_CONFIG_PATH", config)+ with caplog.at_level("WARNING", logger="backtest.loaders.mt5_loader"):+ DataLoader().is_available()+ call = fake_mod.initialize_calls[0]+ assert call["args"] == ("C:/MT5/terminal64.exe",)+ assert not any("picks a terminal" in r.message for r in caplog.records)+# --------------------------------------------------------------------------- ## Registry + routing #diff --git a/agent/tests/test_runner_env.py b/agent/tests/test_runner_env.pyindex 2f388463e..ab0a85db1 100644--- a/agent/tests/test_runner_env.py+++ b/agent/tests/test_runner_env.py@@ -2,6 +2,7 @@from __future__ import annotations+import jsonimport osfrom pathlib import Path@@ -185,6 +186,44 @@ def test_prepare_sandbox_home_reexposes_only_loader_paths(tmp_path: Path) -> Nonassert (vt / "cache").exists()+def test_prepare_sandbox_home_reexposes_mt5_config_without_credentials(tmp_path: Path) -> None:+ """The backtest sandbox must reach the already-running MT5 terminal without+ ever shipping broker credentials to strategy code (#1589).++ The full mt5.json carries login/password/server, so it can never join the+ generic re-expose list; the sandbox gets a secret-free subset+ (terminal_path, timeout) instead.+ """+ real_home = tmp_path / "home"+ vt = real_home / ".vibe-trading"+ vt.mkdir(parents=True)+ (vt / "mt5.json").write_text(+ json.dumps(+ {+ "terminal_path": "C:/MT5/terminal64.exe",+ "timeout": 60,+ "login": 12345678,+ "password": "broker-secret",+ "server": "Exness-Demo",+ }+ ),+ encoding="utf-8",+ )++ sandbox = _prepare_sandbox_home(real_home)+ try:+ sandbox_cfg = sandbox / ".vibe-trading" / "mt5.json"+ assert sandbox_cfg.exists()+ subset = json.loads(sandbox_cfg.read_text(encoding="utf-8"))+ assert subset == {"terminal_path": "C:/MT5/terminal64.exe", "timeout": 60}+ for secret in ("login", "password", "server"):+ assert secret not in subset+ finally:+ import shutil++ shutil.rmtree(sandbox, ignore_errors=True)++def test_prepare_sandbox_home_copy_fallback_when_symlink_privileges_missing(monkeypatch, tmp_path: Path) -> None: