Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(cli): vibe-trading portfolio show | refresh | sources

Haozhe Wuca538e5312aa
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index 5957ec6da..c52803a39 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -71,6 +71,9 @@ UPLOADS_DIR = get_uploads_dir()
EXIT_SUCCESS = 0
EXIT_RUN_FAILED = 1
EXIT_USAGE_ERROR = 2
+
+# Rows printed by `vibe-trading portfolio show` before the combined-holdings table is cut.
+_PORTFOLIO_CLI_MAX_HOLDINGS = 25
RICH_TAG_PATTERN = re.compile(r"\[/?[^\]]+\]")
SWARM_RUN_USAGE = """--swarm-run PRESET '{"k":"v"}'"""
SWARM_RUN_VARS_PREVIEW_CHARS = 80
@@ -3974,7 +3977,15 @@ def cmd_connector_list() -> int:
def cmd_connector_init(connector_id: str, destination: str = ".") -> int:
- """Create a local-only read connector template for Codex to implement."""
+ """Create a local-only read connector template.
+
+ Args:
+ connector_id: Lowercase connector id used for the template directory.
+ destination: Parent directory the template is created in.
+
+ Returns:
+ The process exit code.
+ """
from src.trading.plugin_scaffold import scaffold_connector
try:
@@ -3983,12 +3994,22 @@ def cmd_connector_init(connector_id: str, destination: str = ".") -> int:
console.print(f"[red]{exc}[/red]")
return EXIT_USAGE_ERROR
console.print(f"[green]Created local connector template[/green] {path}")
- console.print("[dim]Implement adapter.py, then run connector validate and connector install.[/dim]")
+ console.print(
+ "[dim]Implement adapter.py from the broker's official read-only API docs, "
+ "then run connector validate and connector install.[/dim]"
+ )
return EXIT_SUCCESS
def cmd_connector_validate(directory: str) -> int:
- """Validate a local read-only connector manifest."""
+ """Validate a local read-only connector manifest.
+
+ Args:
+ directory: Directory holding the connector manifest.
+
+ Returns:
+ The process exit code.
+ """
from src.trading.plugin_scaffold import validate_connector
try:
@@ -4001,7 +4022,14 @@ def cmd_connector_validate(directory: str) -> int:
def cmd_connector_install(directory: str) -> int:
- """Install a validated connector into the user's private connector directory."""
+ """Install a validated connector into the user's private connector directory.
+
+ Args:
+ directory: Directory holding the validated connector.
+
+ Returns:
+ The process exit code.
+ """
from src.trading.plugin_scaffold import install_connector
try:
@@ -4013,6 +4041,171 @@ def cmd_connector_install(directory: str) -> int:
return EXIT_SUCCESS
+def _portfolio_service(service: Any | None = None) -> Any:
+ """Return the injected portfolio service, or build the default one.
+
+ Args:
+ service: Optional pre-built service (tests inject a stub).
+
+ Returns:
+ A ``PortfolioService`` instance.
+ """
+ if service is not None:
+ return service
+ from src.portfolio.service import PortfolioService
+
+ return PortfolioService()
+
+
+def _print_portfolio_snapshot(snapshot: dict[str, Any]) -> None:
+ """Render one portfolio snapshot: totals, per-source accounts, holdings, warnings.
+
+ Args:
+ snapshot: A snapshot envelope as produced by ``PortfolioService``.
+ """
+ totals = snapshot.get("totals") or {}
+ usd = float(totals.get("usd") or 0.0)
+ cny = float(totals.get("cny") or 0.0)
+ state = "[green]complete[/green]" if snapshot.get("complete") else "[yellow]INCOMPLETE[/yellow]"
+ console.print(
+ f"Snapshot [cyan]{rich_escape(str(snapshot.get('created_at') or '?'))}[/cyan] · {state} · "
+ f"total [bold]{usd:,.2f} USD[/bold] / {cny:,.0f} CNY"
+ )
+
+ accounts = Table(title="Sources", box=box.SIMPLE_HEAVY, show_lines=False)
+ accounts.add_column("Source")
+ accounts.add_column("Connector")
+ accounts.add_column("Status", justify="center")
+ accounts.add_column("Total USD", justify="right")
+ accounts.add_column("Last success")
+ for row in snapshot.get("accounts") or []:
+ ok = row.get("status") == "ok"
+ total = row.get("total_usd")
+ accounts.add_row(
+ rich_escape(str(row.get("label") or row.get("source_id") or "?")),
+ rich_escape(str(row.get("broker") or "")),
+ "[green]ok[/green]" if ok else f"[red]{rich_escape(str(row.get('status')))}[/red]",
+ f"{float(total):,.2f}" if total is not None else "[dim]excluded[/dim]",
+ rich_escape(str(row.get("last_success_at") or "never")),
+ )
+ console.print(accounts)
+
+ holdings = Table(title="Holdings (combined across sources)", box=box.SIMPLE_HEAVY, show_lines=False)
+ holdings.add_column("Symbol")
+ holdings.add_column("Type")
+ holdings.add_column("Value USD", justify="right")
+ holdings.add_column("Weight", justify="right")
+ holdings.add_column("Unrealized P/L USD", justify="right")
+ holdings.add_column("Sources")
+ for row in (snapshot.get("combined_holdings") or [])[:_PORTFOLIO_CLI_MAX_HOLDINGS]:
+ value = float(row.get("market_value_usd") or 0.0)
+ pnl = row.get("unrealized_pnl_usd")
+ holdings.add_row(
+ rich_escape(str(row.get("symbol") or "?")),
+ rich_escape(str(row.get("asset_type") or "")),
+ f"{value:,.2f}",
+ f"{(value / usd * 100):.1f}%" if usd > 0 else "—",
+ f"{float(pnl):,.2f}" if pnl is not None else "—",
+ rich_escape(", ".join(str(item) for item in (row.get("sources") or row.get("brokers") or []))),
+ )
+ console.print(holdings)
+ for warning in snapshot.get("warnings") or []:
+ console.print(f"[yellow]![/yellow] {rich_escape(str(warning))}")
+
+
+def cmd_portfolio_show(service: Any | None = None) -> int:
+ """Print the latest stored portfolio snapshot.
+
+ Args:
+ service: Optional ``PortfolioService`` (tests inject a stub).
+
+ Returns:
+ The process exit code.
+ """
+ snapshot = _portfolio_service(service).latest()
+ if snapshot is None:
+ console.print(
+ "[dim]No portfolio snapshot yet. Select sources on the Web UI Portfolio page "
+ "(or `vibe-trading portfolio sources`), then run `vibe-trading portfolio refresh`.[/dim]"
+ )
+ return EXIT_SUCCESS
+ _print_portfolio_snapshot(snapshot)
+ return EXIT_SUCCESS
+
+
+def cmd_portfolio_refresh(service: Any | None = None) -> int:
+ """Read every enabled source now, store a new snapshot, and print it.
+
+ A source that fails is reported and excluded from the totals; the command
+ then exits non-zero so scripts notice the portfolio is incomplete.
+
+ Args:
+ service: Optional ``PortfolioService`` (tests inject a stub).
+
+ Returns:
+ ``EXIT_SUCCESS`` for a complete snapshot, ``EXIT_RUN_FAILED`` otherwise.
+ """
+ try:
+ snapshot = _portfolio_service(service).refresh()
+ except RuntimeError as exc:
+ console.print(f"[red]{rich_escape(str(exc))}[/red]")
+ return EXIT_RUN_FAILED
+ _print_portfolio_snapshot(snapshot)
+ return EXIT_SUCCESS if snapshot.get("complete") else EXIT_RUN_FAILED
+
+
+def cmd_portfolio_sources(service: Any | None = None) -> int:
+ """List the local read-only connections and whether the portfolio uses them.
+
+ Args:
+ service: Optional ``PortfolioService`` (tests inject a stub).
+
+ Returns:
+ The process exit code.
+ """
+ rows = _portfolio_service(service).sources()
+ table = Table(title="Portfolio sources", box=box.SIMPLE_HEAVY, show_lines=False)
+ table.add_column("Selected", justify="center", width=8)
+ table.add_column("Connection")
+ table.add_column("Connector")
+ table.add_column("Env")
+ table.add_column("Transport")
+ table.add_column("Credentials", justify="center")
+ for row in rows:
+ table.add_row(
+ "[green]*[/green]" if row.get("selected") else "",
+ f"[cyan]{rich_escape(str(row.get('connection_id') or row.get('id')))}[/cyan]\n[dim]{rich_escape(str(row.get('label') or ''))}[/dim]",
+ rich_escape(str(row.get("connector") or "")),
+ rich_escape(str(row.get("environment") or "")),
+ rich_escape(str(row.get("transport") or "")),
+ "[green]ok[/green]" if row.get("credentials_configured") else "[dim]-[/dim]",
+ )
+ console.print(table)
+ if not rows:
+ console.print("[dim]No local connections yet. Create one on the Web UI Portfolio page (Manage accounts → Connection center).[/dim]")
+ return EXIT_SUCCESS
+
+
+def _dispatch_portfolio(args: argparse.Namespace) -> int:
+ """Route ``vibe-trading portfolio <subcommand>``; bare ``portfolio`` shows.
+
+ Args:
+ args: Parsed CLI arguments.
+
+ Returns:
+ The process exit code.
+ """
+ sub = getattr(args, "portfolio_command", None) or "show"
+ if sub == "show":
+ return cmd_portfolio_show()
+ if sub == "refresh":
+ return cmd_portfolio_refresh()
+ if sub == "sources":
+ return cmd_portfolio_sources()
+ console.print(f"[red]Unknown portfolio subcommand: {sub}[/red]")
+ return EXIT_USAGE_ERROR
+
+
def cmd_connector_use(profile_id: str) -> int:
"""Select the default trading connector profile."""
from src.trading.profiles import profile_by_id, save_selected_profile_id
@@ -4989,6 +5182,19 @@ def _build_parser() -> argparse.ArgumentParser:
memory_forget_parser.add_argument("name", help="Memory title or filename stem")
memory_forget_parser.add_argument("-y", "--yes", action="store_true", help="Skip confirmation prompt")
+ portfolio_parser = subparsers.add_parser(
+ "portfolio",
+ help="Read-only multi-broker portfolio (the Web UI /portfolio page, in the terminal)",
+ )
+ portfolio_subparsers = portfolio_parser.add_subparsers(dest="portfolio_command")
+ portfolio_subparsers.add_parser("show", help="Print the latest stored snapshot")
+ portfolio_subparsers.add_parser(
+ "refresh", help="Read every enabled source now, store a new snapshot, and print it"
+ )
+ portfolio_subparsers.add_parser(
+ "sources", help="List local read-only connections and whether the portfolio uses them"
+ )
+
connector_parser = subparsers.add_parser("connector", help="Manage trading connector profiles")
connector_subparsers = connector_parser.add_subparsers(dest="connector_command")
@@ -6014,6 +6220,8 @@ def main(argv: list[str] | None = None) -> int:
if args.command == "strategy-evidence":
from cli.commands.strategy_evidence import dispatch as _strategy_evidence_dispatch
return _coerce_exit_code(_strategy_evidence_dispatch(args))
+ if args.command == "portfolio":
+ return _coerce_exit_code(_dispatch_portfolio(args))
if args.command == "connector":
return _coerce_exit_code(_dispatch_connector(args))
if args.command == "memory":
diff --git a/agent/tests/test_cli_portfolio.py b/agent/tests/test_cli_portfolio.py
new file mode 100644
index 000000000..b561bbc2d
--- /dev/null
+++ b/agent/tests/test_cli_portfolio.py
@@ -0,0 +1,175 @@
+"""CLI surface for the read-only portfolio: ``vibe-trading portfolio show|refresh|sources``.
+
+The Web UI and the ``portfolio_summary`` tool already expose the snapshot; the
+CLI is the third surface the project's full-stack rule asks for. These tests
+drive the renderers through a stub service so no connector, network or runtime
+directory is touched.
+"""
+
+from __future__ import annotations
+
+from argparse import Namespace
+
+import pytest
+
+from cli import _legacy
+
+pytestmark = pytest.mark.unit
+
+
+class _Service:
+ """Minimal stand-in for ``PortfolioService``."""
+
+ def __init__(self, snapshot=None, sources=(), refresh_error=None) -> None:
+ self._snapshot = snapshot
+ self._sources = list(sources)
+ self._refresh_error = refresh_error
+ self.refresh_calls = 0
+
+ def latest(self):
+ """Return the scripted snapshot (``None`` when nothing is stored)."""
+ return self._snapshot
+
+ def refresh(self):
+ """Return the scripted snapshot or raise the scripted error."""
+ self.refresh_calls += 1
+ if self._refresh_error is not None:
+ raise self._refresh_error
+ return self._snapshot
+
+ def sources(self):
+ """Return the scripted source catalog rows."""
+ return list(self._sources)
+
+
+_SNAPSHOT = {
+ "snapshot_id": "abc",
+ "created_at": "2026-08-22T05:00:00+00:00",
+ "complete": False,
+ "totals": {"usd": 1500.0, "cny": 10800.0},
+ "accounts": [
+ {
+ "source_id": "ibkr",
+ "label": "IBKR",
+ "broker": "ibkr",
+ "status": "ok",
+ "total_usd": 1500.0,
+ "last_success_at": "2026-08-22T05:00:00+00:00",
+ },
+ {
+ "source_id": "binance",
+ "label": "Binance",
+ "broker": "binance",
+ "status": "error",
+ "error": "ConnectionError",
+ "total_usd": None,
+ "last_success_at": None,
+ },
+ ],
+ "combined_holdings": [
+ {
+ "symbol": "AAPL",
+ "asset_type": "stock",
+ "market_value_usd": 1500.0,
+ "unrealized_pnl_usd": 250.0,
+ "sources": ["IBKR"],
+ }
+ ],
+ "warnings": ["These sources failed to refresh and their value is excluded: Binance."],
+}
+
+
+def test_show_prints_totals_sources_holdings_and_warnings(capsys) -> None:
+ rc = _legacy.cmd_portfolio_show(service=_Service(snapshot=_SNAPSHOT))
+ out = capsys.readouterr().out
+ assert rc == _legacy.EXIT_SUCCESS
+ assert "INCOMPLETE" in out
+ assert "1,500.00" in out
+ assert "IBKR" in out and "Binance" in out
+ assert "excluded" in out # the failed source has no total
+ assert "AAPL" in out and "100.0%" in out
+ assert "failed to refresh" in out
+
+
+def test_show_without_snapshot_points_at_refresh(capsys) -> None:
+ rc = _legacy.cmd_portfolio_show(service=_Service(snapshot=None))
+ out = capsys.readouterr().out
+ assert rc == _legacy.EXIT_SUCCESS
+ assert "portfolio refresh" in out
+
+
+def test_refresh_prints_and_exits_nonzero_when_incomplete(capsys) -> None:
+ service = _Service(snapshot=_SNAPSHOT)
+ rc = _legacy.cmd_portfolio_refresh(service=service)
+ out = capsys.readouterr().out
+ assert service.refresh_calls == 1
+ assert rc == _legacy.EXIT_RUN_FAILED
+ assert "INCOMPLETE" in out
+
+
+def test_refresh_exits_zero_for_a_complete_snapshot() -> None:
+ complete = {**_SNAPSHOT, "complete": True, "accounts": _SNAPSHOT["accounts"][:1], "warnings": []}
+ assert _legacy.cmd_portfolio_refresh(service=_Service(snapshot=complete)) == _legacy.EXIT_SUCCESS
+
+
+def test_refresh_reports_a_runtime_error_instead_of_crashing(capsys) -> None:
+ rc = _legacy.cmd_portfolio_refresh(
+ service=_Service(refresh_error=RuntimeError("Add and enable at least one read-only account"))
+ )
+ out = capsys.readouterr().out
+ assert rc == _legacy.EXIT_RUN_FAILED
+ assert "at least one read-only account" in out
+
+
+def test_sources_marks_selected_and_credentialed_rows(capsys) -> None:
+ rows = [
+ {
+ "connection_id": "ibkr-live",
+ "label": "IBKR main",
+ "connector": "ibkr",
+ "environment": "live",
+ "transport": "local_tws",
+ "selected": True,
+ "credentials_configured": False,
+ },
+ {
+ "connection_id": "mybroker-live",
+ "label": "Plugin",
+ "connector": "mybroker",
+ "environment": "live",
+ "transport": "local_plugin",
+ "selected": False,
+ "credentials_configured": True,
+ },
+ ]
+ rc = _legacy.cmd_portfolio_sources(service=_Service(sources=rows))
+ out = capsys.readouterr().out
+ assert rc == _legacy.EXIT_SUCCESS
+ assert "ibkr-live" in out and "mybroker-live" in out
+ assert "local_plugin" in out
+ assert "*" in out # the selected marker
+
+
+def test_sources_without_connections_explains_where_to_create_one(capsys) -> None:
+ _legacy.cmd_portfolio_sources(service=_Service(sources=[]))
+ assert "No local connections yet" in capsys.readouterr().out
+
+
+def test_dispatch_defaults_to_show_and_routes_subcommands(monkeypatch) -> None:
+ calls: list[str] = []
+ monkeypatch.setattr(_legacy, "cmd_portfolio_show", lambda: calls.append("show") or 0)
+ monkeypatch.setattr(_legacy, "cmd_portfolio_refresh", lambda: calls.append("refresh") or 0)
+ monkeypatch.setattr(_legacy, "cmd_portfolio_sources", lambda: calls.append("sources") or 0)
+ assert _legacy._dispatch_portfolio(Namespace(portfolio_command=None)) == 0
+ assert _legacy._dispatch_portfolio(Namespace(portfolio_command="refresh")) == 0
+ assert _legacy._dispatch_portfolio(Namespace(portfolio_command="sources")) == 0
+ assert calls == ["show", "refresh", "sources"]
+ assert _legacy._dispatch_portfolio(Namespace(portfolio_command="bogus")) == _legacy.EXIT_USAGE_ERROR
+
+
+def test_parser_registers_the_portfolio_subcommands() -> None:
+ parser = _legacy._build_parser()
+ assert parser.parse_args(["portfolio"]).portfolio_command is None
+ for sub in ("show", "refresh", "sources"):
+ args = parser.parse_args(["portfolio", sub])
+ assert args.command == "portfolio" and args.portfolio_command == sub