Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(finance): keep journal and portfolio money in the correct currency and cost basis

Haozhe Wu9142a58a7b61
diff --git a/agent/src/portfolio/normalization.py b/agent/src/portfolio/normalization.py
index 2d37ebe2e..df30a26c6 100644
--- a/agent/src/portfolio/normalization.py
+++ b/agent/src/portfolio/normalization.py
@@ -11,8 +11,9 @@ have dedicated branches:
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.
+as crypto/stablecoin and quote against USDT. Futu uses its explicit
+average_cost, because its securities cost_price includes realized gains.
+Other connectors fall through unchanged when their field semantics match.
"""
from __future__ import annotations
@@ -143,6 +144,12 @@ def normalize_position(broker: str, row: dict[str, Any]) -> dict[str, Any]:
),
)
)
+ if broker == "futu":
+ # Futu's cost_price is diluted by realized gains, not the remaining
+ # position's purchase cost. Never derive unrealized P&L from it.
+ # If neither average_cost nor unrealized_pl was reported, P&L stays
+ # unavailable; the connector still preserves both raw cost bases.
+ cost = _decimal(row.get("average_cost"))
market_price = _decimal(
row.get(
"market_price",
diff --git a/agent/src/portfolio/store.py b/agent/src/portfolio/store.py
index 3b199f16a..80023c1c6 100644
--- a/agent/src/portfolio/store.py
+++ b/agent/src/portfolio/store.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import json
import sqlite3
+from decimal import Decimal, InvalidOperation
from pathlib import Path
from typing import Any
@@ -172,12 +173,20 @@ class PortfolioStore:
).fetchall()
history = []
for row in rows:
+ payload = json.loads(row["payload"])
if valuation_version is not None or complete_only:
- payload = json.loads(row["payload"])
if valuation_version is not None and payload.get("valuation_version") != valuation_version:
continue
if complete_only and not _derived_totals_are_complete(payload):
continue
+ total_hkd = None
+ try:
+ usd_hkd = Decimal(str((payload.get("fx") or {}).get("usd_hkd")))
+ usd = Decimal(row["total_usd"])
+ if usd_hkd.is_finite() and usd_hkd > 0 and usd.is_finite():
+ total_hkd = str(usd * usd_hkd)
+ except (InvalidOperation, ValueError, TypeError):
+ pass # Historical snapshots without FX stay explicitly unpriced.
history.append(
{
"id": row["id"],
@@ -185,6 +194,7 @@ class PortfolioStore:
"complete": row["complete"],
"total_usd": row["total_usd"],
"total_cny": row["total_cny"],
+ "total_hkd": total_hkd,
}
)
if len(history) >= row_limit:
diff --git a/agent/src/skills/trade-journal/SKILL.md b/agent/src/skills/trade-journal/SKILL.md
index ec62eda4f..374163361 100644
--- a/agent/src/skills/trade-journal/SKILL.md
+++ b/agent/src/skills/trade-journal/SKILL.md
@@ -76,7 +76,15 @@ analyze_trade_journal(file_path="uploads/xxx.csv", filter_expr="market=china_a")
```
Note: PnL uses FIFO lot matching; unmatched open positions are excluded from
-win rate / PnL ratio (only closed round-trips count).
+win rate / PnL ratio (only closed round-trips count). Drawdown starts from
+zero realized PnL, so the first losing close counts.
+
+For mixed-currency journals, `total_pnl`, `total_dividends`, `max_drawdown`
+and `profit_loss_ratio` are currency-keyed objects. Present each currency
+separately; never add their values or average their ratios. Dividend-only
+journals follow the same rule. `overtrading.by_currency` contains each
+currency’s activity diagnosis; mixed journals rank `top_symbols` by trade
+count and label amounts with their currency. No FX conversion is implied.
## Presenting results to the user
diff --git a/agent/src/tools/trade_journal_tool.py b/agent/src/tools/trade_journal_tool.py
index 7fd1472bd..2307e9535 100644
--- a/agent/src/tools/trade_journal_tool.py
+++ b/agent/src/tools/trade_journal_tool.py
@@ -237,17 +237,10 @@ def _compute_profile(df: pd.DataFrame) -> dict[str, Any]:
dividend cash rows; those are summed into ``total_dividends`` and
``total_pnl`` but never counted as trades.
- Money is never summed across currencies (#1808). With a single
- settlement currency, ``total_pnl`` / ``max_drawdown`` / ``total_dividends``
- stay plain floats and the profile is byte-for-byte the legacy shape. When
- round-trips span more than one currency they become per-currency dicts
- (e.g. ``{"USD": 100.0, "HKD": 1000.0}``) plus a ``currency_warning`` —
- the same no-FX-conversion convention the shadow backtest reports
- (#997/#1310). Ratio metrics (win_rate, profit_loss_ratio) stay
- dimensionless on the full sample. Dividend rows settle in their symbol's
- currency, so they join that currency's pool even when the market has no
- round-trip here — the cash is real and dropping it would understate the
- pool.
+ Monetary metrics and the average-win/average-loss ratio are computed
+ within each settlement currency. Single-currency journals retain scalar
+ values; mixed journals return currency-keyed mappings. Win rate and
+ holding time remain sample-wide because they do not add money amounts.
Returns:
Dict with avg_holding_days, trade_frequency_per_week, win_rate,
@@ -269,7 +262,6 @@ def _compute_profile(df: pd.DataFrame) -> dict[str, Any]:
# silent omission (#1808).
div_rows = df[df["side"] == "dividend"]
dividend_amounts = div_rows["amount"]
- total_dividends = round(float(dividend_amounts.sum()), 2)
dividends_by_currency: dict[str, float] = {}
for symbol, amount in div_rows.groupby("symbol")["amount"].sum().items():
cur = code_currency(symbol)
@@ -294,53 +286,50 @@ def _compute_profile(df: pd.DataFrame) -> dict[str, Any]:
)
mixed = len(currencies) > 1
- if not rts_df.empty:
- wins = rts_df[rts_df["pnl"] > 0]
- losses = rts_df[rts_df["pnl"] < 0]
- avg_win = wins["pnl"].mean() if len(wins) else 0.0
- avg_loss = losses["pnl"].mean() if len(losses) else 0.0
- win_rate = round(len(wins) / len(rts_df), 4)
- pnl_ratio = round(_safe_div(avg_win, abs(avg_loss)), 2) if avg_loss else float("inf") if avg_win else 0.0
- avg_hold = round(rts_df["hold_days"].mean(), 2)
- if mixed:
- # Per-currency pools, dividends included where their market
- # traded; no FX translation (shadow-backtest convention #997/#1310).
- total_pnl = {
- cur: round(float(
- rts_df.loc[rts_df["currency"] == cur, "pnl"].sum()
- + dividends_by_currency.get(cur, 0.0)
- ), 2)
- for cur in currencies
- }
- max_drawdown = {}
- for cur in currencies:
- pool = rts_df[rts_df["currency"] == cur].sort_values("sell_dt")
- pnl = pool["pnl"].cumsum()
- drawdown = (pnl - pnl.cummax()).min()
- max_drawdown[cur] = (
- round(float(drawdown), 2) if pd.notna(drawdown) else 0.0
- )
- else:
- total_pnl = round(float(rts_df["pnl"].sum()) + total_dividends, 2)
- # Cumulative PnL → max drawdown
- cum = rts_df.sort_values("sell_dt")["pnl"].cumsum()
- running_max = cum.cummax()
- drawdown = (cum - running_max).min()
- max_drawdown = round(float(drawdown), 2) if pd.notna(drawdown) else 0.0
- else:
- win_rate = pnl_ratio = avg_hold = max_drawdown = 0.0
- total_pnl = total_dividends
-
+ win_rate = round(sum(rt["pnl"] > 0 for rt in rts) / len(rts), 4) if rts else 0.0
+ avg_hold = round(float(rts_df["hold_days"].mean()), 2) if rts else 0.0
+ pnl_by_currency = {}
+ drawdown_by_currency = {}
+ ratio_by_currency = {}
+ for currency in currencies:
+ pool = sorted((rt for rt in rts if rt["currency"] == currency),
+ key=lambda rt: rt["sell_dt"])
+ pnl = pd.Series([rt["pnl"] for rt in pool], dtype=float)
+ wins, losses = pnl[pnl > 0], pnl[pnl < 0]
+ avg_win = float(wins.mean()) if len(wins) else 0.0
+ avg_loss = float(losses.mean()) if len(losses) else 0.0
+ ratio_by_currency[currency] = (
+ round(avg_win / abs(avg_loss), 2) if avg_loss
+ else float("inf") if avg_win else 0.0
+ )
+ pnl_by_currency[currency] = round(float(pnl.sum()) + dividends_by_currency.get(currency, 0.0), 2)
+ # The realized-PnL curve starts at zero, before the first close.
+ # Otherwise a losing first trade becomes the peak and disappears.
+ cumulative = pnl.cumsum()
+ drawdown = (cumulative - cumulative.cummax().clip(lower=0)).min()
+ drawdown_by_currency[currency] = round(float(drawdown), 2) if pd.notna(drawdown) else 0.0
+
+ dividend_totals = {cur: round(dividends_by_currency.get(cur, 0.0), 2) for cur in currencies}
+ total_pnl = pnl_by_currency if mixed else next(iter(pnl_by_currency.values()), 0.0)
+ max_drawdown = drawdown_by_currency if mixed else next(iter(drawdown_by_currency.values()), 0.0)
+ pnl_ratio = ratio_by_currency if mixed else next(iter(ratio_by_currency.values()), 0.0)
+ total_dividends = dividend_totals if mixed else next(iter(dividend_totals.values()), 0.0)
+
+ mixed_trade_currencies = len({code_currency(symbol) for symbol in trades_df["symbol"]}) > 1
top_symbols = (
trades_df.groupby("symbol")
.agg(trades=("symbol", "count"), total_amount=("amount", "sum"))
- .sort_values("total_amount", ascending=False)
+ .sort_values("trades" if mixed_trade_currencies else "total_amount", ascending=False)
.head(10)
.round(2)
.reset_index()
.to_dict(orient="records")
)
+ if mixed_trade_currencies:
+ for entry in top_symbols:
+ entry["currency"] = code_currency(entry["symbol"])
+
market_dist = trades_df["market"].value_counts().to_dict()
hourly_dist = trades_df["datetime"].dt.hour.value_counts().sort_index().to_dict()
hourly_dist = {int(h): int(c) for h, c in hourly_dist.items()}
@@ -375,7 +364,7 @@ def _compute_profile(df: pd.DataFrame) -> dict[str, Any]:
for cur in currencies
},
"currency_warning": (
- "Round-trips span multiple settlement currencies; totals are "
+ "Journal cash flows span multiple settlement currencies; monetary metrics are "
"reported per currency with no FX conversion."
),
} if mixed else {}),
@@ -565,9 +554,26 @@ def _compute_behavior(df: pd.DataFrame) -> dict[str, Any]:
return {"error": "empty trade journal"}
trades_df = df[df["side"].isin(("buy", "sell"))]
rts_df = pd.DataFrame(pair_trades_fifo(df))
+ currencies = sorted({code_currency(symbol) for symbol in trades_df["symbol"]})
+ if len(currencies) > 1:
+ by_currency = {
+ currency: _overtrading(
+ trades_df[trades_df["symbol"].map(code_currency) == currency],
+ rts_df[rts_df["currency"] == currency] if not rts_df.empty else rts_df,
+ )
+ for currency in currencies
+ }
+ overtrading = {
+ "severity": max((result["severity"] for result in by_currency.values()),
+ key=("low", "medium", "high").index),
+ "by_currency": by_currency,
+ "evidence": "Activity and realized PnL compared separately by settlement currency; no FX conversion.",
+ }
+ else:
+ overtrading = _overtrading(trades_df, rts_df)
return {
"disposition_effect": _disposition_effect(rts_df),
- "overtrading": _overtrading(trades_df, rts_df),
+ "overtrading": overtrading,
"chasing_momentum": _chasing_momentum(trades_df),
"anchoring": _anchoring(trades_df),
}
diff --git a/agent/tests/test_futu_position_cost_bases.py b/agent/tests/test_futu_position_cost_bases.py
index 6aef21f8f..8dde6d47c 100644
--- a/agent/tests/test_futu_position_cost_bases.py
+++ b/agent/tests/test_futu_position_cost_bases.py
@@ -7,6 +7,9 @@ The fields come from ``PositionListQuery.unpack_rsp`` in the SDK module
field the response does not carry with ``NoneDataValue``, the string
``"N/A"``, rather than omitting the key.
+Field semantics: https://openapi.futunn.com/futu-api-doc/en/trade/get-position-list.html
+Average cost and unrealized P&L are unavailable for securities paper accounts.
+
All rows are synthetic: invented symbols and values in the shape the SDK
returns.
"""
@@ -130,10 +133,24 @@ def test_reported_unrealized_pl_is_the_valued_pnl() -> None:
assert valued["unrealized_pnl_usd"] == pytest.approx(-750.0)
-def test_unreported_unrealized_pl_is_not_valued_as_zero() -> None:
- """An unreported P&L falls back to price against cost instead of a flat 0."""
+def test_missing_average_cost_and_unrealized_pl_stay_unavailable() -> None:
+ """Diluted cost alone cannot establish the unrealized part of P&L."""
row = normalize_position("futu", futu_sdk._position_to_dict(NEW_FIELDS_UNREPORTED))
valued = value_position(row, rates=RATES)
- assert valued["unrealized_pnl_usd"] == pytest.approx(-25.0)
+ assert valued["unrealized_pnl_usd"] is None
+ assert valued["cost_price"] is None
+
+
+def test_portfolio_displays_average_purchase_cost_not_diluted_cost() -> None:
+ row = normalize_position("futu", futu_sdk._position_to_dict(DILUTED_COST_WENT_NEGATIVE))
+ assert row["cost_price"] == 20.0
+ assert value_position(row, rates=RATES)["unrealized_pnl_usd"] == pytest.approx(75.0)
+
+
+def test_average_cost_can_price_pnl_when_broker_does_not_report_it() -> None:
+ payload = {**PL_VAL_MIXES_REALIZED, "unrealized_pl": "N/A"}
+ row = normalize_position("futu", futu_sdk._position_to_dict(payload))
+ assert row["cost_price"] == 12.0
+ assert value_position(row, rates=RATES)["unrealized_pnl_usd"] == pytest.approx(-750.0)
diff --git a/agent/tests/test_portfolio_service.py b/agent/tests/test_portfolio_service.py
index 078e8af87..dda9e9403 100644
--- a/agent/tests/test_portfolio_service.py
+++ b/agent/tests/test_portfolio_service.py
@@ -920,3 +920,17 @@ def test_a_pinned_read_refuses_a_snapshot_valued_under_another_contract(tmp_path
service.store.save_snapshot({**snapshot, "snapshot_id": "old-contract", "valuation_version": 1})
assert service.analysis_context(snapshot_id="old-contract") is None
+
+
[email protected]("rate,expected", [("8", "800"), ("7.5", "750.0"), (None, None), ("NaN", None), (0, None)])
+def test_history_uses_the_saved_hkd_rate(tmp_path, rate, expected):
+ store = PortfolioStore(tmp_path / "history.sqlite3")
+ store.save_snapshot({
+ "snapshot_id": "snapshot", "created_at": "2026-10-13T00:00:00Z",
+ "complete": True, "totals": {"usd": 100, "cny": 700},
+ "fx": {"usd_hkd": rate},
+ })
+ point = store.history()[0]
+ assert point["total_hkd"] == expected
+ assert point["total_usd"] == "100"
+ assert point["total_cny"] == "700"
diff --git a/agent/tests/test_trade_journal_currency_pools.py b/agent/tests/test_trade_journal_currency_pools.py
index ed4f24914..33299abad 100644
--- a/agent/tests/test_trade_journal_currency_pools.py
+++ b/agent/tests/test_trade_journal_currency_pools.py
@@ -93,7 +93,7 @@ def test_dividends_join_their_own_currency_pool() -> None:
])
profile = _compute_profile(df)
assert profile["total_pnl"] == {"HKD": 1050.0, "USD": 100.0}
- assert profile["total_dividends"] == 50.0
+ assert profile["total_dividends"] == {"HKD": 50.0, "USD": 0.0}
assert profile["total_dividends_by_currency"] == {"HKD": 50.0, "USD": 0.0}
@@ -125,7 +125,7 @@ def test_foreign_dividend_flips_profile_to_its_currency_pool() -> None:
])
profile = _compute_profile(df)
assert profile["total_pnl"] == {"HKD": 1000.0, "USD": 25.0}
- assert profile["total_dividends"] == 25.0
+ assert profile["total_dividends"] == {"HKD": 0.0, "USD": 25.0}
assert profile["total_dividends_by_currency"] == {"HKD": 0.0, "USD": 25.0}
@@ -140,3 +140,61 @@ def test_unmatched_positions_do_not_break_currency_pooling() -> None:
profile = _compute_profile(df)
assert profile["total_pnl"] == 1000.0
assert "currency_warning" not in profile
+ assert {row["currency"] for row in profile["top_symbols"]} == {"USD", "HKD"}
+
+
+def test_dividend_only_journal_never_adds_currencies() -> None:
+ profile = _compute_profile(_df([
+ _div("2026-01-02", "AAPL", 25),
+ _div("2026-01-03", "0700.HK", 50),
+ ]))
+ assert profile["total_pnl"] == {"HKD": 50.0, "USD": 25.0}
+ assert profile["total_dividends"] == {"HKD": 50.0, "USD": 25.0}
+ assert profile["max_drawdown"] == {"HKD": 0.0, "USD": 0.0}
+
+
+def test_pnl_ratio_never_divides_different_currencies() -> None:
+ profile = _compute_profile(_df([
+ _rec("2026-01-02", "AAPL", "buy", 10, 100),
+ _rec("2026-01-03", "AAPL", "sell", 10, 90),
+ _rec("2026-01-02", "0700.HK", "buy", 100, 400),
+ _rec("2026-01-03", "0700.HK", "sell", 100, 410),
+ ]))
+ assert profile["profit_loss_ratio"] == {"USD": 0.0, "HKD": float("inf")}
+ assert profile["max_drawdown"] == {"USD": -100.0, "HKD": 0.0}
+ assert all("currency" in row for row in profile["top_symbols"])
+
+
+def test_initial_loss_counts_towards_drawdown() -> None:
+ profile = _compute_profile(_df([
+ _rec("2026-01-02", "AAPL", "buy", 10, 100),
+ _rec("2026-01-03", "AAPL", "sell", 10, 90),
+ _rec("2026-01-04", "AAPL", "buy", 10, 90),
+ _rec("2026-01-05", "AAPL", "sell", 10, 85),
+ ]))
+ assert profile["max_drawdown"] == -150.0
+ assert profile["total_pnl"] == -150.0
+
+
+def test_behavior_compares_activity_within_currencies() -> None:
+ from src.tools.trade_journal_tool import _compute_behavior
+
+ df = _df([
+ _rec("2026-01-02", "AAPL", "buy", 10, 100),
+ _rec("2026-01-03", "AAPL", "sell", 10, 90),
+ _rec("2026-01-04", "0700.HK", "buy", 100, 400),
+ _rec("2026-01-05", "0700.HK", "sell", 100, 410),
+ ])
+ result = _compute_behavior(df)["overtrading"]
+ assert set(result["by_currency"]) == {"USD", "HKD"}
+ assert "busy_day_avg_pnl" not in result
+
+
+def test_behavior_with_only_open_positions_keeps_currency_activity_separate() -> None:
+ from src.tools.trade_journal_tool import _compute_behavior
+
+ result = _compute_behavior(_df([
+ _rec("2026-01-02", "AAPL", "buy", 10, 100),
+ _rec("2026-01-02", "0700.HK", "buy", 100, 400),
+ ]))
+ assert set(result["overtrading"]["by_currency"]) == {"USD", "HKD"}
diff --git a/frontend/src/components/portfolio/PortfolioSourceEditor.tsx b/frontend/src/components/portfolio/PortfolioSourceEditor.tsx
index e12fad0ac..205885ca2 100644
--- a/frontend/src/components/portfolio/PortfolioSourceEditor.tsx
+++ b/frontend/src/components/portfolio/PortfolioSourceEditor.tsx
@@ -98,7 +98,7 @@ export function PortfolioSourceEditor({ open, settings, catalog, saving, onClose
</header>
<div className="flex-1 space-y-6 overflow-y-auto p-5">
- <fieldset><legend className="text-sm font-medium">{t("portfolio.editor.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>
+ <fieldset><legend className="text-sm font-medium">{t("portfolio.editor.currency")}</legend><div className="mt-2 grid grid-cols-3 gap-2">{(["USD", "CNY", "HKD"] 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">{t("portfolio.editor.selected")}</h3><p className="mt-1 text-xs text-muted-foreground">{t("portfolio.editor.selectedHint")}</p></div><span className="text-xs text-muted-foreground">{draft.sources.length}</span></div>
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 78cbae398..20ec6ea02 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -221,6 +221,8 @@ export interface PortfolioHistoryPoint {
complete: number;
total_usd: string;
total_cny: string;
+ /** Historical HKD value at this snapshot’s FX rate; absent means unavailable. */
+ total_hkd?: string | null;
}
export interface PortfolioRefreshState {
diff --git a/frontend/src/pages/Portfolio.tsx b/frontend/src/pages/Portfolio.tsx
index 4ada2cca3..d34a0eea8 100644
--- a/frontend/src/pages/Portfolio.tsx
+++ b/frontend/src/pages/Portfolio.tsx
@@ -66,6 +66,18 @@ function money(value: number | null | undefined, currency: string = "USD") {
}).format(value);
}
+/** Convert only with the FX observation stored on this snapshot. */
+function displayValue(
+ usd: number | null | undefined, cny: number | null | undefined,
+ currency: string, fx: PortfolioSnapshot["fx"] | undefined,
+): number | null {
+ if (currency === "CNY" && cny != null && Number.isFinite(cny)) return cny;
+ if (usd == null || !Number.isFinite(usd)) return null;
+ if (currency === "USD") return usd;
+ const rate = currency === "CNY" ? fx?.usd_cny : currency === "HKD" ? fx?.usd_hkd : fx?.rates?.[currency];
+ return rate != null && Number.isFinite(rate) && rate > 0 ? usd * rate : null;
+}
+
function quantity(value: number | null | undefined) {
if (value == null || !Number.isFinite(value)) return "—";
return new Intl.NumberFormat(uiLocale(), { maximumFractionDigits: 8 }).format(value);
@@ -94,7 +106,7 @@ function slicePercentage(percent: number) {
}
/** Compact tick label for the history axis, e.g. "$120K" / "¥12万". */
-function compactUsd(value: number, currency: string = "USD") {
+function compactMoney(value: number, currency: string = "USD") {
return new Intl.NumberFormat(uiLocale(), {
style: "currency",
currency,
@@ -328,7 +340,7 @@ export function Portfolio() {
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 = snapshot?.totals.display ?? (displayCurrency === "CNY" ? snapshot?.totals.cny : snapshot?.totals.usd);
+ const totalDisplay = displayValue(snapshot?.totals.usd, snapshot?.totals.cny, displayCurrency, snapshot?.fx);
return (
<div className="min-h-screen p-4 sm:p-6 lg:p-8">
@@ -341,7 +353,7 @@ export function Portfolio() {
</div>
<h1 className="text-3xl font-semibold tracking-tight">{t("portfolio.page.title")}</h1>
<p className="mt-2 text-sm text-muted-foreground">{t("portfolio.page.subtitle")}</p>
- {snapshot ? (
+ {snapshot?.fx && Number.isFinite(snapshot.fx.usd_cny) ? (
<p className="mt-2 text-xs text-muted-foreground">
{t(snapshot.fx.stale ? "portfolio.page.fxCached" : "portfolio.page.fxFresh", { rate: snapshot.fx.usd_cny.toFixed(4) })}
</p>
@@ -428,7 +440,7 @@ export function Portfolio() {
</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)} displayCurrency={displayCurrency} onClick={() => { const id = account.source_id ?? account.broker; setSourceFilter((current) => current === id ? "all" : id); }} onReconnect={account.reconnect_required && account.source_id ? () => void reconnectSource(account.source_id!) : undefined} onRetry={!account.reconnect_required ? () => void refresh() : undefined} busy={refreshing || reconnectingSource === (account.source_id ?? account.broker)} actionsDisabled={refreshing || reconnectingSource !== null} />
+ <AccountCard key={account.source_id ?? account.broker} account={account} active={sourceFilter === (account.source_id ?? account.broker)} displayCurrency={displayCurrency} fx={snapshot.fx} onClick={() => { const id = account.source_id ?? account.broker; setSourceFilter((current) => current === id ? "all" : id); }} onReconnect={account.reconnect_required && account.source_id ? () => void reconnectSource(account.source_id!) : undefined} onRetry={!account.reconnect_required ? () => void refresh() : undefined} busy={refreshing || reconnectingSource === (account.source_id ?? account.broker)} actionsDisabled={refreshing || reconnectingSource !== null} />
))}
</div>
</section>
@@ -444,10 +456,9 @@ export function Portfolio() {
<tbody className="divide-y">
{positions.map((row) => {
const weight = snapshot.totals.usd > 0 ? row.market_value_usd / snapshot.totals.usd : 0;
- const fx = snapshot.fx?.usd_cny ?? (snapshot.totals.usd > 0 ? snapshot.totals.cny / snapshot.totals.usd : 7.0);
- const valueMain = row.priced ? (displayCurrency === "CNY" ? money(row.market_value_cny, "CNY") : money(row.market_value_usd)) : "—";
- const valueAlt = row.priced ? (displayCurrency === "CNY" ? money(row.market_value_usd) : money(row.market_value_cny, "CNY")) : t("portfolio.holdings.unpriced");
- const pnlDisplay = row.unrealized_pnl_usd == null ? null : (displayCurrency === "CNY" ? row.unrealized_pnl_usd * fx : row.unrealized_pnl_usd);
+ 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.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">{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>
@@ -531,14 +542,10 @@ function RefreshProgress({ state, settings }: { state: PortfolioRefreshState; se
* it renders the failure, the error text and the last successful read time
* instead of a value, so nothing on the card suggests it is part of the total.
*/
-function AccountCard({ account, active, displayCurrency, onClick, onReconnect, onRetry, busy, actionsDisabled }: { account: PortfolioAccount; active: boolean; displayCurrency: string; onClick: () => void; onReconnect?: () => void; onRetry?: () => void; busy: boolean; actionsDisabled: boolean }) {
+function AccountCard({ account, active, displayCurrency, fx, onClick, onReconnect, onRetry, busy, actionsDisabled }: { account: PortfolioAccount; active: boolean; displayCurrency: string; fx: PortfolioSnapshot["fx"]; onClick: () => void; onReconnect?: () => void; onRetry?: () => void; busy: boolean; actionsDisabled: boolean }) {
const { t } = useTranslation();
const failed = account.status === "error";
- const displayValue = account.total_display ?? (
- displayCurrency === "USD" ? account.total_usd :
- displayCurrency === "CNY" ? account.total_cny :
- null
- );
+ const accountDisplay = displayValue(account.total_usd, account.total_cny, displayCurrency, fx);
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 gap-3">
<div><div className="font-medium">{account.label ?? account.broker.toUpperCase()}</div><div className="mt-1 flex flex-wrap items-center gap-2 text-xs"><BrokerBadge broker={account.broker} /><PortfolioCompatibilityBadge compatibility={account.portfolio_compatibility} /></div></div>
@@ -551,7 +558,7 @@ function AccountCard({ account, active, displayCurrency, onClick, onReconnect, o
</>
) : (
<>
- <div className="mt-4 text-2xl font-semibold">{money(displayValue, displayCurrency)}</div>
+ <div className="mt-4 text-2xl font-semibold">{money(accountDisplay, displayCurrency)}</div>
<div className="mt-1 text-xs text-muted-foreground">{displayCurrency === "USD" ? money(account.total_cny, "CNY") : money(account.total_usd)} · {t("portfolio.accounts.positions", { count: account.position_count ?? 0 })}</div>
<div className="mt-4 flex items-center justify-between border-t pt-3 text-xs"><span className="text-positive">{t("portfolio.accounts.fresh")}</span><span className="text-muted-foreground">{dateTime(account.last_success_at)}</span></div>
</>
@@ -643,11 +650,11 @@ function HistoryChart({ history, currency = "USD" }: { history: PortfolioHistory
backgroundColor: theme.tooltipBg,
borderColor: theme.tooltipBorder,
textStyle: { color: theme.tooltipText },
- 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), currency)}`; },
+ formatter: (items: Array<{ dataIndex: number; value: number }>) => { const item = items[0]; const row = rows[item.dataIndex]; return `${dateTime(row?.created_at)}<br/>${money(item?.value == null ? null : Number(item.value), currency)}`; },
},
xAxis: { type: "category", boundaryGap: false, data: rows.map((row) => new Date(row.created_at).toLocaleString(uiLocale(), { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" })), axisLabel: { color: theme.textColor, hideOverlap: true }, axisLine: { lineStyle: { color: theme.gridColor } } },
- yAxis: { type: "value", scale: true, axisLabel: { color: theme.textColor, formatter: (v: number) => compactUsd(v, currency) }, splitLine: { lineStyle: { color: theme.gridColor, opacity: 0.45 } } },
- series: [{ type: "line", data: rows.map((row) => Number(currency === "CNY" ? row.total_cny : 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)" } }],
+ yAxis: { type: "value", scale: true, axisLabel: { color: theme.textColor, formatter: (v: number) => compactMoney(v, currency) }, splitLine: { lineStyle: { color: theme.gridColor, opacity: 0.45 } } },
+ series: [{ type: "line", data: rows.map((row) => { const value = currency === "USD" ? row.total_usd : currency === "CNY" ? row.total_cny : currency === "HKD" ? row.total_hkd : null; return value == null ? null : Number(value); }), 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);
diff --git a/frontend/src/pages/__tests__/Portfolio.test.tsx b/frontend/src/pages/__tests__/Portfolio.test.tsx
index 542eb4d2d..f514fc9df 100644
--- a/frontend/src/pages/__tests__/Portfolio.test.tsx
+++ b/frontend/src/pages/__tests__/Portfolio.test.tsx
@@ -1,9 +1,12 @@
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { Portfolio } from "@/pages/Portfolio";
import { api } from "@/lib/api";
import i18n from "@/i18n";
+const chartOptions = vi.hoisted(() => vi.fn());
+vi.mock("@/lib/echarts", () => ({ echarts: { init: () => ({ setOption: chartOptions, on: vi.fn(), off: vi.fn(), resize: vi.fn(), dispose: vi.fn() }) } }));
+
vi.mock("@/lib/api", async () => {
const actual = await vi.importActual<typeof import("@/lib/api")>("@/lib/api");
return {
@@ -408,4 +411,33 @@ describe("Portfolio page", () => {
await waitFor(() => expect(mocked.reconnectPortfolioSource).toHaveBeenCalledWith("ibkr-auth"));
expect(screen.queryByRole("button", { name: i18n.t("portfolio.accounts.retryRead") })).not.toBeInTheDocument();
});
+ it.each(["USD", "CNY", "HKD"])("shows holdings, PnL and history in %s", async (currency) => {
+ const width = vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(640);
+ mocked.getPortfolioSettings.mockResolvedValue({ ...portfolioConfiguration, settings: { ...portfolioConfiguration.settings, display_currency: currency } });
+ mocked.getPortfolioHistory.mockResolvedValue({ status: "ok", history: [
+ { id: "historical", created_at: snapshot.created_at, complete: 1, total_usd: "100", total_cny: "700", total_hkd: "800" },
+ { id: "legacy", created_at: snapshot.created_at, complete: 1, total_usd: "100", total_cny: "700", total_hkd: null },
+ ] });
+ try {
+ render(<Portfolio />);
+ const row = (await screen.findByText("AAPL")).closest("tr")!;
+ const format = (value: number) => new Intl.NumberFormat(i18n.language || "en", { style: "currency", currency, maximumFractionDigits: currency === "CNY" ? 0 : 2 }).format(value);
+ const rate = currency === "USD" ? 1 : currency === "CNY" ? 7.2 : 7.8;
+ expect(within(row).getByText(format(300 * rate))).toBeInTheDocument();
+ expect(within(row).getByText(format(100 * rate))).toBeInTheDocument();
+ await waitFor(() => expect(chartOptions.mock.calls.some(([option]) => option.series?.[0]?.type === "line")).toBe(true));
+ const history = chartOptions.mock.calls.map(([option]) => option).find(option => option.series?.[0]?.type === "line");
+ expect(history.series[0].data).toEqual(currency === "HKD" ? [800, null] : currency === "CNY" ? [700, 700] : [100, 100]);
+ expect(history.tooltip.formatter([{ dataIndex: 0, value: history.series[0].data[0] }])).toContain(format(history.series[0].data[0]));
+ } finally { width.mockRestore(); }
+ });
+
+ it("does not invent an FX rate for unconvertible PnL", async () => {
+ mocked.getPortfolioSettings.mockResolvedValue({ ...portfolioConfiguration, settings: { ...portfolioConfiguration.settings, display_currency: "HKD" } });
+ mocked.getPortfolio.mockResolvedValue({ status: "ok", snapshot: { ...snapshot, fx: undefined } });
+ render(<Portfolio />);
+ const row = (await screen.findByText("AAPL")).closest("tr")!;
+ expect(within(row).getAllByRole("cell")[7]).toHaveTextContent("—");
+ });
+
});