"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix: tighten first-batch quote evidence and connection setup
Haozhe Wu011a555ede2a
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex ef944a0a5..a5dde6a78 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -408,3 +408,25 @@ retains the existing one-retry behavior. When moving a helper, update teststo patch the module where it executes; re-exported names preserve imports,not monkeypatch propagation. Verify the existing loop, stream, cancellation,compaction and grounding suites after an extraction.++## Connection-specific gateways and quote times++For a local IBKR or Futu connection, the connection center's Host and Port fields+are saved before Test runs. The saved address applies only to that connection's+checks and portfolio reads; existing broker configuration remains the fallback.+The CLI supports the same persisted address, for example:++```bash+vibe-trading connector setup ibkr-paper-local --connection-id my-gateway --host 127.0.0.1 --port 4002 --skip-check+```++Supply both `--host` and `--port`. Existing agent read tools select the saved+endpoint with `connection_id`. This does not enable order placement or change+the broker's paper/live account checks.++Robinhood portfolio quotes must match the requested symbol. For active,+previously traded instruments, the mapper selects the more recent timestamped+regular-hours or extended-hours trade and reports its as-of time. It does not+label an old print as live. Untraded or inactive instruments remain unpriced;+an invalid quote or mismatched settled-close symbol is surfaced as a pricing+error. Schema-based adapter tests do not replace authenticated broker validation.diff --git a/README.md b/README.mdindex 4d195424f..0d84a49c3 100644--- a/README.md+++ b/README.md@@ -562,6 +562,21 @@ vibe-trading connector setup okx-live-sdk-readonly \The CLI prompts in the local terminal, stores values under that connection id in the OS keyring, and runs the connector's read-only check. The equivalent Web flow is **Portfolio → Manage accounts → Open connection center → choose a template → save to keyring → test connection**. MCP read tools may use `connection_id`; the process resolves its credentials from the vault, so keys never travel through MCP. Existing `~/.vibe-trading/<connector>.json` and environment configurations remain a compatibility fallback until a connection has a complete vault credential set.+For local IBKR and Futu connections, edit **Host / Port** in that connection's+card, then click **Test** to save the address and check it. The CLI equivalent+uses the same saved endpoint:++```bash+vibe-trading connector setup ibkr-paper-local --connection-id my-gateway --host 127.0.0.1 --port 4002 --skip-check+```++The address is scoped to that connection and is also used by agent reads with+its `connection_id`.++Robinhood equity valuations show the quote's as-of time and use the more recent+regular-hours or extended-hours trade. A mismatched symbol, an untraded listing,+or an inactive listing cannot silently become a priced position.+Do not paste broker API keys into an AI chat. Let the AI choose the connector, install the declared dependency, and interpret diagnostics; enter secrets only in the local hidden terminal prompt or local connection form.Read-only connectors you install yourself stay outside the checkout, in `~/.vibe-trading/connectors/<name>/`: a `connector.json` manifest plus an `adapter.py` implementing `check_status` / `get_account_snapshot` / `get_positions`. A manifest declaring any write capability is rejected.diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex 956414d6b..ddac01a60 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -4546,6 +4546,8 @@ def cmd_connector_setup(label: str | None = None,skip_check: bool = False,account: str | None = None,+ host: str | None = None,+ port: int | None = None,) -> int:"""Create a local read-only connection and collect secrets outside AI prompts.@@ -4557,10 +4559,14 @@ def cmd_connector_setup(profile, the account selection that needs the broker).account: Account to scope an account-scoped connection to; without itthe user picks from the broker's account list.+ host: Optional connection-specific IBKR/Futu gateway host; requires port.+ port: Optional connection-specific gateway port; requires host.Returns:The process exit code."""+ from dataclasses import replace+from src.trading.connections import (ConnectionStore,credential_field_catalog,@@ -4574,9 +4580,13 @@ def cmd_connector_setup(profile = profile_by_id(profile_id)if not is_readonly_connection_profile(profile):raise ValueError(f"{profile.id} is not a read-only connection profile")+ if (host is None) != (port is None):+ raise ValueError("gateway endpoint requires both --host and --port")local_id = str(connection_id or f"{profile.connector}-{profile.environment}").strip().lower()store = ConnectionStore()connection = store.ensure(local_id, profile.id, label or profile.label)+ if host is not None:+ connection = store.save(replace(connection, endpoint={"host": host, "port": port}))fields = credential_field_catalog(profile.id)names = [str(field["name"]) for field in fields]status = store.credentials.status(connection.id, names) if names else {}@@ -5423,6 +5433,8 @@ def _dispatch_connector(args: argparse.Namespace) -> int:label=args.label,skip_check=args.skip_check,account=args.account,+ host=args.host,+ port=args.port,)if sub == "select-account":return cmd_connector_select_account(@@ -5777,6 +5789,12 @@ def _build_parser() -> argparse.ArgumentParser:connector_setup.add_argument("--connection-id", default=None)connector_setup.add_argument("--label", default=None)connector_setup.add_argument("--skip-check", action="store_true")+ connector_setup.add_argument(+ "--host", default=None, help="Connection-specific IBKR/Futu gateway host (requires --port)"+ )+ connector_setup.add_argument(+ "--port", type=int, default=None, help="Connection-specific gateway port (requires --host)"+ )connector_setup.add_argument("--account",default=None,diff --git a/agent/src/agent/grounding/evidence.py b/agent/src/agent/grounding/evidence.pyindex fe11c2920..ca3223780 100644--- a/agent/src/agent/grounding/evidence.py+++ b/agent/src/agent/grounding/evidence.py@@ -1304,9 +1304,7 @@ class _EvidenceMixin:sibling = value.get("currency")sibling = sibling.strip().upper() if isinstance(sibling, str) else Nonelocal_currency = (- {"RMB": "CNY", "CNH": "CNY"}.get(sibling, sibling)- if sibling in _CURRENCY_CODES- else declared_currency+ {"RMB": "CNY", "CNH": "CNY"}.get(sibling, sibling) if sibling in _CURRENCY_CODES else None)local_timestamp = next((@@ -1529,4 +1527,3 @@ class _EvidenceMixin:))room -= 1-diff --git a/agent/src/portfolio/service.py b/agent/src/portfolio/service.pyindex b19482221..258d0dd36 100644--- a/agent/src/portfolio/service.py+++ b/agent/src/portfolio/service.py@@ -1094,6 +1094,13 @@ class PortfolioService:price = _quote_price(quote)normalized["market_price"] = _number(price) if price else Nonenormalized["price_currency"] = normalized["currency"]+ quote_view = quote.get("quote") or {}+ if broker == "robinhood":+ if quote_view.get("price_as_of"):+ normalized["price_as_of"] = quote_view["price_as_of"]+ normalized["pricing_basis"] = f"Robinhood quote as of {quote_view['price_as_of']}"+ if quote_view.get("price_error"):+ normalized["price_error"] = str(quote_view["price_error"])[:160]if isinstance(quote, dict) and quote.get("mapping_error"):# The broker answered but the reply did not match its# mapped shape: the row stays unpriced with the reasondiff --git a/agent/src/trading/connectors/robinhood/mcp.py b/agent/src/trading/connectors/robinhood/mcp.pyindex c9e745151..1ec319b04 100644--- a/agent/src/trading/connectors/robinhood/mcp.py+++ b/agent/src/trading/connectors/robinhood/mcp.py@@ -15,16 +15,10 @@ What the shapes are built from, and nothing else:#1428 (2026-09-16). ``data`` allows exactly ``positions`` and ``next``. An itemcarries ``symbol``, ``quantity`` and an optional ``average_buy_price``, and noprice or currency.-* ``get_equity_quotes``, the paginated tools' argument schemas and the ``type``- / ``next`` descriptions: the server's advertised ``tools/list`` metadata,- transcribed in the third-party ``kevin1chun/robinhood-for-agents`` repo- (``docs/official-mcp-tools.json``, live capture 2026-10-12, refreshed by an- authenticated login and checked verbatim by that repo's parity tests). Every- claim of that transcription that can be cross-checked against an independent- capture matches: its ``get_equity_positions`` ``outputSchema`` equals the- schema posted on #1428 field for field, and its quote fields match two other- third-party captures (``gordil/robin-python-SDK`` docs, real responses parsed- by ``Oft3r/agentic-trading-desk``).+* ``get_equity_quotes`` and pagination schemas: the third-party transcription+ at ``kevin1chun/robinhood-for-agents@16b3d800e7f29e9d450f45663d054a7b5adcd4b3``+ in ``docs/official-mcp-tools.json``. This is captured schema evidence, not a+ claim that this adapter has been verified against a live authenticated account.The descriptions this mapping relies on: a position item's ``type`` is theposition direction — ``'long' (positive quantity), 'short' (negative),@@ -40,6 +34,7 @@ official settled ``close``.from __future__ import annotations+from datetime import datetimefrom decimal import Decimal, InvalidOperationfrom typing import Any, Callable@@ -354,14 +349,13 @@ def portfolio_summary(envelope: Any) -> dict[str, Any]:}-def quote_summary(envelope: Any) -> dict[str, Any] | None:+def quote_summary(envelope: Any, *, expected_symbol: str | None = None) -> dict[str, Any] | None:"""Map a ``get_equity_quotes`` reply to the quote view the portfolio prices with.The generic read asks for one symbol, so the reply must carry exactly one``results`` entry. The mapping hands the reply's prices to the shared quote- reader under its own names: ``last_trade_price`` — the regular-hours print,- which the server describes as staying frozen at the closing price after the- close — becomes ``last``; the official settled ``close.price`` becomes+ reader under its own names: the more recent timestamped regular/extended+ hours trade becomes ``last``; the official settled ``close.price`` becomes``close``; ``bid_price`` / ``ask_price`` become ``bid`` / ``ask``. A closedbook reports those as ``"0"``, which the shared reader treats as no price.``has_traded=False`` means the price fields are meaningless, so they are@@ -371,6 +365,7 @@ def quote_summary(envelope: Any) -> dict[str, Any] | None:Args:envelope: ``MCPServerAdapter.call_tool`` result for``get_equity_quotes``.+ expected_symbol: Requested symbol, when called through the trading service.Returns:``None`` when the reply advertises no result rows (the symbol resolved@@ -422,10 +417,39 @@ def quote_summary(envelope: Any) -> dict[str, Any] | None:state = quote.get("state")if not isinstance(state, str) or not state.strip():raise RobinhoodShapeError(f"{tool} quote state is missing")+ symbol = quote.get("symbol")+ if not isinstance(symbol, str) or not symbol.strip():+ raise RobinhoodShapeError(f"{tool} quote symbol is missing")+ symbol = symbol.strip().upper()+ if expected_symbol and symbol != expected_symbol.strip().upper():+ raise RobinhoodShapeError(f"{tool} quote symbol does not match the requested symbol")+ usable = has_traded and state.strip() == "active"prices: dict[str, str | None] = {"last": None, "bid": None, "ask": None}- if has_traded:+ price_as_of = None+ if usable:for field, name in (("last_trade_price", "last"), ("bid_price", "bid"), ("ask_price", "ask")):prices[name] = _decimal_text(quote.get(field), f"quote.{field}", tool)+ trades = []+ for price_field, time_field in (+ ("last_trade_price", "venue_last_trade_time"),+ ("last_non_reg_trade_price", "venue_last_non_reg_trade_time"),+ ):+ raw_price = quote.get(price_field)+ if raw_price is None:+ continue+ price = _decimal_text(raw_price, f"quote.{price_field}", tool)+ if Decimal(price) <= 0:+ continue+ stamp = quote.get(time_field)+ try:+ parsed = datetime.fromisoformat(stamp.replace("Z", "+00:00"))+ if parsed.utcoffset() is None:+ raise ValueError("missing timezone")+ except (AttributeError, TypeError, ValueError):+ raise RobinhoodShapeError(f"{tool} quote.{time_field} is not a timestamp with timezone") from None+ trades.append((parsed, price, stamp))+ if trades:+ _, prices["last"], price_as_of = max(trades, key=lambda item: item[0])close_price = Noneclose = entry.get("close")if close is not None:@@ -437,16 +461,22 @@ def quote_summary(envelope: Any) -> dict[str, Any] | None:unexpected = sorted(set(close) - CLOSE_FIELDS)if unexpected:raise RobinhoodShapeError(f"{tool} close has unmapped fields: {', '.join(unexpected)}")- if close.get("price") is not None:+ if not isinstance(close.get("symbol"), str) or close["symbol"].strip().upper() != symbol:+ raise RobinhoodShapeError(f"{tool} close symbol does not match quote symbol")+ if usable and close.get("price") is not None:close_price = _decimal_text(close.get("price"), "close.price", tool)+ if not price_as_of and Decimal(close_price) > 0:+ price_as_of = close.get("date")return {- "symbol": quote.get("symbol"),+ "symbol": symbol,"last": prices["last"],"close": close_price,"bid": prices["bid"],"ask": prices["ask"],"has_traded": has_traded,"state": state.strip(),+ "price_as_of": price_as_of,+ "price_error": None if usable else f"Robinhood quote has_traded={has_traded}, state={state.strip()}",}@@ -541,7 +571,7 @@ def account_choices(envelope: Any) -> list[dict[str, Any]]:return choices-def normalize_result(operation: str, envelope: dict[str, Any]) -> dict[str, Any]:+def normalize_result(operation: str, envelope: dict[str, Any], *, expected_symbol: str | None = None) -> dict[str, Any]:"""Add the generic account / positions / accounts / quote view to a Robinhood reply.The broker reply is kept as it came. A reply that does not match the mapped@@ -552,6 +582,7 @@ def normalize_result(operation: str, envelope: dict[str, Any]) -> dict[str, Any]Args:operation: Generic operation that produced the reply.envelope: ``MCPServerAdapter.call_tool`` result.+ expected_symbol: Symbol that a single-symbol quote must match.Returns:A shallow copy with ``account``, ``positions`` or ``accounts`` added, or@@ -561,7 +592,7 @@ def normalize_result(operation: str, envelope: dict[str, Any]) -> dict[str, Any]"account": ("account", portfolio_summary),"positions": ("positions", position_rows),"accounts": ("accounts", account_choices),- "quote": ("quote", quote_summary),+ "quote": ("quote", lambda value: quote_summary(value, expected_symbol=expected_symbol)),}if operation not in mappers or str(envelope.get("status") or "").lower() != "ok":return envelopediff --git a/agent/src/trading/service.py b/agent/src/trading/service.pyindex 16ea9788a..6a0aff734 100644--- a/agent/src/trading/service.py+++ b/agent/src/trading/service.py@@ -1603,7 +1603,12 @@ def _call_remote(call_result = _complete_paginated_reply(profile.connector, operation, call_result, adapter, remote_name, arguments)- call_result = _normalize_remote_result(profile.connector, operation, call_result)+ if profile.connector == "robinhood" and operation == "quote":+ from src.trading.connectors.robinhood.mcp import normalize_result++ call_result = normalize_result(operation, call_result, expected_symbol=arguments.get("symbol"))+ else:+ call_result = _normalize_remote_result(profile.connector, operation, call_result)account_number = arguments.get("account_number")if account_number:call_result = dict(call_result)diff --git a/agent/tests/test_cli_connector_setup.py b/agent/tests/test_cli_connector_setup.pyindex bfe16f543..30f03cb6d 100644--- a/agent/tests/test_cli_connector_setup.py+++ b/agent/tests/test_cli_connector_setup.py@@ -68,3 +68,37 @@ def test_connector_setup_prompts_locally_and_never_writes_secrets_to_registry(assert "key-value" not in registryassert "secret-value" not in registryassert "passphrase-value" not in registry+++def test_connector_setup_saves_the_endpoint_used_by_the_agent_read_path(tmp_path, monkeypatch):+ from src.trading import connections+ from src.tools import trading_connector_tool++ store = ConnectionStore(tmp_path / "connections.json", credential_store=CredentialStore(_MemoryCredentials()))+ monkeypatch.setattr(connections, "ConnectionStore", lambda: store)+ args = _legacy._build_parser().parse_args(+ [+ "connector",+ "setup",+ "ibkr-paper-local",+ "--connection-id",+ "gateway",+ "--host",+ "localhost",+ "--port",+ "4002",+ "--skip-check",+ ]+ )+ monkeypatch.setattr(_legacy, "_ensure_cli_env", lambda: None)+ assert _legacy._dispatch_connector(args) == _legacy.EXIT_SUCCESS+ assert store.get("gateway").endpoint == {"host": "localhost", "port": 4002}+ seen = []++ def read_account(config):+ seen.append((config.host, config.port, config.readonly))+ return {"status": "ok", "account": {}}++ monkeypatch.setattr("src.trading.connectors.ibkr.local.get_account_snapshot", read_account)+ trading_connector_tool.TradingAccountTool().execute(connection="ibkr-paper-local", connection_id="gateway")+ assert seen == [("localhost", 4002, True)]diff --git a/agent/tests/test_grounding_unit_and_scanner_gaps.py b/agent/tests/test_grounding_unit_and_scanner_gaps.pyindex 34223b1cc..c14ddcb6e 100644--- a/agent/tests/test_grounding_unit_and_scanner_gaps.py+++ b/agent/tests/test_grounding_unit_and_scanner_gaps.py@@ -259,3 +259,11 @@ def test_plain_ref_fields_keep_the_fraction_reading(tmp_path: Path) -> None:)assert points.valid is False++[email protected]("nested", [{"value_end": 20.0}, [{"value_end": 20.0}]])+def test_currency_does_not_cross_into_nested_objects(tmp_path, nested):+ ledger = _ledger(tmp_path, {"data": {"currency": "USD", "value_end": 10.0, "child": nested}})+ currencies = {record.field: record.currency for record in ledger._evidence}+ assert currencies.pop("data.value_end") == "USD"+ assert set(currencies.values()) == {None}diff --git a/agent/tests/test_robinhood_mcp_mapping.py b/agent/tests/test_robinhood_mcp_mapping.pyindex 077c9eeee..c492ec5f4 100644--- a/agent/tests/test_robinhood_mcp_mapping.py+++ b/agent/tests/test_robinhood_mcp_mapping.py@@ -259,6 +259,8 @@ def test_quote_summary_maps_the_reply_onto_the_shared_quote_reader_names() -> No"ask": "151","has_traded": True,"state": "active",+ "price_as_of": "2026-10-12T15:59:00Z",+ "price_error": None,}@@ -498,3 +500,24 @@ def test_the_robinhood_live_profile_discloses_options_order_limit() -> None:profile = service.live_runner_profile_for_broker("robinhood")assert "options order placement is not supported" in profile.notes.lower()++[email protected]("stamp", [None, "invalid", "2026-10-12T21:00:00"])+def test_extended_trade_without_a_timezone_cannot_be_selected(stamp):+ quote = rh.quote("AAPL")+ quote.update(last_non_reg_trade_price="120", venue_last_non_reg_trade_time=stamp)+ result = mcp.normalize_result("quote", rh.quotes([rh.quote_result(quote)]))+ assert "timestamp with timezone" in result["mapping_error"]+ assert "quote" not in result+++def test_trade_selection_compares_instants_instead_of_timestamp_strings():+ quote = rh.quote("AAPL", last_trade_price="110")+ quote.update(+ venue_last_trade_time="2026-10-12T15:00:00-04:00",+ last_non_reg_trade_price="100",+ venue_last_non_reg_trade_time="2026-10-12T18:00:00Z",+ )+ result = mcp.quote_summary(rh.quotes([rh.quote_result(quote)]))+ assert result["last"] == "110"+ assert result["price_as_of"] == "2026-10-12T15:00:00-04:00"diff --git a/agent/tests/test_robinhood_portfolio_source.py b/agent/tests/test_robinhood_portfolio_source.pyindex 63fa19ccc..dfc2b3e48 100644--- a/agent/tests/test_robinhood_portfolio_source.py+++ b/agent/tests/test_robinhood_portfolio_source.py@@ -366,3 +366,29 @@ def test_accounts_route_reports_an_unavailable_broker_as_503(tmp_path, monkeypatassert response.status_code == 503assert "token expired" in response.json()["detail"]++[email protected]("case", ["wrong_symbol", "wrong_close_symbol", "never_traded", "inactive"])+def test_quote_identity_and_listing_status_cannot_price_another_position(tmp_path, broker, case):+ broker.replies["get_equity_positions"] = rh.positions([rh.position("AAPL", "4")])+ quote = rh.quote("MSFT" if case == "wrong_symbol" else "AAPL", last_trade_price="0", bid_price="0", ask_price="0")+ close = rh.settled_close("MSFT" if case == "wrong_close_symbol" else quote["symbol"], price="999")+ if case == "never_traded":+ quote["has_traded"] = False+ if case == "inactive":+ quote["state"] = "delisted"+ broker.quotes_by_symbol["AAPL"] = rh.quotes([rh.quote_result(quote, close_row=close)])+ row = _service(tmp_path).refresh()["positions"][0]+ assert row["priced"] is False+ assert row["market_price"] is None+ assert row.get("price_error")+++def test_quote_uses_the_newer_extended_hours_trade_and_retains_its_time(tmp_path, broker):+ broker.replies["get_equity_positions"] = rh.positions([rh.position("AAPL", "4")])+ quote = rh.quote("AAPL", last_trade_price="100")+ quote.update(last_non_reg_trade_price="120", venue_last_non_reg_trade_time="2026-10-12T21:00:00Z")+ broker.quotes_by_symbol["AAPL"] = rh.quotes([rh.quote_result(quote)])+ row = _service(tmp_path).refresh()["positions"][0]+ assert row["market_price"] == 120+ assert "2026-10-12T21:00:00Z" in row["pricing_basis"]diff --git a/frontend/src/components/portfolio/ConnectionCenter.tsx b/frontend/src/components/portfolio/ConnectionCenter.tsxindex 4674eebc3..623f20828 100644--- a/frontend/src/components/portfolio/ConnectionCenter.tsx+++ b/frontend/src/components/portfolio/ConnectionCenter.tsx@@ -226,8 +226,8 @@ function ConnectionCard({ connection, busy, testResult, onTest, onDelete, onSave<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" ? t("portfolio.env.live") : t("portfolio.env.paper")}</span><span>·</span><span>{connection.transport}</span></div></div><div className="flex flex-col items-end gap-2"><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" />{t("portfolio.connections.readOnly")}</span><PortfolioCompatibilityBadge compatibility={connection.portfolio_compatibility} /></div></div>{connection.onboarding ? <SetupContract onboarding={connection.onboarding} /> : null}{socketConnection ? <fieldset disabled={busy !== null} className="mt-4 grid gap-2 sm:grid-cols-2">- <label className="text-xs text-muted-foreground">Host<input type="text" value={host} onChange={(event) => setHost(event.target.value)} required maxLength={253} className={`mt-1 ${fieldClass}`} placeholder="127.0.0.1" autoComplete="off" spellCheck={false} /></label>- <label className="text-xs text-muted-foreground">Port<input type="text" inputMode="numeric" pattern="[0-9]*" value={port} onChange={(event) => setPort(event.target.value)} required maxLength={5} className={`mt-1 ${fieldClass}`} autoComplete="off" /></label>+ <label className="text-xs text-muted-foreground">{t("portfolio.connections.host")}<input type="text" value={host} onChange={(event) => setHost(event.target.value)} required maxLength={253} className={`mt-1 ${fieldClass}`} placeholder="127.0.0.1" autoComplete="off" spellCheck={false} /></label>+ <label className="text-xs text-muted-foreground">{t("portfolio.connections.port")}<input type="text" inputMode="numeric" pattern="[0-9]*" value={port} onChange={(event) => setPort(event.target.value)} required maxLength={5} className={`mt-1 ${fieldClass}`} autoComplete="off" /></label>{endpointError || connection.endpoint_error ? <p role="alert" className="text-xs text-danger sm:col-span-2">{endpointError ?? connection.endpoint_error}</p> : null}</fieldset> : null}{connection.account_selection_required ? <AccountSelector connection={connection} busy={busy} setBusy={setBusy} setMessage={setMessage} onSaved={onSaved} /> : null}diff --git a/frontend/src/components/portfolio/__tests__/ConnectionCenter.test.tsx b/frontend/src/components/portfolio/__tests__/ConnectionCenter.test.tsxindex f911c9ad4..599c3eaf9 100644--- a/frontend/src/components/portfolio/__tests__/ConnectionCenter.test.tsx+++ b/frontend/src/components/portfolio/__tests__/ConnectionCenter.test.tsx@@ -159,6 +159,17 @@ describe("ConnectionCenter IBKR address", () => {mocked.checkConnection.mockResolvedValue({ status: "ok", report: { status: "ok" } });});+ it("localizes gateway field labels", async () => {+ try {+ await i18n.changeLanguage("zh-CN");+ renderCenter(ibkr());+ expect(await screen.findByLabelText("主机")).toHaveValue("127.0.0.1");+ expect(screen.getByLabelText("端口")).toHaveValue("7497");+ } finally {+ await i18n.changeLanguage("en");+ }+ });+it("saves the edited address before testing, without a separate save button", async () => {const connection = ibkr();const onChanged = renderCenter(connection);diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex a5b7482fe..ad6783c54 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -2333,7 +2333,9 @@"accountDefault": " · الافتراضي لدى الوسيط","accountDeactivated": " · معطّل","accountSave": "استخدام هذا الحساب",- "accountSaved": "تم حفظ الحساب."+ "accountSaved": "تم حفظ الحساب.",+ "host": "المضيف",+ "port": "المنفذ"},"imports": {"title": "استيراد extraETF Investments",@@ -2358,7 +2360,8 @@"current": "القيمة الحالية","targetValue": "القيمة المستهدفة","change": "تغير القيمة"- }+ },+ "quoteAsOf": "السعر حتى {{time}}"},"analysis": {"updated": "تم التحديث",diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.jsonindex 1876a886e..f5fdba923 100644--- a/frontend/src/i18n/locales/de.json+++ b/frontend/src/i18n/locales/de.json@@ -2333,7 +2333,9 @@"accountDefault": " · Broker-Standard","accountDeactivated": " · deaktiviert","accountSave": "Dieses Konto verwenden",- "accountSaved": "Konto gespeichert."+ "accountSaved": "Konto gespeichert.",+ "host": "Host",+ "port": "Port"},"imports": {"title": "extraETF Investments importieren",@@ -2358,7 +2360,8 @@"current": "Aktueller Wert","targetValue": "Zielwert","change": "Wertänderung"- }+ },+ "quoteAsOf": "Kursstand: {{time}}"},"analysis": {"updated": "Aktualisiert",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex f33289294..9dc82dd49 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -2333,7 +2333,9 @@"accountDefault": " · broker default","accountDeactivated": " · deactivated","accountSave": "Use this account",- "accountSaved": "Account saved."+ "accountSaved": "Account saved.",+ "host": "Host",+ "port": "Port"},"imports": {"title": "Import extraETF Investments",@@ -2358,7 +2360,8 @@"current": "Current value","targetValue": "Target value","change": "Value change"- }+ },+ "quoteAsOf": "Quote as of {{time}}"},"analysis": {"updated": "Updated",diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex 2f23ac699..07ea48276 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -2333,7 +2333,9 @@"accountDefault": " · predeterminada del bróker","accountDeactivated": " · desactivada","accountSave": "Usar esta cuenta",- "accountSaved": "Cuenta guardada."+ "accountSaved": "Cuenta guardada.",+ "host": "Servidor",+ "port": "Puerto"},"imports": {"title": "Importar extraETF Investments",@@ -2358,7 +2360,8 @@"current": "Valor actual","targetValue": "Valor objetivo","change": "Cambio de valor"- }+ },+ "quoteAsOf": "Cotización a {{time}}"},"analysis": {"updated": "Actualizado",diff --git a/frontend/src/i18n/locales/fa.json b/frontend/src/i18n/locales/fa.jsonindex eb2e4c643..a8086ce2a 100644--- a/frontend/src/i18n/locales/fa.json+++ b/frontend/src/i18n/locales/fa.json@@ -2333,7 +2333,9 @@"accountDefault": " · پیشفرض کارگزار","accountDeactivated": " · غیرفعالشده","accountSave": "استفاده از این حساب",- "accountSaved": "حساب ذخیره شد."+ "accountSaved": "حساب ذخیره شد.",+ "host": "میزبان",+ "port": "درگاه"},"imports": {"title": "وارد کردن extraETF Investments",@@ -2358,7 +2360,8 @@"current": "ارزش فعلی","targetValue": "ارزش هدف","change": "تغییر ارزش"- }+ },+ "quoteAsOf": "قیمت در {{time}}"},"analysis": {"updated": "بهروز شد",diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.jsonindex 700b64d37..561533fce 100644--- a/frontend/src/i18n/locales/id.json+++ b/frontend/src/i18n/locales/id.json@@ -2333,7 +2333,9 @@"accountDefault": " · default broker","accountDeactivated": " · dinonaktifkan","accountSave": "Gunakan akun ini",- "accountSaved": "Akun tersimpan."+ "accountSaved": "Akun tersimpan.",+ "host": "Host",+ "port": "Port"},"imports": {"title": "Impor extraETF Investments",@@ -2358,7 +2360,8 @@"current": "Nilai saat ini","targetValue": "Nilai target","change": "Perubahan nilai"- }+ },+ "quoteAsOf": "Harga per {{time}}"},"analysis": {"updated": "Diperbarui",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex a75e36ba7..8ea25da0f 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -2333,7 +2333,9 @@"accountDefault": "・ブローカーの既定","accountDeactivated": "・無効化済み","accountSave": "この口座を使う",- "accountSaved": "口座を保存しました。"+ "accountSaved": "口座を保存しました。",+ "host": "ホスト",+ "port": "ポート"},"imports": {"title": "extraETF Investments をインポート",@@ -2358,7 +2360,8 @@"current": "現在の評価額","targetValue": "目標額","change": "変更額"- }+ },+ "quoteAsOf": "{{time}} 時点の価格"},"analysis": {"updated": "更新済み",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex e26304e5f..9fba21b21 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -2333,7 +2333,9 @@"accountDefault": " · 브로커 기본값","accountDeactivated": " · 비활성화됨","accountSave": "이 계좌 사용",- "accountSaved": "계좌를 저장했습니다."+ "accountSaved": "계좌를 저장했습니다.",+ "host": "호스트",+ "port": "포트"},"imports": {"title": "extraETF Investments 가져오기",@@ -2358,7 +2360,8 @@"current": "현재 금액","targetValue": "목표 금액","change": "변경 금액"- }+ },+ "quoteAsOf": "{{time}} 기준 시세"},"analysis": {"updated": "업데이트됨",diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.jsonindex bc77c521b..e439dcba8 100644--- a/frontend/src/i18n/locales/pt-BR.json+++ b/frontend/src/i18n/locales/pt-BR.json@@ -2333,7 +2333,9 @@"accountDefault": " · padrão da corretora","accountDeactivated": " · desativada","accountSave": "Usar esta conta",- "accountSaved": "Conta salva."+ "accountSaved": "Conta salva.",+ "host": "Servidor",+ "port": "Porta"},"imports": {"title": "Importar extraETF Investments",@@ -2358,7 +2360,8 @@"current": "Valor atual","targetValue": "Valor-alvo","change": "Alteração de valor"- }+ },+ "quoteAsOf": "Cotação em {{time}}"},"analysis": {"updated": "Atualizado",diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.jsonindex b674fcf04..ada3049bb 100644--- a/frontend/src/i18n/locales/tr.json+++ b/frontend/src/i18n/locales/tr.json@@ -2297,7 +2297,9 @@"accountDefault": " · aracı kurum varsayılanı","accountDeactivated": " · devre dışı","accountSave": "Bu hesabı kullan",- "accountSaved": "Hesap kaydedildi."+ "accountSaved": "Hesap kaydedildi.",+ "host": "Sunucu",+ "port": "Bağlantı noktası"},"imports": {"title": "extraETF Investments içe aktar",@@ -2322,7 +2324,8 @@"current": "Mevcut değer","targetValue": "Hedef değer","change": "Değer değişimi"- }+ },+ "quoteAsOf": "{{time}} itibarıyla fiyat"},"navigation": {"menu": "Özelliklere göz at",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex d89b1eb6f..271e03435 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -2333,7 +2333,9 @@"accountDefault": " · 券商默认","accountDeactivated": " · 已停用","accountSave": "使用这个账户",- "accountSaved": "账户已保存。"+ "accountSaved": "账户已保存。",+ "host": "主机",+ "port": "端口"},"imports": {"title": "导入 extraETF Investments",@@ -2358,7 +2360,8 @@"current": "当前金额","targetValue": "目标金额","change": "调整金额"- }+ },+ "quoteAsOf": "报价时间:{{time}}"},"analysis": {"updated": "已更新",diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 9d60e4dc5..5d2299cc1 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -148,6 +148,7 @@ export interface PortfolioPosition {priced: boolean;updated_at: string;pricing_basis?: string;+ price_as_of?: string;price_error?: string;}diff --git a/frontend/src/pages/Portfolio.tsx b/frontend/src/pages/Portfolio.tsxindex 48c1a6b0e..82a234ee6 100644--- a/frontend/src/pages/Portfolio.tsx+++ b/frontend/src/pages/Portfolio.tsx@@ -460,7 +460,7 @@ export function Portfolio() {const valueMain = row.priced ? money(displayValue(row.market_value_usd, row.market_value_cny, displayCurrency, snapshot.fx), displayCurrency) : "—";const valueAlt = row.priced ? (displayCurrency === "USD" ? money(row.market_value_cny, "CNY") : money(row.market_value_usd)) : t("portfolio.holdings.unpriced");const pnlDisplay = displayValue(row.unrealized_pnl_usd, undefined, displayCurrency, snapshot.fx);- return <tr key={`${row.source_id ?? row.broker}-${row.portfolio_id ?? ""}-${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>{row.portfolio_id && <div className="text-xs text-muted-foreground">{row.portfolio_name} · {row.portfolio_id}</div>}{row.source_mtime && <div className="text-xs text-muted-foreground">{t("portfolio.imports.mtime", { time: dateTime(row.source_mtime) })}</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">{valueMain}</div><div className="text-xs text-muted-foreground">{valueAlt}</div></Td><Td>{row.priced ? percentage(weight) : "—"}</Td><Td><span className={pnlDisplay == null ? "text-muted-foreground" : pnlDisplay >= 0 ? "text-positive" : "text-danger"}>{pnlDisplay == null ? "—" : money(pnlDisplay, displayCurrency)}</span></Td><Td><DataBadge priced={row.priced} /></Td></tr>;+ return <tr key={`${row.source_id ?? row.broker}-${row.portfolio_id ?? ""}-${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>{row.portfolio_id && <div className="text-xs text-muted-foreground">{row.portfolio_name} · {row.portfolio_id}</div>}{row.source_mtime && <div className="text-xs text-muted-foreground">{t("portfolio.imports.mtime", { time: dateTime(row.source_mtime) })}</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>{row.price_as_of && <div className="text-xs text-muted-foreground">{t("portfolio.quoteAsOf", { time: dateTime(row.price_as_of) })}</div>}{row.price_error && <div className="max-w-52 text-xs text-danger">{row.price_error}</div>}</Td><Td><div className="font-medium">{valueMain}</div><div className="text-xs text-muted-foreground">{valueAlt}</div></Td><Td>{row.priced ? percentage(weight) : "—"}</Td><Td><span className={pnlDisplay == null ? "text-muted-foreground" : pnlDisplay >= 0 ? "text-positive" : "text-danger"}>{pnlDisplay == null ? "—" : money(pnlDisplay, displayCurrency)}</span></Td><Td><DataBadge priced={row.priced} /></Td></tr>;})}</tbody></table>diff --git a/frontend/src/pages/__tests__/Portfolio.test.tsx b/frontend/src/pages/__tests__/Portfolio.test.tsxindex 892184d5e..1e7b95b3f 100644--- a/frontend/src/pages/__tests__/Portfolio.test.tsx+++ b/frontend/src/pages/__tests__/Portfolio.test.tsx@@ -138,6 +138,16 @@ const portfolioConfiguration = {};describe("Portfolio page", () => {+ it("shows the quote timestamp and pricing failure beside the position", async () => {+ mocked.getPortfolio.mockResolvedValue({ status: "ok", snapshot: {+ ...snapshot,+ positions: [{ ...snapshot.positions[0], price_as_of: "2026-10-12T21:00:00Z", price_error: "quote symbol does not match" }],+ } });+ render(<Portfolio />);+ expect(await screen.findByText(/Quote as of/)).toBeInTheDocument();+ expect(screen.getByText("quote symbol does not match")).toBeInTheDocument();+ });+it("shows reported cash legs without replacing missing values or netting currencies", async () => {mocked.getPortfolio.mockResolvedValue({ status: "ok", snapshot: {...snapshot,