"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(portfolio): add local multi-broker holdings dashboard
Yang8b2fefe90f58
diff --git a/README.md b/README.mdindex 7e40d3071..371ed83ff 100644--- a/README.md+++ b/README.md@@ -324,6 +324,131 @@ vibe-trading --upload trades_export.csvvibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, and compare it with my actual trades"```+## 💼 Local Multi-Broker Portfolio++The Web UI includes an editable, read-only **Portfolio** page. Choose any+built-in connector profile that declares `account.read`, `positions.read`, and+`readonly=True`; OAuth read-discovery profiles are supported too. A new+installation starts with no selected account. **Manage accounts** lets you add,+disable, rename, and reorder sources, include or exclude cash, and choose USD or+CNY as the primary display currency.++A manual refresh:++- reads each enabled source through the connector registry;+- values holdings in USD and displays a CNY conversion;+- stores immutable snapshots in `~/.vibe-trading/portfolio/portfolio.sqlite3`;+- stores credential-free source preferences in owner-only+ `~/.vibe-trading/portfolio.json`;+- isolates source failures, carries forward the last successful source data,+ and excludes partial snapshots from the history chart;+- detects the same instrument held across multiple sources;+- exports the latest holdings as CSV; and+- exposes a sanitized `portfolio_summary` tool to the built-in Agent.++The Agent context excludes account numbers, credential material, order IDs,+personal names, and local paths. Portfolio arithmetic is deterministic; the LLM+only interprets the sanitized result. No portfolio endpoint or tool can place,+cancel, transfer, or withdraw. The settings API rejects profiles that expose+write capabilities; credentials stay in their connector-specific stores and+never enter `portfolio.json`.++### Local connector instances and Codex workflow++Portfolio sources are **connection instances**, not hard-coded broker names:++- a `TradingProfile` in the repository is a reusable, credential-free template;+- a connection in `~/.vibe-trading/connections.json` is an account instance on+ one computer; and+- `portfolio.json` references only the local `connection_id`.++User-installed connectors live outside the Git checkout under+`~/.vibe-trading/connectors/<connector>/`. Their `connector.json` manifest must+declare `readonly: true` plus `account.read` and `positions.read`; manifests+with order, transfer, cancellation, withdrawal, or other write capabilities+are rejected. Each adapter implements only:++```python+check_status(credentials=..., config=...)+get_account_snapshot(credentials=..., config=...)+get_positions(credentials=..., config=...)+```++The manifest declares credential field names, but never values. Values entered+in the local Connection Center are stored through the operating-system secret+vault (macOS Keychain, Windows Credential Manager, or Linux Secret Service) and+are never returned by the Web API.++Codex can start a connector from the bundled local-only template:++```bash+vibe-trading connector init my-broker --destination /tmp+# Ask Codex to implement /tmp/my-broker/adapter.py from the official read API docs.+vibe-trading connector validate /tmp/my-broker+vibe-trading connector install /tmp/my-broker+```++Restart the local server, open **Portfolio → Manage accounts → Connection+center**, create an account connection from the installed profile, save its+credentials, test it, and then add that connection to the portfolio. Private+plugins and credentials remain local; a public, credential-free connector can+still be contributed separately when useful to the community.++Install the two optional broker SDKs (CCXT for Binance is in the base package):++```bash+pip install "vibe-trading-ai[ibkr,longbridge]"+```++Configure IBKR against a running TWS or IB Gateway session with read-only API+access enabled:++```bash+vibe-trading connector configure ibkr-live-local-readonly --yes+vibe-trading connector check ibkr-live-local-readonly+```++Set the Longbridge credentials in `agent/.env` (or an owner-only+`~/.vibe-trading/longbridge.json`) and use an API application intended for+read access:++```dotenv+LONGBRIDGE_APP_KEY=...+LONGBRIDGE_APP_SECRET=...+LONGBRIDGE_ACCESS_TOKEN=...+```++Store a Binance key with **read-only permission only** in+`~/.vibe-trading/binance.json` and make the file owner-readable only:++```json+{+ "api_key": "...",+ "api_secret": "...",+ "profile": "live-readonly",+ "readonly": true+}+```++```bash+chmod 600 ~/.vibe-trading/binance.json+vibe-trading connector check binance-live-sdk-readonly+vibe-trading connector check longbridge-live-sdk-readonly+```++Build the frontend and start the local server, then open `/portfolio` and press+**Refresh all**:++```bash+cd frontend && npm ci && npm run build && cd ..+vibe-trading serve --port 8899+```++Historical changes begin with the first successful refresh. Until deposits and+withdrawals are imported, the history is an asset-value series and must not be+treated as investment return. Crypto values use USDT as a USD valuation proxy;+the snapshot records this limitation rather than treating it as an exact FX rate.+---## 🧪 Research Workflow@@ -1462,7 +1587,7 @@ endpoint in read-only mode. Add this to `~/.vibe-trading/agent.json`:"mcpServers": {"ibkr": {"type": "streamableHttp",- "url": "https://api.ibkr.com/v1/api/mcp",+ "url": "https://api.ibkr.com/v1/api/mcp-public","auth": {"type": "oauth","scopes": ["mcp.read"],diff --git a/README_zh.md b/README_zh.mdindex fff796065..573c4a0e1 100644--- a/README_zh.md+++ b/README_zh.md@@ -326,6 +326,52 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an---+## 💼 本地多账户持仓++Web UI 提供可编辑的只读 **持仓** 页面。点击“管理账户”,即可从仓库已有的只读连接 Profile 中添加、停用、重命名和排序账户,设置是否计入现金,并选择 USD 或 CNY 作为主要显示货币。新安装默认不选择任何账户。++手动刷新会依次读取所有已启用账户,统一换算 USD/CNY,并把不可变快照保存到 `~/.vibe-trading/portfolio/portfolio.sqlite3`。账户选择等不含密钥的偏好保存在权限为仅当前用户可读写的 `~/.vibe-trading/portfolio.json`。单个账户失败时会继续使用该账户最后一次成功数据;不完整快照不会进入历史曲线。++持仓设置只接受同时声明账户读取、持仓读取和只读能力的连接 Profile,拒绝交易型 Profile。券商密钥仍保留在各连接器自己的凭证存储中,不会进入持仓配置。持仓接口不能下单、撤单、转账或提现;发送给模型的分析上下文也不包含账号、密钥、订单 ID、个人姓名或本机路径。++### 本地连接实例与 Codex 接入流程++持仓数据源现在是“本地连接实例”,而不是写死的券商名称:++- 仓库里的 `TradingProfile` 是不含凭证、可复用的连接模板;+- `~/.vibe-trading/connections.json` 记录这台电脑上的账户连接;+- `portfolio.json` 只引用本地 `connection_id`。++开发者自己的连接器安装在 Git 仓库外的+`~/.vibe-trading/connectors/<connector>/`。其中 `connector.json` 必须声明+`readonly: true`、`account.read` 和 `positions.read`;如果出现下单、撤单、+转账、提现或其他写能力,框架会拒绝加载。连接器只需实现三个统一函数:++```python+check_status(credentials=..., config=...)+get_account_snapshot(credentials=..., config=...)+get_positions(credentials=..., config=...)+```++清单文件只声明需要哪些凭证字段,不保存值。在网页“连接中心”输入的值通过+操作系统凭证库保存(macOS 钥匙串、Windows Credential Manager 或 Linux Secret+Service),Web API 不会返回凭证明文。++Codex 可以用仓库提供的模板快速开始:++```bash+vibe-trading connector init my-broker --destination /tmp+# 让 Codex 根据券商官方只读 API 文档实现 /tmp/my-broker/adapter.py+vibe-trading connector validate /tmp/my-broker+vibe-trading connector install /tmp/my-broker+```++重启本地服务后,打开“持仓 → 管理账户 → 连接中心”,从新安装的 Profile 创建+本机账户连接、保存凭证、测试连接,再加入持仓汇总。私人插件和密钥始终只留在+本机;如果某个连接器适合社区,也可以单独提交一份不含任何凭证的公共实现。++---+## 🧪 Research Workflow多数运行都会遵循同一条证据路径:路由请求、加载正确的市场上下文、执行工具、验证输出,并保持 artifacts 可检查。@@ -1356,7 +1402,7 @@ Vibe-Trading 可以以只读模式直连 Interactive Brokers 的官方远程 MCP"mcpServers": {"ibkr": {"type": "streamableHttp",- "url": "https://api.ibkr.com/v1/api/mcp",+ "url": "https://api.ibkr.com/v1/api/mcp-public","auth": {"type": "oauth","scopes": ["mcp.read"],diff --git a/agent/api_server.py b/agent/api_server.pyindex 8d82263fc..412d76f2c 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -11,7 +11,7 @@ from __future__ import annotationsimport loggingfrom contextlib import asynccontextmanagerfrom pathlib import Path-from typing import Any, AsyncIterator, Dict+from typing import AsyncIteratorfrom fastapi import FastAPI, HTTPException, Request, status # noqa: F401from fastapi.responses import FileResponse # noqa: F401@@ -252,6 +252,13 @@ from src.api.swarm_routes import _get_swarm_runtime # noqa: F401, E402from src.api.live_routes import register_live_routes # noqa: E402register_live_routes(app)+# --- Read-only portfolio dashboard ---+from src.api.portfolio_routes import register_portfolio_routes # noqa: E402+register_portfolio_routes(app)++from src.api.connection_routes import register_connection_routes # noqa: E402+register_connection_routes(app)+from src.api.live_routes import ( # noqa: F401, E402CommitMandateRequest,LiveHaltRequest,@@ -321,19 +328,7 @@ def serve_main(argv: list[str] | None = None) -> int:import argparseimport subprocessimport uvicorn- from fastapi.staticfiles import StaticFiles- from starlette.exceptions import HTTPException as StarletteHTTPException-- class SPAStaticFiles(StaticFiles):- """Serve index.html for browser refreshes on client-side routes."""-- async def get_response(self, path: str, scope: Dict[str, Any]):- try:- return await super().get_response(path, scope)- except StarletteHTTPException as exc:- if exc.status_code != status.HTTP_404_NOT_FOUND:- raise- return await super().get_response("index.html", scope)+ from src.api.spa import SPAStaticFilesparser = argparse.ArgumentParser(description="Vibe-Trading Server")parser.add_argument("--port", type=int, default=8000, help="Listen port (default 8000)")diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex ba738c30b..c1038f92b 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -3965,6 +3965,46 @@ def cmd_connector_list() -> int:return EXIT_SUCCESS+def cmd_connector_init(connector_id: str, destination: str = ".") -> int:+ """Create a local-only read connector template for Codex to implement."""+ from src.trading.plugin_scaffold import scaffold_connector++ try:+ path = scaffold_connector(connector_id, Path(destination))+ except ValueError as exc:+ 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]")+ return EXIT_SUCCESS+++def cmd_connector_validate(directory: str) -> int:+ """Validate a local read-only connector manifest."""+ from src.trading.plugin_scaffold import validate_connector++ try:+ plugin = validate_connector(Path(directory))+ except ValueError as exc:+ console.print(f"[red]{exc}[/red]")+ return EXIT_USAGE_ERROR+ console.print(f"[green]Valid read-only connector[/green] {plugin.profile.id}")+ return EXIT_SUCCESS+++def cmd_connector_install(directory: str) -> int:+ """Install a validated connector into the user's private connector directory."""+ from src.trading.plugin_scaffold import install_connector++ try:+ path = install_connector(Path(directory))+ except ValueError as exc:+ console.print(f"[red]{exc}[/red]")+ return EXIT_USAGE_ERROR+ console.print(f"[green]Installed local connector[/green] {path}")+ return EXIT_SUCCESS++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@@ -4665,6 +4705,12 @@ def _dispatch_connector(args: argparse.Namespace) -> int:sub = getattr(args, "connector_command", None)if sub == "list":return cmd_connector_list()+ if sub == "init":+ return cmd_connector_init(args.connector_id, args.destination)+ if sub == "validate":+ return cmd_connector_validate(args.directory)+ if sub == "install":+ return cmd_connector_install(args.directory)if sub == "use":return cmd_connector_use(args.profile)if sub == "configure":@@ -4922,6 +4968,24 @@ def _build_parser() -> argparse.ArgumentParser:connector_subparsers.add_parser("list", help="List selectable connector profiles")+ connector_init = connector_subparsers.add_parser(+ "init", help="Create a local read-only connector template"+ )+ connector_init.add_argument("connector_id", help="Lowercase connector id")+ connector_init.add_argument(+ "--destination", default=".", help="Parent directory for the template"+ )++ connector_validate = connector_subparsers.add_parser(+ "validate", help="Validate a local connector directory"+ )+ connector_validate.add_argument("directory")++ connector_install = connector_subparsers.add_parser(+ "install", help="Install a validated connector locally"+ )+ connector_install.add_argument("directory")+connector_use = connector_subparsers.add_parser("use", help="Select the default connector profile")connector_use.add_argument("profile", help="Profile id, e.g. ibkr-paper-local")diff --git a/agent/src/api/connection_routes.py b/agent/src/api/connection_routes.pynew file mode 100644index 000000000..f97122e8a--- /dev/null+++ b/agent/src/api/connection_routes.py@@ -0,0 +1,141 @@+"""Local-only API for read-only connection instances and plugin discovery."""++from __future__ import annotations++from fastapi import Depends, FastAPI, HTTPException+from pydantic import BaseModel, Field++from src.api.security import require_auth, require_settings_write_auth+from src.portfolio.config import PortfolioSettingsStore+from src.trading.connections import (+ ConnectionStore,+ TradingConnection,+ credential_fields,+ readonly_profile_catalog,+)+from src.trading.local_plugins import plugin_root+from src.trading.service import check_connection+++class ConnectionRequest(BaseModel):+ id: str = Field(min_length=1, max_length=80)+ profile_id: str = Field(min_length=1, max_length=80)+ label: str = Field(min_length=1, max_length=80)+++class CredentialRequest(BaseModel):+ values: dict[str, str] = Field(default_factory=dict)+++def register_connection_routes(app: FastAPI) -> None:+ def store() -> ConnectionStore:+ return ConnectionStore()++ @app.get("/api/connections", dependencies=[Depends(require_auth)])+ def list_connections():+ return {+ "status": "ok",+ "connections": store().public_list(),+ "profiles": readonly_profile_catalog(),+ "plugin_directory": str(plugin_root()),+ }++ @app.post(+ "/api/connections",+ dependencies=[Depends(require_settings_write_auth)],+ )+ def create_connection(payload: ConnectionRequest):+ try:+ instance = store().create(payload.id, payload.profile_id, payload.label)+ return {"status": "ok", "connection": instance.to_dict()}+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc++ @app.put(+ "/api/connections/{connection_id}",+ dependencies=[Depends(require_settings_write_auth)],+ )+ def update_connection(connection_id: str, payload: ConnectionRequest):+ if payload.id.strip().lower() != connection_id.strip().lower():+ raise HTTPException(+ status_code=400, detail="connection id cannot be changed"+ )+ try:+ instance = store()+ current = instance.get(connection_id)+ if payload.profile_id.strip().lower() != current.profile_id:+ raise ValueError("connection profile cannot be changed")+ updated = instance.save(+ TradingConnection(+ id=current.id,+ profile_id=current.profile_id,+ label=payload.label,+ credential_ref=current.credential_ref,+ created_at=current.created_at,+ )+ )+ return {"status": "ok", "connection": updated.to_dict()}+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc++ @app.post(+ "/api/connections/{connection_id}/credentials",+ dependencies=[Depends(require_settings_write_auth)],+ )+ def save_connection_credentials(connection_id: str, payload: CredentialRequest):+ try:+ instance = store()+ connection = instance.get(connection_id)+ allowed = set(credential_fields(connection.profile_id))+ if not set(payload.values).issubset(allowed):+ raise ValueError(+ "credential payload contains fields not declared by the connector"+ )+ instance.credentials.save(connection.id, payload.values)+ return {+ "status": "ok",+ "credential_status": instance.credentials.status(+ connection.id,+ allowed,+ ),+ }+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc++ @app.post(+ "/api/connections/{connection_id}/check",+ dependencies=[Depends(require_auth)],+ )+ def check_local_connection(connection_id: str):+ try:+ connection = store().get(connection_id)+ report = check_connection(+ connection.profile_id,+ connection_id=connection.id,+ )+ return {+ "status": "ok",+ "connection_id": connection.id,+ "report": report,+ }+ except (RuntimeError, ValueError) as exc:+ raise HTTPException(status_code=503, detail=str(exc)) from exc++ @app.delete(+ "/api/connections/{connection_id}",+ dependencies=[Depends(require_settings_write_auth)],+ )+ def delete_connection(connection_id: str):+ try:+ selected = {+ source.connection_id+ for source in PortfolioSettingsStore().load().sources+ }+ if connection_id.strip().lower() in selected:+ raise ValueError(+ "remove this connection from the portfolio before deleting it"+ )+ store().delete(connection_id)+ return {"status": "ok", "deleted": connection_id}+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from excdiff --git a/agent/src/api/portfolio_routes.py b/agent/src/api/portfolio_routes.pynew file mode 100644index 000000000..7ab24b423--- /dev/null+++ b/agent/src/api/portfolio_routes.py@@ -0,0 +1,144 @@+"""Authenticated Web API for the local read-only portfolio dashboard."""++from __future__ import annotations++import threading+from copy import deepcopy++from fastapi import Depends, FastAPI, HTTPException, Query, Response+from pydantic import BaseModel, Field++from src.api.security import require_auth, require_settings_write_auth+from src.portfolio.service import PortfolioService++_REFRESH_LOCK = threading.Lock()+_REFRESH_OPERATION_LOCK = threading.Lock()+_REFRESH_STATE = {+ "running": False,+ "current": None,+ "sources": {},+}+++class PortfolioSourceRequest(BaseModel):+ connection_id: str+ label: str+ enabled: bool = True+ order: int = 0+ include_cash: bool = True+++class PortfolioSettingsRequest(BaseModel):+ display_currency: str = Field(default="USD", pattern="^(USD|CNY)$")+ sources: list[PortfolioSourceRequest] = Field(default_factory=list, max_length=50)+++def _set_refresh_progress(broker: str, status: str, error: str | None) -> None:+ with _REFRESH_LOCK:+ _REFRESH_STATE["current"] = broker if status == "refreshing" else None+ _REFRESH_STATE["sources"][broker] = {"status": status, "error": error}+++def register_portfolio_routes(app: FastAPI) -> None:+ def service(*, progress: bool = False) -> PortfolioService:+ return PortfolioService(+ progress_callback=_set_refresh_progress if progress else None+ )++ @app.get("/api/portfolio", dependencies=[Depends(require_auth)])+ def latest_portfolio():+ snapshot = service().latest()+ if snapshot is None:+ return {"status": "empty", "snapshot": None}+ return {"status": "ok", "snapshot": snapshot}++ @app.post("/api/portfolio/refresh", dependencies=[Depends(require_auth)])+ def refresh_portfolio():+ if not _REFRESH_OPERATION_LOCK.acquire(blocking=False):+ raise HTTPException(+ status_code=409, detail="portfolio refresh already running"+ )+ try:+ selected = [+ item for item in service().settings()["sources"] if item["enabled"]+ ]+ with _REFRESH_LOCK:+ _REFRESH_STATE.update(+ running=True,+ current=None,+ sources={+ item["connection_id"]: {"status": "pending", "error": None}+ for item in selected+ },+ )+ return {"status": "ok", "snapshot": service(progress=True).refresh()}+ except RuntimeError as exc:+ raise HTTPException(status_code=503, detail=str(exc)) from exc+ finally:+ with _REFRESH_LOCK:+ _REFRESH_STATE["running"] = False+ _REFRESH_STATE["current"] = None+ _REFRESH_OPERATION_LOCK.release()++ @app.get("/api/portfolio/refresh-status", dependencies=[Depends(require_auth)])+ def portfolio_refresh_status():+ with _REFRESH_LOCK:+ refresh = deepcopy(_REFRESH_STATE)+ # ``brokers`` was the original dashboard field name. Keep it as a+ # compatibility alias so an already-open frontend can safely poll+ # a newer backend while its cached assets are being replaced.+ refresh["brokers"] = deepcopy(refresh["sources"])+ return {"status": "ok", "refresh": refresh}++ @app.post(+ "/api/portfolio/sources/{source_id}/reconnect",+ dependencies=[Depends(require_auth)],+ )+ def reconnect_portfolio_source(source_id: str):+ try:+ return service().reconnect_source(source_id)+ except RuntimeError as exc:+ raise HTTPException(status_code=503, detail=str(exc)) from exc++ @app.get("/api/portfolio/settings", dependencies=[Depends(require_auth)])+ def portfolio_settings():+ instance = service()+ return {+ "status": "ok",+ "settings": instance.settings(),+ "catalog": instance.sources(),+ }++ @app.put(+ "/api/portfolio/settings",+ dependencies=[Depends(require_settings_write_auth)],+ )+ def update_portfolio_settings(payload: PortfolioSettingsRequest):+ try:+ instance = service()+ settings = instance.save_settings(payload.model_dump())+ return {"status": "ok", "settings": settings, "catalog": instance.sources()}+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc++ @app.get("/api/portfolio/history", dependencies=[Depends(require_auth)])+ def portfolio_history(limit: int = Query(180, ge=1, le=2000)):+ return {"status": "ok", "history": service().history(limit)}++ @app.get("/api/portfolio/analysis-context", dependencies=[Depends(require_auth)])+ def portfolio_analysis_context():+ context = service().analysis_context()+ if context is None:+ raise HTTPException(status_code=404, detail="no portfolio snapshot exists")+ return {"status": "ok", "context": context}++ @app.get("/api/portfolio/export.csv", dependencies=[Depends(require_auth)])+ def export_portfolio_csv():+ content = service().export_csv()+ if not content:+ raise HTTPException(status_code=404, detail="no portfolio snapshot exists")+ return Response(+ content=content,+ media_type="text/csv; charset=utf-8",+ headers={"Content-Disposition": "attachment; filename=portfolio.csv"},+ )diff --git a/agent/src/api/spa.py b/agent/src/api/spa.pynew file mode 100644index 000000000..7faa9aefc--- /dev/null+++ b/agent/src/api/spa.py@@ -0,0 +1,20 @@+"""Static-file serving rules for the bundled single-page application."""++from __future__ import annotations++from typing import Any++from fastapi.staticfiles import StaticFiles+from starlette.exceptions import HTTPException as StarletteHTTPException+++class SPAStaticFiles(StaticFiles):+ """Serve index.html for browser refreshes on client-side routes."""++ async def get_response(self, path: str, scope: dict[str, Any]):+ try:+ return await super().get_response(path, scope)+ except StarletteHTTPException as exc:+ if exc.status_code != 404:+ raise+ return await super().get_response("index.html", scope)diff --git a/agent/src/config/schema.py b/agent/src/config/schema.pyindex 8062dadeb..9442e85c5 100644--- a/agent/src/config/schema.py+++ b/agent/src/config/schema.py@@ -226,7 +226,8 @@ ROBINHOOD_MCP_SERVER_SEED: dict[str, object] = {# config must pin an explicit tool allowlist plus pass the live order gate.IBKR_MCP_SERVER_SEED: dict[str, object] = {"type": "streamableHttp",- "url": "https://api.ibkr.com/v1/api/mcp",+ "url": "https://api.ibkr.com/v1/api/mcp-public",+ "init_timeout": 300.0,"auth": {"type": "oauth","scopes": ["mcp.read"],diff --git a/agent/src/portfolio/__init__.py b/agent/src/portfolio/__init__.pynew file mode 100644index 000000000..7c0b7f91e--- /dev/null+++ b/agent/src/portfolio/__init__.py@@ -0,0 +1,5 @@+"""Read-only multi-broker portfolio aggregation."""++from .service import PortfolioService++__all__ = ["PortfolioService"]diff --git a/agent/src/portfolio/config.py b/agent/src/portfolio/config.pynew file mode 100644index 000000000..0daff5ea4--- /dev/null+++ b/agent/src/portfolio/config.py@@ -0,0 +1,216 @@+"""Editable, credential-free settings for the portfolio dashboard."""++from __future__ import annotations++import json+import os+import re+import tempfile+from dataclasses import asdict, dataclass+from pathlib import Path+from typing import Any++from src.config.paths import get_runtime_root+from src.trading.connections import ConnectionStore+from src.trading.profiles import list_profiles, profile_by_id+from src.trading.types import TradingProfile++CONFIG_FILENAME = "portfolio.json"+_SOURCE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,79}$")+++@dataclass(frozen=True)+class PortfolioSource:+ """One enabled or disabled local connection selected for aggregation."""++ connection_id: str+ label: str+ enabled: bool = True+ order: int = 0+ include_cash: bool = True++ @property+ def id(self) -> str:+ """Compatibility alias used by snapshots and refresh progress."""+ return self.connection_id++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)+++@dataclass(frozen=True)+class PortfolioSettings:+ """Portfolio display preferences and selected read-only sources."""++ display_currency: str = "USD"+ sources: tuple[PortfolioSource, ...] = ()++ def to_dict(self) -> dict[str, Any]:+ return {+ "display_currency": self.display_currency,+ "sources": [source.to_dict() for source in self.sources],+ }+++def eligible_profiles() -> list[TradingProfile]:+ """Return profiles that are structurally safe for portfolio reads."""+ return sorted(+ (+ profile+ for profile in list_profiles()+ if profile.readonly+ and (+ (+ "account.read" in profile.capabilities+ and "positions.read" in profile.capabilities+ )+ or "mcp.read.discovery" in profile.capabilities+ )+ ),+ key=lambda profile: (profile.connector, profile.environment, profile.label),+ )+++def source_catalog(+ settings: PortfolioSettings,+ connection_store: ConnectionStore | None = None,+) -> list[dict[str, Any]]:+ """Describe configured local connections without exposing secret values."""+ store = connection_store or ConnectionStore()+ selected = {source.connection_id: source for source in settings.sources}+ rows = []+ for connection in store.public_list():+ source = selected.get(connection["id"])+ rows.append(+ {+ **connection,+ "connection_id": connection["id"],+ "selected": source is not None,+ "source_id": source.id if source is not None else None,+ }+ )+ return rows+++def parse_settings(+ payload: dict[str, Any],+ connection_store: ConnectionStore | None = None,+) -> PortfolioSettings:+ """Validate untrusted Web settings against the local connection registry."""+ store = connection_store or ConnectionStore()+ currency = str(payload.get("display_currency") or "USD").strip().upper()+ if currency not in {"USD", "CNY"}:+ raise ValueError("display_currency must be USD or CNY")++ raw_sources = payload.get("sources")+ if not isinstance(raw_sources, list):+ raise ValueError("sources must be a list")+ if len(raw_sources) > 50:+ raise ValueError("at most 50 portfolio sources are allowed")++ seen_ids: set[str] = set()+ sources: list[PortfolioSource] = []+ for index, raw in enumerate(raw_sources):+ if not isinstance(raw, dict):+ raise ValueError("each portfolio source must be an object")+ connection_id = (+ str(raw.get("connection_id") or raw.get("id") or "").strip().lower()+ )+ if not _SOURCE_ID_RE.fullmatch(connection_id):+ raise ValueError(f"invalid portfolio connection id: {connection_id or '?'}")+ legacy_profile_id = str(raw.get("profile_id") or "").strip().lower()+ if legacy_profile_id:+ legacy_profile = profile_by_id(legacy_profile_id)+ connection = store.ensure(+ connection_id,+ legacy_profile.id,+ str(raw.get("label") or legacy_profile.label),+ )+ else:+ connection = store.get(connection_id)+ profile = profile_by_id(connection.profile_id)+ if profile not in eligible_profiles():+ raise ValueError(+ f"connection is not eligible for read-only portfolios: {connection_id}"+ )+ if connection_id in seen_ids:+ raise ValueError("portfolio connection ids must be unique")+ label = str(raw.get("label") or connection.label).strip()+ if (+ not label+ or len(label) > 80+ or any(ord(character) < 32 for character in label)+ ):+ raise ValueError(+ "portfolio source labels must contain 1 to 80 printable characters"+ )+ seen_ids.add(connection_id)+ sources.append(+ PortfolioSource(+ connection_id=connection_id,+ label=label,+ enabled=bool(raw.get("enabled", True)),+ order=int(raw.get("order", index)),+ include_cash=bool(raw.get("include_cash", True)),+ )+ )+ return PortfolioSettings(+ display_currency=currency,+ sources=tuple(sorted(sources, key=lambda item: (item.order, item.id))),+ )+++class PortfolioSettingsStore:+ """Owner-only JSON store containing no broker credentials."""++ def __init__(+ self,+ path: Path | None = None,+ *,+ connection_store: ConnectionStore | None = None,+ ) -> None:+ self.path = path or (get_runtime_root() / CONFIG_FILENAME)+ connection_path = (+ self.path.with_name("connections.json") if path is not None else None+ )+ self.connection_store = connection_store or ConnectionStore(connection_path)++ def load(self) -> PortfolioSettings:+ if self.path.exists():+ try:+ payload = json.loads(self.path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as exc:+ raise ValueError(f"invalid portfolio settings: {exc}") from exc+ if not isinstance(payload, dict):+ raise ValueError("invalid portfolio settings: root must be an object")+ settings = parse_settings(payload, self.connection_store)+ if any("profile_id" in source for source in payload.get("sources", [])):+ self.save(settings)+ return settings++ settings = PortfolioSettings()+ self.save(settings)+ return settings++ def save(self, settings: PortfolioSettings | dict[str, Any]) -> PortfolioSettings:+ validated = (+ parse_settings(settings, self.connection_store)+ if isinstance(settings, dict)+ else parse_settings(settings.to_dict(), self.connection_store)+ )+ self.path.parent.mkdir(parents=True, exist_ok=True)+ descriptor, temporary = tempfile.mkstemp(+ prefix=".portfolio-", suffix=".json", dir=self.path.parent+ )+ try:+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:+ json.dump(validated.to_dict(), handle, ensure_ascii=False, indent=2)+ handle.write("\n")+ handle.flush()+ os.fsync(handle.fileno())+ os.chmod(temporary, 0o600)+ os.replace(temporary, self.path)+ finally:+ if os.path.exists(temporary):+ os.unlink(temporary)+ return validateddiff --git a/agent/src/portfolio/longbridge_worker.py b/agent/src/portfolio/longbridge_worker.pynew file mode 100644index 000000000..b355a53b8--- /dev/null+++ b/agent/src/portfolio/longbridge_worker.py@@ -0,0 +1,57 @@+"""Isolated Longbridge reader for the portfolio dashboard.++The official macOS SDK owns a native runtime which can terminate the Python+process while its contexts are being destroyed. Emit the read-only payload+and exit without running native destructors so a connector issue cannot take+down the portfolio API server.+"""++from __future__ import annotations++import json+import os++MARKER = "VIBE_PORTFOLIO_JSON="+++def main() -> None:+ try:+ from src.trading.connectors.longbridge.sdk import (+ build_config,+ get_account_and_positions,+ get_quotes,+ )++ config = build_config({"profile": "live-readonly", "region": "global"})+ payload = get_account_and_positions(config)+ symbols = [+ str(item.get("symbol") or "")+ for item in payload.get("positions", {}).get("positions", [])+ if item.get("symbol")+ ]+ try:+ payload["quotes"] = get_quotes(symbols, config=config)+ except (+ Exception+ ) as exc: # account totals remain usable if quote permission/network fails+ payload["quotes"] = {+ "status": "error",+ "error": type(exc).__name__,+ "quotes": [],+ }+ print(MARKER + json.dumps(payload, ensure_ascii=False), flush=True)+ os._exit(0)+ except Exception as exc: # noqa: BLE001 - worker returns a redaction-safe code+ print(+ MARKER+ + json.dumps(+ {"error": type(exc).__name__},+ ensure_ascii=False,+ ),+ flush=True,+ )+ os._exit(1)+++if __name__ == "__main__":+ main()diff --git a/agent/src/portfolio/normalization.py b/agent/src/portfolio/normalization.pynew file mode 100644index 000000000..978a1f85c--- /dev/null+++ b/agent/src/portfolio/normalization.py@@ -0,0 +1,317 @@+"""Connector-neutral normalization and valuation helpers."""++from __future__ import annotations++from datetime import datetime, timezone+from decimal import Decimal, InvalidOperation+from typing import Any++from src.trading.types import TradingProfile++STABLECOINS = frozenset({"USDT", "USDC", "FDUSD", "TUSD", "BUSD"})++_TRANSPORT_AUTH = {+ "remote_mcp": ("OAuth", "automatic"),+ "local_tws": ("Local broker session", "session"),+ "broker_sdk": ("API credentials", "provider_managed"),+ "local_plugin": ("Local connector", "provider_managed"),+}+++def _decimal(value: Any, default: Decimal = Decimal("0")) -> Decimal:+ try:+ if value is None or value == "":+ return default+ result = Decimal(str(value))+ return result if result.is_finite() else default+ except (InvalidOperation, ValueError, TypeError):+ return default+++def _number(value: Decimal) -> float:+ return float(value.quantize(Decimal("0.00000001")))+++def _now() -> str:+ return datetime.now(timezone.utc).isoformat()+++def normalize_position(broker: str, row: dict[str, Any]) -> dict[str, Any]:+ """Convert a connector position row to the portfolio wire shape."""+ if broker == "ibkr":+ symbol = str(row.get("symbol") or row.get("local_symbol") or "").upper()+ sec_type = str(row.get("sec_type") or "STK").upper()+ market_price = _decimal(row.get("market_price", row.get("current_price")))+ return {+ "broker": broker,+ "symbol": symbol,+ "quote_symbol": symbol,+ "name": symbol,+ "asset_type": "etf" if sec_type == "ETF" else "stock",+ "market": str(row.get("exchange") or ""),+ "exchange": row.get("exchange"),+ "currency": str(row.get("currency") or "USD").upper(),+ "quantity": _number(_decimal(row.get("position", row.get("quantity")))),+ "cost_price": _number(+ _decimal(row.get("avg_cost", row.get("average_cost")))+ ),+ "market_price": _number(market_price) if market_price > 0 else None,+ "source_market_value": row.get("market_value"),+ "source_unrealized_pnl": row.get("unrealized_pnl"),+ "contract_id": row.get("contract_id"),+ "updated_at": _now(),+ }+ if broker == "longbridge":+ symbol = str(row.get("symbol") or "").upper()+ market = str(row.get("market") or symbol.rsplit(".", 1)[-1]).upper()+ return {+ "broker": broker,+ "symbol": symbol,+ "quote_symbol": symbol,+ "name": str(row.get("symbol_name") or symbol),+ "asset_type": "stock",+ "market": market,+ "currency": str(row.get("currency") or "USD").upper(),+ "quantity": _number(_decimal(row.get("quantity"))),+ "cost_price": _number(_decimal(row.get("cost_price"))),+ "updated_at": _now(),+ }++ symbol = str(row.get("symbol") or row.get("code") or "").upper()+ source = str(row.get("source") or ("spot" if broker == "binance" else "account"))+ currency = str(row.get("currency") or "").upper()+ if not currency:+ currency = "HKD" if symbol.endswith(".HK") else "USD"+ quantity = _decimal(+ row.get(+ "quantity", row.get("qty", row.get("position", row.get("position_qty")))+ )+ )+ cost = _decimal(+ row.get(+ "cost_price",+ row.get("average_cost", row.get("avg_cost", row.get("avg_entry_price"))),+ )+ )+ market_price = _decimal(row.get("market_price", row.get("current_price")))+ source_market_value = row.get("market_value", row.get("market_val"))+ if market_price <= 0 and quantity != 0 and _decimal(source_market_value) > 0:+ market_price = abs(_decimal(source_market_value) / quantity)+ sec_type = str(row.get("sec_type") or "").upper()+ declared_asset_type = str(row.get("asset_type") or "").strip().lower()+ crypto = broker in {"binance", "okx"} or declared_asset_type in {+ "crypto",+ "stablecoin",+ }+ asset_type = declared_asset_type or (+ "stablecoin"+ if symbol in STABLECOINS+ else "crypto" if crypto else "etf" if sec_type == "ETF" else "stock"+ )+ return {+ "broker": broker,+ "symbol": symbol,+ "quote_symbol": str(+ row.get("quote_symbol")+ or (f"{symbol}/USDT" if broker == "binance" else symbol)+ ),+ "name": str(+ row.get("name")+ or row.get("symbol_name")+ or (+ f"{symbol} (Simple Earn)"+ if source == "simple_earn_flexible"+ else symbol+ )+ ),+ "asset_type": asset_type,+ "market": str(row.get("market") or row.get("exchange") or broker).upper(),+ "currency": currency,+ "quantity": _number(quantity),+ "cost_price": _number(cost) if cost > 0 else None,+ "market_price": _number(market_price) if market_price > 0 else None,+ "price_currency": str(row.get("price_currency") or currency).upper(),+ "source_market_value": source_market_value,+ "source_unrealized_pnl": row.get("unrealized_pnl", row.get("unrealized_pl")),+ "free": row.get("free"),+ "used": row.get("used"),+ "source": source,+ "updated_at": _now(),+ }+++def value_position(+ row: dict[str, Any], *, usd_hkd: Decimal, usd_cny: Decimal+) -> dict[str, Any]:+ """Calculate USD/CNY market value and unrealized P/L."""+ price = _decimal(row.get("market_price"))+ quantity = _decimal(row.get("quantity"))+ currency = str(row.get("price_currency") or row.get("currency") or "USD").upper()+ fx_to_usd = Decimal("1")+ if currency == "HKD":+ fx_to_usd = Decimal("1") / usd_hkd+ elif currency == "CNY":+ fx_to_usd = Decimal("1") / usd_cny+ priced = price > 0+ market_usd = quantity * price * fx_to_usd if priced else Decimal("0")+ cost = _decimal(row.get("cost_price"))+ source_pnl = row.get("source_unrealized_pnl")+ pnl_usd = (+ _decimal(source_pnl) * fx_to_usd+ if priced and source_pnl is not None+ else (price - cost) * quantity * fx_to_usd if priced and cost > 0 else None+ )+ row.update(+ priced=priced,+ market_value_usd=_number(market_usd),+ market_value_cny=_number(market_usd * usd_cny),+ unrealized_pnl_usd=_number(pnl_usd) if pnl_usd is not None else None,+ )+ for key in (+ "quote_symbol",+ "exchange",+ "source_market_value",+ "source_unrealized_pnl",+ "contract_id",+ ):+ row.pop(key, None)+ return row+++def _to_usd(+ value: Decimal, currency: str, usd_hkd: Decimal, usd_cny: Decimal+) -> Decimal:+ if currency == "HKD":+ return value / usd_hkd+ if currency == "CNY":+ return value / usd_cny+ return value+++def account_total_usd(+ broker: str,+ account: dict[str, Any],+ usd_hkd: Decimal,+ usd_cny: Decimal,+ fallback: Decimal = Decimal("0"),+) -> Decimal:+ """Extract a connector-reported net liquidation value."""+ if broker == "longbridge":+ total = Decimal("0")+ for row in account.get("balances", []):+ total += _to_usd(+ _decimal(row.get("net_assets")),+ str(row.get("currency") or "USD").upper(),+ usd_hkd,+ usd_cny,+ )+ return total+ if broker == "ibkr":+ candidates: dict[str, Decimal] = {}+ for row in account.get("summary", []):+ if str(row.get("tag") or "").lower() == "netliquidation":+ currency = str(row.get("currency") or "USD").upper()+ candidates[currency] = max(+ candidates.get(currency, Decimal("0")), _decimal(row.get("value"))+ )+ if "USD" in candidates:+ return candidates["USD"]+ return sum(+ (+ _to_usd(value, currency, usd_hkd, usd_cny)+ for currency, value in candidates.items()+ ),+ Decimal("0"),+ )+ nested = account.get("account") if isinstance(account.get("account"), dict) else {}+ currency = str(nested.get("currency") or "USD").upper()+ for key in ("portfolio_value", "total_equity", "equity"):+ value = _decimal(nested.get(key))+ if value > 0:+ return _to_usd(value, currency, usd_hkd, usd_cny)+ total = Decimal("0")+ for row in account.get("assets", []):+ value = _decimal(+ row.get("net_liquidation", row.get("total_assets", row.get("equity")))+ )+ total += _to_usd(+ value, str(row.get("currency") or currency).upper(), usd_hkd, usd_cny+ )+ return total if total > 0 else fallback+++def account_cash_usd(+ broker: str, account: dict[str, Any], usd_hkd: Decimal, usd_cny: Decimal+) -> Decimal:+ """Return broker-reported cash without guessing from missing quotes."""+ rows = account.get("balances", []) if broker == "longbridge" else []+ if rows:+ return max(+ Decimal("0"),+ sum(+ (+ _to_usd(+ _decimal(row.get("total_cash")),+ str(row.get("currency") or "USD").upper(),+ usd_hkd,+ usd_cny,+ )+ for row in rows+ ),+ Decimal("0"),+ ),+ )+ if broker == "ibkr":+ candidates: dict[str, Decimal] = {}+ for row in account.get("summary", []):+ if str(row.get("tag") or "").lower() in {"totalcashvalue", "cashbalance"}:+ currency = str(row.get("currency") or "USD").upper()+ candidates[currency] = max(+ candidates.get(currency, Decimal("0")), _decimal(row.get("value"))+ )+ if "USD" in candidates:+ return max(Decimal("0"), candidates["USD"])+ return max(+ Decimal("0"),+ sum(+ (+ _to_usd(value, currency, usd_hkd, usd_cny)+ for currency, value in candidates.items()+ ),+ Decimal("0"),+ ),+ )+ nested = account.get("account") if isinstance(account.get("account"), dict) else {}+ currency = str(nested.get("currency") or "USD").upper()+ nested_cash = _decimal(nested.get("cash"))+ if nested_cash > 0:+ return _to_usd(nested_cash, currency, usd_hkd, usd_cny)+ return max(+ Decimal("0"),+ sum(+ (+ _to_usd(+ _decimal(row.get("cash", row.get("cash_balance"))),+ str(row.get("currency") or currency).upper(),+ usd_hkd,+ usd_cny,+ )+ for row in account.get("assets", [])+ ),+ Decimal("0"),+ ),+ )+++def auth_metadata(profile: TradingProfile) -> dict[str, Any]:+ """Return public profile metadata without inferring broker-side key permissions."""+ method, renewal = _TRANSPORT_AUTH.get(+ profile.transport,+ (profile.transport.replace("_", " ").title(), "provider_managed"),+ )+ return {+ "method": method,+ "renewal": renewal,+ "readonly": profile.readonly,+ "detail": profile.notes or "Read-only connector profile.",+ }diff --git a/agent/src/portfolio/service.py b/agent/src/portfolio/service.pynew file mode 100644index 000000000..0ac088bb6--- /dev/null+++ b/agent/src/portfolio/service.py@@ -0,0 +1,726 @@+"""Deterministic, read-only aggregation across configured trading profiles."""++from __future__ import annotations++import csv+import io+import json+import subprocess+import sys+import urllib.request+import uuid+from datetime import datetime, timezone+from decimal import Decimal, InvalidOperation+from typing import Any, Callable++from src.portfolio.config import (+ PortfolioSettingsStore,+ PortfolioSource,+ source_catalog,+)+from src.portfolio.normalization import (+ STABLECOINS,+ account_cash_usd,+ account_total_usd,+ auth_metadata,+ normalize_position,+ value_position,+)+from src.portfolio.store import PortfolioStore+from src.trading.profiles import profile_by_id+++def _decimal(value: Any, default: Decimal = Decimal("0")) -> Decimal:+ try:+ if value is None or value == "":+ return default+ result = Decimal(str(value))+ return result if result.is_finite() else default+ except (InvalidOperation, ValueError, TypeError):+ return default+++def _number(value: Decimal) -> float:+ return float(value.quantize(Decimal("0.00000001")))+++def _now() -> str:+ return datetime.now(timezone.utc).isoformat()+++def _quote_price(payload: dict[str, Any]) -> Decimal | None:+ quote = payload.get("quote") or {}+ for key in ("last", "close"):+ price = _decimal(quote.get(key))+ if price > 0:+ return price+ bid, ask = _decimal(quote.get("bid")), _decimal(quote.get("ask"))+ if bid > 0 and ask > 0:+ return (bid + ask) / 2+ return bid if bid > 0 else ask if ask > 0 else None+++class PortfolioService:+ def __init__(+ self,+ store: PortfolioStore | None = None,+ *,+ settings_store: PortfolioSettingsStore | None = None,+ get_account: Callable[..., dict[str, Any]] | None = None,+ get_positions: Callable[..., dict[str, Any]] | None = None,+ get_quote: Callable[..., dict[str, Any]] | None = None,+ get_longbridge_quotes: Callable[..., dict[str, Any]] | None = None,+ fx_fetcher: Callable[[], tuple[Decimal, Decimal, str]] | None = None,+ progress_callback: Callable[[str, str, str | None], None] | None = None,+ ) -> None:+ self._use_longbridge_worker = get_account is None and get_positions is None+ self._noninteractive_ibkr = get_account is None and get_positions is None+ if get_account is None or get_positions is None or get_quote is None:+ from src.trading import service as trading++ get_account = get_account or trading.get_account+ get_positions = get_positions or trading.get_positions+ get_quote = get_quote or trading.get_quote+ self.store = store or PortfolioStore()+ self._get_account = get_account+ self._get_positions = get_positions+ self._get_quote = get_quote+ self._get_longbridge_quotes = get_longbridge_quotes+ self._fx_fetcher = fx_fetcher or self._fetch_fx+ self._progress_callback = progress_callback+ self.settings_store = settings_store or PortfolioSettingsStore()++ def settings(self) -> dict[str, Any]:+ """Return credential-free editable settings."""+ return self.settings_store.load().to_dict()++ def save_settings(self, payload: dict[str, Any]) -> dict[str, Any]:+ """Validate and persist editable settings."""+ return self.settings_store.save(payload).to_dict()++ def sources(self) -> list[dict[str, Any]]:+ """Return local read-only connections eligible for this portfolio."""+ return source_catalog(+ self.settings_store.load(),+ self.settings_store.connection_store,+ )++ def _connection_profile(self, source: PortfolioSource):+ connection = self.settings_store.connection_store.get(source.connection_id)+ return connection, profile_by_id(connection.profile_id)++ def refresh(self) -> dict[str, Any]:+ settings = self.settings_store.load()+ sources = [source for source in settings.sources if source.enabled]+ if not sources:+ raise RuntimeError("请先在持仓页添加并启用至少一个只读账户")+ usd_cny, usd_hkd, fx_at, fx_stale = self._rates()+ refreshed_at = _now()+ results: dict[str, dict[str, Any]] = {}+ # The Longbridge Python SDK wraps a native runtime whose contexts are+ # not safe to create inside this refresh thread pool on macOS. Keep the+ # manual refresh deterministic and sequential; a failed broker remains+ # isolated and never prevents the other accounts from refreshing.+ for source in sources:+ if self._progress_callback is not None:+ self._progress_callback(source.id, "refreshing", None)+ try:+ results[source.id] = self._collect_source(source)+ if self._progress_callback is not None:+ self._progress_callback(source.id, "ok", None)+ except Exception as exc: # read failures are isolated per connector+ connection, profile = self._connection_profile(source)+ results[source.id] = {+ "source_id": source.id,+ "profile_id": connection.profile_id,+ "label": source.label,+ "broker": profile.connector,+ "status": "error",+ "error_code": type(exc).__name__,+ "error": str(exc)[:300],+ "positions": [],+ }+ if self._progress_callback is not None:+ self._progress_callback(source.id, "error", str(exc)[:160])++ positions: list[dict[str, Any]] = []+ accounts: list[dict[str, Any]] = []+ for source in sources:+ result = results[source.id]+ broker = result["broker"]+ connection, profile = self._connection_profile(source)+ if result["status"] != "ok":+ cached = self.store.latest_successful_source(source.id)+ if cached is None:+ accounts.append(+ {+ "source_id": source.id,+ "profile_id": connection.profile_id,+ "label": source.label,+ "broker": broker,+ "status": "error",+ "error": result.get("error"),+ "error_code": result.get("error_code"),+ "auth": auth_metadata(profile),+ }+ )+ continue+ cached_account = dict(cached["account"])+ cached_account.update(+ source_id=source.id,+ profile_id=connection.profile_id,+ label=source.label,+ broker=profile.connector,+ status="stale",+ data_state="cached",+ last_success_at=cached["created_at"],+ error=result.get("error"),+ error_code=result.get("error_code"),+ auth=auth_metadata(profile),+ )+ cached_positions = [dict(item) for item in cached["positions"]]+ cached_priced = sum(+ (+ _decimal(item.get("market_value_usd"))+ for item in cached_positions+ ),+ Decimal("0"),+ )+ cached_cash = _decimal(cached_account.get("cash_usd"))+ cached_unpriced = _decimal(cached_account.get("unpriced_or_other_usd"))+ if "unpriced_or_other_usd" not in cached_account:+ cached_unpriced = max(+ Decimal("0"),+ _decimal(cached_account.get("cash_or_unallocated_usd"))+ - cached_cash,+ )+ if not source.include_cash:+ cached_account["total_usd"] = _number(+ max(+ Decimal("0"),+ _decimal(cached_account.get("total_usd")) - cached_cash,+ )+ )+ cached_cash = Decimal("0")+ cached_account.update(+ priced_value_usd=_number(cached_priced),+ cash_usd=_number(cached_cash),+ unpriced_or_other_usd=_number(cached_unpriced),+ priced_position_count=sum(+ 1 for item in cached_positions if item.get("priced")+ ),+ unpriced_position_count=sum(+ 1 for item in cached_positions if not item.get("priced")+ ),+ )+ cached_account["total_cny"] = _number(+ _decimal(cached_account.get("total_usd")) * usd_cny+ )+ accounts.append(cached_account)+ for cached_position in cached_positions:+ cached_position["source_id"] = source.id+ cached_position["profile_id"] = connection.profile_id+ cached_position["source_label"] = source.label+ cached_position["stale"] = True+ cached_position["market_value_cny"] = _number(+ _decimal(cached_position.get("market_value_usd")) * usd_cny+ )+ positions.append(cached_position)+ continue+ broker_positions = [+ value_position(row, usd_hkd=usd_hkd, usd_cny=usd_cny)+ for row in result["positions"]+ ]+ priced_total = sum(+ (_decimal(row.get("market_value_usd")) for row in broker_positions),+ Decimal("0"),+ )+ account_total = account_total_usd(+ broker,+ result["account"],+ usd_hkd,+ usd_cny,+ priced_total,+ )+ if broker == "binance":+ account_total = priced_total+ cash_total = min(+ account_total,+ account_cash_usd(broker, result["account"], usd_hkd, usd_cny),+ )+ if not source.include_cash:+ account_total = max(Decimal("0"), account_total - cash_total)+ cash_total = Decimal("0")+ unpriced_or_other = max(+ Decimal("0"), account_total - priced_total - cash_total+ )+ priced_count = sum(1 for row in broker_positions if row.get("priced"))+ accounts.append(+ {+ "source_id": source.id,+ "profile_id": connection.profile_id,+ "label": source.label,+ "broker": broker,+ "status": "ok",+ "data_state": "fresh",+ "last_success_at": refreshed_at,+ "total_usd": _number(account_total),+ "total_cny": _number(account_total * usd_cny),+ "priced_value_usd": _number(priced_total),+ "cash_usd": _number(cash_total),+ "unpriced_or_other_usd": _number(unpriced_or_other),+ # Retain the original field for older frontends/API users.+ "cash_or_unallocated_usd": _number(cash_total + unpriced_or_other),+ "position_count": len(broker_positions),+ "priced_position_count": priced_count,+ "unpriced_position_count": len(broker_positions) - priced_count,+ "auth": auth_metadata(profile),+ }+ )+ positions.extend(broker_positions)++ total_usd = sum(+ (_decimal(row.get("total_usd")) for row in accounts), Decimal("0")+ )+ complete = len(accounts) == len(sources) and all(+ row["status"] == "ok" for row in accounts+ )+ priced_usd = sum(+ (_decimal(row.get("priced_value_usd")) for row in accounts), Decimal("0")+ )+ cash_usd = sum(+ (_decimal(row.get("cash_usd")) for row in accounts), Decimal("0")+ )+ unpriced_usd = sum(+ (_decimal(row.get("unpriced_or_other_usd")) for row in accounts),+ Decimal("0"),+ )+ identified_usd = priced_usd + cash_usd+ payload = {+ "snapshot_id": uuid.uuid4().hex,+ "created_at": refreshed_at,+ "complete": complete,+ "display_currency": settings.display_currency,+ "totals": {"usd": _number(total_usd), "cny": _number(total_usd * usd_cny)},+ "valuation": {+ "priced_usd": _number(priced_usd),+ "cash_usd": _number(cash_usd),+ "unpriced_or_other_usd": _number(unpriced_usd),+ "identified_coverage": (+ _number(identified_usd / total_usd) if total_usd > 0 else 0.0+ ),+ },+ "fx": {+ "usd_cny": _number(usd_cny),+ "usd_hkd": _number(usd_hkd),+ "fetched_at": fx_at,+ "stale": fx_stale,+ },+ "accounts": accounts,+ "positions": sorted(+ positions,+ key=lambda row: _decimal(row.get("market_value_usd")),+ reverse=True,+ ),+ "combined_holdings": self._combine_holdings(positions),+ "warnings": self._warnings(accounts, positions, fx_stale),+ }+ self.store.save_snapshot(payload)+ return payload++ def latest(self) -> dict[str, Any] | None:+ snapshot = self.store.latest()+ if snapshot is None:+ return None+ enabled = {+ source.id for source in self.settings_store.load().sources if source.enabled+ }+ observed = {+ str(account.get("source_id") or account.get("broker"))+ for account in snapshot.get("accounts", [])+ }+ return snapshot if enabled and observed == enabled else None++ def reconnect_source(self, source_id: str) -> dict[str, Any]:+ """Run a supported source's interactive OAuth flow on explicit request."""+ from src.config.loader import load_agent_config+ from src.tools.mcp import MCPServerAdapter++ source = next(+ (+ item+ for item in self.settings_store.load().sources+ if item.id == source_id+ ),+ None,+ )+ if source is None:+ raise RuntimeError("未找到该持仓账户")+ _, profile = self._connection_profile(source)+ if profile.transport != "remote_mcp":+ raise RuntimeError("该账户不使用 OAuth,无需重新连接")+ server = (load_agent_config().mcp_servers or {}).get(profile.connector)+ if server is None:+ raise RuntimeError(f"{profile.connector.upper()} MCP 连接尚未配置")+ tools = MCPServerAdapter(+ profile.connector,+ server,+ max_list_tools_attempts=1,+ interactive_oauth=True,+ ).discover_tools()+ return {+ "status": "ok",+ "authorized": True,+ "source_id": source.id,+ "enabled_read_tools": [item.remote_name for item in tools],+ }++ def history(self, limit: int = 180) -> list[dict[str, Any]]:+ return self.store.history(limit, complete_only=True)++ def export_csv(self) -> str:+ snapshot = self.latest()+ if snapshot is None:+ return ""+ fields = [+ "source_id",+ "source_label",+ "profile_id",+ "broker",+ "symbol",+ "name",+ "asset_type",+ "market",+ "currency",+ "quantity",+ "cost_price",+ "market_price",+ "market_value_usd",+ "market_value_cny",+ "unrealized_pnl_usd",+ "priced",+ "updated_at",+ ]+ output = io.StringIO()+ writer = csv.DictWriter(output, fieldnames=fields, extrasaction="ignore")+ writer.writeheader()+ writer.writerows(snapshot["positions"])+ return output.getvalue()++ def analysis_context(self) -> dict[str, Any] | None:+ """Return a credential/account-id-free snapshot suitable for an LLM."""+ snapshot = self.latest()+ if snapshot is None:+ return None+ total = _decimal(snapshot["totals"]["usd"])+ holdings = []+ for row in snapshot.get("combined_holdings", []):+ market_value = _decimal(row.get("market_value_usd"))+ holdings.append(+ {+ "symbol": row["symbol"],+ "asset_type": row["asset_type"],+ "markets": row["markets"],+ "brokers": row["brokers"],+ "market_value_usd": row["market_value_usd"],+ "weight": _number(market_value / total) if total > 0 else 0.0,+ "unrealized_pnl_usd": row["unrealized_pnl_usd"],+ }+ )+ return {+ "as_of": snapshot["created_at"],+ "complete": snapshot["complete"],+ "totals": snapshot["totals"],+ "account_allocation": [+ {+ "broker_alias": f"account_{index + 1}",+ "asset_provider_type": row["broker"],+ "status": row["status"],+ "total_usd": row.get("total_usd"),+ }+ for index, row in enumerate(snapshot["accounts"])+ ],+ "holdings": holdings,+ "warnings": snapshot["warnings"],+ "privacy": "No account numbers, credentials, order IDs, names, or local paths included.",+ }++ @staticmethod+ def _combine_holdings(positions: list[dict[str, Any]]) -> list[dict[str, Any]]:+ grouped: dict[str, dict[str, Any]] = {}+ for row in positions:+ symbol = str(row.get("symbol") or "").upper()+ currency = str(row.get("currency") or "").upper()+ market = str(row.get("market") or "").upper()+ if symbol.endswith(".US"):+ canonical = symbol[:-3]+ elif symbol.endswith(".HK"):+ canonical = symbol[:-3].lstrip("0") or "0"+ else:+ canonical = symbol+ region = (+ "HK"+ if currency == "HKD" or market == "HK" or symbol.endswith(".HK")+ else (+ "CRYPTO"+ if row.get("asset_type") in {"crypto", "stablecoin"}+ else "US"+ )+ )+ key = f"{region}:{canonical}"+ item = grouped.setdefault(+ key,+ {+ "canonical_id": key,+ "symbol": canonical,+ "asset_type": row.get("asset_type"),+ "brokers": [],+ "sources": [],+ "markets": [],+ "market_value_usd": Decimal("0"),+ "market_value_cny": Decimal("0"),+ "unrealized_pnl_usd": Decimal("0"),+ },+ )+ if row.get("broker") not in item["brokers"]:+ item["brokers"].append(row.get("broker"))+ source_label = row.get("source_label") or row.get("broker")+ if source_label not in item["sources"]:+ item["sources"].append(source_label)+ if row.get("market") not in item["markets"]:+ item["markets"].append(row.get("market"))+ item["market_value_usd"] += _decimal(row.get("market_value_usd"))+ item["market_value_cny"] += _decimal(row.get("market_value_cny"))+ item["unrealized_pnl_usd"] += _decimal(row.get("unrealized_pnl_usd"))+ result = []+ for item in grouped.values():+ item["brokers"].sort()+ item["sources"].sort()+ item["markets"] = sorted(str(value) for value in item["markets"] if value)+ item["duplicate_across_brokers"] = len(item["brokers"]) > 1+ for key in ("market_value_usd", "market_value_cny", "unrealized_pnl_usd"):+ item[key] = _number(item[key])+ result.append(item)+ return sorted(+ result, key=lambda row: _decimal(row["market_value_usd"]), reverse=True+ )++ def _collect_source(self, source: PortfolioSource) -> dict[str, Any]:+ connection, profile = self._connection_profile(source)+ if not profile.readonly:+ raise RuntimeError(+ "portfolio sources must use a read-only connector profile"+ )+ broker = profile.connector+ profile_id = profile.id+ longbridge_batch: dict[str, Any] | None = None+ if (+ broker == "longbridge"+ and profile_id == "longbridge-live-sdk-readonly"+ and self._use_longbridge_worker+ ):+ isolated = self._read_longbridge_isolated()+ account = isolated["account"]+ positions_payload = isolated["positions"]+ longbridge_batch = isolated.get("quotes")+ else:+ read_options = (+ {"interactive_oauth": False}+ if broker == "ibkr" and self._noninteractive_ibkr+ else {}+ )+ if profile.transport == "local_plugin":+ read_options["connection_id"] = connection.id+ account = self._get_account(profile_id, **read_options)+ positions_payload = self._get_positions(profile_id, **read_options)+ for label, payload in (("account", account), ("positions", positions_payload)):+ if str(payload.get("status") or "ok").lower() not in {"ok", "success"}:+ raise RuntimeError(+ str(payload.get("error") or f"{broker} {label} read failed")+ )+ normalized_rows = [+ normalize_position(broker, raw)+ for raw in positions_payload.get("positions", [])+ ]+ for row in normalized_rows:+ row.update(+ source_id=source.id,+ profile_id=connection.profile_id,+ source_label=source.label,+ )+ longbridge_prices: dict[str, Decimal] | None = None+ longbridge_price_error: str | None = None+ if broker == "longbridge" and longbridge_batch is not None:+ longbridge_prices = {+ str(item.get("symbol") or "").upper(): _decimal(item.get("last"))+ for item in longbridge_batch.get("quotes", [])+ if _decimal(item.get("last")) > 0+ }+ if str(longbridge_batch.get("status") or "ok").lower() not in {+ "ok",+ "success",+ }:+ longbridge_price_error = str(+ longbridge_batch.get("error") or "Longbridge quote read failed"+ )[:160]+ elif broker == "longbridge" and self._get_longbridge_quotes is not None:+ try:+ batch = self._get_longbridge_quotes(+ [str(row["quote_symbol"]) for row in normalized_rows]+ )+ longbridge_prices = {+ str(item.get("symbol") or "").upper(): _decimal(item.get("last"))+ for item in batch.get("quotes", [])+ if _decimal(item.get("last")) > 0+ }+ except Exception as exc:+ longbridge_prices = {}+ longbridge_price_error = str(exc)[:160]++ rows = []+ for normalized in normalized_rows:+ quantity = _decimal(normalized["quantity"])+ if quantity == 0:+ continue+ try:+ if broker == "binance" and normalized["symbol"] in STABLECOINS:+ normalized["market_price"] = 1.0+ normalized["price_currency"] = "USD"+ normalized["pricing_basis"] = "USDT/USD proxy"+ elif _decimal(normalized.get("market_price")) > 0:+ normalized["price_currency"] = normalized["currency"]+ normalized["pricing_basis"] = f"{broker} position snapshot"+ elif broker == "longbridge" and longbridge_prices is not None:+ price = longbridge_prices.get(+ str(normalized["quote_symbol"]).upper()+ )+ normalized["market_price"] = _number(price) if price else None+ normalized["price_currency"] = normalized["currency"]+ normalized["pricing_basis"] = (+ "Longbridge official quote"+ if longbridge_batch is not None+ else "Fallback market quote"+ )+ if not price and longbridge_price_error:+ normalized["price_error"] = longbridge_price_error+ else:+ quote_symbol = normalized["quote_symbol"]+ quote = self._get_quote(+ quote_symbol,+ profile_id,+ exchange=normalized.get("exchange") or "SMART",+ currency=normalized["currency"],+ sec_type="STK",+ **(+ {"connection_id": connection.id}+ if profile.transport == "local_plugin"+ else {}+ ),+ )+ price = _quote_price(quote)+ normalized["market_price"] = _number(price) if price else None+ normalized["price_currency"] = normalized["currency"]+ except Exception as exc:+ normalized["price_error"] = str(exc)[:160]+ rows.append(normalized)+ return {+ "source_id": source.id,+ "profile_id": connection.profile_id,+ "label": source.label,+ "broker": broker,+ "status": "ok",+ "account": account,+ "positions": rows,+ }++ @staticmethod+ def _read_longbridge_isolated() -> dict[str, Any]:+ marker = "VIBE_PORTFOLIO_JSON="+ process = subprocess.run(+ [sys.executable, "-m", "src.portfolio.longbridge_worker"],+ check=False,+ capture_output=True,+ text=True,+ timeout=40,+ )+ payload: dict[str, Any] | None = None+ for line in reversed(process.stdout.splitlines()):+ if line.startswith(marker):+ parsed = json.loads(line[len(marker) :])+ if isinstance(parsed, dict):+ payload = parsed+ break+ if payload is None:+ raise RuntimeError("Longbridge isolated reader returned no payload")+ if payload.get("error"):+ raise RuntimeError(f"Longbridge isolated reader failed: {payload['error']}")+ if "account" not in payload or "positions" not in payload:+ raise RuntimeError(+ "Longbridge isolated reader returned an incomplete payload"+ )+ return payload++ def _rates(self) -> tuple[Decimal, Decimal, str, bool]:+ try:+ usd_cny, usd_hkd, fetched_at = self._fx_fetcher()+ self.store.save_fx("USD", "CNY", str(usd_cny), fetched_at)+ self.store.save_fx("USD", "HKD", str(usd_hkd), fetched_at)+ return usd_cny, usd_hkd, fetched_at, False+ except Exception:+ cny = self.store.load_fx("USD", "CNY")+ hkd = self.store.load_fx("USD", "HKD")+ if cny is None or hkd is None:+ raise RuntimeError(+ "FX service unavailable and no prior USD/CNY + USD/HKD cache exists"+ )+ return _decimal(cny[0]), _decimal(hkd[0]), min(cny[1], hkd[1]), True++ @staticmethod+ def _fetch_fx() -> tuple[Decimal, Decimal, str]:+ url = "https://api.frankfurter.app/latest?from=USD&to=CNY,HKD"+ request = urllib.request.Request(+ url, headers={"User-Agent": "Vibe-Trading/portfolio"}+ )+ with urllib.request.urlopen(+ request, timeout=8+ ) as response: # noqa: S310 - fixed HTTPS host+ payload = json.load(response)+ return (+ _decimal(payload["rates"]["CNY"]),+ _decimal(payload["rates"]["HKD"]),+ _now(),+ )++ @staticmethod+ def _warnings(+ accounts: list[dict[str, Any]], positions: list[dict[str, Any]], fx_stale: bool+ ) -> list[str]:+ warnings = []+ if fx_stale:+ warnings.append("汇率服务暂时不可用,当前使用上一次成功获取的汇率。")+ stale = [+ str(row.get("label") or row["broker"])+ for row in accounts+ if row["status"] == "stale"+ ]+ if stale:+ warnings.append(+ "以下账户刷新失败,已保留上一次成功数据:" + "、".join(stale)+ )+ failed = [+ str(row.get("label") or row["broker"])+ for row in accounts+ if row["status"] == "error"+ ]+ if failed:+ warnings.append("以下账户尚无可用缓存,请检查连接:" + "、".join(failed))+ unpriced = [+ f"{row['broker']}:{row['symbol']}"+ for row in positions+ if not row.get("priced")+ ]+ if unpriced:+ warnings.append("暂未取得价格的持仓:" + "、".join(unpriced[:20]))+ if any(row.get("broker") == "binance" for row in positions):+ warnings.append("Binance 现货按 USDT≈USD 进行估值。")+ return warningsdiff --git a/agent/src/portfolio/store.py b/agent/src/portfolio/store.pynew file mode 100644index 000000000..6db4226b6--- /dev/null+++ b/agent/src/portfolio/store.py@@ -0,0 +1,148 @@+"""SQLite persistence for immutable portfolio snapshots and FX cache."""++from __future__ import annotations++import json+import sqlite3+from pathlib import Path+from typing import Any++from src.config.paths import get_runtime_root+++class PortfolioStore:+ def __init__(self, path: Path | None = None) -> None:+ self.path = path or (get_runtime_root() / "portfolio" / "portfolio.sqlite3")+ self.path.parent.mkdir(parents=True, exist_ok=True)+ self._init_schema()++ def _connect(self) -> sqlite3.Connection:+ connection = sqlite3.connect(self.path)+ connection.row_factory = sqlite3.Row+ return connection++ def _init_schema(self) -> None:+ with self._connect() as db:+ db.executescript("""+ CREATE TABLE IF NOT EXISTS portfolio_snapshots (+ id TEXT PRIMARY KEY,+ created_at TEXT NOT NULL,+ complete INTEGER NOT NULL,+ total_usd TEXT NOT NULL,+ total_cny TEXT NOT NULL,+ payload TEXT NOT NULL+ );+ CREATE INDEX IF NOT EXISTS idx_portfolio_snapshots_created+ ON portfolio_snapshots(created_at DESC);+ CREATE TABLE IF NOT EXISTS portfolio_fx_cache (+ base TEXT NOT NULL,+ quote TEXT NOT NULL,+ rate TEXT NOT NULL,+ fetched_at TEXT NOT NULL,+ PRIMARY KEY (base, quote)+ );+ """)++ def save_snapshot(self, payload: dict[str, Any]) -> None:+ totals = payload["totals"]+ with self._connect() as db:+ db.execute(+ """+ INSERT INTO portfolio_snapshots+ (id, created_at, complete, total_usd, total_cny, payload)+ VALUES (?, ?, ?, ?, ?, ?)+ """,+ (+ payload["snapshot_id"],+ payload["created_at"],+ int(payload["complete"]),+ str(totals["usd"]),+ str(totals["cny"]),+ json.dumps(payload, ensure_ascii=False, separators=(",", ":")),+ ),+ )++ def latest(self, *, complete_only: bool = False) -> dict[str, Any] | None:+ where = "WHERE complete = 1" if complete_only else ""+ with self._connect() as db:+ row = db.execute(+ f"SELECT payload FROM portfolio_snapshots {where} ORDER BY created_at DESC LIMIT 1"+ ).fetchone()+ return json.loads(row["payload"]) if row else None++ def history(+ self, limit: int = 180, *, complete_only: bool = True+ ) -> list[dict[str, Any]]:+ where = "WHERE complete = 1" if complete_only else ""+ with self._connect() as db:+ rows = db.execute(+ f"""+ SELECT id, created_at, complete, total_usd, total_cny+ FROM portfolio_snapshots+ {where}+ ORDER BY created_at DESC LIMIT ?+ """,+ (max(1, min(int(limit), 2000)),),+ ).fetchall()+ return [dict(row) for row in reversed(rows)]++ def latest_successful_source(self, source_id: str) -> dict[str, Any] | None:+ """Return the newest genuinely fresh payload for one configured source.++ Cached/stale accounts are intentionally skipped so a sequence of failed+ refreshes always points back to the original successful observation and+ preserves its real ``last_success_at`` timestamp.+ """+ with self._connect() as db:+ rows = db.execute("""+ SELECT created_at, payload+ FROM portfolio_snapshots+ ORDER BY created_at DESC LIMIT 2000+ """).fetchall()+ for row in rows:+ payload = json.loads(row["payload"])+ account = next(+ (+ item+ for item in payload.get("accounts", [])+ if (item.get("source_id") or item.get("broker")) == source_id+ and item.get("status") == "ok"+ ),+ None,+ )+ if account is None:+ continue+ return {+ "created_at": str(account.get("last_success_at") or row["created_at"]),+ "account": account,+ "positions": [+ item+ for item in payload.get("positions", [])+ if (item.get("source_id") or item.get("broker")) == source_id+ ],+ }+ return None++ def latest_successful_broker(self, broker: str) -> dict[str, Any] | None:+ """Compatibility alias for snapshots written before configurable sources."""+ return self.latest_successful_source(broker)++ def save_fx(self, base: str, quote: str, rate: str, fetched_at: str) -> None:+ with self._connect() as db:+ db.execute(+ """+ INSERT INTO portfolio_fx_cache (base, quote, rate, fetched_at)+ VALUES (?, ?, ?, ?)+ ON CONFLICT(base, quote) DO UPDATE SET+ rate = excluded.rate, fetched_at = excluded.fetched_at+ """,+ (base, quote, rate, fetched_at),+ )++ def load_fx(self, base: str, quote: str) -> tuple[str, str] | None:+ with self._connect() as db:+ row = db.execute(+ "SELECT rate, fetched_at FROM portfolio_fx_cache WHERE base = ? AND quote = ?",+ (base, quote),+ ).fetchone()+ return (str(row["rate"]), str(row["fetched_at"])) if row else Nonediff --git a/agent/src/tools/mcp.py b/agent/src/tools/mcp.pyindex 6b43a1c68..d1a56244f 100644--- a/agent/src/tools/mcp.py+++ b/agent/src/tools/mcp.py@@ -4,15 +4,18 @@ from __future__ import annotationsimport asyncioimport hashlib+import httpximport jsonimport loggingimport osimport reimport threading+import webbrowserfrom collections.abc import Mappingfrom copy import deepcopyfrom dataclasses import dataclass, is_dataclassfrom typing import Any, Awaitable, Callable, Coroutine, Iterable, Protocol, TypeVar+from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplitfrom fastmcp.client import Clientfrom fastmcp.client.auth import OAuth@@ -30,6 +33,7 @@ except ModuleNotFoundError:from fastmcp.exceptions import McpError, ToolErrorfrom key_value.aio.stores.filetree import FileTreeStore, FileTreeV1KeySanitizationStrategyfrom mcp import types as mcp_types+from mcp.shared.auth import OAuthMetadatafrom pydantic_core import PydanticSerializationError, to_jsonable_pythonfrom src.agent.tools import BaseTool@@ -93,6 +97,97 @@ def _fingerprint_auth(auth: MCPOAuthConfig | None) -> str:return _fingerprint(canonical)+class _RedirectCompatibleOAuth(OAuth):+ """FastMCP OAuth with support for standard HTTP 301 authorization redirects."""++ _IBKR_USER_AGENT = (+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36"+ )++ def __init__(self, *args: Any, allow_interactive: bool = True, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ self._allow_interactive = allow_interactive++ def _pin_ibkr_oauth_metadata(self) -> None:+ """Pin IBKR metadata before token refresh as well as initial consent."""+ if (urlsplit(self.mcp_url).hostname or "").lower() != "api.ibkr.com":+ return+ self.context.auth_server_url = "https://api.ibkr.com/oauth2"+ self.context.oauth_metadata = OAuthMetadata.model_validate(+ {+ "issuer": "https://api.ibkr.com",+ "authorization_endpoint": "https://api.ibkr.com/oauth2/authorize",+ "token_endpoint": "https://api.ibkr.com/oauth2/api/v1/token",+ "registration_endpoint": "https://api.ibkr.com/oauth2/register",+ "scopes_supported": ["mcp.read", "mcp.write"],+ "response_types_supported": ["code"],+ "grant_types_supported": ["authorization_code", "refresh_token"],+ "token_endpoint_auth_methods_supported": ["none"],+ "code_challenge_methods_supported": ["S256"],+ }+ )++ async def _initialize(self) -> None:+ await super()._initialize()+ self._pin_ibkr_oauth_metadata()++ async def async_auth_flow(self, request: httpx.Request):+ """Add WAF-compatible headers to every request generated by OAuth."""+ flow = super().async_auth_flow(request)+ try:+ outgoing = await flow.__anext__()+ while True:+ if (outgoing.url.host or "").lower() == "api.ibkr.com":+ outgoing.headers["User-Agent"] = self._IBKR_USER_AGENT+ outgoing.headers.setdefault("Accept", "application/json, text/html;q=0.9, */*;q=0.8")+ incoming = yield outgoing+ outgoing = await flow.asend(incoming)+ except StopAsyncIteration:+ return+ finally:+ await flow.aclose()++ async def redirect_handler(self, authorization_url: str) -> None:+ if not self._allow_interactive:+ raise RuntimeError("OAuth reauthorization required; use the explicit reconnect action")+ parsed = urlsplit(authorization_url)+ if (parsed.hostname or "").lower() == "api.ibkr.com":+ requested_scopes = (+ list(self._scopes)+ if isinstance(self._scopes, list)+ else str(self._scopes or "").split()+ )+ if requested_scopes != ["mcp.read"]:+ raise RuntimeError("IBKR OAuth must request exactly the mcp.read scope")+ params = dict(parse_qsl(parsed.query, keep_blank_values=True))+ params["scope"] = "mcp.read"+ authorization_url = urlunsplit(+ (+ parsed.scheme,+ parsed.netloc,+ "/oauth2/authorize",+ urlencode(params),+ "",+ )+ )+ # IBKR's protected-resource discovery currently causes some MCP+ # clients to fall back to root /authorize and /token endpoints.+ # Pin the server's published OAuth2 metadata after discovery so the+ # subsequent code exchange also uses the official token endpoint.+ self._pin_ibkr_oauth_metadata()+ async with self.httpx_client_factory() as client:+ response = await client.get(authorization_url, follow_redirects=False)+ if response.status_code == 400:+ raise RuntimeError("OAuth client not found; re-register the client")+ if response.status_code not in (200, 301, 302, 303, 307, 308):+ raise RuntimeError(+ f"Unexpected authorization response: {response.status_code}"+ )+ logger.info("OAuth authorization URL: %s", authorization_url)+ webbrowser.open(authorization_url)++def _make_cache_key(server_name: str, server_config: "MCPServerConfig") -> tuple[str, ...]:"""Build a content-based cache key for MCP tool discovery results.@@ -421,6 +516,7 @@ class MCPServerAdapter:local_server_name: str | None = None,client_factory: ClientFactory | None = None,max_list_tools_attempts: int = 2,+ interactive_oauth: bool = True,) -> None:"""Initialize the MCP server adapter.@@ -440,6 +536,7 @@ class MCPServerAdapter:self.server_config = server_configself._client_factory = client_factory or self._build_clientself._list_tools_attempts = max(1, max_list_tools_attempts)+ self._interactive_oauth = interactive_oauthdef discover_tools(self) -> list[MCPRemoteToolSpec]:"""Discover enabled tools from the remote MCP server.@@ -541,12 +638,17 @@ class MCPServerAdapter:auth = Noneif self.server_config.auth is not None:oauth_config = self.server_config.auth+ oauth_http_timeout = (+ self.server_config.init_timeout+ if self.server_config.init_timeout is not None+ else max(self.server_config.tool_timeout, 30.0)+ )# `mcp_url` is intentionally omitted — StreamableHttpTransport# calls `auth._bind(self.url)` so the URL fills in from the# transport. Token cache is persistent (FileTreeStore), so the# channel stays authorized across CLI invocations and refresh is# handled inside the MCP lib's OAuthClientProvider.- auth = OAuth(+ auth = _RedirectCompatibleOAuth(scopes=list(oauth_config.scopes) or None,client_name=oauth_config.client_name,token_storage=_build_token_store(oauth_config.cache_dir),@@ -554,6 +656,11 @@ class MCPServerAdapter:client_id=oauth_config.client_id,client_secret=oauth_config.client_secret,client_metadata_url=oauth_config.client_metadata_url,+ httpx_client_factory=lambda: httpx.AsyncClient(+ timeout=oauth_http_timeout,+ trust_env=True,+ ),+ allow_interactive=self._interactive_oauth,)transport = StreamableHttpTransport(url=self.server_config.url,diff --git a/agent/src/tools/portfolio_tool.py b/agent/src/tools/portfolio_tool.pynew file mode 100644index 000000000..61e98050c--- /dev/null+++ b/agent/src/tools/portfolio_tool.py@@ -0,0 +1,35 @@+"""Read-only, sanitized portfolio context for model-assisted analysis."""++from __future__ import annotations++import json+from typing import Any++from src.agent.tools import BaseTool+from src.portfolio.service import PortfolioService+++class PortfolioSummaryTool(BaseTool):+ name = "portfolio_summary"+ description = (+ "Read the latest sanitized IBKR, Longbridge and Binance portfolio snapshot. "+ "Returns deterministic totals, account allocation, combined holdings, weights, "+ "unrealized P/L and data-quality warnings. It never returns credentials, account "+ "numbers, order IDs, personal names, or local paths. Use it for portfolio analysis; "+ "use the Web Portfolio refresh button before requesting current data."+ )+ parameters = {"type": "object", "properties": {}, "required": []}+ repeatable = True+ is_readonly = True++ def execute(self, **_: Any) -> str:+ context = PortfolioService().analysis_context()+ if context is None:+ return json.dumps(+ {+ "status": "empty",+ "message": "No portfolio snapshot exists. Refresh the Portfolio page first.",+ },+ ensure_ascii=False,+ )+ return json.dumps({"status": "ok", "context": context}, ensure_ascii=False)diff --git a/agent/src/trading/connections.py b/agent/src/trading/connections.pynew file mode 100644index 000000000..981ae8ee3--- /dev/null+++ b/agent/src/trading/connections.py@@ -0,0 +1,263 @@+"""Credential-free registry of user-owned trading connection instances."""++from __future__ import annotations++import json+import os+import re+import tempfile+from dataclasses import asdict, dataclass+from datetime import datetime, timezone+from pathlib import Path+from typing import Any++from src.config.paths import get_runtime_root+from src.trading.credentials import CredentialStore+from src.trading.local_plugins import discover_plugins, plugin_by_profile_id+from src.trading.profiles import list_profiles, profile_by_id++CONFIG_FILENAME = "connections.json"+_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,79}$")+++def _now() -> str:+ return datetime.now(timezone.utc).isoformat()+++def _credential_reference(profile_id: str, connection_id: str) -> str:+ profile = profile_by_id(profile_id)+ if profile.transport == "local_plugin":+ return CredentialStore.reference(connection_id)+ if profile.transport == "remote_mcp":+ return f"oauth-cache://{profile.connector}"+ if profile.transport == "local_tws":+ return f"local-session://{profile.connector}"+ return f"connector-config://{profile.connector}"+++@dataclass(frozen=True)+class TradingConnection:+ id: str+ profile_id: str+ label: str+ credential_ref: str+ created_at: str++ def to_dict(self) -> dict[str, str]:+ return asdict(self)+++class ConnectionStore:+ """Owner-only metadata store; secret values live in the OS credential vault."""++ def __init__(+ self,+ path: Path | None = None,+ *,+ credential_store: CredentialStore | None = None,+ ) -> None:+ self.path = path or (get_runtime_root() / CONFIG_FILENAME)+ self.credentials = credential_store or CredentialStore()++ def list(self) -> list[TradingConnection]:+ if not self.path.exists():+ return []+ try:+ payload = json.loads(self.path.read_text(encoding="utf-8"))+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:+ raise ValueError(f"invalid local connection registry: {exc}") from exc+ rows = payload.get("connections", []) if isinstance(payload, dict) else []+ if not isinstance(rows, list):+ raise ValueError(+ "invalid local connection registry: connections must be a list"+ )+ return [self._parse(row) for row in rows]++ def get(self, connection_id: str) -> TradingConnection:+ target = str(connection_id or "").strip().lower()+ for connection in self.list():+ if connection.id == target:+ return connection+ raise ValueError(f"unknown local connection: {target or '?'}")++ def save(self, connection: TradingConnection) -> TradingConnection:+ validated = self._parse(connection.to_dict())+ rows = [row for row in self.list() if row.id != validated.id]+ rows.append(validated)+ self._write(sorted(rows, key=lambda row: (row.created_at, row.id)))+ return validated++ def create(+ self, connection_id: str, profile_id: str, label: str+ ) -> TradingConnection:+ normalized_id = str(connection_id or "").strip().lower()+ if any(row.id == normalized_id for row in self.list()):+ raise ValueError(f"local connection already exists: {normalized_id}")+ return self.save(+ TradingConnection(+ id=normalized_id,+ profile_id=profile_id,+ label=label,+ credential_ref=_credential_reference(profile_id, normalized_id),+ created_at=_now(),+ )+ )++ def ensure(+ self, connection_id: str, profile_id: str, label: str+ ) -> TradingConnection:+ try:+ existing = self.get(connection_id)+ except ValueError:+ return self.create(connection_id, profile_id, label)+ if existing.profile_id != str(profile_id or "").strip().lower():+ raise ValueError(+ f"local connection {existing.id} already uses profile {existing.profile_id}"+ )+ return existing++ def delete(self, connection_id: str) -> None:+ connection = self.get(connection_id)+ fields = credential_fields(connection.profile_id)+ self.credentials.delete(connection.id, fields)+ self._write([row for row in self.list() if row.id != connection.id])++ def public_list(self) -> list[dict[str, Any]]:+ result = []+ for connection in self.list():+ profile = profile_by_id(connection.profile_id)+ fields = credential_fields(profile.id)+ field_status = (+ self.credentials.status(connection.id, fields) if fields else {}+ )+ result.append(+ {+ **connection.to_dict(),+ "connector": profile.connector,+ "environment": profile.environment,+ "transport": profile.transport,+ "readonly": profile.readonly,+ "capabilities": list(profile.capabilities),+ "supports_reconnect": profile.transport == "remote_mcp",+ "credential_fields": credential_field_catalog(profile.id),+ "credential_status": field_status,+ "credentials_configured": bool(field_status)+ and all(field_status.values()),+ }+ )+ return result++ @staticmethod+ def _parse(raw: object) -> TradingConnection:+ if not isinstance(raw, dict):+ raise ValueError("each local connection must be an object")+ connection_id = str(raw.get("id") or "").strip().lower()+ if not _ID_RE.fullmatch(connection_id):+ raise ValueError(f"invalid local connection id: {connection_id or '?'}")+ profile_id = str(raw.get("profile_id") or "").strip().lower()+ profile = profile_by_id(profile_id)+ if not profile.readonly or not (+ {"account.read", "positions.read"}.issubset(profile.capabilities)+ or "mcp.read.discovery" in profile.capabilities+ ):+ raise ValueError(+ f"connection profile is not eligible for read-only portfolios: {profile_id}"+ )+ label = str(raw.get("label") or profile.label).strip()+ if (+ not label+ or len(label) > 80+ or any(ord(character) < 32 for character in label)+ ):+ raise ValueError(+ "connection label must contain 1 to 80 printable characters"+ )+ expected_ref = _credential_reference(profile.id, connection_id)+ credential_ref = str(raw.get("credential_ref") or expected_ref)+ if (+ credential_ref == CredentialStore.reference(connection_id)+ and profile.transport != "local_plugin"+ ):+ credential_ref = expected_ref+ if credential_ref != expected_ref:+ raise ValueError(+ "connection credential_ref does not match its local transport"+ )+ return TradingConnection(+ id=connection_id,+ profile_id=profile.id,+ label=label,+ credential_ref=credential_ref,+ created_at=str(raw.get("created_at") or _now()),+ )++ def _write(self, connections: list[TradingConnection]) -> None:+ self.path.parent.mkdir(parents=True, exist_ok=True)+ descriptor, temporary = tempfile.mkstemp(+ prefix=".connections-",+ suffix=".json",+ dir=self.path.parent,+ )+ try:+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:+ json.dump(+ {+ "schema_version": 1,+ "connections": [row.to_dict() for row in connections],+ },+ handle,+ ensure_ascii=False,+ indent=2,+ )+ handle.write("\n")+ handle.flush()+ os.fsync(handle.fileno())+ os.chmod(temporary, 0o600)+ os.replace(temporary, self.path)+ finally:+ if os.path.exists(temporary):+ os.unlink(temporary)+++def credential_field_catalog(profile_id: str) -> list[dict[str, Any]]:+ profile = profile_by_id(profile_id)+ if profile.transport == "local_plugin":+ return [+ field.to_dict()+ for field in plugin_by_profile_id(profile.id).credential_fields+ ]+ return []+++def credential_fields(profile_id: str) -> tuple[str, ...]:+ return tuple(str(row["name"]) for row in credential_field_catalog(profile_id))+++def readonly_profile_catalog() -> list[dict[str, Any]]:+ plugins, errors = discover_plugins()+ plugin_ids = {plugin.profile.id for plugin in plugins}+ rows = []+ for profile in list_profiles():+ if not profile.readonly or not (+ {"account.read", "positions.read"}.issubset(profile.capabilities)+ or "mcp.read.discovery" in profile.capabilities+ ):+ continue+ rows.append(+ {+ "id": profile.id,+ "connector": profile.connector,+ "label": profile.label,+ "environment": profile.environment,+ "transport": profile.transport,+ "capabilities": list(profile.capabilities),+ "readonly": profile.readonly,+ "notes": profile.notes,+ "local_plugin": profile.id in plugin_ids,+ "credential_fields": credential_field_catalog(profile.id),+ "supports_reconnect": profile.transport == "remote_mcp",+ }+ )+ return sorted(+ rows, key=lambda row: (row["connector"], row["environment"], row["label"])+ ) + [{"invalid_plugin": True, **error} for error in errors]diff --git a/agent/src/trading/connectors/binance/sdk.py b/agent/src/trading/connectors/binance/sdk.pyindex 5980aef33..babe6e862 100644--- a/agent/src/trading/connectors/binance/sdk.py+++ b/agent/src/trading/connectors/binance/sdk.py@@ -29,6 +29,7 @@ from pathlib import Pathfrom types import ModuleTypefrom typing import Any, Mappingfrom urllib.parse import urlparse+from urllib.request import getproxiesfrom src.config.paths import get_runtime_root@@ -288,30 +289,63 @@ def get_account_snapshot(config: BinanceConfig | None = None) -> dict[str, Any]:def get_positions(config: BinanceConfig | None = None) -> dict[str, Any]:"""Fetch holdings shaped as positions for the configured account.- Binance spot has no positions; holdings are the non-zero balances. Each row- is ``{symbol, quantity, free, used}`` where ``symbol`` is the asset code and- ``quantity`` is the total balance.+ Binance spot has no positions; holdings are the non-zero balances. On live+ accounts Binance may expose Simple Earn Flexible collateral in the spot+ payload as synthetic ``LD<ASSET>`` balances. When the read-only Simple Earn+ endpoint is available, replace those wrappers with their underlying asset+ and authoritative ``totalAmount`` so portfolio valuation neither misses nor+ double-counts flexible holdings."""cfg = config or load_config()_assert_host(cfg)ex = _exchange(cfg)balance = ex.fetch_balance()+ spot_balances = _nonzero_balances(balance)+ earn_rows: list[dict[str, Any]] = []+ earn_wrappers: set[str] = set()+ earn_note: str | None = None+ if not cfg.is_testnet:+ try:+ payload = ex.sapi_get_simple_earn_flexible_position({"size": 100})+ for item in payload.get("rows", []) if isinstance(payload, Mapping) else []:+ asset = str(_obj_get(item, "asset", "")).strip().upper()+ quantity = _to_float(_obj_get(item, "totalAmount"))+ if not asset or not quantity:+ continue+ earn_wrappers.add(f"LD{asset}")+ earn_rows.append(+ {+ "symbol": asset,+ "quantity": quantity,+ "free": 0.0,+ "used": quantity,+ "source": "simple_earn_flexible",+ }+ )+ except Exception as exc: # noqa: BLE001 - spot holdings still remain usable+ earn_note = f"Simple Earn Flexible holdings unavailable: {type(exc).__name__}"+rows = [{"symbol": _obj_get(row, "asset"),"quantity": _obj_get(row, "total"),"free": _obj_get(row, "free"),"used": _obj_get(row, "used"),+ "source": "spot",}- for row in _nonzero_balances(balance)- ]- return {+ for row in spot_balances+ if str(_obj_get(row, "asset", "")).upper() not in earn_wrappers+ ] + earn_rows+ result = {"status": "ok","profile": cfg.profile,"is_testnet": cfg.is_testnet,"paper_guard": "host_separated","positions": rows,}+ if earn_note:+ result["note"] = earn_note+ return resultdef get_open_orders(config: BinanceConfig | None = None, *, include_executions: bool = False) -> dict[str, Any]:@@ -628,14 +662,33 @@ def _symbol_required_errors() -> tuple[type[BaseException], ...]:def _exchange(cfg: BinanceConfig):"""Build a ccxt ``binance`` client bound to the configured environment."""ccxt = _require_ccxt()- ex = ccxt.binance(- {- "apiKey": cfg.api_key,- "secret": cfg.api_secret,- "enableRateLimit": True,- "timeout": int(cfg.timeout * 1000),- }- )+ client_config: dict[str, Any] = {+ "apiKey": cfg.api_key,+ "secret": cfg.api_secret,+ "enableRateLimit": True,+ "timeout": int(cfg.timeout * 1000),+ # Signed Binance requests have a narrow timestamp window. Let ccxt+ # measure the exchange clock before the first private request so a+ # sleeping laptop or an imperfect system clock does not force users to+ # reconnect or recreate an otherwise valid read-only API key.+ "options": {+ "adjustForTimeDifference": True,+ "recvWindow": 10_000,+ },+ }+ # ``requests``/ccxt does not consistently inherit the macOS System Proxy.+ # urllib resolves both conventional proxy environment variables and the+ # active macOS network proxy, so local desktop connectors follow the same+ # route as the user's browser without persisting proxy details or secrets.+ system_proxies = getproxies()+ proxies = {+ scheme: str(system_proxies[scheme]).strip()+ for scheme in ("http", "https")+ if str(system_proxies.get(scheme) or "").strip()+ }+ if proxies:+ client_config["proxies"] = proxies+ ex = ccxt.binance(client_config)ex.set_sandbox_mode(cfg.is_testnet)return exdiff --git a/agent/src/trading/connectors/ibkr/mcp.py b/agent/src/trading/connectors/ibkr/mcp.pynew file mode 100644index 000000000..a83a6e13c--- /dev/null+++ b/agent/src/trading/connectors/ibkr/mcp.py@@ -0,0 +1,82 @@+"""IBKR official MCP mappings for the generic read-only trading service."""++from __future__ import annotations++from typing import Any++_REMOTE_TOOL_NAMES = {+ "account": "get_account_summary",+ "positions": "get_account_positions",+ "orders": "get_account_orders",+}+++def remote_tool_name(operation: str) -> str | None:+ """Return the official IBKR tool for a generic read operation."""+ return _REMOTE_TOOL_NAMES.get(operation)+++def remote_arguments(operation: str, arguments: dict[str, Any]) -> dict[str, Any]:+ """IBKR's account read tools operate on the authorized account implicitly."""+ return {}+++def normalize_result(operation: str, result: dict[str, Any]) -> dict[str, Any]:+ """Convert official IBKR MCP responses to Vibe-Trading's read shapes."""+ status = str(result.get("status") or "ok").lower()+ if status in {"error", "failed", "not_authorized"}:+ return result++ payload = result.get("data")+ if not isinstance(payload, dict):+ payload = result.get("structured_content")+ if not isinstance(payload, dict):+ payload = {}++ if operation == "account":+ currency = str(payload.get("currency") or "USD").upper()+ tags = {+ "NetLiquidation": "net_liquidation",+ "EquityWithLoanValue": "equity_with_loan_value",+ "BuyingPower": "buying_power",+ "GrossPositionValue": "gross_position_value",+ "TotalCashValue": "total_cash_value",+ "AvailableFunds": "available_funds",+ "InitialMarginReq": "initial_margin",+ "MaintMarginReq": "maintenance_margin",+ "ExcessLiquidity": "excess_liquidity",+ }+ summary = [+ {"tag": tag, "value": payload[key], "currency": currency}+ for tag, key in tags.items()+ if payload.get(key) is not None+ ]+ return {"status": "ok", "summary": summary, **payload}++ if operation == "positions":+ positions = []+ for item in payload.get("positions") or []:+ if not isinstance(item, dict):+ continue+ description = str(item.get("contract_description") or "").strip()+ positions.append(+ {+ "contract_id": item.get("contract_id"),+ "symbol": description,+ "local_symbol": description,+ "position": item.get("position"),+ "market_price": item.get("market_price"),+ "market_value": item.get("market_value"),+ "currency": item.get("currency") or "USD",+ "avg_cost": item.get("average_price"),+ "unrealized_pnl": item.get("unrealized_pnl"),+ "sec_type": item.get("asset_class") or "STK",+ "asset_class": item.get("asset_class"),+ }+ )+ return {"status": "ok", "positions": positions}++ if operation == "orders":+ return {"status": "ok", "orders": payload.get("orders") or []}++ return resultdiff --git a/agent/src/trading/connectors/ibkr/profiles.py b/agent/src/trading/connectors/ibkr/profiles.pyindex f27a377f5..b73cc4576 100644--- a/agent/src/trading/connectors/ibkr/profiles.py+++ b/agent/src/trading/connectors/ibkr/profiles.py@@ -37,8 +37,8 @@ IBKR_PROFILES: tuple[TradingProfile, ...] = (readonly=True,config={"server": "ibkr"},notes=(- "Requires IBKR official MCP OAuth approval. Generic account/position tools "- "stay disabled until IBKR publishes stable read tool names."+ "Uses IBKR's official public MCP endpoint with OAuth mcp.read scope only. "+ "No TWS or IB Gateway process is required."),),)diff --git a/agent/src/trading/connectors/longbridge/sdk.py b/agent/src/trading/connectors/longbridge/sdk.pyindex 2065cf13d..a4b46dbbb 100644--- a/agent/src/trading/connectors/longbridge/sdk.py+++ b/agent/src/trading/connectors/longbridge/sdk.py@@ -341,6 +341,26 @@ def get_positions(config: LongbridgeConfig | None = None) -> dict[str, Any]:return {"status": "ok", "profile": cfg.profile, "paper_guard": "config_declared", "positions": rows}+def get_account_and_positions(config: LongbridgeConfig | None = None) -> dict[str, Any]:+ """Fetch account balances and positions through one native trade context."""+ cfg = config or build_config()+ trade = _trade_context(cfg)+ balances = [_balance_to_dict(item) for item in _as_iter(_call(trade, "account_balance"))]+ positions = [+ _position_to_dict(item)+ for item in _iter_positions(_call(trade, "stock_positions"))+ ]+ common = {+ "status": "ok",+ "profile": cfg.profile,+ "paper_guard": "config_declared",+ }+ return {+ "account": {**common, "balances": balances},+ "positions": {**common, "positions": positions},+ }++#: Longbridge OrderStatus values that mean the order is no longer live (bare#: member names). Used to filter ``today_orders`` (which returns ALL of today's#: orders) down to the genuinely-open ones, so ``open_orders`` matches the other@@ -406,6 +426,17 @@ def get_quote(symbol: str, *, config: LongbridgeConfig | None = None, **_: Any)return {"status": "ok", "symbol": clean, "quote": payload}+def get_quotes(symbols: list[str], *, config: LongbridgeConfig | None = None) -> dict[str, Any]:+ """Fetch last-price snapshots for several symbols using one SDK context."""+ cfg = config or build_config()+ clean = list(dict.fromkeys(symbol.strip().upper() for symbol in symbols if symbol.strip()))+ if not clean:+ return {"status": "ok", "quotes": []}+ quote_ctx = _quote_context(cfg)+ quotes = _call(quote_ctx, "quote", clean)+ return {"status": "ok", "quotes": [_quote_to_dict(item) for item in _as_iter(quotes)]}++def get_historical_bars(symbol: str,*,diff --git a/agent/src/trading/credentials.py b/agent/src/trading/credentials.pynew file mode 100644index 000000000..a95bdd2f1--- /dev/null+++ b/agent/src/trading/credentials.py@@ -0,0 +1,84 @@+"""OS-backed secret storage for local trading connection instances."""++from __future__ import annotations++from collections.abc import Iterable, Mapping+from typing import Protocol++SERVICE_NAME = "Vibe-Trading"+++class CredentialBackend(Protocol):+ def get_password(self, service_name: str, username: str) -> str | None: ...+ def set_password(self, service_name: str, username: str, password: str) -> None: ...+ def delete_password(self, service_name: str, username: str) -> None: ...+++class CredentialStore:+ """Store secrets in Keychain/Credential Manager/Secret Service via keyring."""++ def __init__(self, backend: CredentialBackend | None = None) -> None:+ self._backend = backend++ @property+ def backend(self) -> CredentialBackend:+ if self._backend is None:+ import keyring++ self._backend = keyring+ return self._backend++ @staticmethod+ def reference(connection_id: str) -> str:+ return f"keyring://vibe-trading/{connection_id}"++ @staticmethod+ def _username(connection_id: str, field: str) -> str:+ return f"connection:{connection_id}:{field}"++ def save(self, connection_id: str, values: Mapping[str, str]) -> None:+ """Persist non-empty values; blank fields leave an existing secret unchanged."""+ for field, raw_value in values.items():+ value = str(raw_value or "").strip()+ if value:+ self.backend.set_password(+ SERVICE_NAME,+ self._username(connection_id, field),+ value,+ )++ def load(self, connection_id: str, fields: Iterable[str]) -> dict[str, str]:+ values: dict[str, str] = {}+ for field in fields:+ value = self.backend.get_password(+ SERVICE_NAME,+ self._username(connection_id, field),+ )+ if value:+ values[field] = value+ return values++ def status(self, connection_id: str, fields: Iterable[str]) -> dict[str, bool]:+ result = {}+ for field in fields:+ try:+ result[field] = bool(+ self.backend.get_password(+ SERVICE_NAME,+ self._username(connection_id, field),+ )+ )+ except Exception:+ result[field] = False+ return result++ def delete(self, connection_id: str, fields: Iterable[str]) -> None:+ for field in fields:+ try:+ self.backend.delete_password(+ SERVICE_NAME,+ self._username(connection_id, field),+ )+ except Exception as exc: # keyring backends differ on missing entries+ if "not found" not in str(exc).lower():+ raisediff --git a/agent/src/trading/local_plugins.py b/agent/src/trading/local_plugins.pynew file mode 100644index 000000000..efdb2a509--- /dev/null+++ b/agent/src/trading/local_plugins.py@@ -0,0 +1,186 @@+"""Discovery and loading of user-owned, read-only connector plugins."""++from __future__ import annotations++import importlib.util+import json+import re+from dataclasses import dataclass+from pathlib import Path+from types import ModuleType+from typing import Any++from src.config.paths import get_runtime_root+from src.trading.types import READ_CAPABILITIES, TradingProfile++MANIFEST_FILENAME = "connector.json"+_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,79}$")+_FIELD_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$")+_REQUIRED_CAPABILITIES = {"account.read", "positions.read"}+_ALLOWED_CAPABILITIES = frozenset(READ_CAPABILITIES)+++@dataclass(frozen=True)+class CredentialField:+ name: str+ label: str+ secret: bool = True+ required: bool = True++ def to_dict(self) -> dict[str, Any]:+ return {+ "name": self.name,+ "label": self.label,+ "secret": self.secret,+ "required": self.required,+ }+++@dataclass(frozen=True)+class LocalConnectorPlugin:+ profile: TradingProfile+ directory: Path+ entrypoint: str+ auth_type: str+ credential_fields: tuple[CredentialField, ...]++ @property+ def module_path(self) -> Path:+ return self.directory / self.entrypoint++ def public_dict(self) -> dict[str, Any]:+ return {+ "profile_id": self.profile.id,+ "directory": str(self.directory),+ "auth_type": self.auth_type,+ "credential_fields": [field.to_dict() for field in self.credential_fields],+ }+++def plugin_root() -> Path:+ return get_runtime_root() / "connectors"+++def parse_manifest(path: Path) -> LocalConnectorPlugin:+ """Validate a local manifest as a strictly read-only connector contract."""+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:+ raise ValueError(f"invalid connector manifest at {path}: {exc}") from exc+ if not isinstance(payload, dict) or payload.get("schema_version") != 1:+ raise ValueError("connector manifest schema_version must be 1")+ profile_data = payload.get("profile")+ if not isinstance(profile_data, dict):+ raise ValueError("connector manifest profile must be an object")+ profile_id = str(profile_data.get("id") or "").strip().lower()+ connector = str(profile_data.get("connector") or "").strip().lower()+ if not _ID_RE.fullmatch(profile_id) or not _ID_RE.fullmatch(connector):+ raise ValueError(+ "connector and profile ids must use lowercase letters, numbers, dot, dash, or underscore"+ )+ capabilities = tuple(+ str(value).strip().lower() for value in profile_data.get("capabilities", [])+ )+ if not bool(profile_data.get("readonly")) or not _REQUIRED_CAPABILITIES.issubset(+ capabilities+ ):+ raise ValueError(+ "local connector plugins must be read-only and expose account.read + positions.read"+ )+ unsupported = sorted(set(capabilities) - _ALLOWED_CAPABILITIES)+ if unsupported:+ raise ValueError(+ "local connector plugins may declare read capabilities only: "+ + ", ".join(unsupported)+ )+ environment = str(profile_data.get("environment") or "live").strip().lower()+ if environment not in {"paper", "live"}:+ raise ValueError("connector environment must be paper or live")+ label = str(profile_data.get("label") or profile_id).strip()+ if not label or len(label) > 100:+ raise ValueError("connector label must contain 1 to 100 characters")+ entrypoint = str(payload.get("entrypoint") or "adapter.py").strip()+ if Path(entrypoint).name != entrypoint or not entrypoint.endswith(".py"):+ raise ValueError(+ "connector entrypoint must be a Python file in the manifest directory"+ )+ module_path = path.parent / entrypoint+ if not module_path.is_file():+ raise ValueError(f"connector entrypoint does not exist: {module_path}")+ auth = payload.get("auth") if isinstance(payload.get("auth"), dict) else {}+ fields: list[CredentialField] = []+ for raw in auth.get("fields", []):+ if not isinstance(raw, dict):+ raise ValueError("auth fields must be objects")+ name = str(raw.get("name") or "").strip().lower()+ if not _FIELD_RE.fullmatch(name):+ raise ValueError(f"invalid credential field: {name or '?'}")+ fields.append(+ CredentialField(+ name=name,+ label=str(raw.get("label") or name.replace("_", " ").title()).strip(),+ secret=bool(raw.get("secret", True)),+ required=bool(raw.get("required", True)),+ )+ )+ profile = TradingProfile(+ id=profile_id,+ connector=connector,+ label=label,+ environment=environment, # type: ignore[arg-type]+ transport="local_plugin",+ capabilities=capabilities,+ readonly=True,+ config={"plugin_directory": str(path.parent)},+ notes=str(+ profile_data.get("notes") or "User-installed local read-only connector."+ ).strip(),+ )+ return LocalConnectorPlugin(+ profile=profile,+ directory=path.parent,+ entrypoint=entrypoint,+ auth_type=str(auth.get("type") or "none").strip().lower(),+ credential_fields=tuple(fields),+ )+++def discover_plugins(+ root: Path | None = None,+) -> tuple[list[LocalConnectorPlugin], list[dict[str, str]]]:+ """Discover valid plugins and return field-safe diagnostics for invalid ones."""+ directory = root or plugin_root()+ if not directory.exists():+ return [], []+ plugins: list[LocalConnectorPlugin] = []+ errors: list[dict[str, str]] = []+ for manifest in sorted(directory.glob(f"*/{MANIFEST_FILENAME}")):+ try:+ plugins.append(parse_manifest(manifest))+ except ValueError as exc:+ errors.append({"directory": manifest.parent.name, "error": str(exc)[:300]})+ return plugins, errors+++def plugin_by_profile_id(profile_id: str) -> LocalConnectorPlugin:+ plugins, _ = discover_plugins()+ for plugin in plugins:+ if plugin.profile.id == profile_id:+ return plugin+ raise ValueError(f"unknown local connector plugin profile: {profile_id}")+++def load_adapter(plugin: LocalConnectorPlugin) -> ModuleType:+ """Load a plugin selected by the local operator from its private directory."""+ module_name = (+ f"vibe_local_connector_{plugin.profile.id.replace('-', '_').replace('.', '_')}"+ )+ spec = importlib.util.spec_from_file_location(module_name, plugin.module_path)+ if spec is None or spec.loader is None:+ raise RuntimeError(f"cannot load connector adapter: {plugin.profile.id}")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ for operation in ("check_status", "get_account_snapshot", "get_positions"):+ if not callable(getattr(module, operation, None)):+ raise RuntimeError(f"local connector adapter is missing {operation}()")+ return modulediff --git a/agent/src/trading/plugin_scaffold.py b/agent/src/trading/plugin_scaffold.pynew file mode 100644index 000000000..4a8cd5029--- /dev/null+++ b/agent/src/trading/plugin_scaffold.py@@ -0,0 +1,111 @@+"""Scaffold, validate, and install user-owned local read-only connectors."""++from __future__ import annotations++import json+import re+import shutil+from pathlib import Path++from src.trading.local_plugins import MANIFEST_FILENAME, parse_manifest, plugin_root++_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")++_ADAPTER_TEMPLATE = '''"""Read-only local connector generated by Vibe-Trading.++Implement these functions from the broker's official read API. Never add order,+transfer, withdrawal, or credential logging code to this adapter.+"""++from __future__ import annotations++from typing import Any, Mapping+++def check_status(*, credentials: Mapping[str, str], config: Mapping[str, Any]) -> dict[str, Any]:+ missing = [name for name in ("api_key", "api_secret") if not credentials.get(name)]+ return {+ "status": "ok" if not missing else "error",+ "configured": not missing,+ "readonly": True,+ "missing_fields": missing,+ }+++def get_account_snapshot(*, credentials: Mapping[str, str], config: Mapping[str, Any]) -> dict[str, Any]:+ raise NotImplementedError("Call the broker account endpoint and return a normalized account envelope")+++def get_positions(*, credentials: Mapping[str, str], config: Mapping[str, Any]) -> dict[str, Any]:+ raise NotImplementedError("Call the broker positions endpoint and return {'positions': [...]}")+'''+++def scaffold_connector(connector_id: str, destination: Path) -> Path:+ """Create a safe local connector starter for Codex or a developer to fill in."""+ clean = str(connector_id or "").strip().lower()+ if not _ID_RE.fullmatch(clean):+ raise ValueError("connector id must use lowercase letters, numbers, and dashes")+ target = destination.expanduser().resolve() / clean+ if target.exists():+ raise ValueError(f"destination already exists: {target}")+ target.mkdir(parents=True)+ manifest = {+ "schema_version": 1,+ "profile": {+ "id": f"{clean}-live-readonly",+ "connector": clean,+ "label": f"{clean.title()} Live · Local Read-Only",+ "environment": "live",+ "readonly": True,+ "capabilities": ["account.read", "positions.read"],+ "notes": "User-installed local connector. Credentials remain in the OS credential store.",+ },+ "entrypoint": "adapter.py",+ "auth": {+ "type": "api_key",+ "fields": [+ {+ "name": "api_key",+ "label": "API Key",+ "secret": True,+ "required": True,+ },+ {+ "name": "api_secret",+ "label": "API Secret",+ "secret": True,+ "required": True,+ },+ ],+ },+ }+ (target / MANIFEST_FILENAME).write_text(+ json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",+ encoding="utf-8",+ )+ (target / "adapter.py").write_text(_ADAPTER_TEMPLATE, encoding="utf-8")+ (target / "README.md").write_text(+ f"# {clean} local connector\n\n"+ "This directory is local-only. Implement the official read endpoints in `adapter.py`, "+ "then run `vibe-trading connector validate .` and `vibe-trading connector install .`.\n",+ encoding="utf-8",+ )+ return target+++def validate_connector(directory: Path):+ """Validate a local connector directory without importing its Python code."""+ return parse_manifest(directory.expanduser().resolve() / MANIFEST_FILENAME)+++def install_connector(directory: Path) -> Path:+ """Install a validated local connector under the user's runtime directory."""+ plugin = validate_connector(directory)+ root = plugin_root()+ root.mkdir(parents=True, exist_ok=True)+ target = root / plugin.profile.connector+ if target.exists():+ raise ValueError(f"connector is already installed: {target}")+ shutil.copytree(plugin.directory, target)+ return targetdiff --git a/agent/src/trading/profiles.py b/agent/src/trading/profiles.pyindex 5cc5cd3db..3a13088bb 100644--- a/agent/src/trading/profiles.py+++ b/agent/src/trading/profiles.py@@ -47,8 +47,15 @@ def config_path() -> Path:def list_profiles() -> list[TradingProfile]:- """Return built-in trading connector profiles."""- return list(BUILTIN_PROFILES)+ """Return built-in profiles plus operator-installed local read-only plugins."""+ from src.trading.local_plugins import discover_plugins++ plugins, _ = discover_plugins()+ built_in_ids = {profile.id for profile in BUILTIN_PROFILES}+ local_profiles = [+ plugin.profile for plugin in plugins if plugin.profile.id not in built_in_ids+ ]+ return [*BUILTIN_PROFILES, *local_profiles]def profile_by_id(profile_id: str | None = None) -> TradingProfile:@@ -64,7 +71,7 @@ def profile_by_id(profile_id: str | None = None) -> TradingProfile:ValueError: If the profile id is unknown."""target = (profile_id or load_selected_profile_id()).strip().lower()- for profile in BUILTIN_PROFILES:+ for profile in list_profiles():if profile.id == target:return profileraise ValueError(f"unknown trading connector profile: {target}")diff --git a/agent/src/trading/service.py b/agent/src/trading/service.pyindex 73966d683..c544bb832 100644--- a/agent/src/trading/service.py+++ b/agent/src/trading/service.py@@ -39,6 +39,38 @@ def _sdk_module(connector: str):return importlib.import_module(path)+def _local_plugin_call(+ profile: TradingProfile,+ operation: str,+ overrides: dict[str, Any],+ *args: Any,+ **kwargs: Any,+) -> dict[str, Any]:+ """Call a read operation on a user-installed local connector adapter."""+ from src.trading.connections import ConnectionStore, credential_fields+ from src.trading.local_plugins import load_adapter, plugin_by_profile_id++ connection_id = str(overrides.get("connection_id") or "").strip().lower()+ if not connection_id:+ raise ValueError("local connector plugins require a connection_id")+ store = ConnectionStore()+ connection = store.get(connection_id)+ if connection.profile_id != profile.id:+ raise ValueError("local connection profile does not match the requested plugin")+ plugin = plugin_by_profile_id(profile.id)+ adapter = load_adapter(plugin)+ function = getattr(adapter, operation, None)+ if not callable(function):+ return _unsupported(profile, operation)+ credentials = store.credentials.load(connection.id, credential_fields(profile.id))+ return function(+ *args,+ credentials=credentials,+ config=dict(profile.config),+ **kwargs,+ )++def check_connection(profile_id: str | None = None, **overrides: Any) -> dict[str, Any]:"""Check a connector profile without mutating broker state."""profile = profile_by_id(profile_id)@@ -62,6 +94,10 @@ def check_connection(profile_id: str | None = None, **overrides: Any) -> dict[streport["transport"] = profile.transportreturn report+ if profile.transport == "local_plugin":+ report = _local_plugin_call(profile, "check_status", overrides)+ return _with_profile(profile, report)+return _remote_status(profile)@@ -75,7 +111,17 @@ def get_account(profile_id: str | None = None, **overrides: Any) -> dict[str, Anif profile.transport == "broker_sdk":module = _sdk_module(profile.connector)return _with_profile(profile, module.get_account_snapshot(module.build_config(profile.config, overrides)))- return _call_remote(profile, "account", _account_arg(overrides))+ if profile.transport == "local_plugin":+ return _with_profile(+ profile,+ _local_plugin_call(profile, "get_account_snapshot", overrides),+ )+ return _call_remote(+ profile,+ "account",+ _account_arg(overrides),+ interactive_oauth=bool(overrides.get("interactive_oauth", True)),+ )def get_positions(profile_id: str | None = None, **overrides: Any) -> dict[str, Any]:@@ -88,7 +134,17 @@ def get_positions(profile_id: str | None = None, **overrides: Any) -> dict[str,if profile.transport == "broker_sdk":module = _sdk_module(profile.connector)return _with_profile(profile, module.get_positions(module.build_config(profile.config, overrides)))- return _call_remote(profile, "positions", _account_arg(overrides))+ if profile.transport == "local_plugin":+ return _with_profile(+ profile,+ _local_plugin_call(profile, "get_positions", overrides),+ )+ return _call_remote(+ profile,+ "positions",+ _account_arg(overrides),+ interactive_oauth=bool(overrides.get("interactive_oauth", True)),+ )def get_open_orders(@@ -114,6 +170,16 @@ def get_open_orders(module.build_config(profile.config, overrides), include_executions=include_executions),)+ if profile.transport == "local_plugin":+ return _with_profile(+ profile,+ _local_plugin_call(+ profile,+ "get_open_orders",+ overrides,+ include_executions=include_executions,+ ),+ )return _call_remote(profile, "orders", _account_arg(overrides))@@ -144,6 +210,11 @@ def get_quote(if profile.transport == "broker_sdk":module = _sdk_module(profile.connector)return _with_profile(profile, module.get_quote(symbol, config=module.build_config(profile.config, overrides)))+ if profile.transport == "local_plugin":+ return _with_profile(+ profile,+ _local_plugin_call(profile, "get_quote", overrides, symbol),+ )return _call_remote(profile, "quote", {"symbols": [symbol], "symbol": symbol})@@ -226,6 +297,18 @@ def get_history(limit=limit,),)+ if profile.transport == "local_plugin":+ return _with_profile(+ profile,+ _local_plugin_call(+ profile,+ "get_historical_bars",+ overrides,+ symbol,+ period=period,+ limit=limit,+ ),+ )return _unsupported(profile, "history.read")@@ -966,7 +1049,13 @@ def _account_arg(overrides: dict[str, Any]) -> dict[str, Any]:return {"account_number": account} if account else {}-def _call_remote(profile: TradingProfile, operation: str, arguments: dict[str, Any]) -> dict[str, Any]:+def _call_remote(+ profile: TradingProfile,+ operation: str,+ arguments: dict[str, Any],+ *,+ interactive_oauth: bool = True,+) -> dict[str, Any]:"""Call a known read operation on a remote MCP connector profile."""from src.config.loader import load_agent_configfrom src.live.registry import has_cached_oauth_token@@ -1023,8 +1112,16 @@ def _call_remote(profile: TradingProfile, operation: str, arguments: dict[str, A),}- adapter = MCPServerAdapter(server_name, server)+ adapter = (+ MCPServerAdapter(server_name, server)+ if interactive_oauth+ else MCPServerAdapter(server_name, server, interactive_oauth=False)+ )call_result = adapter.call_tool(remote_name, _remote_arguments(profile.connector, operation, arguments))+ if profile.connector == "ibkr":+ from src.trading.connectors.ibkr.mcp import normalize_result++ call_result = normalize_result(operation, call_result)account_number = arguments.get("account_number")if account_number:call_result = dict(call_result)@@ -1037,6 +1134,10 @@ def _remote_tool_name(connector: str, operation: str) -> str | None:if connector == "robinhood":from src.trading.connectors.robinhood.mcp import remote_tool_name+ return remote_tool_name(operation)+ if connector == "ibkr":+ from src.trading.connectors.ibkr.mcp import remote_tool_name+return remote_tool_name(operation)return None@@ -1046,6 +1147,10 @@ def _remote_arguments(connector: str, operation: str, arguments: dict[str, Any])if connector == "robinhood":from src.trading.connectors.robinhood.mcp import remote_arguments+ return remote_arguments(operation, arguments)+ if connector == "ibkr":+ from src.trading.connectors.ibkr.mcp import remote_arguments+return remote_arguments(operation, arguments)return {}diff --git a/agent/src/trading/types.py b/agent/src/trading/types.pyindex d9c57db94..2cc0ca49d 100644--- a/agent/src/trading/types.py+++ b/agent/src/trading/types.py@@ -6,7 +6,7 @@ from dataclasses import asdict, dataclass, fieldfrom typing import Any, LiteralEnvironment = Literal["paper", "live"]-Transport = Literal["local_tws", "remote_mcp", "broker_sdk"]+Transport = Literal["local_tws", "remote_mcp", "broker_sdk", "local_plugin"]READ_CAPABILITIES = ("account.read",diff --git a/agent/tests/test_connection_routes.py b/agent/tests/test_connection_routes.pynew file mode 100644index 000000000..eea15cda7--- /dev/null+++ b/agent/tests/test_connection_routes.py@@ -0,0 +1,80 @@+from __future__ import annotations++from fastapi import FastAPI+from fastapi.testclient import TestClient++from src.api import connection_routes+from src.trading.connections import ConnectionStore+from src.trading.credentials import CredentialStore+++class _MemoryCredentials:+ def __init__(self):+ self.values: dict[tuple[str, str], str] = {}++ def get_password(self, service_name: str, username: str):+ return self.values.get((service_name, username))++ def set_password(self, service_name: str, username: str, password: str):+ self.values[(service_name, username)] = password++ def delete_password(self, service_name: str, username: str):+ self.values.pop((service_name, username), None)+++def test_connection_routes_create_list_and_check_without_returning_secrets(+ tmp_path,+ monkeypatch,+):+ store = ConnectionStore(+ tmp_path / "connections.json",+ credential_store=CredentialStore(_MemoryCredentials()),+ )+ monkeypatch.setattr(connection_routes, "ConnectionStore", lambda: store)+ monkeypatch.setattr(+ connection_routes,+ "check_connection",+ lambda profile_id, **kwargs: {+ "status": "ok",+ "profile_id": profile_id,+ "connection_id": kwargs["connection_id"],+ },+ )+ app = FastAPI()+ connection_routes.register_connection_routes(app)+ client = TestClient(app)++ created = client.post(+ "/api/connections",+ json={+ "id": "main-binance",+ "profile_id": "binance-live-sdk-readonly",+ "label": "Main Binance",+ },+ )+ assert created.status_code == 200+ listed = client.get("/api/connections").json()+ assert listed["connections"][0]["id"] == "main-binance"+ assert "secret" not in str(listed).lower()+ checked = client.post("/api/connections/main-binance/check")+ assert checked.json()["report"]["connection_id"] == "main-binance"+++def test_connection_routes_reject_credentials_not_declared_by_profile(+ tmp_path, monkeypatch+):+ store = ConnectionStore(+ tmp_path / "connections.json",+ credential_store=CredentialStore(_MemoryCredentials()),+ )+ store.create("main-binance", "binance-live-sdk-readonly", "Main Binance")+ monkeypatch.setattr(connection_routes, "ConnectionStore", lambda: store)+ app = FastAPI()+ connection_routes.register_connection_routes(app)+ client = TestClient(app)++ response = client.post(+ "/api/connections/main-binance/credentials",+ json={"values": {"api_secret": "must-not-be-accepted"}},+ )+ assert response.status_code == 400diff --git a/agent/tests/test_ibkr_mcp_adapter.py b/agent/tests/test_ibkr_mcp_adapter.pynew file mode 100644index 000000000..9fc043638--- /dev/null+++ b/agent/tests/test_ibkr_mcp_adapter.py@@ -0,0 +1,57 @@+from src.trading.connectors.ibkr.mcp import (+ normalize_result,+ remote_arguments,+ remote_tool_name,+)+++def test_ibkr_read_tool_mapping_has_no_write_tools():+ assert remote_tool_name("account") == "get_account_summary"+ assert remote_tool_name("positions") == "get_account_positions"+ assert remote_tool_name("orders") == "get_account_orders"+ assert remote_tool_name("quote") is None+ assert remote_tool_name("submit_order") is None+ assert remote_arguments("positions", {"account_number": "ignored"}) == {}+++def test_normalizes_account_summary_and_positions():+ account = normalize_result(+ "account",+ {+ "status": "ok",+ "data": {+ "currency": "USD",+ "net_liquidation": 1234.5,+ "buying_power": 100,+ },+ },+ )+ assert account["summary"][0] == {+ "tag": "NetLiquidation",+ "value": 1234.5,+ "currency": "USD",+ }++ positions = normalize_result(+ "positions",+ {+ "status": "ok",+ "data": {+ "positions": [+ {+ "contract_id": 42,+ "contract_description": "AAPL",+ "position": 2,+ "market_price": 150,+ "market_value": 300,+ "currency": "USD",+ "average_price": 100,+ "unrealized_pnl": 100,+ "asset_class": "STK",+ }+ ]+ },+ },+ )+ assert positions["positions"][0]["symbol"] == "AAPL"+ assert positions["positions"][0]["market_price"] == 150diff --git a/agent/tests/test_ibkr_mcp_seed.py b/agent/tests/test_ibkr_mcp_seed.pyindex 4e3d8f27a..bb5d0861c 100644--- a/agent/tests/test_ibkr_mcp_seed.py+++ b/agent/tests/test_ibkr_mcp_seed.py@@ -65,7 +65,8 @@ def test_ibkr_seed_validates_as_readonly_probe() -> None:cfg = AgentConfig.model_validate({"mcpServers": {"ibkr": IBKR_MCP_SERVER_SEED}})server = cfg.mcp_servers["ibkr"]- assert server.url == "https://api.ibkr.com/v1/api/mcp"+ assert server.url == "https://api.ibkr.com/v1/api/mcp-public"+ assert server.init_timeout == 300.0assert server.auth is not Noneassert server.auth.scopes == ["mcp.read"]assert server.enabled_tools == ["*"]@@ -88,4 +89,4 @@ def test_ibkr_alias_url_resolves_to_live_broker_and_wraps_writes() -> None:def test_ibkr_lookalike_host_is_not_live_broker() -> None:- assert not is_live_broker("ib", "https://api.ibkr.com.evil.test/v1/api/mcp")+ assert not is_live_broker("ib", "https://api.ibkr.com.evil.test/v1/api/mcp-public")diff --git a/agent/tests/test_local_connections.py b/agent/tests/test_local_connections.pynew file mode 100644index 000000000..47068b830--- /dev/null+++ b/agent/tests/test_local_connections.py@@ -0,0 +1,154 @@+from __future__ import annotations++import json++import pytest++from src.trading.connections import ConnectionStore+from src.trading.credentials import CredentialStore+from src.trading.local_plugins import discover_plugins, parse_manifest+from src.trading.plugin_scaffold import scaffold_connector, validate_connector+++class _MemoryCredentials:+ def __init__(self):+ self.values: dict[tuple[str, str], str] = {}++ def get_password(self, service_name: str, username: str):+ return self.values.get((service_name, username))++ def set_password(self, service_name: str, username: str, password: str):+ self.values[(service_name, username)] = password++ def delete_password(self, service_name: str, username: str):+ self.values.pop((service_name, username), None)+++def test_connection_registry_never_serializes_credentials(tmp_path):+ credentials = CredentialStore(_MemoryCredentials())+ store = ConnectionStore(tmp_path / "connections.json", credential_store=credentials)+ connection = store.create(+ "main-binance",+ "binance-live-sdk-readonly",+ "Main Binance",+ )+ credentials.save(connection.id, {"api_key": "secret-value"})++ payload = (tmp_path / "connections.json").read_text(encoding="utf-8")+ assert "secret-value" not in payload+ assert connection.credential_ref == "connector-config://binance"+ assert (tmp_path / "connections.json").stat().st_mode & 0o777 == 0o600+++def test_connection_registry_normalizes_ids_before_duplicate_checks(tmp_path):+ store = ConnectionStore(+ tmp_path / "connections.json",+ credential_store=CredentialStore(_MemoryCredentials()),+ )+ store.create("main-account", "binance-live-sdk-readonly", "Main account")++ with pytest.raises(ValueError, match="already exists"):+ store.create(" MAIN-ACCOUNT ", "binance-live-sdk-readonly", "Replacement")++ assert store.get("main-account").label == "Main account"+++def test_connection_registry_rejects_control_characters_in_labels(tmp_path):+ store = ConnectionStore(+ tmp_path / "connections.json",+ credential_store=CredentialStore(_MemoryCredentials()),+ )++ with pytest.raises(ValueError, match="printable"):+ store.create("main-account", "binance-live-sdk-readonly", "Main\naccount")+++def test_scaffold_generates_a_valid_readonly_connector(tmp_path):+ target = scaffold_connector("sample-broker", tmp_path)+ plugin = validate_connector(target)++ assert plugin.profile.id == "sample-broker-live-readonly"+ assert plugin.profile.readonly is True+ assert {"account.read", "positions.read"}.issubset(plugin.profile.capabilities)+ assert [field.name for field in plugin.credential_fields] == [+ "api_key",+ "api_secret",+ ]+++def test_manifest_rejects_write_capabilities(tmp_path):+ target = scaffold_connector("unsafe-broker", tmp_path)+ manifest = target / "connector.json"+ payload = json.loads(manifest.read_text(encoding="utf-8"))+ payload["profile"]["capabilities"].append("orders.place")+ manifest.write_text(json.dumps(payload), encoding="utf-8")++ with pytest.raises(ValueError, match="read capabilities only"):+ parse_manifest(manifest)+++def test_manifest_rejects_unknown_non_read_capabilities(tmp_path):+ target = scaffold_connector("unsafe-operation", tmp_path)+ manifest = target / "connector.json"+ payload = json.loads(manifest.read_text(encoding="utf-8"))+ payload["profile"]["capabilities"].append("trade.execute")+ manifest.write_text(json.dumps(payload), encoding="utf-8")++ with pytest.raises(ValueError, match="trade.execute"):+ parse_manifest(manifest)+++def test_discovery_isolates_invalid_local_plugins(tmp_path):+ scaffold_connector("good-broker", tmp_path)+ bad = tmp_path / "bad-broker"+ bad.mkdir()+ (bad / "connector.json").write_text("{}", encoding="utf-8")++ plugins, errors = discover_plugins(tmp_path)++ assert [plugin.profile.connector for plugin in plugins] == ["good-broker"]+ assert errors[0]["directory"] == "bad-broker"+++def test_installed_local_plugin_runs_through_the_trading_read_interface(+ tmp_path,+ monkeypatch,+):+ from src.trading import connections, local_plugins+ from src.trading.service import get_account, get_positions++ monkeypatch.setattr(local_plugins, "get_runtime_root", lambda: tmp_path)+ monkeypatch.setattr(connections, "get_runtime_root", lambda: tmp_path)+ target = scaffold_connector("sample", tmp_path / "connectors")+ manifest = target / "connector.json"+ payload = json.loads(manifest.read_text(encoding="utf-8"))+ payload["auth"]["fields"] = []+ manifest.write_text(json.dumps(payload), encoding="utf-8")+ (target / "adapter.py").write_text(+ """+def check_status(*, credentials, config):+ return {"status": "ok", "readonly": True}++def get_account_snapshot(*, credentials, config):+ return {"account": {"portfolio_value": "42", "currency": "USD"}}++def get_positions(*, credentials, config):+ return {"positions": [{"symbol": "DEMO", "quantity": 1, "current_price": 42}]}+""",+ encoding="utf-8",+ )+ registry = ConnectionStore()+ registry.create("my-sample", "sample-live-readonly", "My Sample")++ assert (+ get_account("sample-live-readonly", connection_id="my-sample")["account"][+ "portfolio_value"+ ]+ == "42"+ )+ assert (+ get_positions("sample-live-readonly", connection_id="my-sample")["positions"][+ 0+ ]["symbol"]+ == "DEMO"+ )diff --git a/agent/tests/test_mcp_oauth_schema.py b/agent/tests/test_mcp_oauth_schema.pyindex d2a812d5d..82b3391e8 100644--- a/agent/tests/test_mcp_oauth_schema.py+++ b/agent/tests/test_mcp_oauth_schema.py@@ -15,6 +15,9 @@ Covers:from __future__ import annotations+import asyncio+from urllib.parse import parse_qs, urlsplit+import pytestfrom fastmcp.client.auth import OAuthfrom fastmcp.client.transports.http import StreamableHttpTransport@@ -31,7 +34,8 @@ from src.config.schema import (MCPServerConfig,MCPServerConfigOverride,)-from src.tools.mcp import MCPServerAdapter+from src.tools import mcp as mcp_module+from src.tools.mcp import MCPServerAdapter, _RedirectCompatibleOAuthpytestmark = pytest.mark.unit@@ -127,7 +131,8 @@ def test_ibkr_seed_is_official_readonly_oauth_probe() -> None:cfg = AgentConfig.model_validate({"mcpServers": {"ibkr": IBKR_MCP_SERVER_SEED}})ibkr = cfg.mcp_servers["ibkr"]assert ibkr.resolved_transport() == "streamableHttp"- assert ibkr.url == "https://api.ibkr.com/v1/api/mcp"+ assert ibkr.url == "https://api.ibkr.com/v1/api/mcp-public"+ assert ibkr.init_timeout == 300.0assert ibkr.auth is not None and ibkr.auth.type == "oauth"assert ibkr.auth.scopes == ["mcp.read"]assert ibkr.auth.cache_dir == "~/.vibe-trading/live/ibkr/oauth"@@ -135,6 +140,62 @@ def test_ibkr_seed_is_official_readonly_oauth_probe() -> None:assert "ibkr" in LIVE_BROKER_SERVER_KEYS+def test_ibkr_oauth_redirect_pins_official_endpoint_and_read_scope(monkeypatch) -> None:+ opened: list[str] = []++ class Response:+ status_code = 302++ class Client:+ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc, tb):+ return None++ async def get(self, url, follow_redirects=False):+ assert follow_redirects is False+ return Response()++ oauth = _RedirectCompatibleOAuth(+ mcp_url="https://api.ibkr.com/v1/api/mcp-public",+ scopes=["mcp.read"],+ client_id="client-id",+ callback_port=8765,+ httpx_client_factory=Client,+ )+ monkeypatch.setattr(mcp_module.webbrowser, "open", opened.append)++ asyncio.run(+ oauth.redirect_handler(+ "https://api.ibkr.com/authorize/?response_type=code&scope=mcp.read%20mcp.write"+ )+ )++ parsed = urlsplit(opened[0])+ assert parsed.path == "/oauth2/authorize"+ assert parse_qs(parsed.query)["scope"] == ["mcp.read"]+ assert str(oauth.context.oauth_metadata.token_endpoint) == (+ "https://api.ibkr.com/oauth2/api/v1/token"+ )+++def test_noninteractive_oauth_refuses_browser_reauthorization(monkeypatch) -> None:+ opened: list[str] = []+ oauth = _RedirectCompatibleOAuth(+ mcp_url="https://api.ibkr.com/v1/api/mcp-public",+ scopes=["mcp.read"],+ client_id="client-id",+ allow_interactive=False,+ )+ monkeypatch.setattr(mcp_module.webbrowser, "open", opened.append)++ with pytest.raises(RuntimeError, match="explicit reconnect"):+ asyncio.run(oauth.redirect_handler("https://api.ibkr.com/oauth2/authorize"))++ assert opened == []++# --------------------------------------------------------------------------- ## Validator rejections# --------------------------------------------------------------------------- #diff --git a/agent/tests/test_portfolio_config.py b/agent/tests/test_portfolio_config.pynew file mode 100644index 000000000..cd60c9991--- /dev/null+++ b/agent/tests/test_portfolio_config.py@@ -0,0 +1,61 @@+from __future__ import annotations++import json++import pytest++from src.portfolio.config import PortfolioSettingsStore, parse_settings, source_catalog+from src.trading.connections import ConnectionStore+++def test_portfolio_settings_round_trip_without_credentials(tmp_path):+ store = PortfolioSettingsStore(tmp_path / "portfolio.json")+ settings = store.save(+ {+ "display_currency": "CNY",+ "sources": [+ {+ "id": "main-stocks",+ "profile_id": "alpaca-live-sdk-readonly",+ "label": "Main stocks",+ "enabled": True,+ "order": 0,+ "include_cash": True,+ }+ ],+ }+ )++ assert store.load() == settings+ assert (tmp_path / "portfolio.json").stat().st_mode & 0o777 == 0o600+ payload = json.loads((tmp_path / "portfolio.json").read_text(encoding="utf-8"))+ assert "api_key" not in json.dumps(payload)+ assert "profile_id" not in json.dumps(payload)+ assert source_catalog(settings, store.connection_store)[0].keys() >= {+ "connection_id",+ "readonly",+ "selected",+ }+++def test_portfolio_settings_reject_trade_profiles():+ connections = ConnectionStore()+ with pytest.raises(ValueError, match="eligible for read-only"):+ parse_settings(+ {+ "display_currency": "USD",+ "sources": [+ {+ "id": "unsafe",+ "profile_id": "binance-live-trade",+ "label": "Unsafe",+ }+ ],+ },+ connections,+ )+++def test_new_install_starts_with_no_selected_sources(tmp_path):+ store = PortfolioSettingsStore(tmp_path / "portfolio.json")+ assert store.load().sources == ()diff --git a/agent/tests/test_portfolio_routes.py b/agent/tests/test_portfolio_routes.pynew file mode 100644index 000000000..008945a85--- /dev/null+++ b/agent/tests/test_portfolio_routes.py@@ -0,0 +1,90 @@+from __future__ import annotations++from fastapi import FastAPI+from fastapi.testclient import TestClient++from src.api import portfolio_routes+++class _Service:+ def __init__(self, **kwargs):+ self.progress_callback = kwargs.get("progress_callback")++ def latest(self):+ return {"snapshot_id": "latest"}++ def refresh(self):+ return {"snapshot_id": "new"}++ def settings(self):+ return {+ "display_currency": "USD",+ "sources": [{"connection_id": "ibkr", "enabled": True}],+ }++ def save_settings(self, payload):+ return payload++ def sources(self):+ return [{"profile_id": "ibkr-live-official-mcp-readonly"}]++ def history(self, limit):+ return [{"id": "one", "limit": limit}]++ def reconnect_source(self, source_id):+ return {"status": "ok", "authorized": True, "source_id": source_id}++ def export_csv(self):+ return "broker,symbol\nibkr,AAPL\n"++ def analysis_context(self):+ return {"privacy": "sanitized"}+++def test_portfolio_routes_are_readonly_and_return_expected_shapes(monkeypatch):+ monkeypatch.setattr(portfolio_routes, "PortfolioService", _Service)+ app = FastAPI()+ portfolio_routes.register_portfolio_routes(app)+ client = TestClient(app)++ assert client.get("/api/portfolio").json()["snapshot"]["snapshot_id"] == "latest"+ assert (+ client.post("/api/portfolio/refresh").json()["snapshot"]["snapshot_id"] == "new"+ )+ refresh = client.get("/api/portfolio/refresh-status").json()["refresh"]+ assert refresh["running"] is False+ assert refresh["sources"] == refresh["brokers"]+ assert (+ client.get("/api/portfolio/history?limit=12").json()["history"][0]["limit"]+ == 12+ )+ settings = client.get("/api/portfolio/settings").json()+ assert settings["settings"]["display_currency"] == "USD"+ saved = client.put(+ "/api/portfolio/settings",+ json={+ "display_currency": "CNY",+ "sources": [+ {+ "connection_id": "ibkr",+ "label": "Main",+ "enabled": True,+ "order": 0,+ "include_cash": True,+ }+ ],+ },+ )+ assert saved.status_code == 200+ assert saved.json()["settings"]["display_currency"] == "CNY"+ assert (+ client.post("/api/portfolio/sources/ibkr/reconnect").json()["source_id"]+ == "ibkr"+ )+ assert (+ client.get("/api/portfolio/analysis-context").json()["context"]["privacy"]+ == "sanitized"+ )+ exported = client.get("/api/portfolio/export.csv")+ assert exported.status_code == 200+ assert "ibkr,AAPL" in exported.textdiff --git a/agent/tests/test_portfolio_service.py b/agent/tests/test_portfolio_service.pynew file mode 100644index 000000000..cf9626742--- /dev/null+++ b/agent/tests/test_portfolio_service.py@@ -0,0 +1,269 @@+from __future__ import annotations++from decimal import Decimal++from src.portfolio.config import PortfolioSettingsStore+from src.portfolio.normalization import auth_metadata+from src.portfolio.service import PortfolioService+from src.portfolio.store import PortfolioStore+from src.trading.types import TradingProfile+++def _settings_store(tmp_path):+ store = PortfolioSettingsStore(tmp_path / "portfolio.json")+ store.connection_store.ensure("ibkr", "ibkr-live-official-mcp-readonly", "IBKR")+ store.connection_store.ensure(+ "longbridge", "longbridge-live-sdk-readonly", "Longbridge"+ )+ store.connection_store.ensure("binance", "binance-live-sdk-readonly", "Binance")+ store.save(+ {+ "display_currency": "USD",+ "sources": [+ {"connection_id": "ibkr", "label": "IBKR", "order": 0},+ {"connection_id": "longbridge", "label": "Longbridge", "order": 1},+ {"connection_id": "binance", "label": "Binance", "order": 2},+ ],+ }+ )+ return store+++def test_refresh_aggregates_three_readonly_connectors(tmp_path):+ accounts = {+ "ibkr-live-official-mcp-readonly": {+ "summary": [{"tag": "NetLiquidation", "value": "1000", "currency": "USD"}]+ },+ "longbridge-live-sdk-readonly": {+ "balances": [{"net_assets": "7800", "currency": "HKD"}]+ },+ "binance-live-sdk-readonly": {"balances": []},+ }+ positions = {+ "ibkr-live-official-mcp-readonly": {+ "positions": [+ {+ "symbol": "AAPL",+ "sec_type": "STK",+ "exchange": "SMART",+ "currency": "USD",+ "position": 2,+ "avg_cost": 100,+ }+ ]+ },+ "longbridge-live-sdk-readonly": {+ "positions": [+ {+ "symbol": "700.HK",+ "symbol_name": "Tencent",+ "quantity": 10,+ "cost_price": 300,+ "currency": "HKD",+ "market": "HK",+ }+ ]+ },+ "binance-live-sdk-readonly": {+ "positions": [+ {"symbol": "BTC", "quantity": 0.1, "free": 0.1, "used": 0},+ {"symbol": "USDT", "quantity": 50, "free": 50, "used": 0},+ ]+ },+ }++ def get_account(profile_id):+ return accounts[profile_id]++ def get_positions(profile_id):+ return positions[profile_id]++ def get_quote(symbol, profile_id, **kwargs):+ prices = {"AAPL": 150, "700.HK": 390, "BTC/USDT": 60000}+ return {"quote": {"last": prices[symbol]}}++ service = PortfolioService(+ PortfolioStore(tmp_path / "portfolio.sqlite3"),+ settings_store=_settings_store(tmp_path),+ get_account=get_account,+ get_positions=get_positions,+ get_quote=get_quote,+ fx_fetcher=lambda: (+ Decimal("7.2"),+ Decimal("7.8"),+ "2026-08-09T00:00:00+00:00",+ ),+ )+ snapshot = service.refresh()++ assert snapshot["complete"] is True+ assert snapshot["totals"]["usd"] == 8050.0+ assert len(snapshot["positions"]) == 4+ assert snapshot["positions"][0]["symbol"] == "BTC"+ assert len(snapshot["combined_holdings"]) == 4+ assert service.latest()["snapshot_id"] == snapshot["snapshot_id"]+ assert len(service.history()) == 1+ assert "broker,symbol" in service.export_csv()+ context = service.analysis_context()+ assert context["privacy"].startswith("No account numbers")+ assert "quantity" not in context["holdings"][0]+++def test_partial_refresh_is_saved_and_marked_incomplete(tmp_path):+ def get_account(profile_id):+ if profile_id.startswith("longbridge"):+ raise ConnectionError("offline")+ return {"summary": []}++ service = PortfolioService(+ PortfolioStore(tmp_path / "portfolio.sqlite3"),+ settings_store=_settings_store(tmp_path),+ get_account=get_account,+ get_positions=lambda profile_id: {"positions": []},+ get_quote=lambda *args, **kwargs: {},+ fx_fetcher=lambda: (+ Decimal("7.2"),+ Decimal("7.8"),+ "2026-08-09T00:00:00+00:00",+ ),+ )++ snapshot = service.refresh()+ assert snapshot["complete"] is False+ assert any("longbridge" in warning.lower() for warning in snapshot["warnings"])+++def test_failed_broker_uses_last_successful_data_without_polluting_history(tmp_path):+ offline = False++ def get_account(profile_id):+ if offline and profile_id.startswith("ibkr"):+ raise ConnectionError("offline")+ if profile_id.startswith("ibkr"):+ return {+ "summary": [+ {"tag": "NetLiquidation", "value": "1000", "currency": "USD"}+ ]+ }+ return {"summary": []}++ service = PortfolioService(+ PortfolioStore(tmp_path / "portfolio.sqlite3"),+ settings_store=_settings_store(tmp_path),+ get_account=get_account,+ get_positions=lambda profile_id: {+ "positions": (+ [+ {+ "symbol": "AAPL",+ "sec_type": "STK",+ "exchange": "SMART",+ "currency": "USD",+ "position": 2,+ "avg_cost": 100,+ }+ ]+ if profile_id.startswith("ibkr")+ else []+ ),+ },+ get_quote=lambda *args, **kwargs: {"quote": {"last": 150}},+ fx_fetcher=lambda: (+ Decimal("7.2"),+ Decimal("7.8"),+ "2026-08-09T00:00:00+00:00",+ ),+ )+ complete = service.refresh()+ offline = True+ partial = service.refresh()++ ibkr = next(item for item in partial["accounts"] if item["broker"] == "ibkr")+ assert complete["complete"] is True+ assert partial["complete"] is False+ assert partial["totals"]["usd"] == complete["totals"]["usd"]+ assert ibkr["status"] == "stale"+ assert ibkr["last_success_at"] == complete["created_at"]+ assert (+ next(item for item in partial["positions"] if item["broker"] == "ibkr")["stale"]+ is True+ )+ assert [item["id"] for item in service.history()] == [complete["snapshot_id"]]+ assert len(service.store.history(complete_only=False)) == 2+++def test_generic_readonly_profile_uses_common_account_and_position_fields(tmp_path):+ settings = PortfolioSettingsStore(tmp_path / "portfolio.json")+ settings.connection_store.ensure(+ "main-stocks",+ "alpaca-live-sdk-readonly",+ "Main stocks",+ )+ settings.save(+ {+ "display_currency": "CNY",+ "sources": [+ {+ "connection_id": "main-stocks",+ "label": "Main stocks",+ "enabled": True,+ "order": 0,+ "include_cash": False,+ }+ ],+ }+ )+ service = PortfolioService(+ PortfolioStore(tmp_path / "portfolio.sqlite3"),+ settings_store=settings,+ get_account=lambda profile_id: {+ "account": {"portfolio_value": "1000", "cash": "200", "currency": "USD"}+ },+ get_positions=lambda profile_id: {+ "positions": [+ {+ "symbol": "AAPL",+ "quantity": "4",+ "average_cost": "150",+ "current_price": "200",+ "market_value": "800",+ }+ ]+ },+ get_quote=lambda *args, **kwargs: {},+ fx_fetcher=lambda: (+ Decimal("7.2"),+ Decimal("7.8"),+ "2026-08-09T00:00:00+00:00",+ ),+ )++ snapshot = service.refresh()+ account = snapshot["accounts"][0]+ position = snapshot["positions"][0]+ assert snapshot["display_currency"] == "CNY"+ assert snapshot["totals"]["usd"] == 800.0+ assert account["source_id"] == "main-stocks"+ assert account["cash_usd"] == 0.0+ assert position["source_label"] == "Main stocks"+ assert position["market_value_usd"] == 800.0+++def test_auth_metadata_describes_the_profile_without_claiming_key_permissions():+ profile = TradingProfile(+ id="example-live-readonly",+ connector="example",+ label="Example",+ environment="live",+ transport="broker_sdk",+ capabilities=("account.read", "positions.read"),+ readonly=True,+ notes="Use credentials configured by the local operator.",+ )++ assert auth_metadata(profile) == {+ "method": "API credentials",+ "renewal": "provider_managed",+ "readonly": True,+ "detail": "Use credentials configured by the local operator.",+ }diff --git a/agent/tests/test_sdk_connectors.py b/agent/tests/test_sdk_connectors.pyindex a3804df19..32dc64c09 100644--- a/agent/tests/test_sdk_connectors.py+++ b/agent/tests/test_sdk_connectors.py@@ -525,6 +525,57 @@ def test_binance_service_unconfigured(monkeypatch, tmp_path) -> None:assert result["connector"] == "binance"+def test_binance_positions_replace_ld_wrappers_with_simple_earn(monkeypatch) -> None:+ class FakeExchange:+ def fetch_balance(self):+ return {+ "USDT": {"free": 12, "used": 0, "total": 12},+ "LDBTC": {"free": 0, "used": 0.9, "total": 0.9},+ }++ def sapi_get_simple_earn_flexible_position(self, params):+ assert params == {"size": 100}+ return {"rows": [{"asset": "BTC", "totalAmount": "1.0"}]}++ monkeypatch.setattr(bn, "_exchange", lambda _cfg: FakeExchange())+ result = bn.get_positions(+ bn.BinanceConfig(api_key="key", api_secret="secret", profile="live-readonly")+ )++ assert result["positions"] == [+ {"symbol": "USDT", "quantity": 12.0, "free": 12.0, "used": 0.0, "source": "spot"},+ {+ "symbol": "BTC",+ "quantity": 1.0,+ "free": 0.0,+ "used": 1.0,+ "source": "simple_earn_flexible",+ },+ ]+++def test_binance_exchange_adjusts_for_server_time(monkeypatch) -> None:+ captured = {}++ class FakeExchange:+ def __init__(self, config):+ captured.update(config)++ def set_sandbox_mode(self, enabled):+ captured["sandbox"] = enabled++ monkeypatch.setattr(bn, "_require_ccxt", lambda: SimpleNamespace(binance=FakeExchange))+ monkeypatch.setattr(bn, "getproxies", lambda: {})++ bn._exchange(bn.BinanceConfig(api_key="key", api_secret="secret", profile="live-readonly"))++ assert captured["options"] == {+ "adjustForTimeDifference": True,+ "recvWindow": 10_000,+ }+ assert captured["sandbox"] is False++# --------------------------------------------------------------------------- ## Futu (local OpenD gateway)# --------------------------------------------------------------------------- #diff --git a/agent/tests/test_trading_connections.py b/agent/tests/test_trading_connections.pyindex 96c526105..8e808c029 100644--- a/agent/tests/test_trading_connections.py+++ b/agent/tests/test_trading_connections.py@@ -50,14 +50,14 @@ def test_remote_call_requires_cached_oauth(monkeypatch: pytest.MonkeyPatch) -> Nassert "connector authorize robinhood-live-mcp" in result["error"]-def test_ibkr_official_profile_does_not_advertise_unknown_generic_reads() -> None:- """IBKR official MCP stays honest until stable remote tool names are known."""+def test_ibkr_official_profile_maps_verified_reads_without_write_tools() -> None:+ """IBKR official MCP maps only the read tools verified by the adapter."""profile = profiles.profile_by_id("ibkr-live-official-mcp-readonly")assert profile.capabilities == ("mcp.read.discovery",)- result = service.get_account(profile.id)- assert result["status"] == "error"- assert "does not support" in result["error"]+ assert service._remote_tool_name("ibkr", "account") == "get_account_summary"+ assert service._remote_tool_name("ibkr", "positions") == "get_account_positions"+ assert service._remote_tool_name("ibkr", "place_order") is Nonedef test_connector_profile_id_for_broker_prefers_live_remote_mcp() -> None:diff --git a/frontend/src/components/layout/Layout.tsx b/frontend/src/components/layout/Layout.tsxindex eda13e248..02552d269 100644--- a/frontend/src/components/layout/Layout.tsx+++ b/frontend/src/components/layout/Layout.tsx@@ -1,7 +1,7 @@import { useTranslation } from "react-i18next";import { useEffect, useRef, useState } from "react";import { Link, Outlet, useLocation, useSearchParams } from "react-router";-import { Activity, BarChart3, Bot, CalendarClock, CandlestickChart, Check, ChevronDown, FileText, Languages, Moon, Sun, Plus, Trash2, Pencil, MessageSquare, ChevronsLeft, ChevronsRight, Settings, Layers, Loader2 } from "lucide-react";+import { Activity, BarChart3, Bot, CalendarClock, CandlestickChart, Check, ChevronDown, FileText, Languages, Moon, Sun, Plus, Trash2, Pencil, MessageSquare, ChevronsLeft, ChevronsRight, Settings, Layers, Loader2, WalletCards } from "lucide-react";import { cn } from "@/lib/utils";import { useDarkMode } from "@/hooks/useDarkMode";import { api, type SessionItem } from "@/lib/api";@@ -24,6 +24,7 @@ export function Layout() {{ to: "/runtime", icon: Activity, label: t('layout.runtime') },{ to: "/scheduled", icon: CalendarClock, label: t('layout.scheduled') },{ to: "/reports", icon: FileText, label: t('layout.reports') },+ { to: "/portfolio", icon: WalletCards, label: t('layout.portfolio', { defaultValue: 'Portfolio' }) },{ to: "/alpha-zoo", icon: Layers, label: t('layout.alphaZoo') },{ to: "/options", icon: CandlestickChart, label: t('layout.optionsLab') },{ to: "/settings", icon: Settings, label: t('layout.settings') },diff --git a/frontend/src/components/portfolio/ConnectionCenter.tsx b/frontend/src/components/portfolio/ConnectionCenter.tsxnew file mode 100644index 000000000..f6eff705c--- /dev/null+++ b/frontend/src/components/portfolio/ConnectionCenter.tsx@@ -0,0 +1,153 @@+import { useEffect, useMemo, useState } from "react";+import { CheckCircle2, FolderCode, Loader2, PlugZap, Plus, ShieldCheck, Trash2, X } from "lucide-react";+import { api, type ConnectionsResponse, type LocalConnection } from "@/lib/api";++interface Props {+ open: boolean;+ zh: boolean;+ onClose: () => void;+ onChanged: () => Promise<void>;+}++const fieldClass = "w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:border-primary focus:ring-2 focus:ring-primary/20";++export function ConnectionCenter({ open, zh, onClose, onChanged }: Props) {+ const [data, setData] = useState<ConnectionsResponse | null>(null);+ const [profileId, setProfileId] = useState("");+ const [connectionId, setConnectionId] = useState("");+ const [label, setLabel] = useState("");+ const [busy, setBusy] = useState<string | null>(null);+ const [message, setMessage] = useState<string | null>(null);++ async function load() {+ setData(await api.getConnections());+ }++ useEffect(() => {+ if (!open) return;+ setMessage(null);+ void load().catch((error) => setMessage(error instanceof Error ? error.message : String(error)));+ }, [open]);++ const profiles = useMemo(() => data?.profiles.filter((profile) => !profile.invalid_plugin) ?? [], [data]);++ function chooseProfile(value: string) {+ setProfileId(value);+ const profile = profiles.find((item) => item.id === value);+ if (!profile) return;+ const ids = new Set(data?.connections.map((item) => item.id) ?? []);+ let id = `${profile.connector}-${profile.environment}`;+ let suffix = 2;+ while (ids.has(id)) id = `${profile.connector}-${profile.environment}-${suffix++}`;+ setConnectionId(id);+ setLabel(profile.label);+ }++ async function create() {+ if (!profileId || !connectionId.trim() || !label.trim()) return;+ setBusy("create");+ setMessage(null);+ try {+ await api.createConnection({ id: connectionId, profile_id: profileId, label });+ await load();+ await onChanged();+ setProfileId("");+ setConnectionId("");+ setLabel("");+ setMessage(zh ? "本地连接已创建。" : "Local connection created.");+ } catch (error) {+ setMessage(error instanceof Error ? error.message : String(error));+ } finally {+ setBusy(null);+ }+ }++ async function test(connection: LocalConnection) {+ setBusy(`test:${connection.id}`);+ setMessage(null);+ try {+ const result = await api.checkConnection(connection.id);+ const ok = result.report.status === "ok" || result.report.configured === true;+ setMessage(ok ? (zh ? `${connection.label} 连接正常。` : `${connection.label} is ready.`) : JSON.stringify(result.report));+ } catch (error) {+ setMessage(error instanceof Error ? error.message : String(error));+ } finally {+ setBusy(null);+ }+ }++ async function remove(connection: LocalConnection) {+ setBusy(`delete:${connection.id}`);+ setMessage(null);+ try {+ await api.deleteConnection(connection.id);+ await load();+ await onChanged();+ } catch (error) {+ setMessage(error instanceof Error ? error.message : String(error));+ } finally {+ setBusy(null);+ }+ }++ if (!open) return null;++ return <div className="fixed inset-0 z-[60] flex justify-end bg-black/40" role="presentation">+ <section className="flex h-full w-full max-w-2xl flex-col border-l bg-background shadow-2xl" role="dialog" aria-modal="true" aria-labelledby="connection-center-title">+ <header className="flex items-start justify-between border-b p-5">+ <div><h2 id="connection-center-title" className="text-lg font-semibold">{zh ? "本地连接中心" : "Local connection center"}</h2><p className="mt-1 text-xs text-muted-foreground">{zh ? "连接定义保存在本机;密钥只进入系统钥匙串。" : "Definitions stay local; secrets go only to the OS credential vault."}</p></div>+ <button type="button" onClick={onClose} className="rounded-md p-2 hover:bg-muted" aria-label={zh ? "关闭连接中心" : "Close connection center"}><X className="h-4 w-4" /></button>+ </header>++ <div className="flex-1 space-y-6 overflow-y-auto p-5">+ {message ? <div className="rounded-md border bg-muted/30 p-3 text-xs break-words">{message}</div> : null}++ <section className="rounded-xl border bg-card p-4">+ <div className="flex items-center gap-2"><Plus className="h-4 w-4 text-primary" /><h3 className="font-medium">{zh ? "创建账户连接" : "Create account connection"}</h3></div>+ <p className="mt-1 text-xs text-muted-foreground">{zh ? "Profile 是公开模板;连接是只属于这台电脑的账户实例。" : "A profile is a public template; a connection is private to this computer."}</p>+ <div className="mt-4 grid gap-3 sm:grid-cols-2">+ <label className="text-xs text-muted-foreground sm:col-span-2">{zh ? "只读连接模板" : "Read-only profile"}<select value={profileId} onChange={(event) => chooseProfile(event.target.value)} className={`mt-1 ${fieldClass}`}><option value="">{zh ? "选择模板…" : "Choose a profile…"}</option>{profiles.map((profile) => <option key={profile.id} value={profile.id}>{profile.label}</option>)}</select></label>+ <label className="text-xs text-muted-foreground">{zh ? "本地连接 ID" : "Local connection ID"}<input value={connectionId} onChange={(event) => setConnectionId(event.target.value.toLowerCase())} className={`mt-1 ${fieldClass}`} placeholder="my-broker-live" /></label>+ <label className="text-xs text-muted-foreground">{zh ? "显示名称" : "Display name"}<input value={label} onChange={(event) => setLabel(event.target.value)} className={`mt-1 ${fieldClass}`} placeholder={zh ? "我的主账户" : "My main account"} /></label>+ </div>+ <button type="button" onClick={() => void create()} disabled={!profileId || busy === "create"} className="mt-3 inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-40">{busy === "create" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}{zh ? "创建本地连接" : "Create connection"}</button>+ </section>++ <section>+ <div className="flex items-end justify-between"><div><h3 className="font-medium">{zh ? "这台电脑上的连接" : "Connections on this computer"}</h3><p className="mt-1 text-xs text-muted-foreground">{data?.connections.length ?? 0} {zh ? "个连接" : "connections"}</p></div><ShieldCheck className="h-5 w-5 text-positive" /></div>+ <div className="mt-3 space-y-3">{data?.connections.map((connection) => <ConnectionCard key={connection.id} connection={connection} zh={zh} busy={busy} onTest={test} onDelete={remove} onSaved={async () => { await load(); await onChanged(); }} setBusy={setBusy} setMessage={setMessage} />)}{data && !data.connections.length ? <div className="rounded-lg border border-dashed p-8 text-center text-sm text-muted-foreground">{zh ? "还没有本地连接" : "No local connections yet"}</div> : null}</div>+ </section>++ <section className="rounded-xl border border-dashed p-4">+ <div className="flex items-center gap-2"><FolderCode className="h-4 w-4" /><h3 className="font-medium">{zh ? "让 Codex 接入新券商" : "Add a broker with Codex"}</h3></div>+ <p className="mt-2 text-xs leading-5 text-muted-foreground">{zh ? "让 Codex 运行 connector init,根据券商官方文档补全只读 adapter,通过 validate 后 install。插件安装在下面的本机目录,不进入项目仓库。" : "Ask Codex to run connector init, implement the read adapter from official docs, validate it, then install it. The plugin stays outside the repository."}</p>+ <code className="mt-3 block overflow-x-auto rounded-md bg-muted p-3 text-xs">{data?.plugin_directory ?? "~/.vibe-trading/connectors"}</code>+ </section>+ </div>+ </section>+ </div>;+}++function ConnectionCard({ connection, zh, busy, onTest, onDelete, onSaved, setBusy, setMessage }: { connection: LocalConnection; zh: boolean; busy: string | null; onTest: (connection: LocalConnection) => Promise<void>; onDelete: (connection: LocalConnection) => Promise<void>; onSaved: () => Promise<void>; setBusy: (value: string | null) => void; setMessage: (value: string | null) => void }) {+ const [values, setValues] = useState<Record<string, string>>({});+ async function saveCredentials() {+ setBusy(`credentials:${connection.id}`);+ setMessage(null);+ try {+ await api.saveConnectionCredentials(connection.id, values);+ setValues({});+ await onSaved();+ setMessage(zh ? "凭证已保存到系统钥匙串。" : "Credentials saved to the OS vault.");+ } catch (error) {+ setMessage(error instanceof Error ? error.message : String(error));+ } finally {+ setBusy(null);+ }+ }+ return <article className="rounded-xl border bg-card p-4">+ <div className="flex items-start justify-between gap-3"><div><div className="font-medium">{connection.label}</div><div className="mt-1 flex flex-wrap gap-2 text-xs text-muted-foreground"><span>{connection.connector.toUpperCase()}</span><span>·</span><span>{connection.environment === "live" ? (zh ? "实盘" : "Live") : (zh ? "模拟" : "Paper")}</span><span>·</span><span>{connection.transport}</span></div></div><span className="inline-flex items-center gap-1 rounded-full bg-positive/10 px-2 py-1 text-xs text-positive"><ShieldCheck className="h-3 w-3" />{zh ? "结构只读" : "Read-only"}</span></div>+ {connection.credential_fields.length ? <div className="mt-4 grid gap-2 sm:grid-cols-2">{connection.credential_fields.map((field) => <label key={field.name} className="text-xs text-muted-foreground">{field.label}{connection.credential_status[field.name] ? <span className="ml-1 text-positive">{zh ? "已保存" : "saved"}</span> : null}<input type={field.secret ? "password" : "text"} value={values[field.name] ?? ""} onChange={(event) => setValues((current) => ({ ...current, [field.name]: event.target.value }))} className={`mt-1 ${fieldClass}`} placeholder={connection.credential_status[field.name] ? "••••••••" : ""} autoComplete="off" /></label>)}</div> : <p className="mt-3 text-xs text-muted-foreground">{connection.transport === "remote_mcp" ? (zh ? "使用 OAuth;需要时通过重新连接完成授权。" : "Uses OAuth; authorize through reconnect when required.") : (zh ? "凭证由现有连接器本地配置管理。" : "Credentials are managed by the existing local connector configuration.")}</p>}+ <div className="mt-4 flex flex-wrap gap-2">{connection.credential_fields.length ? <button type="button" onClick={() => void saveCredentials()} disabled={busy === `credentials:${connection.id}` || !Object.values(values).some(Boolean)} className="inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-40"><ShieldCheck className="h-3.5 w-3.5" />{zh ? "保存到钥匙串" : "Save to vault"}</button> : null}<button type="button" onClick={() => void onTest(connection)} disabled={busy === `test:${connection.id}`} className="inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs">{busy === `test:${connection.id}` ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <PlugZap className="h-3.5 w-3.5" />}{zh ? "测试连接" : "Test"}</button><button type="button" onClick={() => void onDelete(connection)} disabled={busy === `delete:${connection.id}`} className="ml-auto inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs text-danger hover:bg-danger/10"><Trash2 className="h-3.5 w-3.5" />{zh ? "删除" : "Delete"}</button></div>+ {connection.credentials_configured ? <div className="mt-3 flex items-center gap-1.5 text-xs text-positive"><CheckCircle2 className="h-3.5 w-3.5" />{zh ? "所需凭证已配置" : "Required credentials configured"}</div> : null}+ </article>;+}diff --git a/frontend/src/components/portfolio/PortfolioSourceEditor.tsx b/frontend/src/components/portfolio/PortfolioSourceEditor.tsxnew file mode 100644index 000000000..e5aa66089--- /dev/null+++ b/frontend/src/components/portfolio/PortfolioSourceEditor.tsx@@ -0,0 +1,122 @@+import { useEffect, useMemo, useState } from "react";+import { ArrowDown, ArrowUp, Plus, Save, Trash2, X } from "lucide-react";+import { ConnectionCenter } from "@/components/portfolio/ConnectionCenter";+import type {+ PortfolioSettings,+ PortfolioSourceCatalogItem,+ PortfolioSourceSettings,+} from "@/lib/api";++interface Props {+ open: boolean;+ settings: PortfolioSettings | null;+ catalog: PortfolioSourceCatalogItem[];+ saving: boolean;+ zh: boolean;+ onClose: () => void;+ onSave: (settings: PortfolioSettings) => Promise<void>;+ onConnectionsChanged: () => Promise<void>;+}++const fieldClass = "w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:border-primary focus:ring-2 focus:ring-primary/20";++export function PortfolioSourceEditor({ open, settings, catalog, saving, zh, onClose, onSave, onConnectionsChanged }: Props) {+ const [draft, setDraft] = useState<PortfolioSettings | null>(settings);+ const [connectionToAdd, setConnectionToAdd] = useState("");+ const [connectionCenterOpen, setConnectionCenterOpen] = useState(false);++ useEffect(() => {+ if (open && settings) {+ setDraft({ ...settings, sources: settings.sources.map((source) => ({ ...source })) });+ }+ }, [open, settings]);++ useEffect(() => {+ if (!open) return;+ const closeOnEscape = (event: KeyboardEvent) => { if (event.key === "Escape") onClose(); };+ window.addEventListener("keydown", closeOnEscape);+ return () => window.removeEventListener("keydown", closeOnEscape);+ }, [open, onClose]);++ const available = useMemo(() => {+ const selected = new Set(draft?.sources.map((source) => source.connection_id) ?? []);+ return catalog.filter((item) => !selected.has(item.connection_id));+ }, [catalog, draft]);++ if (!open || !draft) return null;++ const updateSource = (index: number, update: Partial<PortfolioSourceSettings>) => {+ setDraft((current) => current && ({+ ...current,+ sources: current.sources.map((source, sourceIndex) => sourceIndex === index ? { ...source, ...update } : source),+ }));+ };++ const move = (index: number, direction: -1 | 1) => {+ const target = index + direction;+ if (target < 0 || target >= draft.sources.length) return;+ const sources = [...draft.sources];+ [sources[index], sources[target]] = [sources[target], sources[index]];+ setDraft({ ...draft, sources: sources.map((source, order) => ({ ...source, order })) });+ };++ const remove = (index: number) => {+ setDraft({+ ...draft,+ sources: draft.sources.filter((_, sourceIndex) => sourceIndex !== index)+ .map((source, order) => ({ ...source, order })),+ });+ };++ const add = () => {+ const connection = available.find((item) => item.connection_id === connectionToAdd) ?? available[0];+ if (!connection) return;+ setDraft({+ ...draft,+ sources: [...draft.sources, {+ connection_id: connection.connection_id,+ label: connection.label,+ enabled: true,+ order: draft.sources.length,+ include_cash: true,+ }],+ });+ setConnectionToAdd("");+ };++ return <div className="fixed inset-0 z-50 flex justify-end bg-black/35" role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget) onClose(); }}>+ <section className="flex h-full w-full max-w-xl flex-col border-l bg-background shadow-2xl" role="dialog" aria-modal="true" aria-labelledby="portfolio-source-editor-title">+ <header className="flex items-start justify-between border-b p-5">+ <div><h2 id="portfolio-source-editor-title" className="text-lg font-semibold">{zh ? "管理持仓账户" : "Manage portfolio accounts"}</h2><p className="mt-1 text-xs text-muted-foreground">{zh ? "这里只保存账户选择和显示偏好,不保存密钥。" : "Only account selection and display preferences are stored here."}</p></div>+ <button type="button" onClick={onClose} className="rounded-md p-2 hover:bg-muted" aria-label={zh ? "关闭" : "Close"}><X className="h-4 w-4" /></button>+ </header>++ <div className="flex-1 space-y-6 overflow-y-auto p-5">+ <fieldset><legend className="text-sm font-medium">{zh ? "主要显示货币" : "Primary display currency"}</legend><div className="mt-2 grid grid-cols-2 gap-2">{(["USD", "CNY"] as const).map((currency) => <button key={currency} type="button" onClick={() => setDraft({ ...draft, display_currency: currency })} className={`rounded-md border px-3 py-2 text-sm ${draft.display_currency === currency ? "border-primary bg-primary/5 text-primary" : "bg-card"}`}>{currency}</button>)}</div></fieldset>++ <section>+ <div className="flex items-end justify-between gap-3"><div><h3 className="text-sm font-medium">{zh ? "已添加账户" : "Selected accounts"}</h3><p className="mt-1 text-xs text-muted-foreground">{zh ? "拖动顺序的替代操作:使用上下箭头。" : "Use the arrow buttons to change display order."}</p></div><span className="text-xs text-muted-foreground">{draft.sources.length}</span></div>+ <div className="mt-3 space-y-3">+ {draft.sources.map((source, index) => {+ const connection = catalog.find((item) => item.connection_id === source.connection_id);+ return <article key={source.connection_id} className="rounded-lg border bg-card p-4">+ <div className="flex items-start gap-3">+ <input type="checkbox" checked={source.enabled} onChange={(event) => updateSource(index, { enabled: event.target.checked })} className="mt-2 h-4 w-4 accent-primary" aria-label={zh ? "启用账户" : "Enable account"} />+ <div className="min-w-0 flex-1"><input value={source.label} onChange={(event) => updateSource(index, { label: event.target.value })} className={fieldClass} aria-label={zh ? "账户名称" : "Account label"} /><div className="mt-2 flex flex-wrap gap-2 text-xs text-muted-foreground"><span>{connection?.connector.toUpperCase()}</span><span>·</span><span>{connection?.environment === "live" ? (zh ? "实盘" : "Live") : (zh ? "模拟" : "Paper")}</span><span>·</span><span>{connection?.transport}</span></div></div>+ <div className="flex gap-1"><button type="button" onClick={() => move(index, -1)} disabled={index === 0} className="rounded p-1.5 hover:bg-muted disabled:opacity-30" aria-label={zh ? "上移" : "Move up"}><ArrowUp className="h-4 w-4" /></button><button type="button" onClick={() => move(index, 1)} disabled={index === draft.sources.length - 1} className="rounded p-1.5 hover:bg-muted disabled:opacity-30" aria-label={zh ? "下移" : "Move down"}><ArrowDown className="h-4 w-4" /></button><button type="button" onClick={() => remove(index)} className="rounded p-1.5 text-danger hover:bg-danger/10" aria-label={zh ? "删除账户" : "Remove account"}><Trash2 className="h-4 w-4" /></button></div>+ </div>+ <label className="mt-3 flex items-center gap-2 text-xs text-muted-foreground"><input type="checkbox" checked={source.include_cash} onChange={(event) => updateSource(index, { include_cash: event.target.checked })} className="h-4 w-4 accent-primary" />{zh ? "计入该账户现金" : "Include this account's cash"}</label>+ </article>;+ })}+ {!draft.sources.length ? <div className="rounded-lg border border-dashed p-8 text-center text-sm text-muted-foreground">{zh ? "还没有添加账户" : "No accounts selected"}</div> : null}+ </div>+ </section>++ <section><div className="flex items-end justify-between gap-3"><div><h3 className="text-sm font-medium">{zh ? "添加本地只读连接" : "Add a local read-only connection"}</h3><p className="mt-1 text-xs text-muted-foreground">{zh ? "这里只选择已经在这台电脑上创建的连接。" : "Choose from connections already created on this computer."}</p></div><button type="button" onClick={() => setConnectionCenterOpen(true)} className="shrink-0 text-xs text-primary">{zh ? "打开连接中心" : "Open connection center"}</button></div><div className="mt-3 flex gap-2"><select value={connectionToAdd} onChange={(event) => setConnectionToAdd(event.target.value)} className={fieldClass} disabled={!available.length}><option value="">{available.length ? (zh ? "选择连接…" : "Choose a connection…") : (zh ? "没有可添加的连接" : "No available connections")}</option>{available.map((connection) => <option key={connection.connection_id} value={connection.connection_id}>{connection.label}</option>)}</select><button type="button" onClick={add} disabled={!available.length} className="inline-flex shrink-0 items-center gap-2 rounded-md border px-3 py-2 text-sm disabled:opacity-40"><Plus className="h-4 w-4" />{zh ? "添加" : "Add"}</button></div></section>+ </div>++ <footer className="flex items-center justify-between gap-3 border-t p-5"><p className="text-xs text-muted-foreground">{zh ? "保存后将刷新已启用账户。" : "Enabled accounts refresh after saving."}</p><div className="flex gap-2"><button type="button" onClick={onClose} className="rounded-md border px-4 py-2 text-sm">{zh ? "取消" : "Cancel"}</button><button type="button" disabled={saving} onClick={() => void onSave({ ...draft, sources: draft.sources.map((source, order) => ({ ...source, order })) })} className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50"><Save className="h-4 w-4" />{saving ? (zh ? "保存中" : "Saving") : (zh ? "保存并刷新" : "Save and refresh")}</button></div></footer>+ </section>+ <ConnectionCenter open={connectionCenterOpen} zh={zh} onClose={() => setConnectionCenterOpen(false)} onChanged={onConnectionsChanged} />+ </div>;+}diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex 528934c2d..11687c078 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -8,6 +8,7 @@"runtime": "مراقبة التداول","scheduled": "المجدولة","reports": "التقارير",+ "portfolio": "المحفظة","alphaZoo": "مكتبة ألفا","settings": "الإعدادات","correlation": "مصفوفة الارتباط",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex d66a41ddd..036c2a3ea 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -13,6 +13,7 @@"runtime": "Runtime","scheduled": "Scheduled","reports": "Reports",+ "portfolio": "Portfolio","alphaZoo": "Alpha Zoo","settings": "Settings","correlation": "Correlation Matrix",diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex 77f3679cf..5d3f80cbe 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -13,6 +13,7 @@"runtime": "Runtime","scheduled": "Programado","reports": "Informes",+ "portfolio": "Cartera","alphaZoo": "Alpha Zoo","settings": "Configuración","correlation": "Matriz de correlación",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex de72586a8..0ea6a60a5 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -8,6 +8,7 @@"runtime": "取引モニター","scheduled": "スケジュール","reports": "レポート",+ "portfolio": "ポートフォリオ","alphaZoo": "アルファ・ライブラリ","settings": "設定","correlation": "相関行列",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex 8d9551cf9..4cc139ce2 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -8,6 +8,7 @@"runtime": "거래 모니터","scheduled": "예약","reports": "리포트",+ "portfolio": "포트폴리오","alphaZoo": "알파 라이브러리","settings": "설정","correlation": "상관 행렬",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex 679170192..cf1a3803c 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -8,6 +8,7 @@"runtime": "交易监控","scheduled": "定时任务","reports": "报告",+ "portfolio": "持仓","alphaZoo": "Alpha 因子库","settings": "设置","correlation": "相关性矩阵",diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 286baf21c..b4dff5d3b 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -62,6 +62,180 @@ export interface CorrelationRegimeResponse {};}+export interface PortfolioPosition {+ source_id?: string;+ profile_id?: string;+ source_label?: string;+ broker: string;+ symbol: string;+ name: string;+ asset_type: string;+ market: string;+ currency: string;+ quantity: number;+ cost_price?: number | null;+ market_price?: number | null;+ market_value_usd: number;+ market_value_cny: number;+ unrealized_pnl_usd?: number | null;+ priced: boolean;+ updated_at: string;+ stale?: boolean;+ pricing_basis?: string;+ price_error?: string;+}++export interface PortfolioAccount {+ source_id?: string;+ profile_id?: string;+ label?: string;+ broker: string;+ status: "ok" | "stale" | "error";+ data_state?: "fresh" | "cached";+ last_success_at?: string;+ total_usd?: number;+ total_cny?: number;+ cash_or_unallocated_usd?: number;+ priced_value_usd?: number;+ cash_usd?: number;+ unpriced_or_other_usd?: number;+ position_count?: number;+ priced_position_count?: number;+ unpriced_position_count?: number;+ error_code?: string;+ error?: string;+ auth?: {+ method: string;+ renewal: "automatic" | "session" | "provider_managed";+ readonly: boolean;+ detail: string;+ };+}++export interface PortfolioSnapshot {+ snapshot_id: string;+ created_at: string;+ complete: boolean;+ display_currency?: "USD" | "CNY";+ totals: { usd: number; cny: number };+ valuation?: {+ priced_usd: number;+ cash_usd: number;+ unpriced_or_other_usd: number;+ identified_coverage: number;+ };+ fx: { usd_cny: number; usd_hkd: number; fetched_at: string; stale: boolean };+ accounts: PortfolioAccount[];+ positions: PortfolioPosition[];+ combined_holdings?: Array<{+ symbol: string;+ market_value_usd: number;+ asset_type?: string;+ brokers?: string[];+ unrealized_pnl_usd?: number;+ }>;+ warnings: string[];+}++export interface PortfolioHistoryPoint {+ id: string;+ created_at: string;+ complete: number;+ total_usd: string;+ total_cny: string;+}++export interface PortfolioRefreshState {+ running: boolean;+ current: string | null;+ sources?: Record<string, { status: "idle" | "pending" | "refreshing" | "ok" | "error"; error?: string | null }>;+ brokers?: Record<string, { status: "idle" | "pending" | "refreshing" | "ok" | "error"; error?: string | null }>;+}++export interface PortfolioSourceSettings {+ connection_id: string;+ label: string;+ enabled: boolean;+ order: number;+ include_cash: boolean;+}++export interface PortfolioSettings {+ display_currency: "USD" | "CNY";+ sources: PortfolioSourceSettings[];+}++export interface PortfolioSourceCatalogItem {+ id: string;+ connection_id: string;+ profile_id: string;+ connector: string;+ label: string;+ environment: "paper" | "live";+ transport: "local_tws" | "remote_mcp" | "broker_sdk" | "local_plugin";+ capabilities: string[];+ readonly: boolean;+ notes: string;+ selected: boolean;+ source_id?: string | null;+ supports_reconnect: boolean;+ credential_fields: CredentialField[];+ credential_status: Record<string, boolean>;+ credentials_configured: boolean;+}++export interface CredentialField {+ name: string;+ label: string;+ secret: boolean;+ required: boolean;+}++export interface LocalConnection {+ id: string;+ profile_id: string;+ label: string;+ connector: string;+ environment: "paper" | "live";+ transport: "local_tws" | "remote_mcp" | "broker_sdk" | "local_plugin";+ readonly: boolean;+ capabilities: string[];+ supports_reconnect: boolean;+ credential_fields: CredentialField[];+ credential_status: Record<string, boolean>;+ credentials_configured: boolean;+}++export interface ReadonlyConnectionProfile {+ id: string;+ connector: string;+ label: string;+ environment: "paper" | "live";+ transport: "local_tws" | "remote_mcp" | "broker_sdk" | "local_plugin";+ capabilities: string[];+ readonly: boolean;+ notes: string;+ local_plugin: boolean;+ credential_fields: CredentialField[];+ supports_reconnect: boolean;+ invalid_plugin?: boolean;+ directory?: string;+ error?: string;+}++export interface ConnectionsResponse {+ status: string;+ connections: LocalConnection[];+ profiles: ReadonlyConnectionProfile[];+ plugin_directory: string;+}++export interface PortfolioSettingsResponse {+ status: string;+ settings: PortfolioSettings;+ catalog: PortfolioSourceCatalogItem[];+}+async function errorFromResponse(res: Response): Promise<ApiError> {let detail = `HTTP ${res.status}`;try {@@ -137,6 +311,45 @@ export const api = {request<CorrelationRegimeResponse>(`/correlation/regime?codes=${encodeURIComponent(codes)}&days=${encodeURIComponent(String(days))}`,),+ getPortfolio: () => request<{ status: string; snapshot: PortfolioSnapshot | null }>("/api/portfolio"),+ refreshPortfolio: () => request<{ status: string; snapshot: PortfolioSnapshot }>("/api/portfolio/refresh", { method: "POST" }),+ getPortfolioRefreshStatus: () => request<{ status: string; refresh: PortfolioRefreshState }>("/api/portfolio/refresh-status"),+ reconnectPortfolioSource: (sourceId: string) =>+ request<{ status: string; authorized: boolean }>(`/api/portfolio/sources/${encodeURIComponent(sourceId)}/reconnect`, { method: "POST" }),+ getPortfolioSettings: () => request<PortfolioSettingsResponse>("/api/portfolio/settings"),+ updatePortfolioSettings: (settings: PortfolioSettings) =>+ request<PortfolioSettingsResponse>("/api/portfolio/settings", {+ method: "PUT",+ body: JSON.stringify(settings),+ }),+ getConnections: () => request<ConnectionsResponse>("/api/connections"),+ createConnection: (payload: { id: string; profile_id: string; label: string }) =>+ request<{ status: string; connection: LocalConnection }>("/api/connections", {+ method: "POST",+ body: JSON.stringify(payload),+ }),+ saveConnectionCredentials: (connectionId: string, values: Record<string, string>) =>+ request<{ status: string; credential_status: Record<string, boolean> }>(+ `/api/connections/${encodeURIComponent(connectionId)}/credentials`,+ { method: "POST", body: JSON.stringify({ values }) },+ ),+ checkConnection: (connectionId: string) =>+ request<{ status: string; connection_id: string; report: Record<string, unknown> }>(+ `/api/connections/${encodeURIComponent(connectionId)}/check`,+ { method: "POST" },+ ),+ deleteConnection: (connectionId: string) =>+ request<{ status: string; deleted: string }>(+ `/api/connections/${encodeURIComponent(connectionId)}`,+ { method: "DELETE" },+ ),+ getPortfolioHistory: (limit = 180) =>+ request<{ status: string; history: PortfolioHistoryPoint[] }>(`/api/portfolio/history?limit=${encodeURIComponent(String(limit))}`),+ downloadPortfolioCsv: async () => {+ const response = await fetch(`${BASE}/api/portfolio/export.csv`, { headers: authHeaders() });+ if (!response.ok) throw await errorFromResponse(response);+ return response.blob();+ },listRuns: (limit?: number) => request<RunListItem[]>(`/runs${limit ? `?limit=${encodeURIComponent(String(limit))}` : ""}`),getRun: (id: string, params: RunDetailParams = {}) => {const q = new URLSearchParams();diff --git a/frontend/src/lib/echarts.ts b/frontend/src/lib/echarts.tsindex 4c9bd644a..3eb6b8a81 100644--- a/frontend/src/lib/echarts.ts+++ b/frontend/src/lib/echarts.ts@@ -1,5 +1,5 @@import * as echarts from "echarts/core";-import { CandlestickChart, LineChart, BarChart, HeatmapChart } from "echarts/charts";+import { CandlestickChart, LineChart, BarChart, HeatmapChart, PieChart } from "echarts/charts";import {GridComponent,TooltipComponent,@@ -10,15 +10,17 @@ import {MarkLineComponent,MarkAreaComponent,VisualMapComponent,+ GraphicComponent,} from "echarts/components";import { CanvasRenderer } from "echarts/renderers";echarts.use([- CandlestickChart, LineChart, BarChart, HeatmapChart,+ CandlestickChart, LineChart, BarChart, HeatmapChart, PieChart,GridComponent, TooltipComponent, LegendComponent,DataZoomComponent, MarkPointComponent,ToolboxComponent, MarkLineComponent, MarkAreaComponent,VisualMapComponent,+ GraphicComponent,CanvasRenderer,]);diff --git a/frontend/src/pages/Portfolio.tsx b/frontend/src/pages/Portfolio.tsxnew file mode 100644index 000000000..8805da04d--- /dev/null+++ b/frontend/src/pages/Portfolio.tsx@@ -0,0 +1,463 @@+import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { useTranslation } from "react-i18next";+import {+ AlertTriangle,+ CheckCircle2,+ Clock3,+ Database,+ Download,+ KeyRound,+ Loader2,+ RefreshCw,+ Search,+ Settings2,+ ShieldCheck,+ WalletCards,+ WifiOff,+} from "lucide-react";+import { PortfolioSourceEditor } from "@/components/portfolio/PortfolioSourceEditor";+import {+ api,+ type PortfolioAccount,+ type PortfolioHistoryPoint,+ type PortfolioRefreshState,+ type PortfolioSettings,+ type PortfolioSnapshot,+ type PortfolioSourceCatalogItem,+} from "@/lib/api";+import { echarts } from "@/lib/echarts";++const BROKER_COLORS: Record<string, string> = {+ IBKR: "#f05a47",+ LONGBRIDGE: "#4f6edb",+ BINANCE: "#f3ba2f",+};++const HOLDING_COLORS = [+ "#4f6edb", "#f3ba2f", "#45a67d", "#8b6fd6", "#ef8354",+ "#2d9cdb", "#d96c9d", "#7f8c8d", "#b5c83b", "#f05a47",+];++function money(value: number | undefined, currency: "USD" | "CNY" = "USD") {+ if (value == null || !Number.isFinite(value)) return "—";+ return new Intl.NumberFormat(undefined, {+ style: "currency",+ currency,+ maximumFractionDigits: currency === "USD" ? 2 : 0,+ }).format(value);+}++function quantity(value: number | undefined) {+ if (value == null || !Number.isFinite(value)) return "—";+ return new Intl.NumberFormat(undefined, { maximumFractionDigits: 8 }).format(value);+}++function price(value: number | undefined | null) {+ if (value == null || !Number.isFinite(value)) return "—";+ return new Intl.NumberFormat(undefined, {+ minimumFractionDigits: value >= 1 ? 2 : 4,+ maximumFractionDigits: value >= 100 ? 2 : value >= 1 ? 4 : 8,+ }).format(value);+}++function percentage(value: number | undefined) {+ if (value == null || !Number.isFinite(value)) return "—";+ return `${(value * 100).toFixed(1)}%`;+}++function dateTime(value: string | undefined) {+ return value ? new Date(value).toLocaleString() : "—";+}++function dayKey(value: string) {+ const date = new Date(value);+ return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;+}++export function Portfolio() {+ const { i18n } = useTranslation();+ const zh = i18n.language.startsWith("zh");+ const [snapshot, setSnapshot] = useState<PortfolioSnapshot | null>(null);+ const [history, setHistory] = useState<PortfolioHistoryPoint[]>([]);+ const [loading, setLoading] = useState(true);+ const [refreshing, setRefreshing] = useState(false);+ const [reconnecting, setReconnecting] = useState(false);+ const [refreshState, setRefreshState] = useState<PortfolioRefreshState | null>(null);+ const [portfolioSettings, setPortfolioSettings] = useState<PortfolioSettings | null>(null);+ const [sourceCatalog, setSourceCatalog] = useState<PortfolioSourceCatalogItem[]>([]);+ const [editorOpen, setEditorOpen] = useState(false);+ const [savingSettings, setSavingSettings] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [query, setQuery] = useState("");+ const [sourceFilter, setSourceFilter] = useState<string>("all");++ async function load() {+ setLoading(true);+ setError(null);+ try {+ const [current, points, configuration] = await Promise.all([+ api.getPortfolio(),+ api.getPortfolioHistory(),+ api.getPortfolioSettings(),+ ]);+ setSnapshot(current.snapshot);+ setHistory(points.history ?? []);+ setPortfolioSettings(configuration.settings);+ setSourceCatalog(configuration.catalog);+ } catch (err) {+ setError(err instanceof Error ? err.message : "Portfolio unavailable");+ } finally {+ setLoading(false);+ }+ }++ async function refresh(settingsOverride?: PortfolioSettings) {+ const activeSettings = settingsOverride ?? portfolioSettings;+ const enabledSources = activeSettings?.sources.filter((source) => source.enabled) ?? [];+ if (!enabledSources.length) {+ setEditorOpen(true);+ return;+ }+ setRefreshing(true);+ setError(null);+ setRefreshState({+ running: true,+ current: null,+ sources: Object.fromEntries(enabledSources.map((source) => [source.connection_id, { status: "pending" as const }])),+ });+ const timer = window.setInterval(() => {+ void api.getPortfolioRefreshStatus()+ .then((result) => setRefreshState(normalizeRefreshState(result.refresh)))+ .catch(() => undefined);+ }, 500);+ try {+ const result = await api.refreshPortfolio();+ setSnapshot(result.snapshot);+ const points = await api.getPortfolioHistory();+ setHistory(points.history ?? []);+ const status = await api.getPortfolioRefreshStatus();+ setRefreshState(normalizeRefreshState(status.refresh));+ } catch (err) {+ setError(err instanceof Error ? err.message : "Refresh failed");+ } finally {+ window.clearInterval(timer);+ setRefreshing(false);+ }+ }++ async function reconnectSource(sourceId: string) {+ setReconnecting(true);+ setError(null);+ try {+ await api.reconnectPortfolioSource(sourceId);+ await refresh();+ } catch (err) {+ setError(err instanceof Error ? err.message : "Account reconnect failed");+ } finally {+ setReconnecting(false);+ }+ }++ async function savePortfolioSettings(settings: PortfolioSettings) {+ setSavingSettings(true);+ setError(null);+ try {+ const result = await api.updatePortfolioSettings(settings);+ setPortfolioSettings(result.settings);+ setSourceCatalog(result.catalog);+ setEditorOpen(false);+ setSourceFilter("all");+ if (result.settings.sources.some((source) => source.enabled)) {+ await refresh(result.settings);+ } else {+ setSnapshot(null);+ }+ } catch (err) {+ setError(err instanceof Error ? err.message : "Unable to save portfolio settings");+ } finally {+ setSavingSettings(false);+ }+ }++ async function reloadConnections() {+ const configuration = await api.getPortfolioSettings();+ setPortfolioSettings(configuration.settings);+ setSourceCatalog(configuration.catalog);+ }++ async function download() {+ try {+ const blob = await api.downloadPortfolioCsv();+ const url = URL.createObjectURL(blob);+ const anchor = document.createElement("a");+ anchor.href = url;+ anchor.download = `portfolio-${new Date().toISOString().slice(0, 10)}.csv`;+ anchor.click();+ URL.revokeObjectURL(url);+ } catch (err) {+ setError(err instanceof Error ? err.message : "Export failed");+ }+ }++ useEffect(() => { void load(); }, []);++ const positions = useMemo(() => {+ const needle = query.trim().toLowerCase();+ return [...(snapshot?.positions ?? [])]+ .filter((row) => sourceFilter === "all" || (row.source_id ?? row.broker) === sourceFilter)+ .filter((row) => !needle || [row.broker, row.symbol, row.name, row.asset_type, row.market]+ .join(" ").toLowerCase().includes(needle))+ .sort((a, b) => (b.market_value_usd ?? 0) - (a.market_value_usd ?? 0));+ }, [snapshot, query, sourceFilter]);++ const brokerAllocation = useMemo(() => (snapshot?.accounts ?? [])+ .filter((row) => row.status !== "error" && (row.total_usd ?? 0) > 0)+ .map((row) => ({+ id: row.source_id ?? row.broker,+ name: row.label ?? row.broker.toUpperCase(),+ value: row.total_usd ?? 0,+ connector: row.broker,+ })), [snapshot]);++ const holdingAllocation = useMemo(() => {+ const rows = [...(snapshot?.combined_holdings ?? [])]+ .filter((row) => row.market_value_usd > 0)+ .sort((a, b) => b.market_value_usd - a.market_value_usd);+ const shown = rows.slice(0, 7).map((row) => ({ name: row.symbol, value: row.market_value_usd }));+ const other = rows.slice(7).reduce((sum, row) => sum + row.market_value_usd, 0);+ if (other > 0) shown.push({ name: zh ? "其他持仓" : "Other", value: other });+ const valuation = snapshot?.valuation;+ if ((valuation?.cash_usd ?? 0) > 0.01) shown.push({ name: zh ? "现金" : "Cash", value: valuation?.cash_usd ?? 0 });+ if ((valuation?.unpriced_or_other_usd ?? 0) > 0.01) shown.push({ name: zh ? "未定价/其他" : "Unpriced / other", value: valuation?.unpriced_or_other_usd ?? 0 });+ if (!valuation && snapshot) {+ const priced = rows.reduce((sum, row) => sum + row.market_value_usd, 0);+ const residual = Math.max(0, snapshot.totals.usd - priced);+ if (residual > 0.01) shown.push({ name: zh ? "现金/未定价" : "Cash / unpriced", value: residual });+ }+ return shown;+ }, [snapshot, zh]);++ const dailyChange = useMemo(() => {+ if (!snapshot || !history.length) return null;+ const sameDay = history.filter((row) => dayKey(row.created_at) === dayKey(snapshot.created_at));+ if (!sameDay.length) return null;+ return snapshot.totals.usd - Number(sameDay[0].total_usd);+ }, [snapshot, history]);++ const latestCompleteAt = history.length ? history[history.length - 1].created_at : undefined;+ const coverage = snapshot?.valuation?.identified_coverage ?? (() => {+ if (!snapshot?.totals.usd) return 0;+ return (snapshot.positions ?? []).reduce((sum, row) => sum + (row.priced ? row.market_value_usd : 0), 0) / snapshot.totals.usd;+ })();+ const displayCurrency = portfolioSettings?.display_currency ?? snapshot?.display_currency ?? "USD";+ const totalDisplay = displayCurrency === "CNY" ? snapshot?.totals.cny : snapshot?.totals.usd;++ return (+ <div className="min-h-screen p-4 sm:p-6 lg:p-8">+ <div className="mx-auto flex w-full max-w-[1500px] flex-col gap-6">+ <header className="flex flex-col gap-4 border-b pb-6 xl:flex-row xl:items-end xl:justify-between">+ <div>+ <div className="mb-3 inline-flex items-center gap-2 rounded-full border bg-card px-3 py-1 text-xs text-muted-foreground">+ <ShieldCheck className="h-3.5 w-3.5 text-positive" />+ {zh ? "本机只读 · 多账户汇总" : "Local read-only · Multi-account"}+ </div>+ <h1 className="text-3xl font-semibold tracking-tight">{zh ? "持仓总览" : "Portfolio"}</h1>+ <p className="mt-2 text-sm text-muted-foreground">+ {zh ? "统一汇总已启用的只读连接;连接失败时保留最后一次成功数据。" : "Unified valuation for enabled read-only connections with stale-safe fallback."}+ </p>+ {snapshot ? <p className="mt-2 text-xs text-muted-foreground">USD/CNY {snapshot.fx.usd_cny.toFixed(4)} · {snapshot.fx.stale ? (zh ? "缓存汇率" : "cached FX") : (zh ? "最新汇率" : "fresh FX")}</p> : null}+ </div>+ <div className="flex flex-wrap gap-2">+ <button onClick={() => setEditorOpen(true)} className="inline-flex items-center gap-2 rounded-md border bg-card px-4 py-2 text-sm">+ <Settings2 className="h-4 w-4" />{zh ? "管理账户" : "Manage accounts"}+ </button>+ <button onClick={() => void download()} disabled={!snapshot} className="inline-flex items-center gap-2 rounded-md border bg-card px-4 py-2 text-sm disabled:opacity-50">+ <Download className="h-4 w-4" /> CSV+ </button>+ <button onClick={() => void refresh()} disabled={refreshing || reconnecting} className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50">+ {refreshing ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}+ {refreshing ? (zh ? "正在刷新" : "Refreshing") : (zh ? "刷新全部账户" : "Refresh all")}+ </button>+ </div>+ </header>++ {error ? <div className="flex items-start gap-2 rounded-lg border border-danger/30 bg-danger/5 p-4 text-sm text-danger"><AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />{error}</div> : null}+ {refreshing && refreshState ? <RefreshProgress state={refreshState} settings={portfolioSettings} zh={zh} /> : null}+ {loading ? <div className="flex h-56 items-center justify-center"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div> : null}++ {!loading && !snapshot ? (+ <section className="rounded-xl border border-dashed p-12 text-center">+ <WalletCards className="mx-auto h-8 w-8 text-muted-foreground" />+ <h2 className="mt-4 font-medium">{zh ? "还没有持仓快照" : "No portfolio snapshot yet"}</h2>+ <p className="mt-2 text-sm text-muted-foreground">{zh ? "添加至少一个只读账户后即可开始汇总。" : "Add at least one read-only account to begin."}</p>+ <button onClick={() => setEditorOpen(true)} className="mt-5 inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground"><Settings2 className="h-4 w-4" />{zh ? "添加账户" : "Add account"}</button>+ </section>+ ) : null}++ {snapshot ? (+ <>+ <section className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">+ <Metric label={zh ? "总资产" : "Total assets"} value={money(totalDisplay, displayCurrency)} note={displayCurrency === "USD" ? money(snapshot.totals.cny, "CNY") : money(snapshot.totals.usd)} icon={<WalletCards className="h-4 w-4" />} />+ <Metric label={zh ? "今日资产变化" : "Today's asset change"} value={dailyChange == null ? "—" : `${dailyChange >= 0 ? "+" : ""}${money(dailyChange)}`} note={zh ? "包含行情、入金和出金影响" : "Includes market moves and cash flows"} tone={dailyChange == null ? undefined : dailyChange >= 0 ? "positive" : "danger"} icon={<Clock3 className="h-4 w-4" />} />+ <Metric label={zh ? "估值覆盖率" : "Valuation coverage"} value={percentage(coverage)} note={zh ? `已定价 ${money(snapshot.valuation?.priced_usd)} · 现金 ${money(snapshot.valuation?.cash_usd)}` : "Priced holdings plus identified cash"} icon={<Database className="h-4 w-4" />} />+ <Metric label={zh ? "最后完整更新" : "Last complete update"} value={latestCompleteAt ? new Date(latestCompleteAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : "—"} note={dateTime(latestCompleteAt)} tone={snapshot.complete ? "positive" : "warning"} icon={snapshot.complete ? <CheckCircle2 className="h-4 w-4" /> : <AlertTriangle className="h-4 w-4" />} />+ </section>++ <section className="grid gap-4 xl:grid-cols-2">+ <AllocationPie title={zh ? "按账户分布" : "Allocation by account"} data={brokerAllocation} centerLabel={money(totalDisplay, displayCurrency)} onSelect={(id) => setSourceFilter(id)} />+ <AllocationPie title={zh ? "按持仓标的分布" : "Allocation by holding"} data={holdingAllocation} centerLabel={zh ? "持仓占比" : "Holdings"} />+ </section>++ {snapshot.warnings.length ? (+ <section className="rounded-lg border border-warning/30 bg-warning/5 p-4 text-sm">+ <div className="mb-2 font-medium text-warning">{zh ? "数据说明" : "Data notes"}</div>+ <div className="space-y-1.5">{snapshot.warnings.map((warning) => <div key={warning} className="flex gap-2"><AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-warning" /><span>{warning}</span></div>)}</div>+ </section>+ ) : null}++ <section>+ <div className="mb-3 flex items-end justify-between gap-3">+ <div><h2 className="font-semibold">{zh ? "账户状态" : "Account status"}</h2><p className="mt-1 text-xs text-muted-foreground">{zh ? "点击账户卡可筛选下方持仓" : "Click an account to filter holdings"}</p></div>+ {sourceFilter !== "all" ? <button className="text-xs text-primary" onClick={() => setSourceFilter("all")}>{zh ? "清除筛选" : "Clear filter"}</button> : null}+ </div>+ <div className="grid gap-3 lg:grid-cols-3">+ {snapshot.accounts.map((account) => (+ <AccountCard key={account.source_id ?? account.broker} account={account} active={sourceFilter === (account.source_id ?? account.broker)} zh={zh} displayCurrency={displayCurrency} onClick={() => { const id = account.source_id ?? account.broker; setSourceFilter((current) => current === id ? "all" : id); }} onReconnect={account.auth?.method === "OAuth" && account.source_id ? () => void reconnectSource(account.source_id!) : undefined} reconnecting={reconnecting} />+ ))}+ </div>+ </section>++ <section className="overflow-hidden rounded-xl border bg-card">+ <div className="flex flex-col gap-3 border-b p-4 lg:flex-row lg:items-center lg:justify-between">+ <div><h2 className="font-semibold">{zh ? "持仓明细" : "Holdings"}</h2><p className="mt-1 text-xs text-muted-foreground">{positions.length} {zh ? "项持仓" : "positions"}</p></div>+ <div className="relative w-full lg:w-72"><Search className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" /><input value={query} onChange={(event) => setQuery(event.target.value)} placeholder={zh ? "搜索账户、标的或市场" : "Search broker, symbol or market"} className="w-full rounded-md border bg-background py-2 pl-9 pr-3 text-sm" /></div>+ </div>+ <div className="overflow-x-auto">+ <table className="w-full min-w-[1050px] text-sm">+ <thead className="bg-muted/40 text-left text-xs text-muted-foreground"><tr><Th>{zh ? "账户" : "Broker"}</Th><Th>{zh ? "标的" : "Symbol"}</Th><Th>{zh ? "类别" : "Type"}</Th><Th>{zh ? "数量" : "Quantity"}</Th><Th>{zh ? "成本 / 现价" : "Cost / Price"}</Th><Th>{zh ? "市值" : "Value"}</Th><Th>{zh ? "占比" : "Weight"}</Th><Th>{zh ? "未实现盈亏" : "Unrealized P/L"}</Th><Th>{zh ? "数据状态" : "Data"}</Th></tr></thead>+ <tbody className="divide-y">+ {positions.map((row) => {+ const weight = snapshot.totals.usd > 0 ? row.market_value_usd / snapshot.totals.usd : 0;+ return <tr key={`${row.source_id ?? row.broker}-${row.symbol}`} className="hover:bg-muted/20"><Td><div className="font-medium">{row.source_label ?? row.broker.toUpperCase()}</div><div className="mt-1 text-xs"><BrokerBadge broker={row.broker} /></div></Td><Td><div className="font-medium">{row.symbol}</div><div className="max-w-52 truncate text-xs text-muted-foreground">{row.name}</div></Td><Td><span className="capitalize text-muted-foreground">{row.asset_type}</span></Td><Td>{quantity(row.quantity)}</Td><Td><div>{price(row.cost_price)}</div><div className="text-xs text-muted-foreground">{price(row.market_price)}</div></Td><Td><div className="font-medium">{row.priced ? money(row.market_value_usd) : "—"}</div><div className="text-xs text-muted-foreground">{row.priced ? money(row.market_value_cny, "CNY") : "未定价"}</div></Td><Td>{row.priced ? percentage(weight) : "—"}</Td><Td><span className={row.unrealized_pnl_usd == null ? "text-muted-foreground" : row.unrealized_pnl_usd >= 0 ? "text-positive" : "text-danger"}>{row.unrealized_pnl_usd == null ? "—" : money(row.unrealized_pnl_usd)}</span></Td><Td><DataBadge stale={row.stale} priced={row.priced} zh={zh} /></Td></tr>;+ })}+ </tbody>+ </table>+ </div>+ </section>++ <HistoryChart history={history} zh={zh} />++ <section className="rounded-xl border bg-card p-5">+ <div className="mb-4 flex items-center gap-2"><KeyRound className="h-4 w-4 text-muted-foreground" /><h2 className="font-semibold">{zh ? "连接与凭证" : "Connections and credentials"}</h2></div>+ <div className="grid gap-3 lg:grid-cols-3">{snapshot.accounts.map((account) => <CredentialCard key={account.source_id ?? account.broker} account={account} zh={zh} />)}</div>+ </section>+ </>+ ) : null}+ </div>+ <PortfolioSourceEditor open={editorOpen} settings={portfolioSettings} catalog={sourceCatalog} saving={savingSettings} zh={zh} onClose={() => setEditorOpen(false)} onSave={savePortfolioSettings} onConnectionsChanged={reloadConnections} />+ </div>+ );+}++function Metric({ label, value, note, icon, tone }: { label: string; value: string; note?: string; icon: ReactNode; tone?: "positive" | "danger" | "warning" }) {+ const toneClass = tone === "positive" ? "text-positive" : tone === "danger" ? "text-danger" : tone === "warning" ? "text-warning" : "";+ return <div className="rounded-xl border bg-card p-5"><div className="flex items-center justify-between text-xs text-muted-foreground"><span>{label}</span>{icon}</div><div className={`mt-3 text-2xl font-semibold tracking-tight ${toneClass}`}>{value}</div>{note ? <div className="mt-1 truncate text-xs text-muted-foreground" title={note}>{note}</div> : null}</div>;+}++function normalizeRefreshState(state: PortfolioRefreshState | null | undefined): PortfolioRefreshState {+ const candidate = state?.sources ?? state?.brokers;+ const sources = candidate && typeof candidate === "object" && !Array.isArray(candidate)+ ? Object.fromEntries(Object.entries(candidate).map(([sourceId, item]) => [+ sourceId,+ item && typeof item === "object" ? item : { status: "pending" as const },+ ]))+ : {};+ return {+ running: Boolean(state?.running),+ current: typeof state?.current === "string" ? state.current : null,+ sources,+ brokers: sources,+ };+}++function RefreshProgress({ state, settings, zh }: { state: PortfolioRefreshState; settings: PortfolioSettings | null; zh: boolean }) {+ const labels = new Map(settings?.sources.map((source) => [source.connection_id, source.label]) ?? []);+ const entries = Object.entries(normalizeRefreshState(state).sources ?? {});+ return <section className="rounded-lg border bg-card p-4"><div className="mb-3 flex items-center gap-2 text-sm font-medium"><Loader2 className="h-4 w-4 animate-spin text-primary" />{zh ? "正在依次读取已启用账户" : "Refreshing enabled accounts sequentially"}</div><div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">{entries.map(([sourceId, item]) => { const status = item.status ?? "pending"; return <div key={sourceId} className="flex items-center justify-between gap-3 rounded-md bg-muted/40 px-3 py-2 text-xs"><span className="truncate font-medium" title={labels.get(sourceId) ?? sourceId}>{labels.get(sourceId) ?? sourceId}</span><span className={status === "ok" ? "text-positive" : status === "error" ? "text-danger" : "text-muted-foreground"}>{status === "refreshing" ? (zh ? "读取中" : "Reading") : status === "ok" ? (zh ? "完成" : "Done") : status === "error" ? (zh ? "失败" : "Failed") : (zh ? "等待" : "Waiting")}</span></div>; })}</div></section>;+}++function AccountCard({ account, active, zh, displayCurrency, onClick, onReconnect, reconnecting }: { account: PortfolioAccount; active: boolean; zh: boolean; displayCurrency: "USD" | "CNY"; onClick: () => void; onReconnect?: () => void; reconnecting: boolean }) {+ const stale = account.status === "stale";+ const failed = account.status === "error";+ return <div role="button" tabIndex={0} onClick={onClick} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") onClick(); }} className={`cursor-pointer rounded-xl border bg-card p-5 transition ${active ? "border-primary ring-1 ring-primary/20" : "hover:border-primary/40"}`}>+ <div className="flex items-center justify-between"><div><div className="font-medium">{account.label ?? account.broker.toUpperCase()}</div><div className="mt-1 text-xs"><BrokerBadge broker={account.broker} /></div></div>{failed ? <WifiOff className="h-4 w-4 text-danger" /> : stale ? <AlertTriangle className="h-4 w-4 text-warning" /> : <CheckCircle2 className="h-4 w-4 text-positive" />}</div>+ {failed ? <p className="mt-4 text-sm text-danger">{zh ? "连接失败,且没有可用缓存" : "Connection failed with no cache"}</p> : <><div className="mt-4 text-2xl font-semibold">{displayCurrency === "CNY" ? money(account.total_cny, "CNY") : money(account.total_usd)}</div><div className="mt-1 text-xs text-muted-foreground">{displayCurrency === "CNY" ? money(account.total_usd) : money(account.total_cny, "CNY")} · {account.position_count ?? 0} {zh ? "项持仓" : "positions"}</div><div className="mt-4 flex items-center justify-between border-t pt-3 text-xs"><span className={stale ? "text-warning" : "text-positive"}>{stale ? (zh ? "使用缓存" : "Cached") : (zh ? "数据正常" : "Fresh")}</span><span className="text-muted-foreground">{dateTime(account.last_success_at)}</span></div></>}+ {(failed || stale) && account.error ? <p className="mt-3 line-clamp-2 text-xs text-muted-foreground" title={account.error}>{account.error}</p> : null}+ {(failed || stale) && onReconnect ? <button onClick={(event) => { event.stopPropagation(); onReconnect(); }} disabled={reconnecting} className="mt-3 inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-50">{reconnecting ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}{zh ? "重新连接" : "Reconnect"}</button> : null}+ </div>;+}++function BrokerBadge({ broker }: { broker: string }) {+ const color = BROKER_COLORS[broker.toUpperCase()] ?? "#7c8493";+ return <span className="inline-flex items-center gap-2 font-medium uppercase"><span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: color }} />{broker}</span>;+}++function DataBadge({ stale, priced, zh }: { stale?: boolean; priced: boolean; zh: boolean }) {+ if (stale) return <span className="rounded-full bg-warning/10 px-2 py-1 text-xs text-warning">{zh ? "缓存" : "Cached"}</span>;+ if (!priced) return <span className="rounded-full bg-muted px-2 py-1 text-xs text-muted-foreground">{zh ? "未定价" : "Unpriced"}</span>;+ return <span className="rounded-full bg-positive/10 px-2 py-1 text-xs text-positive">{zh ? "最新" : "Fresh"}</span>;+}++function CredentialCard({ account, zh }: { account: PortfolioAccount; zh: boolean }) {+ const auth = account.auth;+ const renewal = auth?.renewal === "automatic" ? (zh ? "连接器自动续期" : "Connector-managed renewal") : auth?.renewal === "session" ? (zh ? "依赖本地会话" : "Local session") : (zh ? "由服务商管理有效期" : "Provider-managed validity");+ return <div className="rounded-lg border p-4"><div className="flex items-center justify-between gap-3"><div><span className="font-medium">{account.label ?? account.broker.toUpperCase()}</span><div className="mt-1 text-xs text-muted-foreground">{account.broker.toUpperCase()}</div></div><span className={`shrink-0 rounded-full px-2 py-1 text-xs ${auth?.readonly ? "bg-positive/10 text-positive" : "bg-warning/10 text-warning"}`}>{auth?.readonly ? (zh ? "只读连接模板" : "Read-only profile") : (zh ? "连接模板可写" : "Write-capable profile")}</span></div><div className="mt-3 text-sm">{auth?.method ?? "—"} · {renewal}</div><p className="mt-1 text-xs text-muted-foreground">{auth?.detail ?? "—"}</p></div>;+}++type AllocationDatum = { id?: string; name: string; value: number; connector?: string };++function AllocationPie({ title, data, centerLabel, onSelect }: { title: string; data: AllocationDatum[]; centerLabel: string; onSelect?: (id: string) => void }) {+ const ref = useRef<HTMLDivElement>(null);+ useEffect(() => {+ if (!ref.current || ref.current.clientWidth === 0) return;+ const chart = echarts.init(ref.current);+ const brokerPalette = data.map((item) => BROKER_COLORS[(item.connector ?? item.name).toUpperCase()]).filter(Boolean);+ const palette = brokerPalette.length === data.length ? brokerPalette : HOLDING_COLORS;+ chart.setOption({+ color: palette,+ tooltip: { trigger: "item", formatter: (params: { name: string; value: number; percent: number }) => `${params.name}<br/>${money(params.value)} · ${params.percent.toFixed(1)}%` },+ legend: { type: "scroll", bottom: 0, left: "center", textStyle: { color: "#7c8493" } },+ series: [{ type: "pie", radius: ["46%", "70%"], center: ["50%", "43%"], avoidLabelOverlap: true, padAngle: 2, itemStyle: { borderRadius: 5 }, label: { show: true, formatter: (params: { name: string; percent: number }) => params.percent >= 2 ? `${params.name}\n${params.percent.toFixed(1)}%` : "", fontSize: 12 }, labelLine: { length: 10, length2: 7 }, labelLayout: { hideOverlap: true }, data }],+ graphic: [{ type: "text", left: "center", top: "39%", style: { text: centerLabel, textAlign: "center", fill: "#7c8493", fontSize: 12, fontWeight: 600 } }],+ });+ const resize = () => chart.resize();+ const select = (params: { dataIndex?: number }) => { const item = params.dataIndex == null ? undefined : data[params.dataIndex]; if (item && onSelect) onSelect(item.id ?? item.name); };+ chart.on("click", select);+ window.addEventListener("resize", resize);+ return () => { window.removeEventListener("resize", resize); chart.off("click", select); chart.dispose(); };+ }, [data, centerLabel, onSelect]);+ return <div className="rounded-xl border bg-card p-5"><h2 className="font-semibold">{title}</h2><div ref={ref} className="h-80 w-full" /></div>;+}++function HistoryChart({ history, zh }: { history: PortfolioHistoryPoint[]; zh: boolean }) {+ const ref = useRef<HTMLDivElement>(null);+ useEffect(() => {+ if (!ref.current || ref.current.clientWidth === 0) return;+ const chart = echarts.init(ref.current);+ const rows = history.slice(-180);+ chart.setOption({+ grid: { left: 18, right: 18, top: 25, bottom: 28, containLabel: true },+ tooltip: { trigger: "axis", formatter: (items: Array<{ dataIndex: number; value: number }>) => { const item = items[0]; const row = rows[item.dataIndex]; return `${dateTime(row?.created_at)}<br/>${money(Number(item?.value))}`; } },+ xAxis: { type: "category", boundaryGap: false, data: rows.map((row) => new Date(row.created_at).toLocaleString([], { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" })), axisLabel: { color: "#7c8493", hideOverlap: true }, axisLine: { lineStyle: { color: "#d6d9df" } } },+ yAxis: { type: "value", scale: true, axisLabel: { color: "#7c8493", formatter: (value: number) => `$${Math.round(value / 1000)}k` }, splitLine: { lineStyle: { color: "#d6d9df", opacity: 0.45 } } },+ series: [{ type: "line", data: rows.map((row) => Number(row.total_usd)), smooth: true, symbol: rows.length < 30 ? "circle" : "none", lineStyle: { width: 2, color: "#4f6edb" }, itemStyle: { color: "#4f6edb" }, areaStyle: { color: "rgba(79,110,219,0.10)" } }],+ });+ const resize = () => chart.resize();+ window.addEventListener("resize", resize);+ return () => { window.removeEventListener("resize", resize); chart.dispose(); };+ }, [history]);+ return <section className="rounded-xl border bg-card p-5"><div className="flex items-start justify-between gap-3"><div><h2 className="font-semibold">{zh ? "资产历史" : "Asset history"}</h2><p className="mt-1 text-xs text-muted-foreground">{zh ? "只显示完整快照;资产变化可能包含入金和出金。" : "Complete snapshots only; changes may include cash flows."}</p></div><span className="rounded-full bg-positive/10 px-2 py-1 text-xs text-positive">{history.length} {zh ? "个完整快照" : "complete snapshots"}</span></div>{history.length ? <div ref={ref} className="mt-4 h-64 w-full" /> : <div className="flex h-44 items-center justify-center text-sm text-muted-foreground">{zh ? "完成首次完整刷新后开始积累" : "History begins after a complete refresh"}</div>}</section>;+}++function Th({ children }: { children: ReactNode }) { return <th className="whitespace-nowrap px-4 py-3 font-medium">{children}</th>; }+function Td({ children }: { children: ReactNode }) { return <td className="px-4 py-3">{children}</td>; }diff --git a/frontend/src/pages/__tests__/Portfolio.test.tsx b/frontend/src/pages/__tests__/Portfolio.test.tsxnew file mode 100644index 000000000..927f1e756--- /dev/null+++ b/frontend/src/pages/__tests__/Portfolio.test.tsx@@ -0,0 +1,190 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { Portfolio } from "@/pages/Portfolio";+import { api } from "@/lib/api";++vi.mock("@/lib/api", async () => {+ const actual = await vi.importActual<typeof import("@/lib/api")>("@/lib/api");+ return {+ ...actual,+ api: {+ ...actual.api,+ getPortfolio: vi.fn(),+ refreshPortfolio: vi.fn(),+ getPortfolioRefreshStatus: vi.fn(),+ reconnectPortfolioSource: vi.fn(),+ getPortfolioSettings: vi.fn(),+ updatePortfolioSettings: vi.fn(),+ getConnections: vi.fn(),+ createConnection: vi.fn(),+ saveConnectionCredentials: vi.fn(),+ checkConnection: vi.fn(),+ deleteConnection: vi.fn(),+ getPortfolioHistory: vi.fn(),+ downloadPortfolioCsv: vi.fn(),+ },+ };+});++const mocked = api as unknown as {+ getPortfolio: ReturnType<typeof vi.fn>;+ refreshPortfolio: ReturnType<typeof vi.fn>;+ getPortfolioRefreshStatus: ReturnType<typeof vi.fn>;+ reconnectPortfolioSource: ReturnType<typeof vi.fn>;+ getPortfolioSettings: ReturnType<typeof vi.fn>;+ updatePortfolioSettings: ReturnType<typeof vi.fn>;+ getConnections: ReturnType<typeof vi.fn>;+ createConnection: ReturnType<typeof vi.fn>;+ saveConnectionCredentials: ReturnType<typeof vi.fn>;+ checkConnection: ReturnType<typeof vi.fn>;+ deleteConnection: ReturnType<typeof vi.fn>;+ getPortfolioHistory: ReturnType<typeof vi.fn>;+ downloadPortfolioCsv: ReturnType<typeof vi.fn>;+};++const snapshot = {+ snapshot_id: "snap-1",+ created_at: "2026-08-09T00:00:00Z",+ complete: true,+ totals: { usd: 1000, cny: 7200 },+ valuation: { priced_usd: 800, cash_usd: 200, unpriced_or_other_usd: 0, identified_coverage: 1 },+ fx: { usd_cny: 7.2, usd_hkd: 7.8, fetched_at: "2026-08-09T00:00:00Z", stale: false },+ accounts: [+ { broker: "ibkr", status: "ok" as const, total_usd: 600, total_cny: 4320, position_count: 1, last_success_at: "2026-08-09T00:00:00Z" },+ { broker: "longbridge", status: "ok" as const, total_usd: 300, total_cny: 2160, position_count: 1, last_success_at: "2026-08-09T00:00:00Z" },+ { broker: "binance", status: "ok" as const, total_usd: 100, total_cny: 720, position_count: 1, last_success_at: "2026-08-09T00:00:00Z" },+ ],+ positions: [{+ broker: "ibkr", symbol: "AAPL", name: "Apple", asset_type: "stock", market: "US",+ currency: "USD", quantity: 2, cost_price: 100, market_price: 150,+ market_value_usd: 300, market_value_cny: 2160, unrealized_pnl_usd: 100,+ priced: true, updated_at: "2026-08-09T00:00:00Z",+ }],+ warnings: [],+};++const portfolioConfiguration = {+ status: "ok",+ settings: {+ display_currency: "USD" as const,+ sources: [+ { connection_id: "ibkr", label: "IBKR", enabled: true, order: 0, include_cash: true },+ { connection_id: "longbridge", label: "Longbridge", enabled: true, order: 1, include_cash: true },+ { connection_id: "binance", label: "Binance", enabled: true, order: 2, include_cash: true },+ ],+ },+ catalog: [+ { id: "ibkr", connection_id: "ibkr", profile_id: "ibkr-live-official-mcp-readonly", connector: "ibkr", label: "IBKR", environment: "live" as const, transport: "remote_mcp" as const, capabilities: ["mcp.read.discovery"], readonly: true, notes: "", selected: true, source_id: "ibkr", supports_reconnect: true, credential_fields: [], credential_status: {}, credentials_configured: false },+ { id: "longbridge", connection_id: "longbridge", profile_id: "longbridge-live-sdk-readonly", connector: "longbridge", label: "Longbridge", environment: "live" as const, transport: "broker_sdk" as const, capabilities: ["account.read", "positions.read"], readonly: true, notes: "", selected: true, source_id: "longbridge", supports_reconnect: false, credential_fields: [], credential_status: {}, credentials_configured: false },+ { id: "binance", connection_id: "binance", profile_id: "binance-live-sdk-readonly", connector: "binance", label: "Binance", environment: "live" as const, transport: "broker_sdk" as const, capabilities: ["account.read", "positions.read"], readonly: true, notes: "", selected: true, source_id: "binance", supports_reconnect: false, credential_fields: [], credential_status: {}, credentials_configured: false },+ ],+};++describe("Portfolio page", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocked.getPortfolio.mockResolvedValue({ status: "ok", snapshot });+ mocked.getPortfolioHistory.mockResolvedValue({ status: "ok", history: [] });+ mocked.getPortfolioSettings.mockResolvedValue(portfolioConfiguration);+ mocked.updatePortfolioSettings.mockResolvedValue(portfolioConfiguration);+ mocked.refreshPortfolio.mockResolvedValue({ status: "ok", snapshot });+ mocked.getPortfolioRefreshStatus.mockResolvedValue({+ status: "ok",+ refresh: {+ running: false,+ current: null,+ sources: {+ ibkr: { status: "ok" },+ longbridge: { status: "ok" },+ binance: { status: "ok" },+ },+ },+ });+ mocked.getConnections.mockResolvedValue({+ status: "ok",+ connections: portfolioConfiguration.catalog,+ profiles: [{+ id: "sample-live-readonly",+ connector: "sample",+ label: "Sample Live · Local Read-Only",+ environment: "live",+ transport: "local_plugin",+ capabilities: ["account.read", "positions.read"],+ readonly: true,+ notes: "",+ local_plugin: true,+ credential_fields: [],+ supports_reconnect: false,+ }],+ plugin_directory: "/tmp/vibe/connectors",+ });+ mocked.createConnection.mockResolvedValue({ status: "ok", connection: {} });+ });++ it("renders the combined portfolio and refreshes all connectors", async () => {+ render(<Portfolio />);+ expect(await screen.findByText("AAPL")).toBeInTheDocument();+ expect(screen.getByText("$1,000.00")).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: /Refresh all|刷新全部账户/ }));+ await waitFor(() => expect(mocked.refreshPortfolio).toHaveBeenCalledTimes(1));+ });++ it("keeps rendering when a legacy refresh response has a malformed source", async () => {+ let finishRefresh!: (value: { status: string; snapshot: typeof snapshot }) => void;+ mocked.refreshPortfolio.mockReturnValue(new Promise((resolve) => { finishRefresh = resolve; }));+ mocked.getPortfolioRefreshStatus.mockResolvedValue({+ status: "ok",+ refresh: {+ running: true,+ current: "ibkr",+ brokers: { ibkr: null },+ },+ });++ render(<Portfolio />);+ await screen.findByText("AAPL");+ fireEvent.click(screen.getByRole("button", { name: /Refresh all|刷新全部账户/ }));++ await waitFor(() => expect(mocked.getPortfolioRefreshStatus).toHaveBeenCalled(), { timeout: 2_000 });+ expect(screen.getByRole("heading", { name: /Portfolio|持仓总览/ })).toBeInTheDocument();++ finishRefresh({ status: "ok", snapshot });+ await waitFor(() => expect(mocked.getPortfolioHistory).toHaveBeenCalledTimes(2));+ });++ it("edits selected read-only accounts without collecting credentials", async () => {+ render(<Portfolio />);+ await screen.findByText("AAPL");++ fireEvent.click(screen.getByRole("button", { name: /Manage accounts|管理账户/ }));+ expect(await screen.findByRole("dialog")).toBeInTheDocument();+ const labels = screen.getAllByRole("textbox", { name: /Account label|账户名称/ });+ fireEvent.change(labels[0], { target: { value: "Main IBKR" } });+ fireEvent.click(screen.getByRole("button", { name: /Save and refresh|保存并刷新/ }));++ await waitFor(() => expect(mocked.updatePortfolioSettings).toHaveBeenCalledWith(+ expect.objectContaining({+ sources: expect.arrayContaining([expect.objectContaining({ label: "Main IBKR" })]),+ }),+ ));+ });++ it("creates a computer-local connection from the connection center", async () => {+ render(<Portfolio />);+ await screen.findByText("AAPL");++ fireEvent.click(screen.getByRole("button", { name: /Manage accounts|管理账户/ }));+ fireEvent.click(await screen.findByRole("button", { name: /Open connection center|打开连接中心/ }));+ fireEvent.change(await screen.findByLabelText(/Read-only profile|只读连接模板/), {+ target: { value: "sample-live-readonly" },+ });+ fireEvent.click(screen.getByRole("button", { name: /Create connection|创建本地连接/ }));++ await waitFor(() => expect(mocked.createConnection).toHaveBeenCalledWith({+ id: "sample-live",+ profile_id: "sample-live-readonly",+ label: "Sample Live · Local Read-Only",+ }));+ });+});diff --git a/frontend/src/router.tsx b/frontend/src/router.tsxindex 4ef661878..ffbc9e0b6 100644--- a/frontend/src/router.tsx+++ b/frontend/src/router.tsx@@ -22,6 +22,9 @@ const Scheduled = lazy(() =>const Reports = lazy(() =>import("@/pages/Reports").then((m) => ({ default: m.Reports })),);+const Portfolio = lazy(() =>+ import("@/pages/Portfolio").then((m) => ({ default: m.Portfolio })),+);const Correlation = lazy(() =>import("@/pages/Correlation").then((m) => ({ default: m.Correlation })),);@@ -58,6 +61,7 @@ export const router = createBrowserRouter([{ path: "/runtime", element: wrap(Runtime) },{ path: "/scheduled", element: wrap(Scheduled) },{ path: "/reports", element: wrap(Reports) },+ { path: "/portfolio", element: wrap(Portfolio) },{ path: "/settings", element: wrap(Settings) },{ path: "/runs/:runId", element: wrap(RunDetail) },{ path: "/compare", element: wrap(Compare) },diff --git a/pyproject.toml b/pyproject.tomlindex 80a4fa66a..d77da1600 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -54,6 +54,7 @@ dependencies = ["ccxt>=4.5.71","aiohttp>=3.14.3","cryptography>=50.0.0",+ "keyring>=25.0.0","fastapi>=0.104.0","uvicorn[standard]>=0.24.0","websockets>=12.0",