"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(futu): label multi-currency balances with the requested currency
alex6a4be638ad14
diff --git a/agent/src/trading/connectors/futu/sdk.py b/agent/src/trading/connectors/futu/sdk.pyindex 7c263c7cf..4a0b5f053 100644--- a/agent/src/trading/connectors/futu/sdk.py+++ b/agent/src/trading/connectors/futu/sdk.py@@ -49,6 +49,15 @@ PROFILE_ENVIRONMENTS = {"live": "live",}+#: Currency the funds query requests balances in; it labels a multi-currency+#: account's row (see ``_account_to_dict``). HKD matches the SDK's own default+#: for this argument.+ACCOUNT_CURRENCY = "HKD"++#: Futu's placeholder for a field it does not report, currency included+#: (``NoneDataValue`` / ``Currency.NONE``).+_NO_DATA = "N/A"+#: Maps the connector environment to the Futu ``TrdEnv`` enum member name._ENV_TO_TRD_ENV = {"paper": "SIMULATE",@@ -301,7 +310,9 @@ def get_account_snapshot(config: FutuConfig | None = None) -> dict[str, Any]:try:acc_id = _resolve_acc_id(cfg, trade_ctx)trd_env = _trd_env_enum(cfg)- result = trade_ctx.accinfo_query(trd_env=trd_env, acc_id=acc_id)+ result = trade_ctx.accinfo_query(+ trd_env=trd_env, acc_id=acc_id, currency=ACCOUNT_CURRENCY+ )ret = result[0] if isinstance(result, (list, tuple)) and len(result) >= 2 else Nonefutu = _require_futu()if ret is not None and ret != getattr(futu, "RET_OK", 0):@@ -316,7 +327,7 @@ def get_account_snapshot(config: FutuConfig | None = None) -> dict[str, Any]:"profile": cfg.profile,"trd_env": cfg.trd_env_name,"acc_id": acc_id,- "assets": [_account_to_dict(row) for row in rows],+ "assets": [_account_to_dict(row, ACCOUNT_CURRENCY) for row in rows],}finally:_close(trade_ctx)@@ -1196,7 +1207,29 @@ def _acc_id_of(row: Mapping[str, Any]) -> int:return 0-def _account_to_dict(row: Mapping[str, Any]) -> dict[str, Any]:+def _account_to_dict(+ row: Mapping[str, Any], requested_currency: str | None = None+) -> dict[str, Any]:+ """Normalize one ``accinfo_query`` row.++ A multi-currency account reports ``"N/A"`` as its currency while its+ amounts are denominated in the currency the query requested, so that+ requested currency labels the row. A currency the broker does report is+ kept as is. With neither, the row keeps Futu's ``"N/A"`` rather than an+ empty value: portfolio valuation rejects ``"N/A"``, but reads an empty+ currency as USD.++ Args:+ row: One row from ``accinfo_query``.+ requested_currency: The ``currency`` argument the query was made+ with, or ``None`` if unknown.++ Returns:+ The normalized account mapping.+ """+ currency = str(_first(row, ("currency",), "") or "").upper()+ if currency in ("", _NO_DATA):+ currency = (requested_currency or _NO_DATA).upper()return {"power": _first(row, ("power",)),"total_assets": _first(row, ("total_assets",)),@@ -1204,7 +1237,7 @@ def _account_to_dict(row: Mapping[str, Any]) -> dict[str, Any]:"market_val": _first(row, ("market_val",)),"available_funds": _first(row, ("available_funds",)),"securities_assets": _first(row, ("securities_assets",)),- "currency": str(_first(row, ("currency",), "") or "").upper(),+ "currency": currency,}diff --git a/agent/tests/test_futu_account_currency.py b/agent/tests/test_futu_account_currency.pynew file mode 100644index 000000000..7e920b635--- /dev/null+++ b/agent/tests/test_futu_account_currency.py@@ -0,0 +1,104 @@+"""Currency labelling of Futu account balances.++A Futu multi-currency account reports ``"N/A"`` as the currency of its funds+row, while the amounts are denominated in the currency the query asked for.+Portfolio valuation rejects an unknown currency, so the label has to come from+the request; an empty label would instead be valued as USD.++All rows and amounts are synthetic. The SDK boundary is mocked: no OpenD+gateway, no network, no credentials.+"""++from __future__ import annotations++from decimal import Decimal+from typing import Any++import pytest++from src.portfolio.compatibility import PortfolioContractError+from src.portfolio.fx import build_rates, to_usd+from src.portfolio.normalization import account_total_usd+from src.trading.connectors.futu import sdk as futu_sdk++pytestmark = pytest.mark.unit++#: Synthetic rates: 8 HKD and 7 CNY per USD.+RATES = build_rates(usd_cny=Decimal("7"), usd_hkd=Decimal("8"))+++class _FakeFutu:+ RET_OK = 0++ class TrdEnv:+ SIMULATE = "SIMULATE"+++class _RecordingTradeCtx:+ """Stands in for ``OpenSecTradeContext`` and records the funds query."""++ def __init__(self, rows: list[dict[str, Any]]) -> None:+ self.rows = rows+ self.accinfo_kwargs: dict[str, Any] = {}++ def get_acc_list(self) -> tuple[int, list[dict[str, Any]]]:+ return (0, [{"trd_env": "SIMULATE", "acc_id": 123}])++ def accinfo_query(self, **kwargs: Any) -> tuple[int, list[dict[str, Any]]]:+ self.accinfo_kwargs = kwargs+ return (0, self.rows)++ def close(self) -> None:+ pass+++def test_unreported_currency_takes_the_requested_currency() -> None:+ row = {"currency": "N/A", "total_assets": 1600.0, "cash": 800.0}++ assert futu_sdk._account_to_dict(row, "HKD")["currency"] == "HKD"+ assert futu_sdk._account_to_dict(row, "USD")["currency"] == "USD"+++def test_broker_reported_currency_is_never_overwritten() -> None:+ row = {"currency": "USD", "total_assets": 1600.0}++ assert futu_sdk._account_to_dict(row, "HKD")["currency"] == "USD"++[email protected]("reported", [None, "", "N/A"])[email protected]("requested", [None, "", "HKD"])+def test_no_row_maps_to_an_empty_currency(+ reported: str | None, requested: str | None+) -> None:+ """An empty currency is valued as USD downstream, so it must not appear."""+ row: dict[str, Any] = {"total_assets": 1600.0}+ if reported is not None:+ row["currency"] = reported++ assert futu_sdk._account_to_dict(row, requested)["currency"] != ""+++def test_undetermined_currency_still_fails_valuation_closed() -> None:+ """Without a requested currency there is no label, and valuation refuses."""+ row = futu_sdk._account_to_dict({"currency": "N/A", "total_assets": 1600.0})++ assert row["currency"] == "N/A"+ with pytest.raises(PortfolioContractError):+ to_usd(Decimal("1600"), row["currency"], RATES)+++def test_multi_currency_account_values_at_the_requested_currency(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The label follows the query, not the connection's market filter."""+ ctx = _RecordingTradeCtx([{"currency": "N/A", "total_assets": 1600.0}])+ monkeypatch.setattr(futu_sdk, "_trade_ctx", lambda cfg: ctx)+ monkeypatch.setattr(futu_sdk, "_require_futu", lambda: _FakeFutu)++ snapshot = futu_sdk.get_account_snapshot(+ futu_sdk.FutuConfig(acc_id=123, filter_trdmarket="US")+ )++ assert ctx.accinfo_kwargs["currency"] == futu_sdk.ACCOUNT_CURRENCY+ assert snapshot["assets"][0]["currency"] == futu_sdk.ACCOUNT_CURRENCY+ assert account_total_usd("futu", snapshot, RATES) == Decimal("200")