"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Merge PR #726: fix: Robinhood connector account_number wiring + remote-MCP display shape
Haozhe Wu949ccad59489
diff --cc agent/cli/_legacy.pyindex b08a6d90c,a489c9808..3b3035f62--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@@ -3912,55 -3908,89 +3912,131 @@@ def cmd_connector_checkreturn 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 _normalize_mcp_value(value: Any) -> Any:+ """Unwrap a value from a remote MCP call into plain JSON-safe data.++ Remote connectors (e.g. Robinhood) return their payload as an instance of+ ``fastmcp``'s auto-generated ``Root`` type — a *dataclass* built at runtime+ via ``dataclasses.make_dataclass`` from the tool's JSON Schema, not a+ Pydantic model. ``dataclasses.asdict()`` is the correct unwrap (it also+ recurses into nested dataclass fields, e.g. ``buying_power``); a stray+ Pydantic model elsewhere falls back to ``model_dump()``. Anything else+ (already a dict/list/scalar) is returned as-is.+ """+ import dataclasses++ if dataclasses.is_dataclass(value) and not isinstance(value, type):+ return dataclasses.asdict(value)+ if hasattr(value, "model_dump"):+ return value.model_dump()+ return value+++ def _flatten_account_fields(data: dict[str, Any], prefix: str = "") -> list[tuple[str, str]]:+ """Flatten a remote-MCP account payload into (tag, value) rows.++ Nested one level (e.g. ``buying_power.buying_power``) rather than+ recursing arbitrarily deep, since broker account payloads are shallow.+ Skips ``None`` and zero-valued numeric-looking fields, matching the+ guidance the broker's own response typically includes (zero means no+ holdings in that asset class — noise to omit, not a real 0.00 balance).+ """+ rows: list[tuple[str, str]] = []+ for key, value in data.items():+ if key == "currency" or value is None:+ continue+ label = f"{prefix}{key}"+ normalized = _normalize_mcp_value(value)+ if isinstance(normalized, dict):+ rows.extend(_flatten_account_fields(normalized, prefix=f"{label}."))+ continue+ text = str(normalized)+ try:+ if float(text) == 0.0:+ continue+ except (TypeError, ValueError):+ pass+ rows.append((label, text))+ return rows++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:+ # Not the broker_sdk flat shape — try the remote-MCP nested shape.+ # Robinhood's tool result double-wraps: result["data"] unwraps to+ # {"data": <actual account fields>, "guide": "<advisory text>"},+ # not the fields directly — drill one more level in when present.+ wrapper = _normalize_mcp_value(result.get("data"))+ raw_data = wrapper+ guide = result.get("guide")+ if isinstance(wrapper, dict) and "data" in wrapper and "guide" in wrapper:+ raw_data = _normalize_mcp_value(wrapper.get("data"))+ guide = wrapper.get("guide") or guide+ if isinstance(raw_data, dict):+ currency = raw_data.get("currency", "")+ account_label = result.get("account_number") or accounts+ table = Table(+ title=f"Account Summary · {result.get('profile_id')}", box=box.SIMPLE_HEAVY, show_lines=False+ )+ table.add_column("Field")+ table.add_column("Value", justify="right")+ for tag, value in _flatten_account_fields(raw_data):+ is_currency_code = tag.endswith("currency") or tag.endswith("_currency")+ display = value if is_currency_code else f"{value} {currency}".strip()+ table.add_row(tag, display)+ console.print(f"Account: [cyan]{rich_escape(str(account_label))}[/cyan]")+ console.print(table)+ if guide:+ console.print(f"[dim]{rich_escape(str(guide))}[/dim]")+ return EXIT_SUCCESS+ console.print(f"Accounts: [cyan]{rich_escape(accounts)}[/cyan]")console.print("[dim]No account summary returned.[/dim]")return EXIT_SUCCESS+ console.print(f"Accounts: [cyan]{rich_escape(accounts)}[/cyan]")table = Table(title=f"Account Summary · {result.get('profile_id')}", box=box.SIMPLE_HEAVY, show_lines=False)table.add_column("Account")table.add_column("Tag")