"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(cli): make connector positions/account renderers schema-tolerant
Haozhe Wu2b31effe13e4
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex 11976f322..5089e15e3 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -3908,10 +3908,52 @@ def cmd_connector_check(return EXIT_SUCCESS+def _first_present(row: dict[str, Any], *keys: str) -> Any:+ """Return the first key whose value is not None (0/'' are kept), else None.++ Connectors expose different result schemas (IBKR-style ``position``/``avg_cost``+ vs Longbridge-style ``quantity``/``cost_price``); the shared CLI renderers use+ this to read whichever key a given connector emitted without dropping a real+ zero quantity via a falsy ``or`` chain.+ """+ for key in keys:+ value = row.get(key)+ if value is not None:+ return value+ return None+++def _print_connector_balances(result: dict[str, Any]) -> int:+ """Render the multi-currency balances table returned by ``broker_sdk`` connectors."""+ cell = lambda v: "" if v is None else str(v) # noqa: E731+ table = 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")+ table.add_column("Total Cash", justify="right")+ 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", []):+ table.add_row(+ cell(row.get("currency")),+ cell(row.get("net_assets")),+ cell(row.get("total_cash")),+ cell(row.get("buy_power")),+ cell(row.get("init_margin")),+ cell(row.get("maintenance_margin")),+ )+ console.print(table)+ return EXIT_SUCCESS++def _print_connector_account(result: dict[str, Any]) -> int:accounts = ", ".join(result.get("accounts", [])) or "(none)"console.print(f"Accounts: [cyan]{rich_escape(accounts)}[/cyan]")rows = result.get("summary", [])+ # broker_sdk connectors (Longbridge, …) return a ``balances`` list instead of+ # IBKR-style ``summary`` tag/value rows; render that when present (#735).+ if not rows and result.get("balances"):+ return _print_connector_balances(result)if not rows:console.print("[dim]No account summary returned.[/dim]")return EXIT_SUCCESS@@ -3984,12 +4026,16 @@ def cmd_connector_positions(table.add_column("Avg Cost", justify="right")table.add_column("Currency")for row in rows:+ # Tolerate both IBKR-style and broker_sdk (Longbridge, …) schemas (#735):+ # position→quantity, avg_cost→cost_price, sec_type→market.+ qty = _first_present(row, "position", "quantity")+ avg_cost = _first_present(row, "avg_cost", "cost_price")table.add_row(str(row.get("account") or ""),str(row.get("local_symbol") or row.get("symbol") or ""),- str(row.get("sec_type") or ""),- str(row.get("position") or ""),- str(row.get("avg_cost") or ""),+ str(row.get("sec_type") or row.get("market") or ""),+ "" if qty is None else str(qty),+ "" if avg_cost is None else str(avg_cost),str(row.get("currency") or ""),)console.print(table)diff --git a/agent/tests/test_cli_connector_renderers.py b/agent/tests/test_cli_connector_renderers.pynew file mode 100644index 000000000..8b80b6b90--- /dev/null+++ b/agent/tests/test_cli_connector_renderers.py@@ -0,0 +1,92 @@+"""Regression (#735): connector CLI renderers must tolerate broker_sdk schemas.++The shared ``connector positions`` / ``connector account`` renderers were written+for the IBKR result shape (``position``/``avg_cost``/``sec_type``/``summary``).+Longbridge (and other ``broker_sdk`` connectors) return ``quantity``/``cost_price``/+``market``/``balances``, so every non-matching key rendered as an empty cell.+"""++from __future__ import annotations++from unittest.mock import patch++import pytest++from cli import _legacy++pytestmark = pytest.mark.unit+++def test_first_present_keeps_zero_and_skips_none() -> None:+ row = {"position": 0.0, "quantity": 5.0}+ # A real zero position must win over the fallback key, not be skipped.+ assert _legacy._first_present(row, "position", "quantity") == 0.0+ assert _legacy._first_present({"quantity": 5.0}, "position", "quantity") == 5.0+ assert _legacy._first_present({"position": None, "quantity": 5.0}, "position", "quantity") == 5.0+ assert _legacy._first_present({}, "position", "quantity") is None+++def test_connector_positions_renders_longbridge_schema(capsys) -> None:+ longbridge_result = {+ "status": "ok",+ "profile_id": "longbridge-paper-trade",+ "positions": [+ {+ "symbol": "AAPL.US",+ "symbol_name": "Apple",+ "quantity": 20.0,+ "available_quantity": 20.0,+ "cost_price": 321.5,+ "currency": "USD",+ "market": "US",+ }+ ],+ }+ with patch("src.trading.service.get_positions", return_value=longbridge_result):+ rc = _legacy.cmd_connector_positions("longbridge-paper-trade")++ assert rc == _legacy.EXIT_SUCCESS+ out = capsys.readouterr().out+ assert "AAPL.US" in out+ assert "20" in out # quantity → Qty+ assert "321.5" in out # cost_price → Avg Cost+ assert "US" in out # market → Type+++def test_connector_account_renders_balances_table(capsys) -> None:+ longbridge_account = {+ "status": "ok",+ "profile_id": "longbridge-paper-trade",+ "balances": [+ {+ "currency": "USD",+ "total_cash": 10_000.0,+ "net_assets": 12_345.0,+ "buy_power": 20_000.0,+ "init_margin": 0.0,+ "maintenance_margin": 0.0,+ }+ ],+ }+ rc = _legacy._print_connector_account(longbridge_account)++ assert rc == _legacy.EXIT_SUCCESS+ out = capsys.readouterr().out+ assert "No account summary returned." not in out+ assert "USD" in out+ assert "12" in out and "345" in out # net_assets 12,345 rendered+++def test_connector_account_still_handles_ibkr_summary(capsys) -> None:+ ibkr_account = {+ "status": "ok",+ "profile_id": "ibkr-local",+ "accounts": ["DU123"],+ "summary": [{"account": "DU123", "tag": "NetLiquidation", "value": "50000", "currency": "USD"}],+ }+ rc = _legacy._print_connector_account(ibkr_account)++ assert rc == _legacy.EXIT_SUCCESS+ out = capsys.readouterr().out+ assert "NetLiquidation" in out+ assert "50000" in out