Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(portfolio): convert valuation through rates map

zeus229c85a2d75785f
diff --git a/agent/src/portfolio/normalization.py b/agent/src/portfolio/normalization.py
index ac53c8b67..2d37ebe2e 100644
--- a/agent/src/portfolio/normalization.py
+++ b/agent/src/portfolio/normalization.py
@@ -21,6 +21,7 @@ from datetime import datetime, timezone
from decimal import Decimal, InvalidOperation
from typing import Any
+from src.portfolio.fx import Rates, from_usd, to_usd
from src.trading.types import TradingProfile
STABLECOINS = frozenset({"USDT", "USDC", "FDUSD", "TUSD", "BUSD"})
@@ -188,13 +189,14 @@ 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]:
+def value_position(row: dict[str, Any], *, rates: Rates) -> dict[str, Any]:
"""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.
+ rates: Currency units per USD used to convert non-USD rows. A row in a
+ valid ISO currency without a rate fails closed here instead of
+ being priced as USD.
Returns:
The same row, with ``priced``, ``market_value_usd``,
@@ -204,26 +206,21 @@ def value_position(row: dict[str, Any], *, usd_hkd: Decimal, usd_cny: Decimal) -
price = _decimal(row.get("market_price"))
quantity = _decimal(row.get("quantity"))
currency = str(row.get("price_currency") or row.get("currency") or "USD").upper()
- fx_to_usd = Decimal("1")
- if currency == "HKD":
- fx_to_usd = Decimal("1") / usd_hkd
- elif currency == "CNY":
- fx_to_usd = Decimal("1") / usd_cny
priced = price > 0
- market_usd = quantity * price * fx_to_usd if priced else Decimal("0")
+ market_usd = to_usd(quantity * price, currency, rates) if priced else Decimal("0")
cost = _decimal(row.get("cost_price"))
source_pnl = row.get("source_unrealized_pnl")
pnl_usd = (
- _decimal(source_pnl) * fx_to_usd
+ to_usd(_decimal(source_pnl), currency, rates)
if priced and source_pnl is not None
- else (price - cost) * quantity * fx_to_usd
+ else to_usd((price - cost) * quantity, currency, rates)
if priced and cost > 0
else None
)
row.update(
priced=priced,
market_value_usd=_number(market_usd),
- market_value_cny=_number(market_usd * usd_cny),
+ market_value_cny=_number(from_usd(market_usd, "CNY", rates)),
unrealized_pnl_usd=_number(pnl_usd) if pnl_usd is not None else None,
)
for key in (
@@ -237,19 +234,14 @@ def value_position(row: dict[str, Any], *, usd_hkd: Decimal, usd_cny: Decimal) -
return row
-def _to_usd(value: Decimal, currency: str, usd_hkd: Decimal, usd_cny: Decimal) -> Decimal:
- if currency == "HKD":
- return value / usd_hkd
- if currency == "CNY":
- return value / usd_cny
- return value
+def _to_usd(value: Decimal, currency: str, rates: Rates) -> Decimal:
+ return to_usd(value, currency, rates)
def account_total_usd(
broker: str,
account: dict[str, Any],
- usd_hkd: Decimal,
- usd_cny: Decimal,
+ rates: Rates,
fallback: Decimal = Decimal("0"),
) -> Decimal:
"""Extract a connector-reported net liquidation value.
@@ -257,8 +249,7 @@ def account_total_usd(
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.
+ rates: Currency units per USD for non-USD balances.
fallback: Value returned when the connector reports no total, so a
missing figure never silently becomes zero.
@@ -271,8 +262,7 @@ def account_total_usd(
total += _to_usd(
_decimal(row.get("net_assets")),
str(row.get("currency") or "USD").upper(),
- usd_hkd,
- usd_cny,
+ rates,
)
return total
if broker == "ibkr":
@@ -284,7 +274,7 @@ def account_total_usd(
if "USD" in candidates:
return candidates["USD"]
return sum(
- (_to_usd(value, currency, usd_hkd, usd_cny) for currency, value in candidates.items()),
+ (_to_usd(value, currency, rates) for currency, value in candidates.items()),
Decimal("0"),
)
nested = account.get("account") if isinstance(account.get("account"), dict) else {}
@@ -292,22 +282,21 @@ def account_total_usd(
for key in ("portfolio_value", "total_equity", "equity"):
value = _decimal(nested.get(key))
if value > 0:
- return _to_usd(value, currency, usd_hkd, usd_cny)
+ return _to_usd(value, currency, rates)
total = Decimal("0")
for row in account.get("assets", []):
value = _decimal(row.get("net_liquidation", row.get("total_assets", row.get("equity"))))
- total += _to_usd(value, str(row.get("currency") or currency).upper(), usd_hkd, usd_cny)
+ total += _to_usd(value, str(row.get("currency") or currency).upper(), rates)
return total if total > 0 else fallback
-def account_cash_usd(broker: str, account: dict[str, Any], usd_hkd: Decimal, usd_cny: Decimal) -> Decimal:
+def account_cash_usd(broker: str, account: dict[str, Any], rates: Rates) -> Decimal:
"""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.
+ rates: Currency units per USD for non-USD balances.
Returns:
Cash in USD, never negative and never inferred from an unpriced
@@ -322,8 +311,7 @@ def account_cash_usd(broker: str, account: dict[str, Any], usd_hkd: Decimal, usd
_to_usd(
_decimal(row.get("total_cash")),
str(row.get("currency") or "USD").upper(),
- usd_hkd,
- usd_cny,
+ rates,
)
for row in rows
),
@@ -341,7 +329,7 @@ def account_cash_usd(broker: str, account: dict[str, Any], usd_hkd: Decimal, usd
return max(
Decimal("0"),
sum(
- (_to_usd(value, currency, usd_hkd, usd_cny) for currency, value in candidates.items()),
+ (_to_usd(value, currency, rates) for currency, value in candidates.items()),
Decimal("0"),
),
)
@@ -349,7 +337,7 @@ def account_cash_usd(broker: str, account: dict[str, Any], usd_hkd: Decimal, usd
currency = str(nested.get("currency") or "USD").upper()
nested_cash = _decimal(nested.get("cash"))
if nested_cash > 0:
- return _to_usd(nested_cash, currency, usd_hkd, usd_cny)
+ return _to_usd(nested_cash, currency, rates)
return max(
Decimal("0"),
sum(
@@ -357,8 +345,7 @@ def account_cash_usd(broker: str, account: dict[str, Any], usd_hkd: Decimal, usd
_to_usd(
_decimal(row.get("cash", row.get("cash_balance"))),
str(row.get("currency") or currency).upper(),
- usd_hkd,
- usd_cny,
+ rates,
)
for row in account.get("assets", [])
),