"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(portfolio): a failed source is an error, not a smaller portfolio; feed portfolio_risk_xray
Haozhe Wu2a65405478cd
diff --git a/agent/src/api/portfolio_routes.py b/agent/src/api/portfolio_routes.pyindex 7ab24b423..3b2c31f50 100644--- a/agent/src/api/portfolio_routes.py+++ b/agent/src/api/portfolio_routes.py@@ -33,13 +33,26 @@ class PortfolioSettingsRequest(BaseModel):sources: list[PortfolioSourceRequest] = Field(default_factory=list, max_length=50)-def _set_refresh_progress(broker: str, status: str, error: str | None) -> None:+def _set_refresh_progress(source_id: str, status: str, error: str | None) -> None:+ """Record one source's live refresh state for the polling endpoint.++ Args:+ source_id: The configured source being refreshed.+ status: ``pending``, ``refreshing``, ``ok`` or ``error``.+ error: Short failure text, or ``None``.+ """with _REFRESH_LOCK:- _REFRESH_STATE["current"] = broker if status == "refreshing" else None- _REFRESH_STATE["sources"][broker] = {"status": status, "error": error}+ _REFRESH_STATE["current"] = source_id if status == "refreshing" else None+ _REFRESH_STATE["sources"][source_id] = {"status": status, "error": error}def register_portfolio_routes(app: FastAPI) -> None:+ """Register the authenticated, read-only portfolio endpoints.++ Args:+ app: The FastAPI application to mount the routes on.+ """+def service(*, progress: bool = False) -> PortfolioService:return PortfolioService(progress_callback=_set_refresh_progress if progress else Nonediff --git a/agent/src/portfolio/config.py b/agent/src/portfolio/config.pyindex 0daff5ea4..90dba16ca 100644--- a/agent/src/portfolio/config.py+++ b/agent/src/portfolio/config.py@@ -11,7 +11,10 @@ from pathlib import Pathfrom typing import Anyfrom src.config.paths import get_runtime_root-from src.trading.connections import ConnectionStore+from src.trading.connections import (+ ConnectionStore,+ is_portfolio_connection_profile,+)from src.trading.profiles import list_profiles, profile_by_idfrom src.trading.types import TradingProfile@@ -31,10 +34,19 @@ class PortfolioSource:@propertydef id(self) -> str:- """Compatibility alias used by snapshots and refresh progress."""+ """Return the source identity used by snapshots and refresh progress.++ Returns:+ The underlying local connection id.+ """return self.connection_iddef to_dict(self) -> dict[str, Any]:+ """Return a JSON-serializable copy of this source.++ Returns:+ A plain dict with the same fields as the dataclass.+ """return asdict(self)@@ -46,6 +58,11 @@ class PortfolioSettings:sources: tuple[PortfolioSource, ...] = ()def to_dict(self) -> dict[str, Any]:+ """Return a JSON-serializable copy of these settings.++ Returns:+ A dict with ``display_currency`` and a list of source dicts.+ """return {"display_currency": self.display_currency,"sources": [source.to_dict() for source in self.sources],@@ -53,19 +70,24 @@ class PortfolioSettings:def eligible_profiles() -> list[TradingProfile]:- """Return profiles that are structurally safe for portfolio reads."""+ """Return profiles that are structurally safe for portfolio reads.++ Eligibility is decided by+ :func:`src.trading.connections.is_portfolio_connection_profile` so the+ settings gate and the connection registry can never drift apart: a profile+ qualifies only when it is read-only *and* declares both ``account.read``+ and ``positions.read``. A profile that merely advertises remote tool+ discovery (``mcp.read.discovery``) cannot serve either read, so selecting+ it would produce a source that always fails to refresh.++ Returns:+ Eligible profiles sorted by connector, environment and label.+ """return sorted((profilefor 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- )+ if is_portfolio_connection_profile(profile)),key=lambda profile: (profile.connector, profile.environment, profile.label),)@@ -75,7 +97,17 @@ def source_catalog(settings: PortfolioSettings,connection_store: ConnectionStore | None = None,) -> list[dict[str, Any]]:- """Describe configured local connections without exposing secret values."""+ """Describe configured local connections without exposing secret values.++ Args:+ settings: The currently persisted portfolio settings.+ connection_store: Local connection registry; a default store is used+ when omitted.++ Returns:+ One row per registered local connection, each carrying the public+ connection fields plus ``selected`` and ``source_id``.+ """store = connection_store or ConnectionStore()selected = {source.connection_id: source for source in settings.sources}rows = []@@ -96,7 +128,20 @@ def parse_settings(payload: dict[str, Any],connection_store: ConnectionStore | None = None,) -> PortfolioSettings:- """Validate untrusted Web settings against the local connection registry."""+ """Validate untrusted Web settings against the local connection registry.++ Args:+ payload: Raw settings dict from the Web UI, CLI or a settings file.+ connection_store: Local connection registry; a default store is used+ when omitted.++ Returns:+ Validated, order-normalized settings.++ Raises:+ ValueError: If the display currency, the source list, a connection id,+ a label, or a referenced profile's eligibility is invalid.+ """store = connection_store or ConnectionStore()currency = str(payload.get("display_currency") or "USD").strip().upper()if currency not in {"USD", "CNY"}:@@ -169,6 +214,15 @@ class PortfolioSettingsStore:*,connection_store: ConnectionStore | None = None,) -> None:+ """Bind the store to a settings file and its connection registry.++ Args:+ path: Settings file path. Defaults to ``portfolio.json`` under the+ runtime root (``~/.vibe-trading``).+ connection_store: Local connection registry. When omitted, one is+ created next to ``path`` so tests stay isolated from the+ user's real registry.+ """self.path = path or (get_runtime_root() / CONFIG_FILENAME)connection_path = (self.path.with_name("connections.json") if path is not None else None@@ -176,6 +230,15 @@ class PortfolioSettingsStore:self.connection_store = connection_store or ConnectionStore(connection_path)def load(self) -> PortfolioSettings:+ """Read persisted settings, creating an empty file on first use.++ Returns:+ The validated settings currently on disk.++ Raises:+ ValueError: If the file is unreadable, is not a JSON object, or+ fails validation.+ """if self.path.exists():try:payload = json.loads(self.path.read_text(encoding="utf-8"))@@ -193,6 +256,17 @@ class PortfolioSettingsStore:return settingsdef save(self, settings: PortfolioSettings | dict[str, Any]) -> PortfolioSettings:+ """Validate and atomically persist settings with owner-only permissions.++ Args:+ settings: Settings object or raw dict to validate and store.++ Returns:+ The validated settings that were written.++ Raises:+ ValueError: If validation fails; nothing is written in that case.+ """validated = (parse_settings(settings, self.connection_store)if isinstance(settings, dict)diff --git a/agent/src/portfolio/longbridge_worker.py b/agent/src/portfolio/longbridge_worker.pyindex b355a53b8..0c1d49170 100644--- a/agent/src/portfolio/longbridge_worker.py+++ b/agent/src/portfolio/longbridge_worker.py@@ -15,6 +15,12 @@ MARKER = "VIBE_PORTFOLIO_JSON="def main() -> None:+ """Print the read-only Longbridge payload and exit without native teardown.++ The payload is emitted on stdout behind :data:`MARKER` as JSON. On failure+ only the exception type is reported, so a connector error can never leak+ credentials or account identifiers into the parent process's logs.+ """try:from src.trading.connectors.longbridge.sdk import (build_config,diff --git a/agent/src/portfolio/normalization.py b/agent/src/portfolio/normalization.pyindex 978a1f85c..4c90f5241 100644--- a/agent/src/portfolio/normalization.py+++ b/agent/src/portfolio/normalization.py@@ -1,4 +1,19 @@-"""Connector-neutral normalization and valuation helpers."""+"""Normalization and valuation helpers for connector payloads.++The generic path is the default: any connector whose account and position rows+use the common field names is handled without a line of code here. Two+connectors ship payload shapes the generic reader cannot express and therefore+have dedicated branches:++* ``ibkr`` — the account is a tag/value ``summary`` list, and positions carry+ ``position``/``avg_cost`` with an IB ``sec_type``.+* ``longbridge`` — the account is a per-currency ``balances`` list, and+ positions are market-suffixed symbols with a ``symbol_name``.++Inside the generic path, ``binance`` and ``okx`` additionally classify holdings+as crypto/stablecoin and quote against USDT. Everything else falls through+unchanged, so adding a connector needs no edit to this module.+"""from __future__ import annotations@@ -37,7 +52,17 @@ def _now() -> str:def normalize_position(broker: str, row: dict[str, Any]) -> dict[str, Any]:- """Convert a connector position row to the portfolio wire shape."""+ """Convert a connector position row to the portfolio wire shape.++ Args:+ broker: The connector key, used only to select a dedicated payload+ shape; unknown connectors take the generic path.+ row: One raw position row as the connector reported it.++ Returns:+ A position dict in the portfolio wire shape, unpriced fields left as+ ``None`` rather than guessed.+ """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()@@ -143,7 +168,18 @@ def normalize_position(broker: str, row: dict[str, Any]) -> dict[str, Any]: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."""+ """Calculate USD/CNY market value and unrealized P/L.++ Args:+ row: A normalized position row; it is updated in place.+ usd_hkd: USD/HKD rate used to convert HKD-priced rows.+ usd_cny: USD/CNY rate used to convert CNY-priced rows.++ Returns:+ The same row, with ``priced``, ``market_value_usd``,+ ``market_value_cny`` and ``unrealized_pnl_usd`` filled in and the+ connector-only fields dropped.+ """price = _decimal(row.get("market_price"))quantity = _decimal(row.get("quantity"))currency = str(row.get("price_currency") or row.get("currency") or "USD").upper()@@ -195,7 +231,19 @@ def account_total_usd(usd_cny: Decimal,fallback: Decimal = Decimal("0"),) -> Decimal:- """Extract a connector-reported net liquidation value."""+ """Extract a connector-reported net liquidation value.++ Args:+ broker: The connector key selecting the account payload shape.+ account: The raw account payload.+ usd_hkd: USD/HKD rate for HKD-denominated balances.+ usd_cny: USD/CNY rate for CNY-denominated balances.+ fallback: Value returned when the connector reports no total, so a+ missing figure never silently becomes zero.++ Returns:+ The account's total value in USD.+ """if broker == "longbridge":total = Decimal("0")for row in account.get("balances", []):@@ -243,7 +291,18 @@ def account_total_usd(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."""+ """Return broker-reported cash without guessing from missing quotes.++ Args:+ broker: The connector key selecting the account payload shape.+ account: The raw account payload.+ usd_hkd: USD/HKD rate for HKD-denominated balances.+ usd_cny: USD/CNY rate for CNY-denominated balances.++ Returns:+ Cash in USD, never negative and never inferred from an unpriced+ position.+ """rows = account.get("balances", []) if broker == "longbridge" else []if rows:return max(@@ -304,7 +363,15 @@ def account_cash_usd(def auth_metadata(profile: TradingProfile) -> dict[str, Any]:- """Return public profile metadata without inferring broker-side key permissions."""+ """Return public profile metadata without inferring broker-side key permissions.++ Args:+ profile: The connector profile backing a portfolio source.++ Returns:+ The authentication method, renewal model, read-only flag and the+ profile's own notes.+ """method, renewal = _TRANSPORT_AUTH.get(profile.transport,(profile.transport.replace("_", " ").title(), "provider_managed"),diff --git a/agent/src/portfolio/service.py b/agent/src/portfolio/service.pyindex 0ac088bb6..bbbbf386b 100644--- a/agent/src/portfolio/service.py+++ b/agent/src/portfolio/service.py@@ -28,6 +28,16 @@ from src.portfolio.normalization import ()from src.portfolio.store import PortfolioStorefrom src.trading.profiles import profile_by_id+from src.trading.types import TradingProfile++# ``portfolio_risk_xray`` caps a basket at 50 symbols, and its loaders route on+# the market suffix: ``AAPL`` alone is read as an A-share code, ``AAPL.US`` is+# not (see ``src.market_data._SOURCE_PATTERNS``).+_RISK_XRAY_MAX_SYMBOLS = 50+_LOADER_MARKET_SUFFIXES = frozenset(+ {"US", "HK", "SZ", "SH", "BJ", "KS", "KQ", "NS", "BO", "TO", "V"}+)+_NON_EQUITY_ASSET_TYPES = frozenset({"crypto", "stablecoin", "cash"})def _decimal(value: Any, default: Decimal = Decimal("0")) -> Decimal:@@ -61,6 +71,12 @@ def _quote_price(payload: dict[str, Any]) -> Decimal | None:class PortfolioService:+ """Aggregate every enabled read-only source into one immutable snapshot.++ The service reads; it never places or cancels an order. A source that+ cannot be read contributes nothing at all — see :meth:`refresh`.+ """+def __init__(self,store: PortfolioStore | None = None,@@ -73,8 +89,26 @@ class PortfolioService:fx_fetcher: Callable[[], tuple[Decimal, Decimal, str]] | None = None,progress_callback: Callable[[str, str, str | None], None] | None = None,) -> None:+ """Wire the service to its stores and connector read functions.++ Args:+ store: Snapshot/FX database. Defaults to the runtime-root store.+ settings_store: Editable portfolio settings. Defaults to the+ runtime-root store.+ get_account: Account reader. Defaults to+ ``src.trading.service.get_account``.+ get_positions: Positions reader. Defaults to+ ``src.trading.service.get_positions``.+ get_quote: Single-symbol quote reader. Defaults to+ ``src.trading.service.get_quote``.+ get_longbridge_quotes: Optional batch quote reader used only for+ Longbridge positions the connector reports without a price.+ fx_fetcher: Returns ``(usd_cny, usd_hkd, fetched_at)``. Defaults to+ the built-in HTTPS fetch.+ progress_callback: Called as ``(source_id, status, error)`` while a+ refresh walks its sources.+ """self._use_longbridge_worker = get_account is None and get_positions is None- self._noninteractive_ibkr = get_account is None and get_positions is Noneif get_account is None or get_positions is None or get_quote is None:from src.trading import service as trading@@ -91,29 +125,74 @@ class PortfolioService:self.settings_store = settings_store or PortfolioSettingsStore()def settings(self) -> dict[str, Any]:- """Return credential-free editable settings."""+ """Return credential-free editable settings.++ Returns:+ The persisted display currency and source selection.+ """return self.settings_store.load().to_dict()def save_settings(self, payload: dict[str, Any]) -> dict[str, Any]:- """Validate and persist editable settings."""+ """Validate and persist editable settings.++ Args:+ payload: Untrusted settings from the Web UI or API.++ Returns:+ The validated settings that were written.++ Raises:+ ValueError: If the payload fails validation; nothing is written.+ """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 local read-only connections eligible for this portfolio.++ Returns:+ One catalog row per registered connection, flagged as selected or+ not, and free of secret values.+ """return source_catalog(self.settings_store.load(),self.settings_store.connection_store,)def _connection_profile(self, source: PortfolioSource):+ """Resolve one configured source to its connection and profile.++ Args:+ source: The configured portfolio source.++ Returns:+ A ``(connection, profile)`` pair.+ """connection = self.settings_store.connection_store.get(source.connection_id)return connection, profile_by_id(connection.profile_id)def refresh(self) -> dict[str, Any]:+ """Read every enabled source once and persist an immutable snapshot.++ A source that fails contributes nothing: no positions, no combined+ holdings, and no value in the totals. Its account row carries the+ error and the timestamp of its last healthy read, and the snapshot is+ marked incomplete. A partial read is an error to be surfaced, never a+ quietly shorter portfolio.++ Returns:+ The snapshot envelope that was stored.++ Raises:+ RuntimeError: If no source is enabled, or if FX rates can neither+ be fetched nor loaded from cache.+ """settings = self.settings_store.load()sources = [source for source in settings.sources if source.enabled]if not sources:- raise RuntimeError("请先在持仓页添加并启用至少一个只读账户")+ raise RuntimeError(+ "Add and enable at least one read-only account on the Portfolio "+ "page before refreshing"+ )usd_cny, usd_hkd, fx_at, fx_stale = self._rates()refreshed_at = _now()results: dict[str, dict[str, Any]] = {}@@ -129,16 +208,10 @@ class PortfolioService: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])@@ -147,85 +220,12 @@ class PortfolioService:accounts: list[dict[str, Any]] = []for source in sources:result = results[source.id]- broker = result["broker"]connection, profile = self._connection_profile(source)+ broker = profile.connectorif 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),+ accounts.append(+ self._failed_account(source, connection.profile_id, profile, result))- 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)continuebroker_positions = [value_position(row, usd_hkd=usd_hkd, usd_cny=usd_cny)@@ -262,15 +262,12 @@ class PortfolioService:"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,@@ -282,9 +279,9 @@ class PortfolioService: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- )+ # Every enabled source produces exactly one account row, so a snapshot+ # is complete only when none of them failed.+ complete = all(row["status"] == "ok" for row in accounts)priced_usd = sum((_decimal(row.get("priced_value_usd")) for row in accounts), Decimal("0"))@@ -328,7 +325,52 @@ class PortfolioService:self.store.save_snapshot(payload)return payload+ def _failed_account(+ self,+ source: PortfolioSource,+ profile_id: str,+ profile: TradingProfile,+ result: dict[str, Any],+ ) -> dict[str, Any]:+ """Build the account row for a source that could not be read.++ The row is deliberately valueless: totals are ``None`` and no position+ is contributed, so a failed source can never be mistaken for an account+ that is genuinely worth less. ``last_success_at`` still reports when the+ source was last healthy, when such a snapshot exists.++ Args:+ source: The configured source that failed.+ profile_id: The connection's connector profile id.+ profile: The resolved connector profile.+ result: The captured failure carrying ``error`` and ``error_code``.++ Returns:+ An account row with status ``error`` and no monetary value.+ """+ cached = self.store.latest_successful_source(source.id)+ return {+ "source_id": source.id,+ "profile_id": profile_id,+ "label": source.label,+ "broker": profile.connector,+ "status": "error",+ "error": result.get("error"),+ "error_code": result.get("error_code"),+ "last_success_at": cached["created_at"] if cached is not None else None,+ "total_usd": None,+ "total_cny": None,+ "position_count": 0,+ "auth": auth_metadata(profile),+ }+def latest(self) -> dict[str, Any] | None:+ """Return the newest snapshot, but only if it covers today's selection.++ Returns:+ The snapshot envelope, or ``None`` when no snapshot exists or the+ stored one was taken over a different set of enabled sources.+ """snapshot = self.store.latest()if snapshot is None:return None@@ -342,7 +384,21 @@ class PortfolioService:return snapshot if enabled and observed == enabled else Nonedef reconnect_source(self, source_id: str) -> dict[str, Any]:- """Run a supported source's interactive OAuth flow on explicit request."""+ """Run a source's interactive OAuth flow on explicit user request.++ This is the only interactive path in the portfolio feature; an ordinary+ refresh always reads non-interactively so it can never open a browser.++ Args:+ source_id: The configured source to re-authorize.++ Returns:+ The authorization result and the read tools the server exposes.++ Raises:+ RuntimeError: If the source is unknown, does not use OAuth, or its+ MCP server is not configured.+ """from src.config.loader import load_agent_configfrom src.tools.mcp import MCPServerAdapter@@ -355,13 +411,13 @@ class PortfolioService:None,)if source is None:- raise RuntimeError("未找到该持仓账户")+ raise RuntimeError(f"unknown portfolio source: {source_id}")_, profile = self._connection_profile(source)if profile.transport != "remote_mcp":- raise RuntimeError("该账户不使用 OAuth,无需重新连接")+ raise RuntimeError("this source does not use OAuth; no reconnect is needed")server = (load_agent_config().mcp_servers or {}).get(profile.connector)if server is None:- raise RuntimeError(f"{profile.connector.upper()} MCP 连接尚未配置")+ raise RuntimeError(f"the {profile.connector} MCP connection is not configured")tools = MCPServerAdapter(profile.connector,server,@@ -376,9 +432,26 @@ class PortfolioService:}def history(self, limit: int = 180) -> list[dict[str, Any]]:+ """Return the value series built only from complete snapshots.++ Incomplete snapshots are excluded because a source that failed+ contributes nothing to the total; charting them beside complete ones+ would draw a drop in portfolio value that never happened.++ Args:+ limit: Maximum number of snapshots to return, oldest first.++ Returns:+ One row per complete snapshot with its id, timestamp and totals.+ """return self.store.history(limit, complete_only=True)def export_csv(self) -> str:+ """Render the latest snapshot's positions as CSV.++ Returns:+ The CSV text, or an empty string when no usable snapshot exists.+ """snapshot = self.latest()if snapshot is None:return ""@@ -408,7 +481,16 @@ class PortfolioService:return output.getvalue()def analysis_context(self) -> dict[str, Any] | None:- """Return a credential/account-id-free snapshot suitable for an LLM."""+ """Return a credential/account-id-free snapshot suitable for an LLM.++ The context also carries ``risk_xray_args`` — the ``symbols`` and+ ``weights`` arguments for the existing ``portfolio_risk_xray`` tool.+ The portfolio supplies that tool's arguments; it does not reimplement+ or alter the analysis.++ Returns:+ The sanitized context, or ``None`` when no usable snapshot exists.+ """snapshot = self.latest()if snapshot is None:return None@@ -441,12 +523,95 @@ class PortfolioService:for index, row in enumerate(snapshot["accounts"])],"holdings": holdings,+ "risk_xray_args": self._risk_xray_args(snapshot.get("positions", [])),"warnings": snapshot["warnings"],"privacy": "No account numbers, credentials, order IDs, names, or local paths included.",}+ @staticmethod+ def _risk_xray_symbol(position: dict[str, Any]) -> str | None:+ """Map one held position onto a symbol the market-data loaders accept.++ The loader chain routes on the market suffix, so the connector-reported+ ticker is used as-is when it already carries one (``700.HK``,+ ``600519.SH``) and is qualified from the position's currency/market+ otherwise (IBKR reports a bare ``AAPL``, which would be read as an+ A-share code). A symbol whose market cannot be established is not+ guessed at.++ Args:+ position: A valued position row from a stored snapshot.++ Returns:+ A loader-routable symbol, or ``None`` when the market is unknown.+ """+ symbol = str(position.get("symbol") or "").strip().upper()+ if not symbol:+ return None+ head, _, suffix = symbol.rpartition(".")+ if head and suffix in _LOADER_MARKET_SUFFIXES:+ return symbol+ currency = str(+ position.get("price_currency") or position.get("currency") or ""+ ).upper()+ market = str(position.get("market") or "").upper()+ if currency == "HKD" or market == "HK":+ return f"{symbol}.HK" if symbol.isdigit() else None+ if currency == "USD" and symbol.isalpha():+ return f"{symbol}.US"+ return None++ @classmethod+ def _risk_xray_args(cls, positions: list[dict[str, Any]]) -> dict[str, Any]:+ """Build the ``portfolio_risk_xray`` arguments for the held equities.++ Crypto, stablecoin and cash rows are dropped because the risk x-ray+ prices a long-only equity basket through the daily-bar loaders; so are+ unpriced rows and non-positive values, which carry no weight. The+ remaining positions are merged per symbol across sources and their+ weights renormalized to sum to 1.++ Args:+ positions: The valued positions of a stored snapshot.++ Returns:+ ``{"symbols": [...], "weights": {symbol: weight}}``, empty when the+ snapshot holds no priced equity position.+ """+ values: dict[str, Decimal] = {}+ for position in positions:+ if str(position.get("asset_type") or "").lower() in _NON_EQUITY_ASSET_TYPES:+ continue+ if not position.get("priced"):+ continue+ value = _decimal(position.get("market_value_usd"))+ if value <= 0:+ continue+ symbol = cls._risk_xray_symbol(position)+ if symbol is None:+ continue+ values[symbol] = values.get(symbol, Decimal("0")) + value+ ranked = sorted(values.items(), key=lambda item: (-item[1], item[0]))+ ranked = ranked[:_RISK_XRAY_MAX_SYMBOLS]+ total = sum((value for _, value in ranked), Decimal("0"))+ if total <= 0:+ return {"symbols": [], "weights": {}}+ return {+ "symbols": [symbol for symbol, _ in ranked],+ "weights": {symbol: _number(value / total) for symbol, value in ranked},+ }+@staticmethoddef _combine_holdings(positions: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Merge the same instrument held at several sources into one row.++ Args:+ positions: Valued positions from every successfully read source.++ Returns:+ Holdings sorted by USD value, each flagged when it is held at more+ than one broker.+ """grouped: dict[str, dict[str, Any]] = {}for row in positions:symbol = str(row.get("symbol") or "").upper()@@ -506,6 +671,19 @@ class PortfolioService:)def _collect_source(self, source: PortfolioSource) -> dict[str, Any]:+ """Read one source's account and positions, pricing what the connector omits.++ Args:+ source: The enabled source to read.++ Returns:+ ``{"source_id", "profile_id", "label", "broker", "status",+ "account", "positions"}`` for a successful read.++ Raises:+ RuntimeError: If the profile is not read-only, or either connector+ read returns a non-success status.+ """connection, profile = self._connection_profile(source)if not profile.readonly:raise RuntimeError(@@ -524,12 +702,12 @@ class PortfolioService: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: dict[str, Any] = {}+ if profile.transport == "remote_mcp":+ # A dashboard refresh must never open a browser. reconnect_source()+ # is the one explicit interactive path.+ read_options["interactive_oauth"] = False+ elif profile.transport == "local_plugin":read_options["connection_id"] = connection.idaccount = self._get_account(profile_id, **read_options)positions_payload = self._get_positions(profile_id, **read_options)@@ -635,6 +813,15 @@ class PortfolioService:@staticmethoddef _read_longbridge_isolated() -> dict[str, Any]:+ """Read Longbridge in a throwaway subprocess and parse its payload.++ Returns:+ The worker's account/positions/quotes payload.++ Raises:+ RuntimeError: If the worker emitted no payload, reported an error,+ or returned an incomplete payload.+ """marker = "VIBE_PORTFOLIO_JSON="process = subprocess.run([sys.executable, "-m", "src.portfolio.longbridge_worker"],@@ -661,6 +848,15 @@ class PortfolioService:return payloaddef _rates(self) -> tuple[Decimal, Decimal, str, bool]:+ """Return the USD/CNY and USD/HKD rates used to value this snapshot.++ Returns:+ ``(usd_cny, usd_hkd, fetched_at, stale)`` where ``stale`` marks a+ fall back to the cached rates.++ Raises:+ RuntimeError: If the fetch fails and no cached pair exists.+ """try:usd_cny, usd_hkd, fetched_at = self._fx_fetcher()self.store.save_fx("USD", "CNY", str(usd_cny), fetched_at)@@ -677,6 +873,11 @@ class PortfolioService:@staticmethoddef _fetch_fx() -> tuple[Decimal, Decimal, str]:+ """Fetch USD/CNY and USD/HKD from the public reference-rate endpoint.++ Returns:+ ``(usd_cny, usd_hkd, fetched_at)``.+ """url = "https://api.frankfurter.app/latest?from=USD&to=CNY,HKD"request = urllib.request.Request(url, headers={"User-Agent": "Vibe-Trading/portfolio"}@@ -695,32 +896,44 @@ class PortfolioService:def _warnings(accounts: list[dict[str, Any]], positions: list[dict[str, Any]], fx_stale: bool) -> list[str]:+ """Describe every reason this snapshot must be read with caution.++ Args:+ accounts: The per-source account rows of this snapshot.+ positions: The valued positions that were actually aggregated.+ fx_stale: Whether cached FX rates were used instead of fresh ones.++ Returns:+ English warning strings, safe to render verbatim in any UI.+ """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)+ "Exchange-rate service unavailable; valued with the last "+ "successfully fetched USD/CNY and USD/HKD rates.")failed = [str(row.get("label") or row["broker"])for row in accounts- if row["status"] == "error"+ if row["status"] != "ok"]if failed:- warnings.append("以下账户尚无可用缓存,请检查连接:" + "、".join(failed))+ warnings.append(+ "These sources failed to refresh and their value is excluded "+ "from the totals, positions and combined holdings, so the "+ "portfolio shown here is incomplete: " + ", ".join(failed) + "."+ )unpriced = [f"{row['broker']}:{row['symbol']}"for row in positionsif not row.get("priced")]if unpriced:- warnings.append("暂未取得价格的持仓:" + "、".join(unpriced[:20]))+ warnings.append(+ "No price available for these positions: " + ", ".join(unpriced[:20])+ )if any(row.get("broker") == "binance" for row in positions):- warnings.append("Binance 现货按 USDT≈USD 进行估值。")+ warnings.append(+ "Binance spot balances are valued with USDT treated as 1 USD."+ )return warningsdiff --git a/agent/src/portfolio/store.py b/agent/src/portfolio/store.pyindex 6db4226b6..4430696bd 100644--- a/agent/src/portfolio/store.py+++ b/agent/src/portfolio/store.py@@ -11,7 +11,16 @@ from src.config.paths import get_runtime_rootclass PortfolioStore:+ """SQLite-backed history of immutable portfolio snapshots plus an FX cache."""+def __init__(self, path: Path | None = None) -> None:+ """Open (and create when missing) the snapshot database.++ Args:+ path: Database file path. Defaults to+ ``portfolio/portfolio.sqlite3`` under the runtime root+ (``~/.vibe-trading``).+ """self.path = path or (get_runtime_root() / "portfolio" / "portfolio.sqlite3")self.path.parent.mkdir(parents=True, exist_ok=True)self._init_schema()@@ -44,6 +53,12 @@ class PortfolioStore:""")def save_snapshot(self, payload: dict[str, Any]) -> None:+ """Append one immutable snapshot.++ Args:+ payload: The full snapshot envelope produced by+ :meth:`src.portfolio.service.PortfolioService.refresh`.+ """totals = payload["totals"]with self._connect() as db:db.execute(@@ -63,6 +78,15 @@ class PortfolioStore:)def latest(self, *, complete_only: bool = False) -> dict[str, Any] | None:+ """Return the most recent stored snapshot.++ Args:+ complete_only: Restrict the lookup to snapshots in which every+ enabled source refreshed successfully.++ Returns:+ The snapshot envelope, or ``None`` when nothing matches.+ """where = "WHERE complete = 1" if complete_only else ""with self._connect() as db:row = db.execute(@@ -73,6 +97,18 @@ class PortfolioStore:def history(self, limit: int = 180, *, complete_only: bool = True) -> list[dict[str, Any]]:+ """Return snapshot totals over time, oldest first.++ Args:+ limit: Maximum number of snapshots to read, clamped to 1..2000.+ complete_only: Restrict the series to snapshots in which every+ enabled source refreshed successfully. Charting a mix of+ complete and partial snapshots would draw a value drop that+ never happened.++ Returns:+ One row per snapshot with id, timestamp, completeness and totals.+ """where = "WHERE complete = 1" if complete_only else ""with self._connect() as db:rows = db.execute(@@ -87,11 +123,20 @@ class PortfolioStore: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.+ """Return the newest successfully read payload for one configured source.++ Only accounts with status ``ok`` qualify, so a run of failed refreshes+ keeps pointing back at the original successful observation and its real+ ``last_success_at`` timestamp. The payload is used to report *when* a+ failed source was last healthy; it is never added back into a snapshot's+ totals.++ Args:+ source_id: The configured source id (the local connection id).- 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.+ Returns:+ A dict with ``created_at``, ``account`` and ``positions`` for the+ newest successful observation, or ``None`` if there is none."""with self._connect() as db:rows = db.execute("""@@ -123,11 +168,15 @@ class PortfolioStore:}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:+ """Cache one FX rate so a later outage still has a usable number.++ Args:+ base: Base currency code, e.g. ``USD``.+ quote: Quote currency code, e.g. ``CNY``.+ rate: The rate, stored as text to avoid binary float drift.+ fetched_at: ISO-8601 timestamp of the successful fetch.+ """with self._connect() as db:db.execute("""@@ -140,6 +189,15 @@ class PortfolioStore:)def load_fx(self, base: str, quote: str) -> tuple[str, str] | None:+ """Read the last cached rate for one currency pair.++ Args:+ base: Base currency code, e.g. ``USD``.+ quote: Quote currency code, e.g. ``CNY``.++ Returns:+ ``(rate, fetched_at)`` or ``None`` when the pair was never cached.+ """with self._connect() as db:row = db.execute("SELECT rate, fetched_at FROM portfolio_fx_cache WHERE base = ? AND quote = ?",diff --git a/agent/src/tools/portfolio_tool.py b/agent/src/tools/portfolio_tool.pyindex 61e98050c..09c1a74d4 100644--- a/agent/src/tools/portfolio_tool.py+++ b/agent/src/tools/portfolio_tool.py@@ -10,19 +10,32 @@ from src.portfolio.service import PortfolioServiceclass PortfolioSummaryTool(BaseTool):+ """Expose the latest local portfolio snapshot as sanitized analysis context."""+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."+ "Read the latest sanitized snapshot of the user's locally configured "+ "read-only brokerage accounts. Returns deterministic totals, account "+ "allocation, combined holdings, weights, unrealized P/L, data-quality "+ "warnings, and risk_xray_args (symbols + weights) that can be passed "+ "straight to the portfolio_risk_xray tool. A source that failed to "+ "refresh is reported as an error and excluded from the totals, so a "+ "snapshot with complete=false is missing accounts. It never returns "+ "credentials, account numbers, order IDs, personal names, or local "+ "paths. Use the Web Portfolio refresh button before requesting current "+ "data.")parameters = {"type": "object", "properties": {}, "required": []}repeatable = Trueis_readonly = Truedef execute(self, **_: Any) -> str:+ """Return the sanitized portfolio context as a JSON envelope.++ Returns:+ A JSON string with ``status`` ``ok`` and the context, or ``empty``+ with a hint when no usable snapshot exists.+ """context = PortfolioService().analysis_context()if context is None:return json.dumps(diff --git a/agent/tests/test_portfolio_config.py b/agent/tests/test_portfolio_config.pyindex cd60c9991..8c0fe240d 100644--- a/agent/tests/test_portfolio_config.py+++ b/agent/tests/test_portfolio_config.py@@ -4,8 +4,14 @@ import jsonimport pytest-from src.portfolio.config import PortfolioSettingsStore, parse_settings, source_catalog+from src.portfolio.config import (+ PortfolioSettingsStore,+ eligible_profiles,+ parse_settings,+ source_catalog,+)from src.trading.connections import ConnectionStore+from src.trading.profiles import profile_by_iddef test_portfolio_settings_round_trip_without_credentials(tmp_path):@@ -59,3 +65,36 @@ def test_portfolio_settings_reject_trade_profiles():def test_new_install_starts_with_no_selected_sources(tmp_path):store = PortfolioSettingsStore(tmp_path / "portfolio.json")assert store.load().sources == ()+++def test_a_discovery_only_profile_cannot_back_a_portfolio_source():+ """Tool discovery is not a holdings read, so such a profile is not eligible.++ ``ibkr-live-official-mcp-readonly`` is read-only, but it declares only+ ``mcp.read.discovery``: it can list the remote server's tools and nothing+ else. Accepting it would create a source that fails on every refresh.+ """+ profile = profile_by_id("ibkr-live-official-mcp-readonly")+ assert profile.readonly is True+ assert profile.capabilities == ("mcp.read.discovery",)+ assert profile not in eligible_profiles()+ assert all(+ {"account.read", "positions.read"}.issubset(item.capabilities)+ and item.readonly+ for item in eligible_profiles()+ )++ with pytest.raises(ValueError, match="not eligible for read-only"):+ parse_settings(+ {+ "display_currency": "USD",+ "sources": [+ {+ "id": "discovery-only",+ "profile_id": "ibkr-live-official-mcp-readonly",+ "label": "Discovery only",+ }+ ],+ },+ ConnectionStore(),+ )diff --git a/agent/tests/test_portfolio_service.py b/agent/tests/test_portfolio_service.pyindex cf9626742..7e21cb733 100644--- a/agent/tests/test_portfolio_service.py+++ b/agent/tests/test_portfolio_service.py@@ -2,6 +2,9 @@ from __future__ import annotationsfrom decimal import Decimal+import pytest++from src.portfolio import service as portfolio_servicefrom src.portfolio.config import PortfolioSettingsStorefrom src.portfolio.normalization import auth_metadatafrom src.portfolio.service import PortfolioService@@ -11,7 +14,7 @@ from src.trading.types import TradingProfiledef _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("ibkr", "ibkr-live-local-readonly", "IBKR")store.connection_store.ensure("longbridge", "longbridge-live-sdk-readonly", "Longbridge")@@ -31,7 +34,7 @@ def _settings_store(tmp_path):def test_refresh_aggregates_three_readonly_connectors(tmp_path):accounts = {- "ibkr-live-official-mcp-readonly": {+ "ibkr-live-local-readonly": {"summary": [{"tag": "NetLiquidation", "value": "1000", "currency": "USD"}]},"longbridge-live-sdk-readonly": {@@ -40,7 +43,7 @@ def test_refresh_aggregates_three_readonly_connectors(tmp_path):"binance-live-sdk-readonly": {"balances": []},}positions = {- "ibkr-live-official-mcp-readonly": {+ "ibkr-live-local-readonly": {"positions": [{"symbol": "AAPL",@@ -133,7 +136,8 @@ def test_partial_refresh_is_saved_and_marked_incomplete(tmp_path):assert any("longbridge" in warning.lower() for warning in snapshot["warnings"])-def test_failed_broker_uses_last_successful_data_without_polluting_history(tmp_path):+def test_failed_source_is_excluded_from_totals_and_reports_its_last_success(tmp_path):+ """A source that fails contributes nothing; only its last-healthy time survives."""offline = Falsedef get_account(profile_id):@@ -180,18 +184,223 @@ def test_failed_broker_uses_last_successful_data_without_polluting_history(tmp_pibkr = next(item for item in partial["accounts"] if item["broker"] == "ibkr")assert complete["complete"] is True+ assert complete["totals"]["usd"] == 1000.0++ # The failed source is an error, not a quietly shorter portfolio: its cached+ # value is never added back into any aggregate.assert partial["complete"] is False- assert partial["totals"]["usd"] == complete["totals"]["usd"]- assert ibkr["status"] == "stale"+ assert partial["totals"]["usd"] == 0.0+ assert partial["totals"]["cny"] == 0.0+ assert ibkr["status"] == "error"+ assert ibkr["error_code"] == "ConnectionError"+ assert ibkr["total_usd"] is None+ assert ibkr["total_cny"] is None+ assert ibkr["position_count"] == 0+ assert [item["broker"] for item in partial["positions"] if item["broker"] == "ibkr"] == []+ assert [+ item for item in partial["combined_holdings"] if "ibkr" in item["brokers"]+ ] == []+ assert partial["valuation"]["priced_usd"] == 0.0++ # ...but the dashboard can still say when that source was last healthy.assert ibkr["last_success_at"] == complete["created_at"]- assert (- next(item for item in partial["positions"] if item["broker"] == "ibkr")["stale"]- is True- )++ # No account carries the removed cached/stale state.+ assert {item["status"] for item in partial["accounts"]} == {"ok", "error"}+ assert all("data_state" not in item for item in partial["accounts"])+ assert all("stale" not in item for item in partial["positions"])++ excluded = [+ warning for warning in partial["warnings"] if "excluded" in warning.lower()+ ]+ assert len(excluded) == 1+ assert "IBKR" in excluded[0]+assert [item["id"] for item in service.history()] == [complete["snapshot_id"]]assert len(service.store.history(complete_only=False)) == 2+def test_a_source_that_never_succeeded_reports_no_last_success_time(tmp_path):+ """last_success_at is None rather than invented when no healthy snapshot exists."""++ def get_account(profile_id):+ if profile_id.startswith("ibkr"):+ 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()+ ibkr = next(item for item in snapshot["accounts"] if item["broker"] == "ibkr")+ assert ibkr["status"] == "error"+ assert ibkr["last_success_at"] is None+++def test_remote_mcp_sources_are_read_without_an_interactive_oauth_prompt(+ tmp_path, monkeypatch+):+ """A dashboard refresh must never be able to pop a browser, for any connector."""+ settings = PortfolioSettingsStore(tmp_path / "portfolio.json")+ settings.connection_store.ensure("remote", "alpaca-live-sdk-readonly", "Remote")+ settings.save(+ {+ "display_currency": "USD",+ "sources": [{"connection_id": "remote", "label": "Remote", "order": 0}],+ }+ )+ # A read-only remote_mcp profile whose connector is deliberately not IBKR:+ # the non-interactive read is a property of the transport, not of a broker.+ remote = TradingProfile(+ id="alpaca-live-sdk-readonly",+ connector="examplebroker",+ label="Example remote MCP",+ environment="live",+ transport="remote_mcp",+ capabilities=("account.read", "positions.read"),+ readonly=True,+ )+ monkeypatch.setattr(portfolio_service, "profile_by_id", lambda _: remote)++ seen: list[tuple[str, dict]] = []++ def get_account(profile_id, **options):+ seen.append(("account", options))+ return {"account": {"portfolio_value": "500", "currency": "USD"}}++ def get_positions(profile_id, **options):+ seen.append(("positions", options))+ return {"positions": [{"symbol": "AAPL", "quantity": "2", "market_price": "250"}]}++ service = PortfolioService(+ PortfolioStore(tmp_path / "portfolio.sqlite3"),+ settings_store=settings,+ get_account=get_account,+ get_positions=get_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 True+ assert [call for call, _ in seen] == ["account", "positions"]+ assert [options for _, options in seen] == [+ {"interactive_oauth": False},+ {"interactive_oauth": False},+ ]+++def test_analysis_context_supplies_risk_xray_arguments(tmp_path):+ """The portfolio feeds the existing risk x-ray; it does not reimplement it."""+ accounts = {+ "ibkr-live-local-readonly": {+ "summary": [{"tag": "NetLiquidation", "value": "300", "currency": "USD"}]+ },+ "longbridge-live-sdk-readonly": {+ "balances": [{"net_assets": "3900", "currency": "HKD"}]+ },+ "binance-live-sdk-readonly": {"balances": []},+ }+ positions = {+ "ibkr-live-local-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},+ ]+ },+ }++ service = PortfolioService(+ PortfolioStore(tmp_path / "portfolio.sqlite3"),+ settings_store=_settings_store(tmp_path),+ get_account=lambda profile_id: accounts[profile_id],+ get_positions=lambda profile_id: positions[profile_id],+ get_quote=lambda symbol, profile_id, **kwargs: {+ "quote": {"last": {"AAPL": 150, "700.HK": 390, "BTC/USDT": 60000}[symbol]}+ },+ fx_fetcher=lambda: (+ Decimal("7.2"),+ Decimal("7.8"),+ "2026-08-09T00:00:00+00:00",+ ),+ )+ service.refresh()+ args = service.analysis_context()["risk_xray_args"]++ # Symbols carry the market suffix the risk x-ray's loaders route on: a bare+ # "AAPL" is read as an A-share code by src.market_data.detect_source.+ assert args["symbols"] == ["700.HK", "AAPL.US"]+ assert set(args["weights"]) == set(args["symbols"])+ assert args["weights"]["700.HK"] == pytest.approx(0.625)+ assert args["weights"]["AAPL.US"] == pytest.approx(0.375)+ assert sum(args["weights"].values()) == pytest.approx(1.0)+ # Crypto and stablecoins are not priced by the daily-bar loaders.+ assert not any("BTC" in symbol for symbol in args["symbols"])+ assert not any("USDT" in symbol for symbol in args["symbols"])+++def test_risk_xray_arguments_are_empty_when_nothing_priced_can_be_routed(tmp_path):+ """An unroutable or unpriced book yields no arguments instead of a guess."""+ assert PortfolioService._risk_xray_args(+ [+ {"symbol": "AAPL", "asset_type": "stock", "priced": False, "market_value_usd": 0},+ {+ "symbol": "BTC",+ "asset_type": "crypto",+ "priced": True,+ "market_value_usd": 6000,+ "currency": "USD",+ },+ {+ "symbol": "0700",+ "asset_type": "stock",+ "priced": True,+ "market_value_usd": 500,+ "currency": "JPY",+ "market": "TSE",+ },+ ]+ ) == {"symbols": [], "weights": {}}++def test_generic_readonly_profile_uses_common_account_and_position_fields(tmp_path):settings = PortfolioSettingsStore(tmp_path / "portfolio.json")settings.connection_store.ensure(