Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(portfolio): include Binance assets after clock skew

Yanga7d072714007
diff --git a/agent/src/portfolio/service.py b/agent/src/portfolio/service.py
index b9a7e93fe..0ea354127 100644
--- a/agent/src/portfolio/service.py
+++ b/agent/src/portfolio/service.py
@@ -360,9 +360,17 @@ class PortfolioService:
positions.extend(broker_positions)
total_usd = sum((_decimal(row.get("total_usd")) for row in accounts), Decimal("0"))
- # Every enabled source produces exactly one account row, so a snapshot
- # is complete only when none of them failed.
- complete = all(row["status"] == "ok" for row in accounts)
+ # Binance derives its account total from priced positions. Other
+ # connectors report an independent broker account total, so an
+ # unpriced position there does not make the account total incomplete.
+ complete = all(
+ row["status"] == "ok"
+ and not (
+ row.get("broker") == "binance"
+ and int(row.get("unpriced_position_count") or 0) > 0
+ )
+ for row in accounts
+ )
priced_usd = sum((_decimal(row.get("priced_value_usd")) for row in accounts), Decimal("0"))
cash_usd = sum((_decimal(row.get("cash_usd")) for row in accounts), Decimal("0"))
unpriced_usd = sum(
@@ -1042,7 +1050,21 @@ class PortfolioService:
)
unpriced = [f"{row['broker']}:{row['symbol']}" for row in positions if not row.get("priced")]
if unpriced:
- warnings.append("No price available for these positions: " + ", ".join(unpriced[:20]))
+ warnings.append(
+ "No price available for these positions: "
+ + ", ".join(unpriced[:20])
+ )
+ incomplete_unpriced = [
+ f"{row['broker']}:{row['symbol']}"
+ for row in positions
+ if row.get("broker") == "binance" and not row.get("priced")
+ ]
+ if incomplete_unpriced:
+ warnings.append(
+ "Binance account totals are built from priced positions; these "
+ "holdings are excluded, so this snapshot is incomplete: "
+ + ", ".join(incomplete_unpriced[:20])
+ )
experimental = [
str(row.get("label") or row.get("broker"))
for row in accounts
diff --git a/agent/src/portfolio/store.py b/agent/src/portfolio/store.py
index 9c584a32e..7b7549f36 100644
--- a/agent/src/portfolio/store.py
+++ b/agent/src/portfolio/store.py
@@ -10,6 +10,26 @@ from typing import Any
from src.config.paths import get_runtime_root
+def _derived_totals_are_complete(payload: dict[str, Any]) -> bool:
+ """Reject snapshots whose derived Binance total omitted an unpriced asset."""
+ for account in payload.get("accounts", []):
+ if account.get("broker") != "binance":
+ continue
+ unpriced_count = account.get("unpriced_position_count")
+ if unpriced_count is not None:
+ if int(unpriced_count or 0) > 0:
+ return False
+ continue
+ # Compatibility for snapshots written before account-level counts were
+ # stored: only Binance positions affect a derived account total.
+ if any(
+ row.get("broker") == "binance" and not row.get("priced")
+ for row in payload.get("positions", [])
+ ):
+ return False
+ return True
+
+
class PortfolioStore:
"""SQLite-backed history of immutable portfolio snapshots plus an FX cache."""
@@ -88,11 +108,17 @@ class PortfolioStore:
The snapshot envelope, or ``None`` when nothing matches.
"""
where = "WHERE complete = 1" if complete_only else ""
+ limit = 2000 if complete_only else 1
with self._connect() as db:
- row = db.execute(
- f"SELECT payload FROM portfolio_snapshots {where} ORDER BY created_at DESC LIMIT 1"
- ).fetchone()
- return json.loads(row["payload"]) if row else None
+ rows = db.execute(
+ f"SELECT payload FROM portfolio_snapshots {where} ORDER BY created_at DESC LIMIT ?",
+ (limit,),
+ ).fetchall()
+ for row in rows:
+ payload = json.loads(row["payload"])
+ if not complete_only or _derived_totals_are_complete(payload):
+ return payload
+ return None
def history(
self,
@@ -126,13 +152,15 @@ class PortfolioStore:
{where}
ORDER BY created_at DESC LIMIT ?
""",
- (2000 if valuation_version is not None else row_limit,),
+ (2000 if valuation_version is not None or complete_only else row_limit,),
).fetchall()
history = []
for row in rows:
- if valuation_version is not None:
+ if valuation_version is not None or complete_only:
payload = json.loads(row["payload"])
- if payload.get("valuation_version") != valuation_version:
+ 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
history.append(
{
diff --git a/agent/src/trading/connectors/binance/sdk.py b/agent/src/trading/connectors/binance/sdk.py
index 6c5b1a597..e5f30d76f 100644
--- a/agent/src/trading/connectors/binance/sdk.py
+++ b/agent/src/trading/connectors/binance/sdk.py
@@ -9,11 +9,12 @@ from __future__ import annotations
import json
import math
-from dataclasses import asdict, dataclass
+import re
+from dataclasses import asdict, dataclass, replace
from datetime import datetime, timezone
from pathlib import Path
from types import ModuleType
-from typing import Any, Mapping
+from typing import Any, Callable, Mapping
from urllib.parse import urlparse
from urllib.request import getproxies
@@ -277,7 +278,7 @@ def get_account_snapshot(config: BinanceConfig | None = None) -> dict[str, Any]:
ex = _exchange(cfg)
if cfg.market_type == "usdm":
return _get_usdm_observation(cfg, ex)
- balance = ex.fetch_balance()
+ balance = _read_with_clock_retry(ex, ex.fetch_balance)
rows = _nonzero_balances(balance)
return {
"status": "ok",
@@ -304,14 +305,16 @@ def get_positions(config: BinanceConfig | None = None) -> dict[str, Any]:
ex = _exchange(cfg)
if cfg.market_type == "usdm":
return _get_usdm_observation(cfg, ex)
- balance = ex.fetch_balance()
+ balance = _read_with_clock_retry(ex, ex.fetch_balance)
spot_balances = _nonzero_balances(balance)
earn_rows: list[dict[str, Any]] = []
earn_wrappers: set[str] = set()
earn_note: str | None = None
if not cfg.is_testnet:
try:
- payload = ex.sapi_get_simple_earn_flexible_position({"size": 100})
+ payload = _read_with_clock_retry(
+ ex, lambda: ex.sapi_get_simple_earn_flexible_position({"size": 100})
+ )
for item in payload.get("rows", []) if isinstance(payload, Mapping) else []:
asset = str(_obj_get(item, "asset", "")).strip().upper()
quantity = _to_float(_obj_get(item, "totalAmount"))
@@ -397,7 +400,7 @@ def get_quote(symbol: str, *, config: BinanceConfig | None = None, **_: Any) ->
cfg = config or load_config()
_reject_unsupported_usdm_surface(cfg)
_assert_host(cfg)
- ex = _exchange(cfg)
+ ex = _public_exchange(cfg)
clean = normalize_symbol(symbol)
ticker = ex.fetch_ticker(clean)
return {
@@ -441,7 +444,7 @@ def search_instruments(
except (TypeError, ValueError, OverflowError):
bounded_limit = 10
- markets = _exchange(cfg).load_markets()
+ markets = _public_exchange(cfg).load_markets()
if not isinstance(markets, Mapping):
raise BinanceConfigError("Binance load_markets returned a non-mapping payload")
@@ -494,7 +497,7 @@ def get_historical_bars(
cfg = config or load_config()
_reject_unsupported_usdm_surface(cfg)
_assert_host(cfg)
- ex = _exchange(cfg)
+ ex = _public_exchange(cfg)
clean = normalize_symbol(symbol)
timeframe = _TIMEFRAME_MAP.get(period.strip(), "1d")
bars = ex.fetch_ohlcv(clean, timeframe=timeframe, limit=int(limit))
@@ -762,6 +765,37 @@ def _get_usdm_observation(cfg: BinanceConfig, exchange: Any) -> dict[str, Any]:
raise BinanceConfigError(str(exc)) from None
+def _read_with_clock_retry(exchange: Any, read: Callable[[], Any]) -> Any:
+ """Retry one rejected signed read after refreshing Binance's clock offset.
+
+ Binance rejects timestamps more than one second ahead regardless of the
+ configured recvWindow. CCXT calibrates on market loading, but a sleeping
+ laptop or inconsistent network timing can still invalidate a later read.
+ The extra one-second cushion applies only after that specific rejection.
+ """
+ try:
+ return read()
+ except Exception as exc:
+ message = str(exc)
+ if not (
+ re.search(r'["\']?code["\']?\s*:\s*-1021\b', message)
+ and "ahead of the server" in message.lower()
+ ):
+ raise
+ exchange.load_time_difference()
+ exchange.options["timeDifference"] += 1_000
+ return read()
+
+
+def _public_exchange(cfg: BinanceConfig):
+ """Use the selected Binance host without credentials for public market data.
+
+ CCXT otherwise loads Binance currencies through a signed SAPI request when
+ market loading sees an API key, even for an ordinary public ticker.
+ """
+ return _exchange(replace(cfg, api_key="", api_secret=""))
+
+
def _exchange(cfg: BinanceConfig):
"""Build a ccxt Binance client bound to the configured market/environment."""
ccxt = _require_ccxt()
diff --git a/agent/tests/test_portfolio_service.py b/agent/tests/test_portfolio_service.py
index 02e71ad85..718a6a760 100644
--- a/agent/tests/test_portfolio_service.py
+++ b/agent/tests/test_portfolio_service.py
@@ -108,6 +108,102 @@ def test_refresh_aggregates_three_readonly_connectors(tmp_path):
assert "quantity" not in context["holdings"][0]
+def test_unpriced_binance_btc_marks_snapshot_incomplete(tmp_path):
+ settings = _settings_store(tmp_path)
+ settings.save(
+ {
+ "display_currency": "USD",
+ "sources": [{"connection_id": "binance", "label": "Binance", "order": 0}],
+ }
+ )
+
+ def failed_quote(*_args, **_kwargs):
+ raise RuntimeError('binance {"code":-1021,"msg":"Timestamp was ahead of the server"}')
+
+ service = PortfolioService(
+ PortfolioStore(tmp_path / "portfolio.sqlite3"),
+ settings_store=settings,
+ get_account=lambda _profile_id: {"balances": []},
+ get_positions=lambda _profile_id: {
+ "positions": [
+ {"symbol": "BTC", "quantity": 0.08601717, "source": "simple_earn_flexible"}
+ ]
+ },
+ get_quote=failed_quote,
+ fx_fetcher=lambda: (
+ Decimal("7.2"),
+ Decimal("7.8"),
+ "2026-09-17T00:00:00+08:00",
+ ),
+ )
+
+ snapshot = service.refresh()
+
+ assert snapshot["complete"] is False
+ assert snapshot["accounts"][0]["status"] == "ok"
+ assert snapshot["positions"][0]["symbol"] == "BTC"
+ assert snapshot["positions"][0]["priced"] is False
+ assert snapshot["totals"]["usd"] == 0.0
+ assert any("holdings are excluded" in warning and "binance:BTC" in warning for warning in snapshot["warnings"])
+ assert service.history() == []
+
+ # Older versions stored this exact shape with complete=true. Do not use
+ # such a row as a valid history point after upgrading.
+ service.store.save_snapshot(
+ {**snapshot, "snapshot_id": "old-mislabeled-row", "complete": True}
+ )
+ assert service.history() == []
+ assert service.store.latest(complete_only=True) is None
+
+
+def test_unpriced_ibkr_position_keeps_reported_account_total_complete(tmp_path):
+ settings = _settings_store(tmp_path)
+ settings.save(
+ {
+ "display_currency": "USD",
+ "sources": [{"connection_id": "ibkr", "label": "IBKR", "order": 0}],
+ }
+ )
+
+ service = PortfolioService(
+ PortfolioStore(tmp_path / "portfolio.sqlite3"),
+ settings_store=settings,
+ get_account=lambda _profile_id: {
+ "summary": [
+ {"tag": "NetLiquidation", "value": "1000", "currency": "USD"}
+ ]
+ },
+ get_positions=lambda _profile_id: {
+ "positions": [
+ {
+ "symbol": "AAPL",
+ "sec_type": "STK",
+ "exchange": "SMART",
+ "currency": "USD",
+ "position": 2,
+ "avg_cost": 100,
+ }
+ ]
+ },
+ get_quote=lambda *_args, **_kwargs: (_ for _ in ()).throw(
+ RuntimeError("quote unavailable")
+ ),
+ fx_fetcher=lambda: (
+ Decimal("7.2"),
+ Decimal("7.8"),
+ "2026-09-17T00:00:00+08:00",
+ ),
+ )
+
+ snapshot = service.refresh()
+
+ assert snapshot["complete"] is True
+ assert snapshot["totals"]["usd"] == 1000.0
+ assert snapshot["positions"][0]["priced"] is False
+ assert len(service.history()) == 1
+ assert service.store.latest(complete_only=True) is not None
+
+
def test_latest_enriches_legacy_snapshot_with_current_compatibility(tmp_path):
store = PortfolioStore(tmp_path / "portfolio.sqlite3")
settings = _settings_store(tmp_path)
diff --git a/agent/tests/test_sdk_connectors.py b/agent/tests/test_sdk_connectors.py
index 16cbbfbb2..82c5e9fa9 100644
--- a/agent/tests/test_sdk_connectors.py
+++ b/agent/tests/test_sdk_connectors.py
@@ -522,6 +522,32 @@ def test_binance_classification() -> None:
assert BINANCE_TOOL_CLASS["load_markets"] is ToolClass.READ
+def test_binance_quote_uses_public_client_without_credentials(monkeypatch) -> None:
+ captured = {}
+
+ class FakeExchange:
+ def fetch_ticker(self, symbol):
+ assert symbol == "BTC/USDT"
+ return {"last": 75000}
+
+ def build_exchange(config):
+ captured["config"] = config
+ return FakeExchange()
+
+ monkeypatch.setattr(bn, "_exchange", build_exchange)
+ result = bn.get_quote(
+ "BTCUSDT",
+ config=bn.BinanceConfig(
+ api_key="private-key", api_secret="private-secret", profile="live-readonly"
+ ),
+ )
+
+ assert result["quote"]["last"] == 75000
+ assert captured["config"].api_key == ""
+ assert captured["config"].api_secret == ""
+ assert captured["config"].host == bn.LIVE_HOST
+
+
def test_binance_search_instruments_resolves_exact_active_spot_pair(monkeypatch) -> None:
class FakeExchange:
def load_markets(self):
@@ -664,6 +690,111 @@ def test_binance_exchange_adjusts_for_server_time(monkeypatch) -> None:
assert captured["sandbox"] is False
+def test_binance_account_read_resyncs_once_when_timestamp_is_ahead(monkeypatch) -> None:
+ class FakeExchange:
+ def __init__(self):
+ self.options = {"timeDifference": 0}
+ self.reads = 0
+ self.syncs = 0
+
+ def fetch_balance(self):
+ self.reads += 1
+ if self.reads == 1:
+ raise RuntimeError(
+ 'binance {"code":-1021,"msg":"Timestamp for this request was '
+ '1000ms ahead of the server\'s time."}'
+ )
+ return {"USDT": {"free": 12, "used": 0, "total": 12}}
+
+ def load_time_difference(self):
+ self.syncs += 1
+ self.options["timeDifference"] = 1500
+
+ exchange = FakeExchange()
+ monkeypatch.setattr(bn, "_exchange", lambda _cfg: exchange)
+
+ result = bn.get_account_snapshot(bn.BinanceConfig(profile="live-readonly"))
+
+ assert result["status"] == "ok"
+ assert exchange.reads == 2
+ assert exchange.syncs == 1
+ assert exchange.options["timeDifference"] == 2500
+
+
+def test_binance_clock_retry_does_not_repeat_other_errors() -> None:
+ class FakeExchange:
+ def load_time_difference(self):
+ raise AssertionError("unrelated failures must not resync")
+
+ reads = 0
+
+ def fail():
+ nonlocal reads
+ reads += 1
+ raise RuntimeError('binance {"code":-2015,"msg":"Invalid API-key"}')
+
+ with pytest.raises(RuntimeError, match="Invalid API-key"):
+ bn._read_with_clock_retry(FakeExchange(), fail)
+ assert reads == 1
+
+
+def test_binance_clock_retry_stops_after_second_rejection() -> None:
+ class FakeExchange:
+ def __init__(self):
+ self.options = {"timeDifference": 0}
+ self.syncs = 0
+
+ def load_time_difference(self):
+ self.syncs += 1
+ self.options["timeDifference"] = 1500
+
+ exchange = FakeExchange()
+ reads = 0
+
+ def fail():
+ nonlocal reads
+ reads += 1
+ raise RuntimeError('binance {"code":-1021,"msg":"Timestamp was 1000ms ahead of the server"}')
+
+ with pytest.raises(RuntimeError, match="ahead of the server"):
+ bn._read_with_clock_retry(exchange, fail)
+ assert reads == 2
+ assert exchange.syncs == 1
+
+
+def test_binance_positions_resyncs_simple_earn_read(monkeypatch) -> None:
+ class FakeExchange:
+ def __init__(self):
+ self.options = {"timeDifference": 0}
+ self.earn_reads = 0
+
+ def fetch_balance(self):
+ return {"LDBTC": {"free": 0, "used": 0.9, "total": 0.9}}
+
+ def sapi_get_simple_earn_flexible_position(self, params):
+ assert params == {"size": 100}
+ self.earn_reads += 1
+ if self.earn_reads == 1:
+ raise RuntimeError(
+ 'binance {"code":-1021,"msg":"Timestamp for this request was '
+ '1000ms ahead of the server\'s time."}'
+ )
+ return {"rows": [{"asset": "BTC", "totalAmount": "1.0"}]}
+
+ def load_time_difference(self):
+ self.options["timeDifference"] = 1600
+
+ exchange = FakeExchange()
+ monkeypatch.setattr(bn, "_exchange", lambda _cfg: exchange)
+
+ result = bn.get_positions(bn.BinanceConfig(profile="live-readonly"))
+
+ assert exchange.earn_reads == 2
+ assert result["positions"] == [
+ {"symbol": "BTC", "quantity": 1.0, "free": 0.0, "used": 1.0, "source": "simple_earn_flexible"}
+ ]
+
+
# --------------------------------------------------------------------------- #
# Futu (local OpenD gateway)
# --------------------------------------------------------------------------- #