Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(futu): emit the connection_state envelope /live/status consumes

Haozhe Wuc7f4cbef3c2d
diff --git a/agent/src/trading/connectors/futu/sdk.py b/agent/src/trading/connectors/futu/sdk.py
index 9275cf555..c72facd85 100644
--- a/agent/src/trading/connectors/futu/sdk.py
+++ b/agent/src/trading/connectors/futu/sdk.py
@@ -29,6 +29,7 @@ from __future__ import annotations
import json
import socket
from dataclasses import asdict, dataclass
+from datetime import datetime, timezone
from pathlib import Path
from types import ModuleType
from typing import Any, Mapping
@@ -233,8 +234,16 @@ def check_status(config: FutuConfig | None = None) -> dict[str, Any]:
A health report dict.
"""
cfg = config or load_config()
+ # ``connection_state``/``error_code``/``last_checked_at`` are the envelope
+ # /live/status reads through a closed vocabulary (live_routes.py
+ # _CONNECTION_STATES / _ERROR_CODES). Omitting them is not a cosmetic gap:
+ # the Web UI treats anything other than "connected"/"ready" as unavailable,
+ # so a working OpenD connection rendered as down. Same shape as longbridge.
report: dict[str, Any] = {
"status": "ok",
+ "connection_state": "connected",
+ "error_code": None,
+ "error": None,
"config": _public_config(cfg),
"sdk": {"package": "futu-api", "installed": futu_available()},
"paper_guard": "trd_env_acc_list",
@@ -244,30 +253,42 @@ def check_status(config: FutuConfig | None = None) -> dict[str, Any]:
gateway_open = tcp_port_open(cfg.host, cfg.port)
report["gateway"] = {"host": cfg.host, "port": cfg.port, "open": gateway_open}
if not gateway_open:
- report["status"] = "error"
- report["error"] = (
+ return _status_error(
+ report,
+ "network_unreachable",
f"No Futu OpenD gateway is listening at {cfg.host}:{cfg.port}. "
- "Start OpenD, log in, and confirm the API port."
+ "Start OpenD, log in, and confirm the API port.",
)
- return report
if not report["sdk"]["installed"]:
- report["status"] = "error"
- report["error"] = "Optional dependency missing: install with `pip install futu-api`."
- return report
+ return _status_error(
+ report,
+ "sdk_missing",
+ "Optional dependency missing: install with `pip install futu-api`.",
+ )
try:
snapshot = get_account_snapshot(cfg)
except Exception as exc: # noqa: BLE001 - health endpoint reports cleanly
- report["status"] = "error"
- report["error"] = str(exc)
- return report
+ return _status_error(report, "broker_error", str(exc))
report["account"] = {
"profile": cfg.profile,
"trd_env": cfg.trd_env_name,
"acc_id": snapshot.get("acc_id"),
}
+ report["last_checked_at"] = datetime.now(timezone.utc).isoformat()
+ return report
+
+
+def _status_error(report: dict[str, Any], code: str, message: str) -> dict[str, Any]:
+ """Stamp a failed health report with the closed-vocabulary diagnostics."""
+ report.update(
+ status="error",
+ connection_state="error",
+ error_code=code,
+ error=message,
+ )
return report
diff --git a/agent/tests/test_futu_check_status_envelope.py b/agent/tests/test_futu_check_status_envelope.py
new file mode 100644
index 000000000..500ec10fe
--- /dev/null
+++ b/agent/tests/test_futu_check_status_envelope.py
@@ -0,0 +1,76 @@
+"""The Futu health report must carry the envelope ``/live/status`` consumes.
+
+``check_status`` used to return only ``status``/``error``. The Web UI reads
+``connection_state`` through a closed vocabulary in ``live_routes`` and treats
+anything other than ``connected``/``ready`` as unavailable, so a working OpenD
+connection rendered as down. These tests pin the envelope against the ACTUAL
+consumer's vocabulary rather than against a hand-copied list, so widening the
+vocabulary on one side without the other fails here.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from src.api.live_routes import _CONNECTION_STATES, _ERROR_CODES
+from src.trading.connectors.futu import sdk as futu_sdk
+
+
+def cfg() -> Any:
+ return futu_sdk.FutuConfig()
+
+
+def _patch(monkeypatch, *, port_open=True, installed=True, snapshot=None, raises=None):
+ monkeypatch.setattr(futu_sdk, "tcp_port_open", lambda host, port: port_open)
+ monkeypatch.setattr(futu_sdk, "futu_available", lambda: installed)
+
+ def _snapshot(config=None):
+ if raises is not None:
+ raise raises
+ return snapshot or {"acc_id": 42}
+
+ monkeypatch.setattr(futu_sdk, "get_account_snapshot", _snapshot)
+
+
+def test_healthy_report_is_connected_and_timestamped(monkeypatch, cfg):
+ _patch(monkeypatch)
+ report = futu_sdk.check_status(cfg)
+ assert report["status"] == "ok"
+ assert report["connection_state"] == "connected"
+ assert report["error_code"] is None
+ assert report["error"] is None
+ assert report["last_checked_at"]
+
+
+ ("kwargs", "expected_code"),
+ [
+ ({"port_open": False}, "network_unreachable"),
+ ({"installed": False}, "sdk_missing"),
+ ({"raises": RuntimeError("acc list failed")}, "broker_error"),
+ ],
+)
+def test_failure_reports_carry_a_closed_vocabulary_code(
+ monkeypatch, cfg, kwargs, expected_code
+):
+ _patch(monkeypatch, **kwargs)
+ report = futu_sdk.check_status(cfg)
+ assert report["status"] == "error"
+ assert report["connection_state"] == "error"
+ assert report["error_code"] == expected_code
+ assert report["error"]
+
+
+def test_every_emitted_value_survives_the_route_vocabulary(monkeypatch, cfg):
+ """The route drops any value outside its frozensets — none may be dropped."""
+ cases = [{}, {"port_open": False}, {"installed": False},
+ {"raises": RuntimeError("boom")}]
+ for kwargs in cases:
+ _patch(monkeypatch, **kwargs)
+ report = futu_sdk.check_status(cfg)
+ assert report["connection_state"] in _CONNECTION_STATES
+ if report["error_code"] is not None:
+ assert report["error_code"] in _ERROR_CODES