"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(cli): connector account renders Binance, Futu and Trading 212 accounts (#1539)
Haozhe Wu20a56cdc5dfa
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex 60efbe939..ab01144ff 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -4630,8 +4630,32 @@ def _first_present(row: dict[str, Any], *keys: str) -> Any:def _print_connector_balances(result: dict[str, Any]) -> int:- """Render the multi-currency balances table returned by ``broker_sdk`` connectors."""+ """Render the ``balances`` list returned by ``broker_sdk`` connectors.++ Two row shapes arrive here. Longbridge reports one row per currency with+ net assets, cash, buying power and margins. ccxt (Binance spot) reports one+ row per asset with ``free`` / ``used`` / ``total``, where ``used`` is locked+ in open orders. Each shape gets its own columns: read through the other+ one's keys, every cell was empty (#1539), and a coin quantity is not a+ net-asset figure.+ """cell = lambda v: "" if v is None else str(v) # noqa: E731+ rows = result.get("balances", [])+ if any("asset" in row for row in rows):+ table = Table(+ title=f"Asset Balances · {result.get('profile_id')}",+ caption=f"{len(rows)} non-zero balances",+ box=box.SIMPLE_HEAVY,+ show_lines=False,+ )+ table.add_column("Asset")+ table.add_column("Free", justify="right")+ table.add_column("Locked", justify="right")+ table.add_column("Total", justify="right")+ for row in rows:+ table.add_row(cell(row.get("asset")), cell(row.get("free")), cell(row.get("used")), cell(row.get("total")))+ console.print(table)+ return EXIT_SUCCESStable = Table(title=f"Account Balances · {result.get('profile_id')}", box=box.SIMPLE_HEAVY, show_lines=False)table.add_column("Currency")table.add_column("Net Assets", justify="right")@@ -4639,7 +4663,7 @@ def _print_connector_balances(result: dict[str, Any]) -> int:table.add_column("Buy Power", justify="right")table.add_column("Init Margin", justify="right")table.add_column("Maint Margin", justify="right")- for row in result.get("balances", []):+ for row in rows:table.add_row(cell(row.get("currency")),cell(row.get("net_assets")),@@ -4652,6 +4676,29 @@ def _print_connector_balances(result: dict[str, Any]) -> int:return EXIT_SUCCESS+def _print_connector_assets(result: dict[str, Any]) -> int:+ """Render Futu's per-currency ``assets`` rows from ``accinfo_query``."""+ cell = lambda v: "" if v is None else str(v) # noqa: E731+ table = Table(title=f"Account Assets · {result.get('profile_id')}", box=box.SIMPLE_HEAVY, show_lines=False)+ table.add_column("Currency")+ table.add_column("Total Assets", justify="right")+ table.add_column("Cash", justify="right")+ table.add_column("Market Value", justify="right")+ table.add_column("Available Funds", justify="right")+ table.add_column("Buying Power", justify="right")+ for row in result.get("assets", []):+ table.add_row(+ cell(row.get("currency")),+ cell(row.get("total_assets")),+ cell(row.get("cash")),+ cell(row.get("market_val")),+ cell(row.get("available_funds")),+ cell(row.get("power")),+ )+ console.print(table)+ return EXIT_SUCCESS++def _normalize_mcp_value(value: Any) -> Any:"""Unwrap a value from a remote MCP call into plain JSON-safe data.@@ -4766,9 +4813,15 @@ def _print_connector_account(result: dict[str, Any]) -> int:label = accounts if accounts != "(none)" else result.get("profile_id", result.get("profile", "unknown"))console.print(f"Accounts: [cyan]{rich_escape(str(label))}[/cyan]")return _print_connector_balances(result)+ if not rows and result.get("assets"):+ return _print_connector_assets(result)account_data = _normalize_mcp_value(result.get("account"))if not rows and isinstance(account_data, dict) and account_data:return _print_connector_account_mapping(result, account_data)+ # Trading 212 returns its cash and account metadata as two separate mappings.+ split = {key: result[key] for key in ("cash", "metadata") if isinstance(result.get(key), dict) and result[key]}+ if not rows and split:+ return _print_connector_account_mapping(result, split)if not rows:# Not the broker_sdk flat shape — try the remote-MCP nested shape.# Robinhood's tool result double-wraps: result["data"] unwraps todiff --git a/agent/tests/test_cli_connector_renderers.py b/agent/tests/test_cli_connector_renderers.pyindex cfeb2b3ce..af1522699 100644--- a/agent/tests/test_cli_connector_renderers.py+++ b/agent/tests/test_cli_connector_renderers.py@@ -78,6 +78,90 @@ def test_connector_account_renders_balances_table(capsys) -> None:assert "12" in out and "345" in out # net_assets 12,345 rendered+def test_connector_account_renders_ccxt_asset_balances(capsys) -> None:+ """#1539: Binance spot rows are asset/free/used/total, not Longbridge's keys."""+ from src.trading.connectors.binance.shaping import nonzero_balances++ ccxt_balance = {+ "info": {},+ "BTC": {"free": 0.5, "used": 0.125, "total": 0.625},+ "USDT": {"free": 1000.0, "used": 0.0, "total": 1000.0},+ "DUST": {"free": 0.0, "used": 0.0, "total": 0.0},+ "free": {}, "used": {}, "total": {},+ }+ binance_account = {+ "status": "ok",+ "profile": "paper",+ "profile_id": "binance-paper-trade",+ "is_testnet": True,+ "balances": nonzero_balances(ccxt_balance),+ }++ rc = _legacy._print_connector_account(binance_account)++ assert rc == _legacy.EXIT_SUCCESS+ out = capsys.readouterr().out+ assert "Net Assets" not in out, "a coin quantity must not be labelled net assets"+ btc = next(line for line in out.splitlines() if "BTC" in line)+ assert "0.5" in btc and "0.125" in btc and "0.625" in btc+ assert any("USDT" in line and "1000.0" in line for line in out.splitlines())+ assert "DUST" not in out+ assert "2 non-zero balances" in out+++def test_connector_account_renders_futu_assets(capsys) -> None:+ """#1539: Futu's accinfo_query rows arrive as ``assets``, not ``balances``."""+ from src.trading.connectors.futu.sdk import _account_to_dict++ futu_account = {+ "status": "ok",+ "profile_id": "futu-paper-trade",+ "trd_env": "SIMULATE",+ "acc_id": 1,+ "assets": [+ _account_to_dict(+ {+ "power": 250000.0,+ "total_assets": 123456.0,+ "cash": 23456.0,+ "market_val": 100000.0,+ "available_funds": 20000.0,+ "securities_assets": 123456.0,+ "currency": "hkd",+ }+ )+ ],+ }++ rc = _legacy._print_connector_account(futu_account)++ assert rc == _legacy.EXIT_SUCCESS+ out = capsys.readouterr().out+ assert "No account summary returned." not in out+ row = next(line for line in out.splitlines() if "HKD" in line)+ for value in ("123456.0", "23456.0", "100000.0", "20000.0", "250000.0"):+ assert value in row+++def test_connector_account_renders_trading212_cash_and_metadata(capsys) -> None:+ """#1539: Trading 212 splits the account into ``cash`` and ``metadata`` mappings."""+ trading212_account = {+ "status": "ok",+ "profile_id": "trading212-live-readonly",+ "cash": {"free": 1000.5, "total": 1500.25, "invested": 499.75, "ppl": 12.5, "blocked": 0.0},+ "metadata": {"currencyCode": "EUR", "id": 4242},+ }++ rc = _legacy._print_connector_account(trading212_account)++ assert rc == _legacy.EXIT_SUCCESS+ out = capsys.readouterr().out+ assert "No account summary returned." not in out+ assert "cash.free" in out and "1000.5" in out+ assert "cash.total" in out and "1500.25" in out+ assert "metadata.currencyCode" in out and "EUR" in out++def test_connector_account_still_handles_ibkr_summary(capsys) -> None:ibkr_account = {"status": "ok",