Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix: complete review repairs for the ten integrated PRs

Haozhe Wu5cf5291e0a39
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5b4f2ae27..bcf1ea3d3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,36 @@ This project adheres to [Semantic Versioning](https://semver.org/).
### Fixed
+- **Global futures routing and pricing**: digit-bearing contracts such as
+ `M2K=F` and `6EZ2026.CME`, including `local:` inputs, reach the global
+ futures engine with their full product code. OJ and ZR use quote-unit
+ multipliers of 150 and 2,000; MYM and M2K use the existing micro-contract
+ commission convention. Missing pricing-table entries are recorded in run
+ diagnostics instead of silently appearing to be verified prices (#1965,
+ #1966, #1968).
+- **Longbridge cash disclosures** now preserve each currency's available,
+ withdrawable, frozen and settling cash, plus reported financing limits,
+ through account reads, Portfolio snapshots, the CLI, API, agent context and
+ the Web account card. Negative balances and unavailable values remain
+ distinct (#1940).
+- **Portfolio errors** redact credential-bearing URLs and error text on
+ refresh, progress and historical snapshot reads. Binance's regional HTTP
+ 451 restriction has an explicit, localized explanation (#1937).
+- **Audit rotation** verifies the complete segmented chain on repeated
+ rotations, allocates archive numbers past gaps and four-digit counters,
+ and refuses to overwrite an existing archive (#1962).
+- **Research data quality**: a single IC observation has no sample standard
+ deviation; repeated decimal grouping is accepted only with valid digit
+ groups, preserving explicit separator choices and refusing malformed
+ amounts (#1963, #1964).
+- **Weixin attachments** use exclusively created local files so repeated
+ names, identical URLs and concurrent downloads cannot overwrite earlier
+ attachments (#1967).
+- **MiniMax Flash** is the default for direct MiniMax endpoints, with
+ reasoning history retained across tool calls. Official gateway model
+ lists prefer discovered current routes while keeping paid variants and
+ other available models selectable (#1936).
+
- **A retried provider error no longer halts live model decisions for the
day**. 0.1.18 announced every failed stream, compaction call or cancelled
response that reported no usage as missing usage, which the live decision
diff --git a/README.md b/README.md
index a47faa2e8..a52987003 100644
--- a/README.md
+++ b/README.md
@@ -1045,7 +1045,7 @@ vibe-trading-mcp # start MCP server (stdio)
> **Supported LLM providers:** OpenRouter, OpenAI, Anthropic (native Messages API), DeepSeek, OpenCode (Go / Zen), Gemini, Groq, DashScope/Qwen, Zhipu, Moonshot/Kimi, MiniMax, SiliconFlow (CN + Global), Xiaomi MIMO, Novita AI, iFlytek Spark, Z.ai, NVIDIA NIM, ModelScope, GitHub Copilot, Claude Code CLI, Ollama (local). When no `*_BASE_URL` is set, each provider falls back to its canonical endpoint, so just a key is enough. See `.env.example` for config.
-MiniMax onboarding defaults to `MiniMax-M3.1-Flash`, with `MiniMax-M3` as the alternative in Settings. Both the global and China API endpoints are supported. Saved model IDs and custom endpoints remain editable; the ordinary model list hides older MiniMax text suggestions. MiniMax uses the API's default thinking depth, and Flash's reasoning is preserved across tool turns.
+MiniMax onboarding defaults to `MiniMax-M3.1-Flash`, with `MiniMax-M3` as the alternative in Settings. Both the global and China API endpoints are supported. Saved model IDs and custom endpoints remain editable; official MiniMax endpoints suggest the current pair, while gateways retain every discovered route, including paid variants. MiniMax uses the API's default thinking depth, and Flash's reasoning is preserved across tool turns.
> **Tip:** All markets work without any API keys thanks to automatic fallback. yfinance/Yahoo (HK/US/Canada/UK), OKX (crypto), and AKShare (A-shares, US, HK, futures, forex) are all free. LSE `.L` quotes must declare GBP or GBp so pence can be normalized before GBP accounting. Tushare token is optional; tencent, baostock and AKShare are the no-token A-share fallbacks.
diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.py
index aed18027d..2b519f4c2 100644
--- a/agent/backtest/engines/_market_hooks.py
+++ b/agent/backtest/engines/_market_hooks.py
@@ -151,24 +151,25 @@ _MARKET_PATTERNS = [
),
"futures",
),
- # Global futures: product+month-code (e.g. ESZ4, CLF25, GCM2025)
- (re.compile(r"^[A-Z]{2,4}[FGHJKMNQUVXZ]\d{1,2}$", re.I), "futures"),
+ # Global futures: product+month-code, including digit-bearing products
+ # (ESZ4, CLF25, GCM2025, M2KZ4, 6EZ2026). Pure numeric ids stay excluded.
+ (re.compile(r"^(?:[A-Z][A-Z0-9]{1,4}|[0-9][A-Z][A-Z0-9]{0,3})[FGHJKMNQUVXZ]\d{1,4}$", re.I), "futures"),
# Global futures: product+YYMM (e.g. CL2412, ES2503)
- (re.compile(r"^[A-Z]{2,4}\d{4}$", re.I), "futures"),
+ (re.compile(r"^(?:[A-Z][A-Z0-9]{1,4}|[0-9][A-Z][A-Z0-9]{0,3})\d{4}$", re.I), "futures"),
# Global futures: bare product code with exchange (e.g. ES.CME)
- (re.compile(r"^[A-Z]{2,4}\.(CME|CBOT|NYMEX|COMEX|ICE|EUREX)$", re.I), "futures"),
+ (re.compile(r"^(?:[A-Z][A-Z0-9]{0,4}|[0-9][A-Z][A-Z0-9]{0,3})\.(CME|CBOT|NYMEX|COMEX|ICE|EUREX)$", re.I), "futures"),
# Global futures: dated contract carrying its venue (ESZ4.CME, CL2412.NYMEX,
# GCM2025.COMEX). The bare dated forms above matched, and the continuous
# form with a venue matched, but the combination fell through every pattern
# to the a_share default below — a USD contract then priced in CNY under
# T+1 with no shorting. Same class as #1394 on the global side. The product
- # width opens to {1,4} here (not on the bare forms) because a recognized
+ # width includes single-letter products here (not on the bare forms): a recognized
# futures venue already proves the class: CBOT lists single-letter grains
- # (C, S, W, O), which ``^[A-Z]{2,4}\d{4}$`` cannot express without also
+ # (C, S, W, O), which a two-character minimum cannot express without also
# claiming bare codes it has no venue to justify.
(
re.compile(
- r"^[A-Z]{1,4}(?:[FGHJKMNQUVXZ]\d{1,2}|\d{4})\.(CME|CBOT|NYMEX|COMEX|ICE|EUREX)$",
+ r"^(?:[A-Z][A-Z0-9]{0,4}|[0-9][A-Z][A-Z0-9]{0,3})(?:[FGHJKMNQUVXZ]\d{1,4}|\d{4})\.(CME|CBOT|NYMEX|COMEX|ICE|EUREX)$",
re.I,
),
"futures",
@@ -195,7 +196,7 @@ _MARKET_PATTERNS = [
# 6-character pairs, so narrowing it to {6} would drop shorter forms
# already covered here for no gain.
(re.compile(r"^[A-Z]{3,6}=X$", re.I), "forex"),
- (re.compile(r"^[A-Z]{2,5}=F$", re.I), "futures"),
+ (re.compile(r"^(?:[A-Z][A-Z0-9]{0,4}|[0-9][A-Z][A-Z0-9]{0,3})=F$", re.I), "futures"),
# Bare 6-character precious-metal / FX symbols (``XAUUSD``, ``XAGUSD``,
# ``XPTUSD``, ``XPDUSD``, ``EURUSD``, ``GBPUSD``, ``USDJPY``, ``USDCHF``,
# ``AUDUSD``, ``NZDUSD``, ``USDCAD``). Whitelist-restricted to a small
@@ -401,7 +402,9 @@ def _is_china_futures(code: str) -> bool:
# collide with a CN product (e.g. ``M2412.CBOT`` — US soybean meal).
return _EXCHANGE_ALIASES.get(parts[1], parts[1]) in _CHINA_EXCHANGES
# Bare code (no exchange suffix): fall back to product-code heuristic.
- m = re.match(r"([A-Za-z]+)\d+", parts[0])
+ # Match the whole Chinese delivery code: M2K and M6E begin with the
+ # Chinese soybean-meal product M but are not M contracts.
+ m = re.fullmatch(r"([A-Za-z]+)\d+", parts[0])
if m:
product = m.group(1).lower()
if product in _CN_FUTURES_PRODUCTS:
diff --git a/agent/backtest/engines/global_futures.py b/agent/backtest/engines/global_futures.py
index 645627edb..803d94eb5 100644
--- a/agent/backtest/engines/global_futures.py
+++ b/agent/backtest/engines/global_futures.py
@@ -19,6 +19,7 @@ from typing import Any, Dict, Mapping, TypeVar
import pandas as pd
from backtest.engines.china_a import _blocked_by_limit
+from backtest.engines._market_hooks import strip_local_prefix
from backtest.engines.futures_base import FuturesBaseEngine
logger = logging.getLogger(__name__)
@@ -160,7 +161,11 @@ def _extract_product(symbol: str) -> str:
Returns:
Product code (e.g. 'ES', 'CL', 'GC', '6E', 'M2K').
"""
- code = symbol.split(".")[0].upper()
+ code = strip_local_prefix(symbol).split(".")[0].upper()
+ if code.endswith("=F"):
+ # Yahoo's explicit continuous-contract suffix already identifies the
+ # complete product, including digit-bearing names such as M2K/M6E.
+ return code[:-2]
if code in _KNOWN_PRODUCTS:
return code
@@ -170,18 +175,18 @@ def _extract_product(symbol: str) -> str:
return listed
# Pattern 1: product + month-code + year (ESZ4, CLF25, GCM2025, 6EZ4)
- m = re.match(r"(\d[A-Z]|[A-Z]{2,4})([FGHJKMNQUVXZ])(\d{1,4})$", code)
+ m = re.match(r"([A-Z0-9]{1,5})([FGHJKMNQUVXZ])(\d{1,4})$", code)
if m:
return m.group(1)
# Pattern 2: product + YYMM (NQ2503, CL2412, 6EH25)
- m = re.match(r"(\d?[A-Z]+)(\d{4})$", code)
+ m = re.match(r"([A-Z0-9]{1,5})(\d{4})$", code)
if m:
return m.group(1)
# Pattern 3: bare product or fallback
- m = re.match(r"(\d?[A-Z]+)", code)
- return m.group(1) if m else code
+ m = re.fullmatch(r"[A-Z0-9]{1,5}", code)
+ return m.group(0) if m else code
class GlobalFuturesEngine(FuturesBaseEngine):
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index d7bd01518..a7978dc59 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -4217,6 +4217,9 @@ def _print_portfolio_snapshot(snapshot: dict[str, Any]) -> None:
)
console.print(accounts)
for row in snapshot.get("accounts", []):
+ if row.get("status") == "ok" and row.get("balance_details"):
+ console.print(rich_escape(str(row.get("label") or row.get("broker") or "")))
+ _print_balance_details(row["balance_details"])
if row.get("import_metadata"):
meta = row["import_metadata"]
console.print(f"extraETF file mtime: {rich_escape(meta['source_mtime'])}; expires: {rich_escape(meta['expires_at'])}; holdings only, no cash")
@@ -4751,9 +4754,37 @@ def _print_connector_balances(result: dict[str, Any]) -> int:
cell(row.get("maintenance_margin")),
)
console.print(table)
+ _print_balance_details(rows)
return EXIT_SUCCESS
+def _print_balance_details(rows: list[dict[str, Any]]) -> None:
+ """Print broker cash legs and financing in each reported currency.
+
+ Args:
+ rows: Balance rows from a connector or a saved portfolio snapshot.
+ """
+ cell = lambda value: "—" if value is None else rich_escape(str(value)) # noqa: E731
+ for row in rows:
+ if not row.get("cash_infos") and all(row.get(key) is None for key in (
+ "max_finance_amount", "remaining_finance_amount"
+ )):
+ continue
+ currency = cell(row.get("currency"))
+ console.print(f"Cash and financing · {currency}")
+ console.print(f"Financing limit: {cell(row.get('max_finance_amount'))} {currency}; "
+ f"Remaining financing: {cell(row.get('remaining_finance_amount'))} {currency}")
+ table = Table(box=box.SIMPLE_HEAVY)
+ for name in ("Currency", "Available", "Withdrawable", "Frozen", "Settling"):
+ table.add_column(name)
+ for cash in row.get("cash_infos") or []:
+ table.add_row(*(cell(cash.get(key)) for key in (
+ "currency", "available_cash", "withdraw_cash", "frozen_cash", "settling_cash"
+ )))
+ if table.row_count:
+ console.print(table)
+
+
def _print_connector_assets(result: dict[str, Any]) -> int:
"""Render Futu's per-currency ``assets`` rows from ``accinfo_query``."""
cell = lambda v: "" if v is None else str(v) # noqa: E731
diff --git a/agent/src/api/settings_routes.py b/agent/src/api/settings_routes.py
index ba39196b8..6bf9aaf41 100644
--- a/agent/src/api/settings_routes.py
+++ b/agent/src/api/settings_routes.py
@@ -365,31 +365,12 @@ async def _list_provider_models(
warning_code="model_list_unavailable",
)
- # Curate only known gateway text namespaces at their official endpoints.
- # Never invent availability: retain current routes only when discovery returned them.
- gateway_choices = {
- ("openrouter", "https://openrouter.ai/api/v1"): (
- "minimax/minimax-", ["minimax/minimax-m3.1-flash:free", "minimax/minimax-m3"]
- ),
- ("opencode", "https://opencode.ai/zen/v1"): (
- "minimax-", ["minimax-m3.1-flash-free", "minimax-m3"]
- ),
- ("opencode", "https://opencode.ai/zen/go/v1"): (
- "minimax-", ["minimax-m3.1-flash-free", "minimax-m3"]
- ),
- }
- if choices := gateway_choices.get((provider.name, base_url.rstrip("/"))):
- prefix, current = choices
- text_models = []
- for model in models:
- suffix = model.removeprefix(prefix).lower() if model.startswith(prefix) else ""
- if suffix == "01" or (suffix.startswith("m") and suffix[1:2].isdigit()):
- text_models.append(model)
- if text_models:
- first = models.index(text_models[0])
- remaining = [model for model in models if model not in text_models]
- remaining[first:first] = [model for model in current if model in models]
- models = remaining
+ # Prefer configured recommendations without deleting discovered routes.
+ # Paid variants, legacy models and future releases remain selectable.
+ official_endpoints = {provider.default_base_url, *provider.base_url_options}
+ if base_url.rstrip("/") in official_endpoints:
+ preferred = [model for model in provider.model_options if model in models]
+ models = preferred + [model for model in models if model not in preferred]
discovered = bool(models)
if provider.default_model not in models:
diff --git a/agent/src/channels/weixin.py b/agent/src/channels/weixin.py
index e98e601e5..1c6cbb732 100644
--- a/agent/src/channels/weixin.py
+++ b/agent/src/channels/weixin.py
@@ -16,6 +16,7 @@ import json
import os
import random
import re
+import tempfile
import time
import uuid
from collections import OrderedDict
@@ -914,22 +915,22 @@ class WeixinChannel(BaseChannel):
media_dir = get_media_dir("weixin")
ext = _ext_for_type(media_type)
- # Always make the on-disk name unique, even when the sender
- # supplied a filename (ITEM_FILE): two different messages can
- # share the same original filename (e.g. repeated "report.pdf"),
- # and without a unique stem the second download silently
- # overwrites the first on disk, corrupting any earlier
- # conversation turn that already referenced that path.
- ts = int(time.time())
- hash_seed = encrypt_query_param or full_url
- h = abs(hash(hash_seed)) % 100000
if filename:
stem, orig_ext = os.path.splitext(os.path.basename(filename))
- safe_name = f"{stem}_{ts}_{h}{orig_ext or ext}"
else:
- safe_name = f"{media_type}_{ts}_{h}{ext}"
- file_path = media_dir / safe_name
- file_path.write_bytes(data)
+ stem, orig_ext = media_type, ext
+ # Exclusive creation also protects same-second retries and hash
+ # collisions; time plus a truncated URL hash is not unique.
+ with tempfile.NamedTemporaryFile(
+ dir=media_dir, prefix=f"{stem[:32]}_", suffix=orig_ext or ext, delete=False
+ ) as downloaded:
+ file_path = Path(downloaded.name)
+ try:
+ downloaded.write(data)
+ except Exception:
+ downloaded.close()
+ file_path.unlink(missing_ok=True)
+ raise
return str(file_path)
except Exception:
diff --git a/agent/src/entities/ingest.py b/agent/src/entities/ingest.py
index 28c60bc45..9cc5272cb 100644
--- a/agent/src/entities/ingest.py
+++ b/agent/src/entities/ingest.py
@@ -24,6 +24,7 @@ from __future__ import annotations
import csv
import logging
import math
+import re
from dataclasses import dataclass, field
from datetime import date, datetime
from pathlib import Path
@@ -135,6 +136,35 @@ def _resolve_columns(
return resolved
+def _ungroup_number(text: str, grouping: str, decimal: str | None = None) -> str:
+ """Normalize declared grouping only when every digit group is valid.
+
+ Args:
+ text: Signed numeric text, optionally with a scientific exponent.
+ grouping: Group separator to remove.
+ decimal: Decimal separator, or None for a grouped integer.
+
+ Returns:
+ Numeric text using a dot decimal separator and no grouping.
+
+ Raises:
+ ValueError: Group widths are malformed or grouping occurs in a fraction.
+ """
+ parts = re.split(r"([eE][+-]?\d+)$", text, maxsplit=1)
+ mantissa = parts[0]
+ integer, separator, fraction = mantissa.partition(decimal) if decimal else (mantissa, "", "")
+ if grouping in fraction:
+ raise ValueError(f"{text!r} has digit grouping in its fractional part")
+ if grouping in integer:
+ escaped = re.escape(grouping)
+ # Western groups of three, or Indian groups of two ending in three.
+ pattern = rf"[+-]?(?:\d{{1,3}}(?:{escaped}\d{{3}})+|\d{{1,2}}(?:{escaped}\d{{2}})+{escaped}\d{{3}})"
+ if re.fullmatch(pattern, integer) is None:
+ raise ValueError(f"{text!r} has malformed digit grouping")
+ normalized = integer.replace(grouping, "") + ("." + fraction if separator else "")
+ return normalized + (parts[1] if len(parts) > 1 else "")
+
+
def _to_plain_number(text: str, decimal_separator: str | None) -> str:
"""Reduce a grouped decimal string to a form ``float`` accepts.
@@ -146,9 +176,8 @@ def _to_plain_number(text: str, decimal_separator: str | None) -> str:
Returns:
The same number using ``.`` as the decimal separator and no grouping.
- A separator that appears twice or more is always digit grouping: a number
- carries at most one decimal separator, so ``"1,234,567"`` and
- ``"1.234.567"`` are both 1234567 whichever locale wrote them.
+ Repeated separators identify grouping only when the digit groups are valid;
+ malformed amounts are rejected rather than silently concatenated.
Raises:
ValueError: If the value uses a single comma whose role cannot be
@@ -160,20 +189,20 @@ def _to_plain_number(text: str, decimal_separator: str | None) -> str:
"""
if decimal_separator is not None:
grouping = "," if decimal_separator == "." else "."
- return text.replace(grouping, "").replace(decimal_separator, ".")
+ return _ungroup_number(text, grouping, decimal_separator)
has_dot = "." in text
has_comma = "," in text
if has_dot and has_comma:
# The rightmost separator is the decimal one; the other groups digits.
if text.rindex(".") > text.rindex(","):
- return text.replace(",", "")
- return text.replace(".", "").replace(",", ".")
+ return _ungroup_number(text, ",", ".")
+ return _ungroup_number(text, ".", ",")
if has_dot and text.count(".") > 1:
- return text.replace(".", "") # 1.234.567 cannot be a decimal point
+ return _ungroup_number(text, ".")
if has_comma:
if text.count(",") > 1:
- return text.replace(",", "") # 1,234,567 cannot be a decimal comma
+ return _ungroup_number(text, ",")
raise ValueError(
f"{text!r} uses a single comma and could be either "
f"{text.replace(',', '')} (comma groups thousands) or "
diff --git a/agent/src/governance/ledger.py b/agent/src/governance/ledger.py
index 03bfc31ba..420af028e 100644
--- a/agent/src/governance/ledger.py
+++ b/agent/src/governance/ledger.py
@@ -53,6 +53,7 @@ import hashlib
import json
import logging
import os
+import re
from dataclasses import dataclass
from pathlib import Path
from typing import Any, BinaryIO, Iterable, Iterator, Mapping
@@ -605,10 +606,16 @@ def archive_segments(path: Path) -> list[Path]:
path: Active ledger path, e.g. ``.../audit_chain.jsonl``.
Returns:
- Sorted archive paths. Sorting is lexicographic over a zero-padded
- counter, which is why the counter is padded.
+ Archive paths in numeric counter order, including counters wider than
+ the minimum padding after segment 9999.
"""
- return sorted(path.parent.glob(f"{path.stem}.[0-9]" + "[0-9]" * (ARCHIVE_SUFFIX_WIDTH - 1) + path.suffix))
+ pattern = re.compile(rf"{re.escape(path.stem)}\.(\d{{{ARCHIVE_SUFFIX_WIDTH},}}){re.escape(path.suffix)}")
+ numbered = []
+ for candidate in path.parent.iterdir() if path.parent.exists() else ():
+ match = pattern.fullmatch(candidate.name)
+ if match:
+ numbered.append((int(match[1]), candidate))
+ return [candidate for _, candidate in sorted(numbered)]
def rotate_if_needed(
@@ -635,7 +642,7 @@ def rotate_if_needed(
Args:
path: Active ledger path.
max_bytes: Size at or above which the active file is sealed.
- fsync: Whether to fsync the directory after the rename.
+ fsync: Whether to fsync the directory after sealing the segment.
Returns:
The archive path when a rotation happened, else None.
@@ -660,9 +667,14 @@ def rotate_if_needed(
if not result.ok:
raise LedgerCorruptionError(result.first_break)
- counter = len(archive_segments(path)) + 1
+ segments = archive_segments(path)
+ counter = int(segments[-1].stem.rsplit(".", 1)[1]) + 1 if segments else 1
archive = path.with_name(f"{path.stem}.{counter:0{ARCHIVE_SUFFIX_WIDTH}d}{path.suffix}")
- path.rename(archive)
+ # link() fails atomically if the destination exists; rename() can replace
+ # a sealed segment on POSIX. A crash between link and unlink retains both
+ # copies and is detected as a duplicate sequence rather than losing data.
+ os.link(path, archive)
+ path.unlink()
if fsync:
_fsync_dir(path.parent)
return archive
diff --git a/agent/src/portfolio/normalization.py b/agent/src/portfolio/normalization.py
index df30a26c6..b0cc68ebb 100644
--- a/agent/src/portfolio/normalization.py
+++ b/agent/src/portfolio/normalization.py
@@ -297,6 +297,43 @@ def account_total_usd(
return total if total > 0 else fallback
+def account_balance_details(broker: str, account: dict[str, Any]) -> list[dict[str, Any]]:
+ """Expose reported cash legs and financing without adding them to totals.
+
+ Args:
+ broker: Connector whose balance schema is being read.
+ account: Connector-reported account payload.
+
+ Returns:
+ Balance disclosures in their original currencies; unavailable amounts
+ remain None, and negative balances retain their sign.
+ """
+ if broker != "longbridge":
+ return []
+
+ def amount(value: Any) -> float | None:
+ parsed = _decimal(value, Decimal("NaN"))
+ return float(parsed) if parsed.is_finite() else None
+
+ details = []
+ for row in account.get("balances", []):
+ details.append({
+ "currency": row.get("currency"),
+ "max_finance_amount": amount(row.get("max_finance_amount")),
+ "remaining_finance_amount": amount(row.get("remaining_finance_amount")),
+ "cash_infos": [
+ {
+ "currency": cash.get("currency"),
+ **{key: amount(cash.get(key)) for key in (
+ "available_cash", "withdraw_cash", "frozen_cash", "settling_cash"
+ )},
+ }
+ for cash in row.get("cash_infos") or []
+ ],
+ })
+ return details
+
+
def account_cash_usd(broker: str, account: dict[str, Any], rates: Rates) -> Decimal:
"""Return broker-reported cash without guessing from missing quotes.
diff --git a/agent/src/portfolio/service.py b/agent/src/portfolio/service.py
index 2a0cd76e8..8911c64f0 100644
--- a/agent/src/portfolio/service.py
+++ b/agent/src/portfolio/service.py
@@ -28,6 +28,7 @@ from src.portfolio.compatibility import (
from src.portfolio.fx import FxQuote, Rates, build_rates, from_usd
from src.portfolio.normalization import (
STABLECOINS,
+ account_balance_details,
account_cash_usd,
account_total_usd,
auth_metadata,
@@ -35,6 +36,7 @@ from src.portfolio.normalization import (
value_position,
)
from src.portfolio.store import PortfolioStore
+from src.tools.redaction import redact_text
from src.trading.connections import requires_account_selection
from src.trading.profiles import profile_by_id
from src.trading.types import TradingProfile
@@ -85,7 +87,8 @@ _AUTH_REQUIRED_MARKERS = (
_REDACT_URL_QUERY = re.compile(r"(?i)(https?://[^\s?#]+)\?[^\s#]+")
_REDACT_SECRET_PARAMETER = re.compile(
- r"(?i)\b(signature|api[_-]?key|secret)=([^&\s]+)"
+ r"""(?i)(["']?\b(?:signature|api[_-]?key|secret)["']?\s*[:=]\s*)"""
+ r"""(?:\[redacted\]|"[^"]*"|'[^']*'|[^&\s,}\]]+)"""
)
@@ -108,8 +111,9 @@ def _portfolio_error_details(
"Confirm Binance is available for your region and that your account uses its supported API endpoint.",
)
- message = _REDACT_URL_QUERY.sub(r"\1?<query redacted>", message)
- message = _REDACT_SECRET_PARAMETER.sub(r"\1=<redacted>", message)
+ message = redact_text(message)
+ message = _REDACT_URL_QUERY.sub(r"\1?<redacted-query>", message)
+ message = _REDACT_SECRET_PARAMETER.sub(r"\1<redacted>", message)
return default_code, message[:300]
@@ -403,6 +407,7 @@ class PortfolioService:
priced_count = sum(
1 for row in broker_positions if row.get("priced")
)
+ balance_details = account_balance_details(broker, result["account"])
except Exception as exc:
error_code, error = _portfolio_error_details(
exc,
@@ -442,6 +447,7 @@ class PortfolioService:
),
"priced_value_usd": _number(priced_total),
"cash_usd": _number(cash_total),
+ "balance_details": balance_details,
"unpriced_or_other_usd": _number(unpriced_or_other),
"position_count": len(broker_positions),
"priced_position_count": priced_count,
@@ -790,6 +796,7 @@ class PortfolioService:
"asset_provider_type": row["broker"],
"status": row["status"],
"total_usd": row.get("total_usd"),
+ "balance_details": row.get("balance_details", []),
"source_kind": row.get("source_kind", "connection"),
"file_evidence": {
key: row["import_metadata"].get(key)
diff --git a/agent/src/providers/llm_providers.json b/agent/src/providers/llm_providers.json
index c3fb687ce..94208ba59 100644
--- a/agent/src/providers/llm_providers.json
+++ b/agent/src/providers/llm_providers.json
@@ -6,7 +6,12 @@
"base_url_env": "OPENROUTER_BASE_URL",
"default_model": "deepseek/deepseek-v4-pro",
"default_base_url": "https://openrouter.ai/api/v1",
- "api_key_required": true
+ "api_key_required": true,
+ "model_options": [
+ "minimax/minimax-m3.1-flash:free",
+ "minimax/minimax-m3.1-flash",
+ "minimax/minimax-m3"
+ ]
},
{
"name": "openai",
@@ -57,7 +62,12 @@
"https://opencode.ai/zen/go/v1",
"https://opencode.ai/zen/v1"
],
- "api_key_required": true
+ "api_key_required": true,
+ "model_options": [
+ "minimax-m3.1-flash-free",
+ "minimax-m3.1-flash",
+ "minimax-m3"
+ ]
},
{
"name": "siliconflow-cn",
diff --git a/agent/tests/test_entities_grouping_validation.py b/agent/tests/test_entities_grouping_validation.py
new file mode 100644
index 000000000..9a9aa12f6
--- /dev/null
+++ b/agent/tests/test_entities_grouping_validation.py
@@ -0,0 +1,40 @@
+"""Grouping inference must not turn malformed amounts into invented money."""
+
+import pytest
+
+from src.entities.ingest import CashFlowIngestError, load_cashflows
+
+
[email protected]("text", ["1..234", "1.23.45", "1.234.56", "1,,234", "1,23,45", "1,23,45.67"])
+def test_malformed_grouping_is_refused_by_file_ingestion(tmp_path, text):
+ path = tmp_path / "flows.csv"
+ path.write_text(f'date,amount,kind,currency\n2026-01-01,"{text}",coupon,EUR\n')
+ with pytest.raises(CashFlowIngestError, match="grouping"):
+ load_cashflows(path)
+
+
+ "text,separator,expected",
+ [
+ ("1.234.567", None, 1234567),
+ ("(1.234.567,89)", None, -1234567.89),
+ ("12,34,567.89", None, 1234567.89),
+ ("1.234.567e-3", None, 1234.567),
+ ("1,234", ".", 1234),
+ ("1,234", ",", 1.234),
+ ("1.234", ",", 1234),
+ ("1.234", ".", 1.234),
+ ],
+)
+def test_valid_grouping_and_explicit_ambiguity_resolution(tmp_path, text, separator, expected):
+ path = tmp_path / "flows.csv"
+ path.write_text(f'date,amount,kind,currency\n2026-01-01,"{text}",recallable_distribution,EUR\n')
+ assert load_cashflows(path, decimal_separator=separator)[0].amount == pytest.approx(expected)
+
+
[email protected]("text,separator", [("1,23,45", "."), ("1.23.45", ","), ("1,234.5,6", ".")])
+def test_declaring_decimal_does_not_authorize_malformed_grouping(tmp_path, text, separator):
+ path = tmp_path / "flows.csv"
+ path.write_text(f'date,amount,kind,currency\n2026-01-01,"{text}",coupon,EUR\n')
+ with pytest.raises(CashFlowIngestError, match="grouping"):
+ load_cashflows(path, decimal_separator=separator)
diff --git a/agent/tests/test_global_futures_digit_routing.py b/agent/tests/test_global_futures_digit_routing.py
new file mode 100644
index 000000000..a1713059a
--- /dev/null
+++ b/agent/tests/test_global_futures_digit_routing.py
@@ -0,0 +1,131 @@
+"""Digit-bearing contracts must reach the engine and its actual pricing tables."""
+
+from __future__ import annotations
+
+import pytest
+
+from backtest.engines._market_hooks import _detect_market, code_currency
+from backtest.engines.global_futures import GlobalFuturesEngine, _extract_product
+from backtest.runner import _create_market_engine
+
+
+ "symbol,product,multiplier,commission",
+ [
+ ("M2K=F", "M2K", 5, 0.62),
+ ("M2KZ4", "M2K", 5, 0.62),
+ ("M2K2503", "M2K", 5, 0.62),
+ ("M2K.CME", "M2K", 5, 0.62),
+ ("M2KZ2026.CME", "M2K", 5, 0.62),
+ ("6E=F", "6E", 125000, 2.25),
+ ("6EZ4", "6E", 125000, 2.25),
+ ("6E2503", "6E", 125000, 2.25),
+ ("6EZ2026.CME", "6E", 125000, 2.25),
+ ("MYM=F", "MYM", 0.5, 0.62),
+ ("OJ=F", "OJ", 150, 2.5),
+ ("ZR=F", "ZR", 2000, 2.5),
+ ],
+)
[email protected]("local", [False, True])
+def test_contract_reaches_runner_pricing(symbol, product, multiplier, commission, local):
+ symbol = f"local:{symbol.lower()}" if local else symbol
+ engine = _create_market_engine("local", {"codes": [symbol]}, [symbol])
+ assert isinstance(engine, GlobalFuturesEngine)
+ assert _detect_market(symbol) == "futures"
+ assert code_currency(symbol) == "USD"
+ assert _extract_product(symbol) == product
+ assert engine.get_contract_multiplier(symbol) == multiplier
+ engine._active_symbol = symbol
+ assert engine.calc_commission(2, 100, 1, True) == 2 * commission
+ assumptions = engine._engine_diagnostics().get("pricing_assumptions", [])
+ assert assumptions == (
+ [{"product": product, "field": "commission", "value": 2.5}] if product in {"OJ", "ZR"} else []
+ )
+
+
[email protected]("symbol", ["M6E=F", "M6EZ4", "M6EZ2026.CME"])
+def test_unlisted_digit_product_is_reported_without_invented_pricing(symbol):
+ engine = _create_market_engine("local", {}, [symbol])
+ assert isinstance(engine, GlobalFuturesEngine)
+ assert _extract_product(symbol) == "M6E"
+ engine.get_contract_multiplier(symbol)
+ assert engine._engine_diagnostics()["pricing_assumptions"] == [
+ {"product": "M6E", "field": "contract_multiplier", "value": 50}
+ ]
+
+
+ "symbol,market",
+ [
+ ("600519", "a_share"),
+ ("600519.SH", "a_share"),
+ ("123=F", "a_share"),
+ ("123Z4", "a_share"),
+ ("BTC-USDT", "crypto"),
+ ("EURUSD=X", "forex"),
+ ("BRK.B.US", "us_equity"),
+ ("IF2406.CFFEX", "futures"),
+ ("RB0", "futures"),
+ ],
+)
+def test_other_market_boundaries_are_preserved(symbol, market):
+ assert _detect_market(symbol) == market
+
+
+ "symbol,multiplier,fee",
+ [("M2K=F", 5, 0.62), ("6E=F", 125000, 2.25), ("OJ=F", 150, 2.5), ("ZR=F", 2000, 2.5), ("M6E=F", 50, 2.5)],
+)
+def test_local_csv_reaches_runner_and_persisted_trades(tmp_path, monkeypatch, symbol, multiplier, fee):
+ """Execute the public runner with real local data, signal loading and output."""
+ import json
+ import pandas as pd
+ import dotenv
+ import backtest.loaders.local_loader as local_loader
+ from backtest import runner
+
+ dates = pd.date_range("2026-01-01", periods=40, freq="B")
+ prices = tmp_path / "prices.csv"
+ pd.DataFrame({"date": dates, "open": 10.0, "high": 10.1, "low": 9.9, "close": 10.0, "volume": 1e9}).to_csv(
+ prices, index=False
+ )
+ bridge = tmp_path / "bridge.json"
+ bridge.write_text(json.dumps({"sources": [{"symbol": symbol, "type": "csv", "path": str(prices)}]}))
+ monkeypatch.setattr(local_loader, "_CONFIG_PATH", bridge)
+ monkeypatch.setattr(dotenv, "load_dotenv", lambda *args, **kwargs: False)
+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))
+ run = tmp_path / "run"
+ (run / "code").mkdir(parents=True)
+ (run / "code" / "signal_engine.py").write_text(
+ "import pandas as pd\nclass SignalEngine:\n"
+ " def generate(self, data_map):\n"
+ " return {code: pd.Series(1.0, index=frame.index) for code, frame in data_map.items()}\n"
+ )
+ (run / "config.json").write_text(
+ json.dumps(
+ {
+ "source": "local",
+ "codes": [f"local:{symbol}"],
+ "initial_cash": 10_000_000,
+ "start_date": str(dates[0].date()),
+ "end_date": str(dates[-1].date()),
+ "slippage": 0,
+ "leverage": 1,
+ }
+ )
+ )
+ runner.main(run)
+ trades = pd.read_csv(run / "artifacts" / "trades.csv")
+ assert not trades.empty
+ assert set(trades["code"]) == {symbol}
+ fills = [json.loads(line) for line in (run / "artifacts" / "fills.jsonl").read_text().splitlines()]
+ assert len(fills) == 2
+ for fill in fills:
+ quantity = abs(fill["signed_quantity"])
+ assert fill["fee"] / quantity == pytest.approx(fee)
+ assert fill["notional"] / (quantity * fill["execution_price"]) == multiplier
+ metrics = json.loads((run / "run_card.json").read_text())["structured_metrics"]
+ assumptions = metrics.get("pricing_assumptions", [])
+ assert (any(row["field"] == "contract_multiplier" for row in assumptions)) == (symbol == "M6E=F")
+ # A listed product must not silently take ES's multiplier of 50.
+ assert trades.iloc[0]["qty"] <= 10_000_000 / (10 * multiplier)
diff --git a/agent/tests/test_governance_rotation_boundaries.py b/agent/tests/test_governance_rotation_boundaries.py
new file mode 100644
index 000000000..b0de228a7
--- /dev/null
+++ b/agent/tests/test_governance_rotation_boundaries.py
@@ -0,0 +1,61 @@
+"""Rotation preserves sealed bytes and refuses corrupt historical segments."""
+
+import os
+
+import pytest
+
+from src.governance.ledger import (
+ LedgerCorruptionError,
+ append_record,
+ archive_segments,
+ rotate_if_needed,
+ verify_chain_with_archives,
+)
+
+
[email protected]("number", [2, 9999])
+def test_number_gaps_and_counter_width_do_not_overwrite_history(tmp_path, number):
+ path = tmp_path / "audit.jsonl"
+ append_record(path, {"value": 1})
+ first = rotate_if_needed(path, 1)
+ renamed = path.with_name(f"audit.{number:04d}.jsonl")
+ first.rename(renamed)
+ sealed = renamed.read_bytes()
+ append_record(path, {"value": 2})
+ second = rotate_if_needed(path, 1)
+ assert second.name == f"audit.{number + 1:04d}.jsonl"
+ assert renamed.read_bytes() == sealed
+ append_record(path, {"value": 3})
+ assert archive_segments(path) == [renamed, second]
+ result = verify_chain_with_archives(path)
+ assert result.ok and result.record_count == 3
+
+
+def test_rotation_refuses_corruption_in_sealed_history(tmp_path):
+ path = tmp_path / "audit.jsonl"
+ append_record(path, {"value": 1})
+ sealed = rotate_if_needed(path, 1)
+ append_record(path, {"value": 2})
+ sealed.write_text(sealed.read_text().replace('"value": 1', '"value": 9'))
+ active = path.read_bytes()
+ with pytest.raises(LedgerCorruptionError):
+ rotate_if_needed(path, 1)
+ assert path.read_bytes() == active
+ assert archive_segments(path) == [sealed]
+
+
+def test_racing_archive_destination_is_never_replaced(tmp_path, monkeypatch):
+ path = tmp_path / "audit.jsonl"
+ append_record(path, {"value": 1})
+ before = path.read_bytes()
+ link = os.link
+
+ def collision(source, destination):
+ destination.write_bytes(b"existing sealed bytes")
+ link(source, destination)
+
+ monkeypatch.setattr(os, "link", collision)
+ with pytest.raises(FileExistsError):
+ rotate_if_needed(path, 1)
+ assert path.read_bytes() == before
+ assert (tmp_path / "audit.0001.jsonl").read_bytes() == b"existing sealed bytes"
diff --git a/agent/tests/test_minimax_flash.py b/agent/tests/test_minimax_flash.py
index 940ea90a8..6dc029e74 100644
--- a/agent/tests/test_minimax_flash.py
+++ b/agent/tests/test_minimax_flash.py
@@ -288,7 +288,9 @@ def test_gateway_picker_preserves_other_models_and_custom_endpoints(
monkeypatch, provider_name, endpoint, prefix, flash, custom_endpoint
):
m3, legacy, media = prefix + "m3", prefix + "m2.7", prefix + "music"
- available = [m3, legacy, flash, "other/text-model", media]
+ paid_flash = prefix + "m3.1-flash"
+ future = prefix + "m4"
+ available = [m3, legacy, flash, paid_flash, future, "other/text-model", media]
client_type = httpx.AsyncClient
transport = httpx.MockTransport(
lambda request: httpx.Response(
@@ -308,10 +310,11 @@ def test_gateway_picker_preserves_other_models_and_custom_endpoints(
)
)
assert "other/text-model" in result.models and media in result.models
+ assert paid_flash in result.models and future in result.models
if custom_endpoint:
assert legacy in result.models
else:
- assert legacy not in result.models
+ assert legacy in result.models
assert result.models.index(flash) < result.models.index(m3)
diff --git a/agent/tests/test_portfolio_cash_and_error_details.py b/agent/tests/test_portfolio_cash_and_error_details.py
new file mode 100644
index 000000000..1ad7a860b
--- /dev/null
+++ b/agent/tests/test_portfolio_cash_and_error_details.py
@@ -0,0 +1,142 @@
+"""Read-path regressions for cash disclosures and sanitized connector errors."""
+
+from decimal import Decimal
+import json
+
+import pytest
+
+from src.portfolio.config import PortfolioSettingsStore
+from src.portfolio.service import PortfolioService, _portfolio_error_details
+from src.portfolio.store import PortfolioStore
+
+
+def _service(tmp_path, broker, reader, progress=None):
+ settings = PortfolioSettingsStore(tmp_path / "settings.json")
+ profile = f"{broker}-live-sdk-readonly"
+ settings.connection_store.ensure(broker, profile, broker)
+ settings.save({"display_currency": "USD", "sources": [{"connection_id": broker}]})
+ return PortfolioService(
+ PortfolioStore(tmp_path / "portfolio.sqlite"),
+ settings_store=settings,
+ get_account=reader,
+ get_positions=lambda *args, **kwargs: {"positions": []},
+ get_quote=lambda *args, **kwargs: {},
+ fx_fetcher=lambda: (Decimal("7.2"), Decimal("7.8"), "2026-10-23T00:00:00Z"),
+ progress_callback=progress,
+ )
+
+
+ "message",
+ [
+ "request https://api.example/read?signature=synthetic-signature&api_key=synthetic-key",
+ "Authorization: Bearer synthetic-bearer",
+ '{"api_key": "synthetic-key", "signature": "synthetic-signature"}',
+ "failed https://user:[email protected]/read",
+ ],
+)
+def test_errors_use_shared_credential_redaction(message):
+ code, error = _portfolio_error_details(message)
+ assert code == "ConnectorReadError"
+ for secret in ("synthetic-signature", "synthetic-key", "synthetic-bearer", "synthetic-password"):
+ assert secret not in error
+ assert _portfolio_error_details(error)[1] == error
+
+
+def test_binance_restriction_is_distinct_from_other_failures():
+ assert (
+ _portfolio_error_details("HTTP 451 restricted location", broker="binance")[0] == "binance_restricted_location"
+ )
+ for text, broker in [
+ ("HTTP 451 other error", "binance"),
+ ("HTTP 401 eligibility", "binance"),
+ ("HTTP 451 eligibility", "other"),
+ ]:
+ assert _portfolio_error_details(text, broker=broker)[0] == "ConnectorReadError"
+
+
+def test_failed_reads_progress_and_old_snapshots_are_sanitized(tmp_path):
+ message = "HTTP 500 https://api.example/read?signature=synthetic-signature Authorization: Bearer synthetic-bearer"
+
+ def fail(*args, **kwargs):
+ raise RuntimeError(message)
+
+ progress = []
+ service = _service(tmp_path, "binance", fail, lambda *args: progress.append(args))
+ snapshot = service.refresh()
+ assert not snapshot["complete"]
+ assert "synthetic-" not in json.dumps(
+ [snapshot, progress, service.latest(), service.snapshot_by_id(snapshot["snapshot_id"])]
+ )
+ # Simulate an immutable snapshot persisted before the sanitization fix.
+ snapshot["snapshot_id"] = "legacy-errors"
+ snapshot["accounts"][0]["error"] = message
+ service.store.save_snapshot(snapshot)
+ assert "synthetic-" not in json.dumps(service.snapshot_by_id("legacy-errors"))
+ assert "synthetic-signature" in service.store.get("legacy-errors")["accounts"][0]["error"]
+
+
+def test_longbridge_cash_survives_store_api_context_and_cli(tmp_path, capsys, monkeypatch):
+ account = {
+ "balances": [
+ {
+ "currency": "HKD",
+ "net_assets": 7800,
+ "total_cash": 7300,
+ "max_finance_amount": 5000,
+ "remaining_finance_amount": 0,
+ "cash_infos": [
+ {
+ "currency": "USD",
+ "available_cash": 1000,
+ "withdraw_cash": None,
+ "frozen_cash": 0,
+ "settling_cash": 0,
+ },
+ {
+ "currency": "HKD",
+ "available_cash": -500,
+ "withdraw_cash": -600,
+ "frozen_cash": 500,
+ "settling_cash": -200,
+ },
+ ],
+ }
+ ]
+ }
+ service = _service(tmp_path, "longbridge", lambda *args, **kwargs: account)
+ snapshot = service.refresh()
+ assert snapshot["complete"]
+ assert snapshot["totals"]["usd"] == 1000
+ details = snapshot["accounts"][0]["balance_details"]
+ assert details[0]["cash_infos"][1]["available_cash"] == -500
+ assert details[0]["cash_infos"][0]["withdraw_cash"] is None
+ assert details[0]["remaining_finance_amount"] == 0
+ assert service.latest()["accounts"][0]["balance_details"] == details
+ assert service.analysis_context()["account_allocation"][0]["balance_details"] == details
+
+ from src.tools import portfolio_tool
+
+ monkeypatch.setattr(portfolio_tool, "PortfolioService", lambda: service)
+ result = json.loads(portfolio_tool.PortfolioSummaryTool().execute())
+ assert result["context"]["account_allocation"][0]["balance_details"] == details
+
+ from cli import _legacy
+
+ _legacy._print_connector_balances(account)
+ _legacy.cmd_portfolio_show(service=service)
+ output = capsys.readouterr().out
+ assert "-500" in output and "Remaining financing" in output and "USD" in output
+
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+ from src.api import portfolio_routes
+
+ monkeypatch.setattr(portfolio_routes, "PortfolioService", lambda **kwargs: service)
+ app = FastAPI()
+ app.dependency_overrides[portfolio_routes.require_auth] = lambda: None
+ portfolio_routes.register_portfolio_routes(app)
+ with TestClient(app) as client:
+ response = client.get("/api/portfolio")
+ assert response.status_code == 200
+ assert response.json()["snapshot"]["accounts"][0]["balance_details"] == details
diff --git a/agent/tests/test_weixin_media_filename_collision.py b/agent/tests/test_weixin_media_filename_collision.py
index 672150587..3e3936bc7 100644
--- a/agent/tests/test_weixin_media_filename_collision.py
+++ b/agent/tests/test_weixin_media_filename_collision.py
@@ -50,6 +50,28 @@ def _file_item(encrypt_query_param: str, full_url: str) -> dict:
class TestFileDownloadFilenameCollision:
+ @pytest.mark.parametrize("same_url", [True, False])
+ def test_same_second_and_hash_collisions_preserve_both_files(
+ self, channel: WeixinChannel, monkeypatch: pytest.MonkeyPatch, same_url: bool
+ ) -> None:
+ monkeypatch.setattr(weixin_mod.time, "time", lambda: 1000)
+ monkeypatch.setattr(weixin_mod, "hash", lambda value: 7, raising=False)
+
+ async def run():
+ paths = []
+ for index, payload in enumerate((b"first", b"second")):
+ channel._client = _FakeClient(payload)
+ paths.append(await channel._download_media_item(
+ _file_item("same" if same_url else str(index), "https://cdn/file"),
+ "file", "report.pdf",
+ ))
+ return paths
+
+ paths = asyncio.run(run())
+ assert None not in paths
+ assert paths[0] != paths[1]
+ assert [Path(path).read_bytes() for path in paths] == [b"first", b"second"]
+
def test_same_filename_from_two_messages_does_not_overwrite(
self, channel: WeixinChannel
) -> None:
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index b367cf0ea..a5b7482fe 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -2206,6 +2206,14 @@
"failed": "تعذّرت قراءته — غير محتسب في الإجمالي",
"lastSuccess": "آخر قراءة ناجحة {{time}}",
"noSuccess": "لا توجد قراءة ناجحة بعد",
+ "cashDetails": "النقد والتمويل",
+ "reportingCurrency": "عملة التقرير",
+ "financingLimit": "حد التمويل",
+ "financingRemaining": "التمويل المتبقي",
+ "cashAvailable": "النقد المتاح",
+ "cashWithdrawable": "النقد القابل للسحب",
+ "cashFrozen": "النقد المجمد",
+ "cashSettling": "النقد قيد التسوية",
"binanceRestrictedLocation": "حظرت Binance هذه القراءة (HTTP 451): موقع الشبكة الحالي مقيّد. تحقق من توفر Binance في منطقتك واستخدم واجهة API الرسمية المدعومة.",
"reconnect": "إعادة الاتصال",
"retryRead": "إعادة محاولة القراءة"
diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json
index c3bab7aa4..1876a886e 100644
--- a/frontend/src/i18n/locales/de.json
+++ b/frontend/src/i18n/locales/de.json
@@ -2206,6 +2206,14 @@
"failed": "Konnte nicht gelesen werden — nicht in der Summe enthalten",
"lastSuccess": "Letzter erfolgreicher Abruf {{time}}",
"noSuccess": "Noch kein erfolgreicher Abruf",
+ "cashDetails": "Barmittel und Finanzierung",
+ "reportingCurrency": "Berichtswährung",
+ "financingLimit": "Finanzierungslimit",
+ "financingRemaining": "Verbleibende Finanzierung",
+ "cashAvailable": "Verfügbares Guthaben",
+ "cashWithdrawable": "Auszahlbares Guthaben",
+ "cashFrozen": "Gesperrtes Guthaben",
+ "cashSettling": "Guthaben in Abwicklung",
"binanceRestrictedLocation": "Binance hat diesen Abruf (HTTP 451) blockiert: Der aktuelle Netzwerkstandort ist eingeschränkt. Prüfe, ob Binance in deiner Region verfügbar ist, und verwende den unterstützten API-Endpunkt.",
"reconnect": "Neu verbinden",
"retryRead": "Lesen wiederholen"
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 1c763e9db..f33289294 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -2206,6 +2206,14 @@
"failed": "Could not be read — not counted in the total",
"lastSuccess": "Last successful read {{time}}",
"noSuccess": "No successful read yet",
+ "cashDetails": "Cash and financing",
+ "reportingCurrency": "Reporting currency",
+ "financingLimit": "Financing limit",
+ "financingRemaining": "Remaining financing",
+ "cashAvailable": "Available",
+ "cashWithdrawable": "Withdrawable",
+ "cashFrozen": "Frozen",
+ "cashSettling": "Settling",
"binanceRestrictedLocation": "Binance blocked this read (HTTP 451): the current network location is restricted. Check Binance availability for your region and use its supported API endpoint.",
"reconnect": "Reconnect",
"retryRead": "Retry read"
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index ead651b34..2f23ac699 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -2206,6 +2206,14 @@
"failed": "No se pudo leer: no cuenta en el total",
"lastSuccess": "Última lectura correcta {{time}}",
"noSuccess": "Todavía sin ninguna lectura correcta",
+ "cashDetails": "Efectivo y financiación",
+ "reportingCurrency": "Moneda del informe",
+ "financingLimit": "Límite de financiación",
+ "financingRemaining": "Financiación disponible",
+ "cashAvailable": "Efectivo disponible",
+ "cashWithdrawable": "Efectivo retirable",
+ "cashFrozen": "Efectivo bloqueado",
+ "cashSettling": "Efectivo pendiente de liquidación",
"binanceRestrictedLocation": "Binance bloqueó esta lectura (HTTP 451): la ubicación de red actual está restringida. Comprueba la disponibilidad de Binance en tu región y usa su endpoint API compatible.",
"reconnect": "Volver a conectar",
"retryRead": "Reintentar lectura"
diff --git a/frontend/src/i18n/locales/fa.json b/frontend/src/i18n/locales/fa.json
index 7f29851ca..eb2e4c643 100644
--- a/frontend/src/i18n/locales/fa.json
+++ b/frontend/src/i18n/locales/fa.json
@@ -2206,6 +2206,14 @@
"failed": "خوانده نشد — در جمع لحاظ نمی‌شود",
"lastSuccess": "آخرین خواندن موفق {{time}}",
"noSuccess": "هنوز خواندن موفقی نداشته است",
+ "cashDetails": "وجه نقد و تأمین مالی",
+ "reportingCurrency": "ارز گزارش",
+ "financingLimit": "سقف تأمین مالی",
+ "financingRemaining": "تأمین مالی باقی‌مانده",
+ "cashAvailable": "وجه نقد در دسترس",
+ "cashWithdrawable": "وجه نقد قابل برداشت",
+ "cashFrozen": "وجه نقد مسدودشده",
+ "cashSettling": "وجه نقد در حال تسویه",
"binanceRestrictedLocation": "Binance این خواندن را مسدود کرد (HTTP 451): موقعیت فعلی شبکه محدود است. دسترس‌پذیری Binance در منطقه خود را بررسی کنید و از درگاه API پشتیبانی‌شده استفاده کنید.",
"reconnect": "اتصال دوباره",
"retryRead": "تلاش دوباره برای خواندن"
diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json
index 2255695bf..700b64d37 100644
--- a/frontend/src/i18n/locales/id.json
+++ b/frontend/src/i18n/locales/id.json
@@ -2206,6 +2206,14 @@
"failed": "Tidak dapat dibaca — tidak dihitung dalam total",
"lastSuccess": "Terakhir berhasil dibaca {{time}}",
"noSuccess": "Belum pernah berhasil dibaca",
+ "cashDetails": "Kas dan pembiayaan",
+ "reportingCurrency": "Mata uang laporan",
+ "financingLimit": "Batas pembiayaan",
+ "financingRemaining": "Sisa pembiayaan",
+ "cashAvailable": "Kas tersedia",
+ "cashWithdrawable": "Kas yang dapat ditarik",
+ "cashFrozen": "Kas dibekukan",
+ "cashSettling": "Kas dalam penyelesaian",
"binanceRestrictedLocation": "Binance memblokir pembacaan ini (HTTP 451): lokasi jaringan saat ini dibatasi. Periksa ketersediaan Binance di wilayah Anda dan gunakan endpoint API yang didukung.",
"reconnect": "Hubungkan ulang",
"retryRead": "Coba baca lagi"
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index 29adc87cc..a75e36ba7 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -2206,6 +2206,14 @@
"failed": "読み取れませんでした — 合計に含まれていません",
"lastSuccess": "最後に読み取れたのは {{time}}",
"noSuccess": "まだ一度も読み取れていません",
+ "cashDetails": "現金と信用枠",
+ "reportingCurrency": "報告通貨",
+ "financingLimit": "信用取引枠",
+ "financingRemaining": "残りの信用取引枠",
+ "cashAvailable": "利用可能な現金",
+ "cashWithdrawable": "出金可能な現金",
+ "cashFrozen": "凍結中の現金",
+ "cashSettling": "決済待ちの現金",
"binanceRestrictedLocation": "Binance が読み取りを拒否しました(HTTP 451)。現在のネットワーク所在地は利用制限の対象です。お住まいの地域で Binance が利用可能か確認し、サポート対象の公式 API エンドポイントを使用してください。",
"reconnect": "再接続",
"retryRead": "再読み込み"
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index 2b15e43fd..e26304e5f 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -2206,6 +2206,14 @@
"failed": "읽지 못했습니다 — 합계에 포함되지 않음",
"lastSuccess": "마지막으로 성공한 읽기 {{time}}",
"noSuccess": "아직 성공한 읽기가 없습니다",
+ "cashDetails": "현금 및 융자",
+ "reportingCurrency": "보고 통화",
+ "financingLimit": "융자 한도",
+ "financingRemaining": "남은 융자 한도",
+ "cashAvailable": "사용 가능 현금",
+ "cashWithdrawable": "출금 가능 현금",
+ "cashFrozen": "동결 현금",
+ "cashSettling": "결제 대기 현금",
"binanceRestrictedLocation": "Binance가 이 읽기를 차단했습니다(HTTP 451). 현재 네트워크 위치가 제한되어 있습니다. 해당 지역에서 Binance를 사용할 수 있는지 확인하고 지원되는 공식 API 엔드포인트를 사용하세요.",
"reconnect": "다시 연결",
"retryRead": "다시 읽기"
diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.json
index 8b27946c7..bc77c521b 100644
--- a/frontend/src/i18n/locales/pt-BR.json
+++ b/frontend/src/i18n/locales/pt-BR.json
@@ -2206,6 +2206,14 @@
"failed": "Não foi possível ler – não foi contabilizado no total",
"lastSuccess": "Última leitura bem-sucedida {{time}}",
"noSuccess": "Nenhuma leitura bem-sucedida ainda",
+ "cashDetails": "Caixa e financiamento",
+ "reportingCurrency": "Moeda do relatório",
+ "financingLimit": "Limite de financiamento",
+ "financingRemaining": "Financiamento restante",
+ "cashAvailable": "Caixa disponível",
+ "cashWithdrawable": "Caixa para saque",
+ "cashFrozen": "Caixa bloqueado",
+ "cashSettling": "Caixa em liquidação",
"binanceRestrictedLocation": "A Binance bloqueou esta leitura (HTTP 451): a localização atual da rede é restrita. Verifique a disponibilidade da Binance na sua região e use o endpoint de API compatível.",
"reconnect": "Reconectar",
"retryRead": "Tente ler novamente"
diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.json
index d670eb80f..b674fcf04 100644
--- a/frontend/src/i18n/locales/tr.json
+++ b/frontend/src/i18n/locales/tr.json
@@ -2170,6 +2170,14 @@
"failed": "Okunamadı; toplama katılmadı",
"lastSuccess": "Son başarılı okuma: {{time}}",
"noSuccess": "Henüz başarılı okuma yok",
+ "cashDetails": "Nakit ve finansman",
+ "reportingCurrency": "Raporlama para birimi",
+ "financingLimit": "Finansman limiti",
+ "financingRemaining": "Kalan finansman",
+ "cashAvailable": "Kullanılabilir nakit",
+ "cashWithdrawable": "Çekilebilir nakit",
+ "cashFrozen": "Bloke nakit",
+ "cashSettling": "Takas bekleyen nakit",
"binanceRestrictedLocation": "Binance bu okumayı engelledi (HTTP 451): mevcut ağ konumu kısıtlı. Bölgenizde Binance kullanılabilirliğini kontrol edin ve desteklenen API uç noktasını kullanın.",
"reconnect": "Yeniden bağlan",
"retryRead": "Okumayı yeniden dene"
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index 7606cde15..d89b1eb6f 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -2206,6 +2206,14 @@
"failed": "读取失败 — 未计入合计",
"lastSuccess": "上一次成功读取于 {{time}}",
"noSuccess": "尚未成功读取过",
+ "cashDetails": "现金与融资",
+ "reportingCurrency": "报告币种",
+ "financingLimit": "融资额度",
+ "financingRemaining": "剩余融资额度",
+ "cashAvailable": "可用现金",
+ "cashWithdrawable": "可提取现金",
+ "cashFrozen": "冻结现金",
+ "cashSettling": "待结算现金",
"binanceRestrictedLocation": "Binance 返回 HTTP 451,当前网络出口地区受限,暂时无法读取。请确认所在地区可使用 Binance,并检查账户对应的官方 API 入口。",
"reconnect": "重新连接",
"retryRead": "重试读取"
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index d21141fad..b7c083f3b 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -167,6 +167,18 @@ export interface PortfolioConnectorCompatibility {
* as history — never as a current valuation.
*/
export interface PortfolioAccount {
+ balance_details?: {
+ currency: string | null;
+ max_finance_amount: number | null;
+ remaining_finance_amount: number | null;
+ cash_infos: {
+ currency: string | null;
+ available_cash: number | null;
+ withdraw_cash: number | null;
+ frozen_cash: number | null;
+ settling_cash: number | null;
+ }[];
+ }[];
source_kind?: "connection" | "extraetf";
import_metadata?: { source_mtime: string; expires_at: string; as_of_source: string } | null;
source_id?: string;
diff --git a/frontend/src/pages/Portfolio.tsx b/frontend/src/pages/Portfolio.tsx
index d5d838233..48c1a6b0e 100644
--- a/frontend/src/pages/Portfolio.tsx
+++ b/frontend/src/pages/Portfolio.tsx
@@ -565,6 +565,7 @@ function AccountCard({ account, active, displayCurrency, fx, onClick, onReconnec
<>
<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>
+ <AccountBalanceDetails balances={account.balance_details} />
<div className="mt-4 flex items-center justify-between border-t pt-3 text-xs"><span className="text-positive">{account.source_kind === "extraetf" ? t("portfolio.imports.source") : t("portfolio.accounts.fresh")}</span><span className="text-muted-foreground">{dateTime(account.import_metadata?.source_mtime ?? account.last_success_at)}</span></div>
</>
)}
@@ -574,6 +575,35 @@ function AccountCard({ account, active, displayCurrency, fx, onClick, onReconnec
</div>;
}
+function AccountBalanceDetails({ balances }: { balances: PortfolioAccount["balance_details"] }) {
+ const { t } = useTranslation();
+ const visible = balances?.filter((balance) => balance.cash_infos.length || balance.max_finance_amount != null || balance.remaining_finance_amount != null);
+ if (!visible?.length) return null;
+ const amount = (value: number | null, currency: string | null) => value == null ? "—" : currency ? money(value, currency) : value.toLocaleString();
+ return <details className="mt-4 border-t pt-3 text-xs" onClick={(event) => event.stopPropagation()} onKeyDown={(event) => event.stopPropagation()}>
+ <summary className="cursor-pointer font-medium">{t("portfolio.accounts.cashDetails")}</summary>
+ {visible.map((balance, index) => <div key={index} className="mt-3 space-y-3">
+ <div className="text-muted-foreground">{t("portfolio.accounts.reportingCurrency")}: {balance.currency ?? "—"}</div>
+ <dl className="grid grid-cols-2 gap-2">
+ <div><dt className="text-muted-foreground">{t("portfolio.accounts.financingLimit")}</dt><dd>{amount(balance.max_finance_amount, balance.currency)}</dd></div>
+ <div><dt className="text-muted-foreground">{t("portfolio.accounts.financingRemaining")}</dt><dd>{amount(balance.remaining_finance_amount, balance.currency)}</dd></div>
+ </dl>
+ {balance.cash_infos.map((cash, cashIndex) => <div key={cashIndex} className="rounded-lg bg-muted/50 p-3">
+ <div className="mb-2 font-medium">{cash.currency ?? "—"}</div>
+ <dl className="grid grid-cols-2 gap-2">
+ {([
+ ["cashAvailable", cash.available_cash], ["cashWithdrawable", cash.withdraw_cash],
+ ["cashFrozen", cash.frozen_cash], ["cashSettling", cash.settling_cash],
+ ] as const).map(([key, value]) => <div key={key}>
+ <dt className="text-muted-foreground">{t(`portfolio.accounts.${key}`)}</dt>
+ <dd className={value != null && value < 0 ? "text-danger" : ""}>{amount(value, cash.currency)}</dd>
+ </div>)}
+ </dl>
+ </div>)}
+ </div>)}
+ </details>;
+}
+
function BrokerBadge({ broker }: { broker: string }) {
const color = BROKER_COLORS[broker.toUpperCase()] ?? "#7c8493";
return <span className="inline-flex items-center gap-2 font-medium uppercase"><span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: color }} />{broker}</span>;
diff --git a/frontend/src/pages/__tests__/Portfolio.test.tsx b/frontend/src/pages/__tests__/Portfolio.test.tsx
index f514fc9df..892184d5e 100644
--- a/frontend/src/pages/__tests__/Portfolio.test.tsx
+++ b/frontend/src/pages/__tests__/Portfolio.test.tsx
@@ -138,6 +138,41 @@ const portfolioConfiguration = {
};
describe("Portfolio page", () => {
+ it("shows reported cash legs without replacing missing values or netting currencies", async () => {
+ mocked.getPortfolio.mockResolvedValue({ status: "ok", snapshot: {
+ ...snapshot,
+ accounts: [{ ...snapshot.accounts[1], balance_details: [{
+ currency: "HKD", max_finance_amount: 5000, remaining_finance_amount: 0,
+ cash_infos: [
+ { currency: "USD", available_cash: 1000, withdraw_cash: null, frozen_cash: 0, settling_cash: 0 },
+ { currency: "HKD", available_cash: -500, withdraw_cash: -600, frozen_cash: 500, settling_cash: -200 },
+ ],
+ }] }],
+ } });
+ render(<Portfolio />);
+ const summary = await screen.findByText(i18n.t("portfolio.accounts.cashDetails"));
+ const details = summary.closest("details")!;
+ fireEvent.click(summary);
+ expect(details.textContent).toContain("HKD");
+ expect(details.textContent).toContain("USD");
+ const amounts = within(details).getAllByText(i18n.t("portfolio.accounts.cashAvailable")).map((label) => label.nextElementSibling!);
+ expect(amounts[0].textContent).toContain("1,000");
+ expect(amounts[1].textContent).toMatch(/^-.*500\.00$/);
+ expect(amounts[1]).toHaveClass("text-danger");
+ expect(within(details).getAllByText(i18n.t("portfolio.accounts.cashWithdrawable"))[0].nextElementSibling).toHaveTextContent("—");
+ expect(within(details).getByText("Remaining financing").nextElementSibling).toHaveTextContent("0.00");
+ });
+
+ it("explains Binance's region restriction using the typed failure code", async () => {
+ mocked.getPortfolio.mockResolvedValue({ status: "ok", snapshot: {
+ ...snapshotWithFailedSource,
+ accounts: [{ ...snapshotWithFailedSource.accounts.at(-1)!, error_code: "binance_restricted_location", error: "connector fallback text" }],
+ } });
+ render(<Portfolio />);
+ expect(await screen.findByText(i18n.t("portfolio.accounts.binanceRestrictedLocation"))).toBeInTheDocument();
+ expect(screen.queryByText("connector fallback text")).not.toBeInTheDocument();
+ });
+
it("exports the displayed observation by id and reports a revoked snapshot", async () => {
const context = { snapshot_id: "snap-1", totals: { usd: 1000 }, read_identity: { mode: "pinned" } };
mocked.getPortfolioAnalysisContext.mockResolvedValue({ status: "ok", context });