Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(portfolio): preserve Futu HKD valuations

JaxonHu102401b2a3ced503
diff --git a/README.md b/README.md
index c2f9c8bef..cb8088b5a 100644
--- a/README.md
+++ b/README.md
@@ -349,6 +349,8 @@ The Web UI adds a read-only **Portfolio** page that aggregates holdings across t
| **Immutable snapshots** | Each refresh is stored in `~/.vibe-trading/portfolio/portfolio.sqlite3`; credential-free settings live in `~/.vibe-trading/portfolio.json` and `connections.json`. |
| **Export & analysis** | CSV export, plus a sanitized `portfolio_summary` agent tool whose `risk_xray_args` pass straight into `portfolio_risk_xray`. The same snapshot prints in the terminal with `vibe-trading portfolio show` (`refresh` / `sources` alongside). |
+Broker-reported source currencies are preserved during valuation: HKD account totals and positions, including Futu `HK.*` holdings, are converted with the snapshot USD/HKD rate before USD and CNY values are displayed. Older snapshots remain stored, but value history compares only snapshots produced by the current valuation methodology to avoid false gains or losses after a valuation fix.
+
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.
```bash
diff --git a/agent/src/portfolio/normalization.py b/agent/src/portfolio/normalization.py
index 4c90f5241..bc5978333 100644
--- a/agent/src/portfolio/normalization.py
+++ b/agent/src/portfolio/normalization.py
@@ -104,9 +104,12 @@ def normalize_position(broker: str, row: dict[str, Any]) -> dict[str, Any]:
symbol = str(row.get("symbol") or row.get("code") or "").upper()
source = str(row.get("source") or ("spot" if broker == "binance" else "account"))
+ market = str(row.get("market") or row.get("exchange") or broker).upper()
currency = str(row.get("currency") or "").upper()
if not currency:
- currency = "HKD" if symbol.endswith(".HK") else "USD"
+ currency = (
+ "HKD" if symbol.startswith("HK.") or symbol.endswith(".HK") else "USD"
+ )
quantity = _decimal(
row.get(
"quantity", row.get("qty", row.get("position", row.get("position_qty")))
@@ -150,7 +153,7 @@ def normalize_position(broker: str, row: dict[str, Any]) -> dict[str, Any]:
)
),
"asset_type": asset_type,
- "market": str(row.get("market") or row.get("exchange") or broker).upper(),
+ "market": market,
"currency": currency,
"quantity": _number(quantity),
"cost_price": _number(cost) if cost > 0 else None,
diff --git a/agent/src/portfolio/service.py b/agent/src/portfolio/service.py
index bbbbf386b..11859f741 100644
--- a/agent/src/portfolio/service.py
+++ b/agent/src/portfolio/service.py
@@ -34,6 +34,7 @@ from src.trading.types import TradingProfile
# 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
+PORTFOLIO_VALUATION_VERSION = 2
_LOADER_MARKET_SUFFIXES = frozenset(
{"US", "HK", "SZ", "SH", "BJ", "KS", "KQ", "NS", "BO", "TO", "V"}
)
@@ -295,6 +296,7 @@ class PortfolioService:
identified_usd = priced_usd + cash_usd
payload = {
"snapshot_id": uuid.uuid4().hex,
+ "valuation_version": PORTFOLIO_VALUATION_VERSION,
"created_at": refreshed_at,
"complete": complete,
"display_currency": settings.display_currency,
@@ -374,6 +376,8 @@ class PortfolioService:
snapshot = self.store.latest()
if snapshot is None:
return None
+ if snapshot.get("valuation_version") != PORTFOLIO_VALUATION_VERSION:
+ return None
enabled = {
source.id for source in self.settings_store.load().sources if source.enabled
}
@@ -444,7 +448,11 @@ class PortfolioService:
Returns:
One row per complete snapshot with its id, timestamp and totals.
"""
- return self.store.history(limit, complete_only=True)
+ return self.store.history(
+ limit,
+ complete_only=True,
+ valuation_version=PORTFOLIO_VALUATION_VERSION,
+ )
def export_csv(self) -> str:
"""Render the latest snapshot's positions as CSV.
diff --git a/agent/src/portfolio/store.py b/agent/src/portfolio/store.py
index 4430696bd..9c584a32e 100644
--- a/agent/src/portfolio/store.py
+++ b/agent/src/portfolio/store.py
@@ -95,7 +95,11 @@ class PortfolioStore:
return json.loads(row["payload"]) if row else None
def history(
- self, limit: int = 180, *, complete_only: bool = True
+ self,
+ limit: int = 180,
+ *,
+ complete_only: bool = True,
+ valuation_version: int | None = None,
) -> list[dict[str, Any]]:
"""Return snapshot totals over time, oldest first.
@@ -105,22 +109,43 @@ class PortfolioStore:
enabled source refreshed successfully. Charting a mix of
complete and partial snapshots would draw a value drop that
never happened.
+ valuation_version: Restrict the series to snapshots produced by
+ one valuation methodology. Legacy rows are retained but cannot
+ create false changes beside a newer methodology.
Returns:
One row per snapshot with id, timestamp, completeness and totals.
"""
+ row_limit = max(1, min(int(limit), 2000))
where = "WHERE complete = 1" if complete_only else ""
with self._connect() as db:
rows = db.execute(
f"""
- SELECT id, created_at, complete, total_usd, total_cny
+ SELECT id, created_at, complete, total_usd, total_cny, payload
FROM portfolio_snapshots
{where}
ORDER BY created_at DESC LIMIT ?
""",
- (max(1, min(int(limit), 2000)),),
+ (2000 if valuation_version is not None else row_limit,),
).fetchall()
- return [dict(row) for row in reversed(rows)]
+ history = []
+ for row in rows:
+ if valuation_version is not None:
+ payload = json.loads(row["payload"])
+ if payload.get("valuation_version") != valuation_version:
+ continue
+ history.append(
+ {
+ "id": row["id"],
+ "created_at": row["created_at"],
+ "complete": row["complete"],
+ "total_usd": row["total_usd"],
+ "total_cny": row["total_cny"],
+ }
+ )
+ if len(history) >= row_limit:
+ break
+ return list(reversed(history))
def latest_successful_source(self, source_id: str) -> dict[str, Any] | None:
"""Return the newest successfully read payload for one configured source.
diff --git a/agent/src/trading/connectors/futu/sdk.py b/agent/src/trading/connectors/futu/sdk.py
index 34154df0e..9275cf555 100644
--- a/agent/src/trading/connectors/futu/sdk.py
+++ b/agent/src/trading/connectors/futu/sdk.py
@@ -27,7 +27,6 @@ DataFrame which we convert with ``to_dict("records")`` before field mapping.
from __future__ import annotations
import json
-import os
import socket
from dataclasses import asdict, dataclass
from pathlib import Path
@@ -1172,6 +1171,7 @@ def _account_to_dict(row: Mapping[str, Any]) -> dict[str, Any]:
"market_val": _first(row, ("market_val",)),
"available_funds": _first(row, ("available_funds",)),
"securities_assets": _first(row, ("securities_assets",)),
+ "currency": str(_first(row, ("currency",), "") or "").upper(),
}
@@ -1185,6 +1185,8 @@ def _position_to_dict(row: Mapping[str, Any]) -> dict[str, Any]:
"pl_ratio": _first(row, ("pl_ratio",)),
"pl_val": _first(row, ("pl_val",)),
"position_side": str(_first(row, ("position_side",), "")),
+ "market": str(_first(row, ("position_market",), "") or "").upper(),
+ "currency": str(_first(row, ("currency",), "") or "").upper(),
}
diff --git a/agent/tests/test_futu_portfolio_currency.py b/agent/tests/test_futu_portfolio_currency.py
new file mode 100644
index 000000000..bee4ab308
--- /dev/null
+++ b/agent/tests/test_futu_portfolio_currency.py
@@ -0,0 +1,158 @@
+from __future__ import annotations
+
+from decimal import Decimal
+
+import pytest
+
+from src.portfolio.config import PortfolioSettingsStore
+from src.portfolio.normalization import normalize_position
+from src.portfolio.service import PortfolioService
+from src.portfolio.store import PortfolioStore
+from src.trading.connectors.futu import sdk as futu_sdk
+
+USD_CNY = Decimal("7")
+USD_HKD = Decimal("8")
+SNAPSHOT_AT = "2000-01-01T00:00:00+00:00"
+
+
+def _settings_store(tmp_path) -> PortfolioSettingsStore:
+ settings = PortfolioSettingsStore(tmp_path / "portfolio.json")
+ settings.connection_store.ensure(
+ "futu-test",
+ "futu-live-sdk-readonly",
+ "Synthetic Futu",
+ )
+ settings.save(
+ {
+ "display_currency": "USD",
+ "sources": [
+ {
+ "connection_id": "futu-test",
+ "label": "Synthetic Futu",
+ "order": 0,
+ }
+ ],
+ }
+ )
+ return settings
+
+
+def _service(tmp_path, account: dict, position: dict) -> PortfolioService:
+ return PortfolioService(
+ PortfolioStore(tmp_path / "portfolio.sqlite3"),
+ settings_store=_settings_store(tmp_path),
+ get_account=lambda profile_id: {"assets": [account]},
+ get_positions=lambda profile_id: {"positions": [position]},
+ get_quote=lambda *args, **kwargs: {},
+ fx_fetcher=lambda: (USD_CNY, USD_HKD, SNAPSHOT_AT),
+ )
+
+
+def test_futu_hkd_position_and_account_total_are_converted_to_usd(tmp_path) -> None:
+ account = futu_sdk._account_to_dict(
+ {
+ "total_assets": "1600",
+ "cash": "800",
+ "market_val": "800",
+ "currency": "HKD",
+ }
+ )
+ position = futu_sdk._position_to_dict(
+ {
+ "code": "HK.SYNTH",
+ "qty": "100",
+ "cost_price": "10",
+ "market_val": "800",
+ "pl_val": "-200",
+ "position_market": "HK",
+ "currency": "HKD",
+ }
+ )
+
+ snapshot = _service(tmp_path, account, position).refresh()
+ holding = snapshot["positions"][0]
+
+ assert holding["symbol"] == "HK.SYNTH"
+ assert holding["market"] == "HK"
+ assert holding["currency"] == "HKD"
+ assert holding["price_currency"] == "HKD"
+ assert holding["market_value_usd"] == pytest.approx(100.0)
+ assert holding["market_value_cny"] == pytest.approx(700.0)
+ assert holding["unrealized_pnl_usd"] == pytest.approx(-25.0)
+ assert snapshot["totals"]["usd"] == pytest.approx(200.0)
+ assert snapshot["totals"]["cny"] == pytest.approx(1400.0)
+
+
+def test_futu_hk_prefix_infers_hkd_when_currency_is_missing() -> None:
+ row = normalize_position(
+ "futu",
+ {
+ "code": "HK.SYNTH",
+ "qty": 100,
+ "cost_price": 10,
+ "market_val": 800,
+ },
+ )
+
+ assert row["currency"] == "HKD"
+ assert row["price_currency"] == "HKD"
+
+
+def test_non_futu_hk_market_without_currency_keeps_usd_fallback() -> None:
+ row = normalize_position(
+ "examplebroker",
+ {
+ "symbol": "SYNTHETIC",
+ "market": "HK",
+ "quantity": 2,
+ "market_price": 10,
+ },
+ )
+
+ assert row["currency"] == "USD"
+ assert row["price_currency"] == "USD"
+
+
+def test_legacy_valuation_snapshots_do_not_mix_with_current_history(tmp_path) -> None:
+ store = PortfolioStore(tmp_path / "portfolio.sqlite3")
+ store.save_snapshot(
+ {
+ "snapshot_id": "legacy-v1",
+ "created_at": "1999-12-31T23:00:00+00:00",
+ "complete": True,
+ "totals": {"usd": 1600.0, "cny": 11200.0},
+ "accounts": [
+ {
+ "source_id": "futu-test",
+ "broker": "futu",
+ "status": "ok",
+ }
+ ],
+ "positions": [],
+ }
+ )
+ account = futu_sdk._account_to_dict(
+ {"total_assets": "1600", "cash": "800", "currency": "HKD"}
+ )
+ position = futu_sdk._position_to_dict(
+ {
+ "code": "HK.SYNTH",
+ "qty": "100",
+ "cost_price": "10",
+ "market_val": "800",
+ "position_market": "HK",
+ "currency": "HKD",
+ }
+ )
+ service = _service(tmp_path, account, position)
+
+ assert service.latest() is None
+
+ current = service.refresh()
+
+ assert current["valuation_version"] == 2
+ assert [row["id"] for row in service.history()] == [current["snapshot_id"]]
+ assert [row["id"] for row in store.history()] == [
+ "legacy-v1",
+ current["snapshot_id"],
+ ]