Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(binance): add read-only USD-M account snapshots

zygora50cc17490cc6
diff --git a/agent/backtest/binance_account_reconciliation.py b/agent/backtest/binance_account_reconciliation.py
index df7bfc80c..0f684afd7 100644
--- a/agent/backtest/binance_account_reconciliation.py
+++ b/agent/backtest/binance_account_reconciliation.py
@@ -11,7 +11,7 @@ from __future__ import annotations
from dataclasses import dataclass
import math
import re
-from typing import Literal
+from typing import Any, Literal, Mapping
import pandas as pd
@@ -130,6 +130,96 @@ class BinanceAccountSnapshot:
raise ValueError("fidelity flags must be unique")
+def snapshot_from_binance_usdm_observation(
+ observation: Mapping[str, Any],
+) -> BinanceAccountSnapshot:
+ """Normalize the strict connector payload into immutable offline evidence."""
+ if observation.get("status") != "ok":
+ raise ValueError("connector observation status must be ok")
+ if observation.get("source") != "binance-usdm":
+ raise ValueError("connector observation source must be binance-usdm")
+ if observation.get("market_type") != "usdm":
+ raise ValueError("connector observation market_type must be usdm")
+ if observation.get("schema_version") != "binance-usdm-account-observation-v1":
+ raise ValueError("unsupported connector observation schema_version")
+ if observation.get("source_profile") != "binance-live-sdk-readonly":
+ raise ValueError("connector observation source_profile is unsupported")
+ configuration_hash = observation.get("configuration_hash")
+ if not isinstance(configuration_hash, str) or not re.fullmatch(
+ r"[0-9a-f]{64}", configuration_hash
+ ):
+ raise ValueError("connector observation configuration_hash must be SHA-256")
+
+ account = observation.get("account")
+ positions = observation.get("positions")
+ flags = observation.get("fidelity_flags")
+ if not isinstance(account, Mapping):
+ raise ValueError("connector observation account must be a mapping")
+ if not isinstance(positions, list):
+ raise ValueError("connector observation positions must be a list")
+ if not isinstance(flags, list) or any(not isinstance(flag, str) for flag in flags):
+ raise ValueError("connector observation fidelity_flags must be strings")
+ required_flags = {"client_observation_time", "sequential_signed_reads"}
+ if not required_flags.issubset(flags):
+ raise ValueError("connector observation is missing required fidelity flags")
+ if _observation_float(account, "open_order_initial_margin") != 0:
+ raise ValueError("connector observation must have zero open-order margin")
+
+ try:
+ normalized_positions = tuple(
+ BinancePositionSnapshot(
+ symbol=str(position["symbol"]),
+ quantity=_observation_float(position, "quantity"),
+ entry_price=_observation_float(position, "entry_price"),
+ leverage=_observation_float(position, "leverage"),
+ margin_mode=str(position["margin_mode"]), # type: ignore[arg-type]
+ isolated_margin=(
+ None
+ if position.get("isolated_margin") is None
+ else _observation_float(position, "isolated_margin")
+ ),
+ unrealized_pnl=_observation_float(position, "unrealized_pnl"),
+ initial_margin=_observation_float(position, "initial_margin"),
+ maintenance_margin=_observation_float(position, "maintenance_margin"),
+ )
+ for position in positions
+ if isinstance(position, Mapping)
+ )
+ if len(normalized_positions) != len(positions):
+ raise ValueError("connector observation position must be a mapping")
+ observed_at = pd.Timestamp(observation["observed_at"])
+ return BinanceAccountSnapshot(
+ schema_version="binance-usdm-account-observation-v1",
+ observed_at=_require_utc_timestamp(observed_at, "observed_at"),
+ source="binance-usdm",
+ source_profile="binance-live-sdk-readonly",
+ configuration_hash=configuration_hash,
+ data_status="complete",
+ wallet_balance=_observation_float(account, "wallet_balance"),
+ margin_balance=_observation_float(account, "margin_balance"),
+ available_balance=_observation_float(account, "available_balance"),
+ total_unrealized_pnl=_observation_float(account, "total_unrealized_pnl"),
+ total_initial_margin=_observation_float(account, "total_initial_margin"),
+ total_maintenance_margin=_observation_float(
+ account, "total_maintenance_margin"
+ ),
+ positions=normalized_positions,
+ fidelity_flags=tuple(flags),
+ )
+ except (KeyError, TypeError) as exc:
+ raise ValueError("connector observation is missing required fields") from exc
+
+
+def _observation_float(values: Mapping[str, Any], field: str) -> float:
+ try:
+ value = float(values[field])
+ except (KeyError, TypeError, ValueError) as exc:
+ raise ValueError(f"connector observation field {field} must be numeric") from exc
+ if not math.isfinite(value):
+ raise ValueError(f"connector observation field {field} must be finite")
+ return value
+
+
@dataclass(frozen=True)
class ReconciliationTolerance:
"""Versioned numeric and timestamp tolerances for one comparison."""
diff --git a/agent/src/tools/trading_connector_tool.py b/agent/src/tools/trading_connector_tool.py
index d3dfa148e..a8bc3e86d 100644
--- a/agent/src/tools/trading_connector_tool.py
+++ b/agent/src/tools/trading_connector_tool.py
@@ -160,6 +160,19 @@ TRADING_COMMON_PARAMETERS = {
"type": "integer",
"description": "Optional local TWS/Gateway client id override for local profiles.",
},
+ "market_type": {
+ "type": "string",
+ "enum": ["spot", "usdm"],
+ "description": (
+ "Optional Binance read market. USD-M is accepted only by the "
+ "live read-only Binance profile."
+ ),
+ },
+ "observation_absolute_tolerance": {
+ "type": "number",
+ "minimum": 0,
+ "description": "Optional USD-M sequential-read coherence tolerance.",
+ },
"account": {
"type": "string",
"description": "Optional account code filter when supported by the connector.",
@@ -200,6 +213,11 @@ def _overrides(kwargs: dict[str, Any]) -> dict[str, Any]:
"port": _int_or_none(kwargs.get("port"), "port"),
"client_id": _int_or_none(kwargs.get("client_id"), "client_id"),
"account": _connection(kwargs.get("account")),
+ "market_type": _connection(kwargs.get("market_type")),
+ "observation_absolute_tolerance": _num_or_none(
+ kwargs.get("observation_absolute_tolerance"),
+ "observation_absolute_tolerance",
+ ),
}
diff --git a/agent/src/trading/connectors/binance/__init__.py b/agent/src/trading/connectors/binance/__init__.py
index c30b25270..181d645dc 100644
--- a/agent/src/trading/connectors/binance/__init__.py
+++ b/agent/src/trading/connectors/binance/__init__.py
@@ -1,4 +1,4 @@
-"""Binance (spot) trading connector.
+"""Binance trading connector with opt-in read-only USD-M account evidence.
Read-only account/market access in Layer A via the ``ccxt`` library's unified
``binance`` exchange client (REST). A ``broker_sdk`` transport. Order placement
diff --git a/agent/src/trading/connectors/binance/classification.py b/agent/src/trading/connectors/binance/classification.py
index b41770c78..a73310c02 100644
--- a/agent/src/trading/connectors/binance/classification.py
+++ b/agent/src/trading/connectors/binance/classification.py
@@ -1,4 +1,4 @@
-"""Curated read/write classification for Binance (ccxt) spot operations.
+"""Curated read/write classification for supported Binance ccxt operations.
Keys are the ccxt unified method names this connector uses. Order-mutating ccxt
calls are pinned WRITE so the live gate never treats them as plain reads;
@@ -10,7 +10,7 @@ from __future__ import annotations
from src.live.classification import ToolClass
-#: Binance (ccxt) spot operation read/write catalog.
+#: Binance ccxt operation read/write catalog, including two USD-M signed reads.
BINANCE_TOOL_CLASS: dict[str, ToolClass] = {
# READ
"fetch_balance": ToolClass.READ,
@@ -18,6 +18,8 @@ BINANCE_TOOL_CLASS: dict[str, ToolClass] = {
"fetch_my_trades": ToolClass.READ,
"fetch_ticker": ToolClass.READ,
"fetch_ohlcv": ToolClass.READ,
+ "fapiprivatev2_get_account": ToolClass.READ,
+ "fapiprivatev3_get_positionrisk": ToolClass.READ,
# WRITE
"create_order": ToolClass.WRITE,
"cancel_order": ToolClass.WRITE,
diff --git a/agent/src/trading/connectors/binance/profiles.py b/agent/src/trading/connectors/binance/profiles.py
index 571556c40..519366d9a 100644
--- a/agent/src/trading/connectors/binance/profiles.py
+++ b/agent/src/trading/connectors/binance/profiles.py
@@ -1,4 +1,4 @@
-"""Built-in Binance (spot) connector profiles.
+"""Built-in Binance connector profiles.
Read-only paper (testnet) and live profiles plus order-placing paper and live
profiles. Paper and live use different key pairs and different hosts, so they
@@ -29,13 +29,17 @@ BINANCE_PROFILES: tuple[TradingProfile, ...] = (
TradingProfile(
id="binance-live-sdk-readonly",
connector="binance",
- label="Binance Spot Live · ccxt Read-Only",
+ label="Binance Live · ccxt Read-Only",
environment="live",
transport="broker_sdk",
capabilities=READ_CAPABILITIES,
readonly=True,
config={"profile": "live-readonly"},
- notes="Reads a Binance spot live account only (api.binance.com). Order placement is not exposed in this profile.",
+ notes=(
+ "Reads a Binance spot live account (api.binance.com). Account and "
+ "position reads may explicitly select USD-M Shadow Account mode "
+ "(fapi.binance.com); that mode exposes no order or market-data surface."
+ ),
),
TradingProfile(
id="binance-paper-trade",
diff --git a/agent/src/trading/connectors/binance/sdk.py b/agent/src/trading/connectors/binance/sdk.py
index babe6e862..1c00f0d85 100644
--- a/agent/src/trading/connectors/binance/sdk.py
+++ b/agent/src/trading/connectors/binance/sdk.py
@@ -1,30 +1,16 @@
-"""Read-only Binance (spot) connector via the ``ccxt`` unified exchange client.
-
-Wraps ccxt's ``binance`` exchange for the five read operations the trading layer
-exposes (account / positions / orders / quote / history). No order-placement
-method is exposed here — writes are introduced in a later layer behind the paper
-guard and, for live, the mandate gate.
-
-Paper-vs-live is structural: ``profile == "paper"`` builds the client with
-``set_sandbox_mode(True)`` (host ``testnet.binance.vision``) using the testnet
-key pair; a live profile uses ``set_sandbox_mode(False)`` (host
-``api.binance.com``) with the live key pair. A testnet key cannot reach the live
-host, so the configured host — recorded as ``host`` / ``paper_guard`` in every
-payload — is the authoritative discriminator. There is no paper/live field in
-any response; the host is the guard.
-
-Note: the testnet host may migrate (``testnet.binance.vision`` historically vs
-``demo-api.binance.com``), so ``testnet_host`` is config-overridable.
-
-Note: Binance spot has NO positions — holdings are simply non-zero balances. So
-``get_positions`` derives position-shaped rows from the non-zero ``total``
-balances returned by ``fetch_balance``.
+"""Binance ccxt connector with host-separated spot profiles.
+
+The live read-only profile may opt into ``market_type="usdm"`` for strict
+Shadow Account evidence. USD-M permits only signed account and position reads
+against ``fapi.binance.com``; all order and market-data surfaces are rejected.
"""
from __future__ import annotations
import json
+import math
from dataclasses import asdict, dataclass
+from datetime import datetime, timezone
from pathlib import Path
from types import ModuleType
from typing import Any, Mapping
@@ -32,6 +18,22 @@ from urllib.parse import urlparse
from urllib.request import getproxies
from src.config.paths import get_runtime_root
+from src.trading.connectors.binance.shaping import (
+ as_iter as _as_iter,
+ nonzero_balances as _nonzero_balances,
+ normalize_symbol,
+ obj_get as _obj_get,
+ ohlcv_to_dict as _ohlcv_to_dict,
+ order_to_dict as _order_to_dict,
+ to_float as _to_float,
+ trade_to_dict as _trade_to_dict,
+)
+from src.trading.connectors.binance.usdm import (
+ DEFAULT_OBSERVATION_ABSOLUTE_TOLERANCE,
+ UsdMObservationError,
+ assert_exchange_endpoints,
+ read_account_observation,
+)
CONFIG_FILENAME = "binance.json"
@@ -44,10 +46,7 @@ PROFILE_ENVIRONMENTS = {
DEFAULT_TESTNET_HOST = "https://testnet.binance.vision"
LIVE_HOST = "https://api.binance.com"
-
-#: Common quote assets, longest-first, used to split a slashless symbol.
-_QUOTE_ASSETS = ("USDT", "USDC", "BUSD", "TUSD", "FDUSD", "BTC", "ETH", "BNB")
-
+USDM_LIVE_HOST = "https://fapi.binance.com"
class BinanceDependencyError(RuntimeError):
"""Raised when the optional ``ccxt`` package is not installed."""
@@ -57,45 +56,16 @@ class BinanceConfigError(RuntimeError):
"""Raised when the connector configuration is missing or invalid."""
-def normalize_symbol(symbol: str) -> str:
- """Normalize a symbol to ccxt unified ``BASE/QUOTE`` format.
-
- Accepts ``BTC/USDT`` (passed through, uppercased), ``BTC-USDT`` (hyphen
- rewritten to slash), or a slashless ``BTCUSDT`` (split before a known quote
- asset). If the slashless form has no recognized quote suffix, the uppercased
- input is returned unchanged.
-
- Args:
- symbol: The raw symbol string from a caller.
-
- Returns:
- A ccxt unified symbol such as ``BTC/USDT``.
- """
- clean = (symbol or "").strip().upper().replace("-", "/")
- if "/" in clean:
- return clean
- for quote in _QUOTE_ASSETS:
- if clean.endswith(quote) and len(clean) > len(quote):
- return f"{clean[: -len(quote)]}/{quote}"
- return clean
-
-
@dataclass(frozen=True)
class BinanceConfig:
- """Binance (spot) connector connection settings.
-
- Args:
- api_key: Binance API key (testnet and live use different keys).
- api_secret: Binance API secret.
- profile: ``paper``, ``live-readonly`` or ``live``.
- testnet_host: Testnet REST host (overridable; may migrate upstream).
- timeout: Network timeout in seconds.
- readonly: Always true for this layer; order methods are not exposed.
+ """Binance connector connection settings.
"""
api_key: str = ""
api_secret: str = ""
profile: str = "paper"
+ market_type: str = "spot"
+ observation_absolute_tolerance: float = DEFAULT_OBSERVATION_ABSOLUTE_TOLERANCE
testnet_host: str = DEFAULT_TESTNET_HOST
timeout: float = 15.0
readonly: bool = True
@@ -107,10 +77,34 @@ class BinanceConfig:
profile = str(payload.get("profile") or "paper").strip().lower()
if profile not in PROFILE_ENVIRONMENTS:
raise BinanceConfigError("profile must be 'paper', 'live-readonly' or 'live'")
+ market_type = str(payload.get("market_type") or "spot").strip().lower()
+ if market_type not in {"spot", "usdm"}:
+ raise BinanceConfigError("market_type must be 'spot' or 'usdm'")
+ if market_type == "usdm" and profile != "live-readonly":
+ raise BinanceConfigError(
+ "market_type 'usdm' is available only through the live-readonly profile"
+ )
+ raw_tolerance = payload.get("observation_absolute_tolerance")
+ try:
+ tolerance = float(
+ raw_tolerance
+ if raw_tolerance is not None
+ else DEFAULT_OBSERVATION_ABSOLUTE_TOLERANCE
+ )
+ except (TypeError, ValueError) as exc:
+ raise BinanceConfigError(
+ "observation_absolute_tolerance must be non-negative and finite"
+ ) from exc
+ if not math.isfinite(tolerance) or tolerance < 0:
+ raise BinanceConfigError(
+ "observation_absolute_tolerance must be non-negative and finite"
+ )
return cls(
api_key=str(payload.get("api_key") or "").strip(),
api_secret=str(payload.get("api_secret") or "").strip(),
profile=profile,
+ market_type=market_type,
+ observation_absolute_tolerance=tolerance,
testnet_host=str(payload.get("testnet_host") or DEFAULT_TESTNET_HOST).strip(),
timeout=float(payload.get("timeout") or 15.0),
readonly=bool(payload.get("readonly", True)),
@@ -122,6 +116,8 @@ class BinanceConfig:
api_key: str | None = None,
api_secret: str | None = None,
profile: str | None = None,
+ market_type: str | None = None,
+ observation_absolute_tolerance: float | None = None,
testnet_host: str | None = None,
) -> "BinanceConfig":
"""Return a copy with CLI/tool overrides applied."""
@@ -132,6 +128,10 @@ class BinanceConfig:
payload["api_secret"] = api_secret
if profile is not None:
payload["profile"] = profile
+ if market_type is not None:
+ payload["market_type"] = market_type
+ if observation_absolute_tolerance is not None:
+ payload["observation_absolute_tolerance"] = observation_absolute_tolerance
if testnet_host is not None:
payload["testnet_host"] = testnet_host
return BinanceConfig.from_mapping(payload)
@@ -149,10 +149,15 @@ class BinanceConfig:
@property
def host(self) -> str:
"""Return the REST host this profile connects to."""
+ if self.market_type == "usdm":
+ return USDM_LIVE_HOST
return self.testnet_host if self.is_testnet else LIVE_HOST
-_OVERRIDE_KEYS = ("api_key", "api_secret", "profile", "testnet_host")
+_OVERRIDE_KEYS = (
+ "api_key", "api_secret", "profile", "market_type",
+ "observation_absolute_tolerance", "testnet_host",
+)
def build_config(profile_config: Mapping[str, Any] | None = None, overrides: Mapping[str, Any] | None = None) -> "BinanceConfig":
@@ -162,12 +167,6 @@ def build_config(profile_config: Mapping[str, Any] | None = None, overrides: Map
``~/.vibe-trading/binance.json``; the selected connector profile supplies the
``profile`` intent; CLI/tool overrides win last.
- Args:
- profile_config: The connector profile's ``config`` dict.
- overrides: Per-call overrides (only known config keys are applied).
-
- Returns:
- A normalized :class:`BinanceConfig`.
"""
base = asdict(load_config())
for key, value in dict(profile_config or {}).items():
@@ -257,16 +256,18 @@ def check_status(config: BinanceConfig | None = None) -> dict[str, Any]:
report["error"] = str(exc)
return report
- report["account"] = {
+ account_summary = {
"profile": cfg.profile,
"is_testnet": cfg.is_testnet,
- "balances": len(snapshot.get("balances", [])),
}
+ count_field = "positions" if cfg.market_type == "usdm" else "balances"
+ account_summary[count_field] = len(snapshot.get(count_field, []))
+ report["account"] = account_summary
return report
def get_account_snapshot(config: BinanceConfig | None = None) -> dict[str, Any]:
- """Fetch the spot account balance for the configured account.
+ """Fetch spot balances or a strict USD-M Shadow Account observation.
Returns the non-zero balances (each with ``free`` / ``used`` / ``total``)
from ccxt's unified ``fetch_balance``.
@@ -274,6 +275,8 @@ def get_account_snapshot(config: BinanceConfig | None = None) -> dict[str, Any]:
cfg = config or load_config()
_assert_host(cfg)
ex = _exchange(cfg)
+ if cfg.market_type == "usdm":
+ return _get_usdm_observation(cfg, ex)
balance = ex.fetch_balance()
rows = _nonzero_balances(balance)
return {
@@ -287,7 +290,7 @@ def get_account_snapshot(config: BinanceConfig | None = None) -> dict[str, Any]:
def get_positions(config: BinanceConfig | None = None) -> dict[str, Any]:
- """Fetch holdings shaped as positions for the configured account.
+ """Fetch spot holdings or strict USD-M position evidence.
Binance spot has no positions; holdings are the non-zero balances. On live
accounts Binance may expose Simple Earn Flexible collateral in the spot
@@ -299,6 +302,8 @@ def get_positions(config: BinanceConfig | None = None) -> dict[str, Any]:
cfg = config or load_config()
_assert_host(cfg)
ex = _exchange(cfg)
+ if cfg.market_type == "usdm":
+ return _get_usdm_observation(cfg, ex)
balance = ex.fetch_balance()
spot_balances = _nonzero_balances(balance)
earn_rows: list[dict[str, Any]] = []
@@ -358,6 +363,7 @@ def get_open_orders(config: BinanceConfig | None = None, *, include_executions:
symbol, so it is also wrapped and degrades to an empty list with a note.
"""
cfg = config or load_config()
+ _reject_unsupported_usdm_surface(cfg)
_assert_host(cfg)
ex = _exchange(cfg)
symbol_required = _symbol_required_errors()
@@ -389,6 +395,7 @@ def get_open_orders(config: BinanceConfig | None = None, *, include_executions:
def get_quote(symbol: str, *, config: BinanceConfig | None = None, **_: Any) -> dict[str, Any]:
"""Fetch a latest ticker snapshot for ``symbol`` (ccxt unified format)."""
cfg = config or load_config()
+ _reject_unsupported_usdm_surface(cfg)
_assert_host(cfg)
ex = _exchange(cfg)
clean = normalize_symbol(symbol)
@@ -426,6 +433,7 @@ def get_historical_bars(
) -> dict[str, Any]:
"""Fetch historical OHLCV bars for ``symbol`` (ccxt unified format)."""
cfg = config or load_config()
+ _reject_unsupported_usdm_surface(cfg)
_assert_host(cfg)
ex = _exchange(cfg)
clean = normalize_symbol(symbol)
@@ -498,6 +506,12 @@ def place_order(
"""
cfg = config or load_config()
+ if cfg.market_type == "usdm":
+ return {
+ "status": "error",
+ "error": "Binance USD-M Shadow Account is read-only",
+ }
+
side_clean = str(side or "").strip().lower()
if side_clean not in ("buy", "sell"):
return {"status": "error", "error": "side must be 'buy' or 'sell'."}
@@ -601,6 +615,12 @@ def cancel_order(
"""
cfg = config or load_config()
+ if cfg.market_type == "usdm":
+ return {
+ "status": "error",
+ "error": "Binance USD-M Shadow Account is read-only",
+ }
+
order_id_clean = str(order_id or "").strip()
if not order_id_clean:
return {"status": "error", "error": "order_id is required to cancel an order."}
@@ -659,8 +679,32 @@ def _symbol_required_errors() -> tuple[type[BaseException], ...]:
return classes or (ValueError,)
+def _utc_now() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+def _reject_unsupported_usdm_surface(cfg: BinanceConfig) -> None:
+ if cfg.market_type == "usdm":
+ raise BinanceConfigError(
+ "Binance USD-M Shadow Account exposes account and position reads only"
+ )
+
+
+def _get_usdm_observation(cfg: BinanceConfig, exchange: Any) -> dict[str, Any]:
+ try:
+ return read_account_observation(
+ exchange,
+ source_profile="binance-live-sdk-readonly",
+ host=cfg.host,
+ now=_utc_now,
+ absolute_tolerance=cfg.observation_absolute_tolerance,
+ )
+ except UsdMObservationError as exc:
+ raise BinanceConfigError(str(exc)) from None
+
+
def _exchange(cfg: BinanceConfig):
- """Build a ccxt ``binance`` client bound to the configured environment."""
+ """Build a ccxt Binance client bound to the configured market/environment."""
ccxt = _require_ccxt()
client_config: dict[str, Any] = {
"apiKey": cfg.api_key,
@@ -688,8 +732,14 @@ def _exchange(cfg: BinanceConfig):
}
if proxies:
client_config["proxies"] = proxies
- ex = ccxt.binance(client_config)
+ exchange_class = ccxt.binanceusdm if cfg.market_type == "usdm" else ccxt.binance
+ ex = exchange_class(client_config)
ex.set_sandbox_mode(cfg.is_testnet)
+ if cfg.market_type == "usdm":
+ try:
+ assert_exchange_endpoints(ex)
+ except UsdMObservationError as exc:
+ raise BinanceConfigError(str(exc)) from None
return ex
@@ -708,7 +758,8 @@ def _assert_host(cfg: BinanceConfig) -> None:
f"Configured profile is paper, but the resolved host '{host}' is not the testnet host '{expected}'."
)
return
- expected = urlparse(LIVE_HOST).hostname or LIVE_HOST
+ expected_url = USDM_LIVE_HOST if cfg.market_type == "usdm" else LIVE_HOST
+ expected = urlparse(expected_url).hostname or expected_url
if host != expected:
raise BinanceConfigError(
f"Configured profile is live, but the resolved host '{host}' is not the live host '{expected}'."
@@ -733,102 +784,3 @@ def _public_config(cfg: BinanceConfig) -> dict[str, Any]:
data["api_key"] = data["api_key"][:4] + "***"
data["host"] = cfg.host
return data
-
-
-# ---------------------------------------------------------------------------
-# Defensive field extraction (ccxt returns dicts; stay defensive anyway)
-# ---------------------------------------------------------------------------
-
-
-def _as_iter(value: Any) -> list[Any]:
- if value is None:
- return []
- if isinstance(value, (list, tuple)):
- return list(value)
- return [value]
-
-
-def _obj_get(obj: Any, name: str, default: Any = None) -> Any:
- if obj is None:
- return default
- if isinstance(obj, Mapping):
- return obj.get(name, default)
- return getattr(obj, name, default)
-
-
-def _to_float(value: Any) -> float | None:
- try:
- return float(value)
- except (TypeError, ValueError):
- return None
-
-
-def _nonzero_balances(balance: Any) -> list[dict[str, Any]]:
- """Extract non-zero per-asset balances from a ccxt ``fetch_balance`` result.
-
- ccxt returns a dict keyed by asset (each ``{free, used, total}``) plus
- aggregate ``total`` / ``free`` / ``used`` maps and metadata keys (``info``,
- ``timestamp``, ``datetime``, ``free``, ``used``, ``total``). We iterate the
- per-asset sub-dicts and keep those with a non-zero total.
- """
- rows: list[dict[str, Any]] = []
- if not isinstance(balance, Mapping):
- return rows
- skip = {"info", "timestamp", "datetime", "free", "used", "total"}
- for asset, detail in balance.items():
- if asset in skip or not isinstance(detail, Mapping):
- continue
- total = _to_float(detail.get("total"))
- if not total:
- continue
- rows.append(
- {
- "asset": asset,
- "free": _to_float(detail.get("free")),
- "used": _to_float(detail.get("used")),
- "total": total,
- }
- )
- return rows
-
-
-def _order_to_dict(item: Any) -> dict[str, Any]:
- return {
- "order_id": str(_obj_get(item, "id", "")),
- "symbol": _obj_get(item, "symbol"),
- "side": str(_obj_get(item, "side", "")),
- "order_type": str(_obj_get(item, "type", "")),
- "price": _obj_get(item, "price"),
- "quantity": _obj_get(item, "amount"),
- "filled": _obj_get(item, "filled"),
- "remaining": _obj_get(item, "remaining"),
- "status": str(_obj_get(item, "status", "")),
- "time": str(_obj_get(item, "timestamp", "")),
- }
-
-
-def _trade_to_dict(item: Any) -> dict[str, Any]:
- return {
- "trade_id": str(_obj_get(item, "id", "")),
- "order_id": str(_obj_get(item, "order", "")),
- "symbol": _obj_get(item, "symbol"),
- "side": str(_obj_get(item, "side", "")),
- "price": _obj_get(item, "price"),
- "quantity": _obj_get(item, "amount"),
- "cost": _obj_get(item, "cost"),
- "time": str(_obj_get(item, "timestamp", "")),
- }
-
-
-def _ohlcv_to_dict(item: Any) -> dict[str, Any]:
- """Shape a ccxt OHLCV row (``[ts, o, h, l, c, v]``) into a named dict."""
- row = list(item) if isinstance(item, (list, tuple)) else []
- row += [None] * (6 - len(row))
- return {
- "time": str(row[0] if row[0] is not None else ""),
- "open": row[1],
- "high": row[2],
- "low": row[3],
- "close": row[4],
- "volume": row[5],
- }
diff --git a/agent/src/trading/connectors/binance/shaping.py b/agent/src/trading/connectors/binance/shaping.py
new file mode 100644
index 000000000..f6fb8efb3
--- /dev/null
+++ b/agent/src/trading/connectors/binance/shaping.py
@@ -0,0 +1,107 @@
+"""Pure symbol and response shaping helpers for the Binance connector."""
+
+from __future__ import annotations
+
+from typing import Any, Mapping
+
+
+_QUOTE_ASSETS = ("USDT", "USDC", "BUSD", "TUSD", "FDUSD", "BTC", "ETH", "BNB")
+
+
+def normalize_symbol(symbol: str) -> str:
+ """Normalize a symbol to ccxt unified ``BASE/QUOTE`` format."""
+ clean = (symbol or "").strip().upper().replace("-", "/")
+ if "/" in clean:
+ return clean
+ for quote in _QUOTE_ASSETS:
+ if clean.endswith(quote) and len(clean) > len(quote):
+ return f"{clean[: -len(quote)]}/{quote}"
+ return clean
+
+
+def as_iter(value: Any) -> list[Any]:
+ if value is None:
+ return []
+ if isinstance(value, (list, tuple)):
+ return list(value)
+ return [value]
+
+
+def obj_get(obj: Any, name: str, default: Any = None) -> Any:
+ if obj is None:
+ return default
+ if isinstance(obj, Mapping):
+ return obj.get(name, default)
+ return getattr(obj, name, default)
+
+
+def to_float(value: Any) -> float | None:
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def nonzero_balances(balance: Any) -> list[dict[str, Any]]:
+ """Extract non-zero per-asset balances from a ccxt balance response."""
+ rows: list[dict[str, Any]] = []
+ if not isinstance(balance, Mapping):
+ return rows
+ skip = {"info", "timestamp", "datetime", "free", "used", "total"}
+ for asset, detail in balance.items():
+ if asset in skip or not isinstance(detail, Mapping):
+ continue
+ total = to_float(detail.get("total"))
+ if not total:
+ continue
+ rows.append(
+ {
+ "asset": asset,
+ "free": to_float(detail.get("free")),
+ "used": to_float(detail.get("used")),
+ "total": total,
+ }
+ )
+ return rows
+
+
+def order_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "order_id": str(obj_get(item, "id", "")),
+ "symbol": obj_get(item, "symbol"),
+ "side": str(obj_get(item, "side", "")),
+ "order_type": str(obj_get(item, "type", "")),
+ "price": obj_get(item, "price"),
+ "quantity": obj_get(item, "amount"),
+ "filled": obj_get(item, "filled"),
+ "remaining": obj_get(item, "remaining"),
+ "status": str(obj_get(item, "status", "")),
+ "time": str(obj_get(item, "timestamp", "")),
+ }
+
+
+def trade_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "trade_id": str(obj_get(item, "id", "")),
+ "order_id": str(obj_get(item, "order", "")),
+ "symbol": obj_get(item, "symbol"),
+ "side": str(obj_get(item, "side", "")),
+ "price": obj_get(item, "price"),
+ "quantity": obj_get(item, "amount"),
+ "cost": obj_get(item, "cost"),
+ "time": str(obj_get(item, "timestamp", "")),
+ }
+
+
+def ohlcv_to_dict(item: Any) -> dict[str, Any]:
+ """Shape a ccxt OHLCV row into a named dictionary."""
+ row = list(item) if isinstance(item, (list, tuple)) else []
+ row += [None] * (6 - len(row))
+ return {
+ "time": str(row[0] if row[0] is not None else ""),
+ "open": row[1],
+ "high": row[2],
+ "low": row[3],
+ "close": row[4],
+ "volume": row[5],
+ }
diff --git a/agent/src/trading/connectors/binance/usdm.py b/agent/src/trading/connectors/binance/usdm.py
new file mode 100644
index 000000000..cf691f0d7
--- /dev/null
+++ b/agent/src/trading/connectors/binance/usdm.py
@@ -0,0 +1,354 @@
+"""Strict shaping for read-only Binance USD-M account observations.
+
+The caller owns the authenticated ccxt client and host guard. This module only
+invokes the two allowlisted account reads and joins their responses; it cannot
+create a connection or submit an order.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Mapping
+from datetime import datetime
+import hashlib
+import json
+import math
+from typing import Any
+from urllib.parse import urlparse
+
+
+SCHEMA_VERSION = "binance-usdm-account-observation-v1"
+FIDELITY_FLAGS = ["client_observation_time", "sequential_signed_reads"]
+DEFAULT_OBSERVATION_ABSOLUTE_TOLERANCE = 1e-4
+OBSERVATION_RELATIVE_TOLERANCE = 1e-8
+CloseEnough = Callable[[float, float], bool]
+
+
+class UsdMObservationError(ValueError):
+ """Raised when Binance reports an unsupported or incoherent account state."""
+
+
+def assert_exchange_endpoints(exchange: Any) -> None:
+ """Require exact HTTPS base URLs for the two signed USD-M reads."""
+ urls = getattr(exchange, "urls", None)
+ api_urls = urls.get("api") if isinstance(urls, Mapping) else None
+ expected_paths = {
+ "fapiPrivateV2": "/fapi/v2",
+ "fapiPrivateV3": "/fapi/v3",
+ }
+ for endpoint, expected_path in expected_paths.items():
+ url = str(api_urls.get(endpoint, "")) if isinstance(api_urls, Mapping) else ""
+ parsed = urlparse(url)
+ if (
+ parsed.scheme != "https"
+ or parsed.hostname != "fapi.binance.com"
+ or parsed.port is not None
+ or parsed.path.rstrip("/") != expected_path
+ or parsed.query
+ or parsed.fragment
+ ):
+ raise UsdMObservationError(
+ f"Binance USD-M endpoint '{endpoint}' resolved to unapproved host or path '{url}'."
+ )
+
+
+def read_account_observation(
+ exchange: Any,
+ *,
+ source_profile: str,
+ host: str,
+ now: Callable[[], datetime],
+ absolute_tolerance: float = DEFAULT_OBSERVATION_ABSOLUTE_TOLERANCE,
+) -> dict[str, Any]:
+ """Read and normalize one fail-closed, single-asset USD-M observation."""
+ if not math.isfinite(absolute_tolerance) or absolute_tolerance < 0:
+ raise UsdMObservationError("observation absolute tolerance must be non-negative and finite")
+
+ def close_enough(left: float, right: float) -> bool:
+ return math.isclose(
+ left,
+ right,
+ rel_tol=OBSERVATION_RELATIVE_TOLERANCE,
+ abs_tol=absolute_tolerance,
+ )
+
+ started_at = now()
+ account = exchange.fapiprivatev2_get_account()
+ position_risk = exchange.fapiprivatev3_get_positionrisk()
+ observed_at = now()
+ if not isinstance(account, Mapping) or not isinstance(position_risk, list):
+ raise UsdMObservationError("Binance USD-M returned an invalid account payload")
+
+ account_values = _account_values(account, close_enough)
+ positions = _join_positions(account, position_risk, close_enough)
+ _require_coherent_totals(account_values, positions, close_enough)
+ configuration_hash = _configuration_hash(source_profile, host, absolute_tolerance)
+ return {
+ "status": "ok",
+ "profile": "live-readonly",
+ "source_profile": source_profile,
+ "market_type": "usdm",
+ "source": "binance-usdm",
+ "host": host,
+ "paper_guard": "host_separated",
+ "schema_version": SCHEMA_VERSION,
+ "configuration_hash": configuration_hash,
+ "observation_started_at": started_at.isoformat(),
+ "observed_at": observed_at.isoformat(),
+ "observation_span_seconds": (observed_at - started_at).total_seconds(),
+ "account": account_values,
+ "positions": positions,
+ "fidelity_flags": list(FIDELITY_FLAGS),
+ }
+
+
+def _account_values(account: Mapping[str, Any], close_enough: CloseEnough) -> dict[str, float]:
+ if account.get("multiAssetsMargin") is not False:
+ raise UsdMObservationError("Binance USD-M Shadow Account does not support multi-asset margin")
+ usdt_asset = _require_usdt_assets(account)
+ open_order_margin = _number(
+ account.get("totalOpenOrderInitialMargin"),
+ "totalOpenOrderInitialMargin",
+ non_negative=True,
+ )
+ if open_order_margin != 0:
+ raise UsdMObservationError("Binance USD-M Shadow Account requires zero open-order margin")
+ values = {
+ "wallet_balance": _number(account.get("totalWalletBalance"), "totalWalletBalance"),
+ "margin_balance": _number(account.get("totalMarginBalance"), "totalMarginBalance"),
+ "available_balance": _number(account.get("availableBalance"), "availableBalance"),
+ "total_unrealized_pnl": _number(account.get("totalUnrealizedProfit"), "totalUnrealizedProfit"),
+ "total_initial_margin": _number(
+ account.get("totalPositionInitialMargin"),
+ "totalPositionInitialMargin",
+ non_negative=True,
+ ),
+ "total_maintenance_margin": _number(account.get("totalMaintMargin"), "totalMaintMargin", non_negative=True),
+ "open_order_initial_margin": open_order_margin,
+ }
+ asset_fields = {
+ "wallet_balance": "walletBalance",
+ "margin_balance": "marginBalance",
+ "available_balance": "availableBalance",
+ "total_unrealized_pnl": "unrealizedProfit",
+ "total_initial_margin": "positionInitialMargin",
+ "total_maintenance_margin": "maintMargin",
+ "open_order_initial_margin": "openOrderInitialMargin",
+ }
+ if any(
+ not close_enough(values[name], _number(usdt_asset.get(field), field)) for name, field in asset_fields.items()
+ ):
+ raise UsdMObservationError("Binance USD-M account totals and USDT asset totals are incoherent")
+ return values
+
+
+def _join_positions(
+ account: Mapping[str, Any],
+ position_risk: list[Any],
+ close_enough: CloseEnough,
+) -> list[dict[str, Any]]:
+ account_rows = _mapping_rows(account.get("positions"), "account positions")
+ risk_rows = _mapping_rows(position_risk, "position risk")
+ _require_one_way(account_rows)
+ _require_one_way(risk_rows)
+
+ account_active = _active_by_symbol(account_rows, "account")
+ risk_active = _active_by_symbol(risk_rows, "position risk")
+ if set(account_active) != set(risk_active):
+ raise UsdMObservationError("Binance USD-M position reads are incoherent")
+
+ result: list[dict[str, Any]] = []
+ for raw_symbol in sorted(account_active):
+ account_row = account_active[raw_symbol]
+ risk_row = risk_active[raw_symbol]
+ quantity = _number(account_row.get("positionAmt"), "positionAmt")
+ risk_quantity = _number(risk_row.get("positionAmt"), "positionAmt")
+ entry_price = _number(account_row.get("entryPrice"), "entryPrice", positive=True)
+ risk_entry = _number(risk_row.get("entryPrice"), "entryPrice", positive=True)
+ if not math.isclose(quantity, risk_quantity, rel_tol=0, abs_tol=1e-12) or not math.isclose(
+ entry_price, risk_entry, rel_tol=0, abs_tol=1e-12
+ ):
+ raise UsdMObservationError("Binance USD-M position reads are incoherent")
+ open_order_margins = (
+ _number(
+ account_row.get("openOrderInitialMargin"),
+ "openOrderInitialMargin",
+ non_negative=True,
+ ),
+ _number(
+ risk_row.get("openOrderInitialMargin"),
+ "openOrderInitialMargin",
+ non_negative=True,
+ ),
+ )
+ if any(open_order_margins):
+ raise UsdMObservationError("Binance USD-M Shadow Account requires zero open-order margin")
+ for account_field, risk_field in (
+ ("positionInitialMargin", "positionInitialMargin"),
+ ("maintMargin", "maintMargin"),
+ ("unrealizedProfit", "unRealizedProfit"),
+ ):
+ if not close_enough(
+ _number(account_row.get(account_field), account_field),
+ _number(risk_row.get(risk_field), risk_field),
+ ):
+ raise UsdMObservationError("Binance USD-M position reads are incoherent")
+ if str(risk_row.get("marginAsset") or "").upper() != "USDT":
+ raise UsdMObservationError("Binance USD-M Shadow Account supports USDT collateral only")
+ isolated = account_row.get("isolated")
+ if not isinstance(isolated, bool):
+ raise UsdMObservationError("Binance USD-M margin mode is missing")
+ isolated_margin = _number(
+ risk_row.get("isolatedMargin"),
+ "isolatedMargin",
+ non_negative=True,
+ )
+ if isolated and isolated_margin == 0:
+ raise UsdMObservationError("Binance USD-M isolated position requires positive isolated margin")
+ if not isolated and isolated_margin != 0:
+ raise UsdMObservationError("Binance USD-M cross position must report zero isolated margin")
+ result.append(
+ {
+ "symbol": _canonical_symbol(raw_symbol),
+ "quantity": quantity,
+ "entry_price": entry_price,
+ "leverage": _number(account_row.get("leverage"), "leverage", positive=True),
+ "margin_mode": "isolated" if isolated else "cross",
+ "isolated_margin": isolated_margin if isolated else None,
+ "unrealized_pnl": _number(risk_row.get("unRealizedProfit"), "unRealizedProfit"),
+ "initial_margin": _number(
+ risk_row.get("positionInitialMargin"),
+ "positionInitialMargin",
+ non_negative=True,
+ ),
+ "maintenance_margin": _number(risk_row.get("maintMargin"), "maintMargin", non_negative=True),
+ "update_time": _integer(risk_row.get("updateTime"), "updateTime"),
+ }
+ )
+ return result
+
+
+def _require_usdt_assets(account: Mapping[str, Any]) -> Mapping[str, Any]:
+ assets = _mapping_rows(account.get("assets"), "assets")
+ usdt_asset: Mapping[str, Any] | None = None
+ balance_fields = (
+ "walletBalance",
+ "marginBalance",
+ "availableBalance",
+ "initialMargin",
+ "positionInitialMargin",
+ "openOrderInitialMargin",
+ "maintMargin",
+ "unrealizedProfit",
+ )
+ for asset in assets:
+ symbol = str(asset.get("asset") or "").upper()
+ balances = tuple(_number(asset.get(field), field) for field in balance_fields)
+ if symbol == "USDT":
+ if usdt_asset is not None:
+ raise UsdMObservationError("Binance USD-M assets must include exactly one USDT row")
+ usdt_asset = asset
+ elif any(value != 0 for value in balances):
+ raise UsdMObservationError("Binance USD-M Shadow Account supports the USDT asset only")
+ if usdt_asset is None:
+ raise UsdMObservationError("Binance USD-M assets must include USDT")
+ return usdt_asset
+
+
+def _require_coherent_totals(
+ account: Mapping[str, float],
+ positions: list[dict[str, Any]],
+ close_enough: CloseEnough,
+) -> None:
+ comparisons = (
+ (
+ account["total_unrealized_pnl"],
+ sum(row["unrealized_pnl"] for row in positions),
+ ),
+ (
+ account["total_initial_margin"],
+ sum(row["initial_margin"] for row in positions),
+ ),
+ (
+ account["total_maintenance_margin"],
+ sum(row["maintenance_margin"] for row in positions),
+ ),
+ (
+ account["margin_balance"],
+ account["wallet_balance"] + account["total_unrealized_pnl"],
+ ),
+ )
+ if any(not close_enough(reported, derived) for reported, derived in comparisons):
+ raise UsdMObservationError("Binance USD-M account totals are incoherent")
+
+
+def _mapping_rows(value: Any, name: str) -> list[Mapping[str, Any]]:
+ if not isinstance(value, list) or any(not isinstance(row, Mapping) for row in value):
+ raise UsdMObservationError(f"Binance USD-M {name} payload is invalid")
+ return value
+
+
+def _require_one_way(rows: list[Mapping[str, Any]]) -> None:
+ if any(str(row.get("positionSide") or "").upper() != "BOTH" for row in rows):
+ raise UsdMObservationError("Binance USD-M Shadow Account requires one-way position mode")
+
+
+def _active_by_symbol(rows: list[Mapping[str, Any]], source: str) -> dict[str, Mapping[str, Any]]:
+ active: dict[str, Mapping[str, Any]] = {}
+ for row in rows:
+ quantity = _number(row.get("positionAmt"), "positionAmt")
+ if quantity == 0:
+ continue
+ symbol = str(row.get("symbol") or "").upper()
+ _canonical_symbol(symbol)
+ if symbol in active:
+ raise UsdMObservationError(f"duplicate {source} position symbol")
+ active[symbol] = row
+ return active
+
+
+def _canonical_symbol(symbol: str) -> str:
+ if not symbol.endswith("USDT") or len(symbol) <= 4 or not symbol.isalnum():
+ raise UsdMObservationError("Binance USD-M supports canonical */USDT symbols only")
+ return f"{symbol[:-4]}-USDT-PERP"
+
+
+def _number(
+ value: Any,
+ name: str,
+ *,
+ non_negative: bool = False,
+ positive: bool = False,
+) -> float:
+ try:
+ number = float(value)
+ except (TypeError, ValueError) as exc:
+ raise UsdMObservationError(f"Binance USD-M field {name} must be numeric") from exc
+ if not math.isfinite(number):
+ raise UsdMObservationError(f"Binance USD-M field {name} must be finite")
+ if positive and number <= 0:
+ raise UsdMObservationError(f"Binance USD-M field {name} must be positive")
+ if non_negative and number < 0:
+ raise UsdMObservationError(f"Binance USD-M field {name} must be non-negative")
+ return number
+
+
+def _integer(value: Any, name: str) -> int:
+ number = _number(value, name, non_negative=True)
+ if not number.is_integer():
+ raise UsdMObservationError(f"Binance USD-M field {name} must be an integer")
+ return int(number)
+
+
+def _configuration_hash(source_profile: str, host: str, absolute_tolerance: float) -> str:
+ payload = {
+ "schema_version": SCHEMA_VERSION,
+ "source_profile": source_profile,
+ "market_type": "usdm",
+ "host": host,
+ "account_endpoint": "/fapi/v2/account",
+ "position_endpoint": "/fapi/v3/positionRisk",
+ "observation_absolute_tolerance": absolute_tolerance,
+ "observation_relative_tolerance": OBSERVATION_RELATIVE_TOLERANCE,
+ }
+ encoded = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
+ return hashlib.sha256(encoded).hexdigest()
diff --git a/agent/tests/test_binance_account_reconciliation.py b/agent/tests/test_binance_account_reconciliation.py
index f235bf0db..68eaba4a5 100644
--- a/agent/tests/test_binance_account_reconciliation.py
+++ b/agent/tests/test_binance_account_reconciliation.py
@@ -27,6 +27,44 @@ from backtest.perpetual_risk import (
OBSERVED_AT = pd.Timestamp("2026-08-15T08:00:00Z")
+def _connector_observation(**changes: object) -> dict[str, object]:
+ observation: dict[str, object] = {
+ "status": "ok",
+ "schema_version": "binance-usdm-account-observation-v1",
+ "observed_at": "2026-08-15T08:00:00+00:00",
+ "source": "binance-usdm",
+ "source_profile": "binance-live-sdk-readonly",
+ "market_type": "usdm",
+ "configuration_hash": "a" * 64,
+ "account": {
+ "wallet_balance": 1_000.0,
+ "margin_balance": 1_100.0,
+ "available_balance": 490.0,
+ "total_unrealized_pnl": 100.0,
+ "total_initial_margin": 610.0,
+ "total_maintenance_margin": 24.4,
+ "open_order_initial_margin": 0.0,
+ },
+ "positions": [
+ {
+ "symbol": "BTC-USDT-PERP",
+ "quantity": 0.1,
+ "entry_price": 60_000.0,
+ "leverage": 10.0,
+ "margin_mode": "cross",
+ "isolated_margin": None,
+ "unrealized_pnl": 100.0,
+ "initial_margin": 610.0,
+ "maintenance_margin": 24.4,
+ "update_time": 1_787_664_600_000,
+ }
+ ],
+ "fidelity_flags": ["client_observation_time", "sequential_signed_reads"],
+ }
+ observation.update(changes)
+ return observation
+
+
def _local_cross() -> tuple[AccountState, RiskSnapshot]:
position = PositionState("BTC-USDT-PERP", 0.1, 60_000.0, 10.0, 3.0, None)
account = AccountState(1_000.0, (position,), "cross")
@@ -80,6 +118,73 @@ def test_snapshot_contracts_are_frozen_and_reject_spot_sources() -> None:
)
+def test_connector_observation_normalizes_into_frozen_snapshot() -> None:
+ snapshot = reconciliation_module.snapshot_from_binance_usdm_observation(
+ _connector_observation()
+ )
+
+ assert snapshot == BinanceAccountSnapshot(
+ schema_version="binance-usdm-account-observation-v1",
+ observed_at=OBSERVED_AT,
+ source="binance-usdm",
+ source_profile="binance-live-sdk-readonly",
+ configuration_hash="a" * 64,
+ data_status="complete",
+ wallet_balance=1_000.0,
+ margin_balance=1_100.0,
+ available_balance=490.0,
+ total_unrealized_pnl=100.0,
+ total_initial_margin=610.0,
+ total_maintenance_margin=24.4,
+ positions=(
+ BinancePositionSnapshot(
+ "BTC-USDT-PERP",
+ 0.1,
+ 60_000.0,
+ 10.0,
+ "cross",
+ None,
+ 100.0,
+ 610.0,
+ 24.4,
+ ),
+ ),
+ fidelity_flags=("client_observation_time", "sequential_signed_reads"),
+ )
+
+
+ "observation",
+ [
+ _connector_observation(status="error"),
+ _connector_observation(source="binance-spot"),
+ _connector_observation(market_type="spot"),
+ _connector_observation(schema_version="unexpected-schema"),
+ _connector_observation(fidelity_flags=[]),
+ _connector_observation(source_profile=None),
+ _connector_observation(source_profile="other-readonly"),
+ _connector_observation(configuration_hash=None),
+ _connector_observation(configuration_hash="not-a-sha256"),
+ _connector_observation(
+ account={
+ "wallet_balance": 1_000.0,
+ "margin_balance": 1_100.0,
+ "available_balance": 490.0,
+ "total_unrealized_pnl": 100.0,
+ "total_initial_margin": 610.0,
+ "total_maintenance_margin": 24.4,
+ "open_order_initial_margin": 1.0,
+ }
+ ),
+ ],
+)
+def test_connector_observation_normalizer_fails_closed(
+ observation: dict[str, object],
+) -> None:
+ with pytest.raises(ValueError):
+ reconciliation_module.snapshot_from_binance_usdm_observation(observation)
+
+
def test_matching_snapshot_completes_comparison_without_validation_claim() -> None:
account, risk = _local_cross()
diff --git a/agent/tests/test_binance_usdm_readonly.py b/agent/tests/test_binance_usdm_readonly.py
new file mode 100644
index 000000000..4027babcb
--- /dev/null
+++ b/agent/tests/test_binance_usdm_readonly.py
@@ -0,0 +1,509 @@
+"""Read-only Binance USD-M connector coverage for Shadow Account observations."""
+
+from __future__ import annotations
+
+from copy import deepcopy
+from datetime import datetime, timezone
+from types import SimpleNamespace
+
+import pytest
+
+from src.tools import trading_connector_tool
+from src.trading.connectors.binance import sdk as bn
+from src.trading.connectors.binance.classification import BINANCE_TOOL_CLASS
+from src.live.classification import ToolClass
+
+
+def _account_payload() -> dict[str, object]:
+ return {
+ "multiAssetsMargin": False,
+ "totalWalletBalance": "1000",
+ "totalMarginBalance": "1050",
+ "availableBalance": "700",
+ "totalUnrealizedProfit": "50",
+ "totalPositionInitialMargin": "180",
+ "totalMaintMargin": "9",
+ "totalOpenOrderInitialMargin": "0",
+ "assets": [
+ {
+ "asset": "USDT",
+ "walletBalance": "1000",
+ "marginBalance": "1050",
+ "availableBalance": "700",
+ "initialMargin": "180",
+ "positionInitialMargin": "180",
+ "openOrderInitialMargin": "0",
+ "maintMargin": "9",
+ "unrealizedProfit": "50",
+ }
+ ],
+ "positions": [
+ {
+ "symbol": "BTCUSDT",
+ "positionSide": "BOTH",
+ "positionAmt": "0.01",
+ "entryPrice": "60000",
+ "leverage": "10",
+ "isolated": False,
+ "positionInitialMargin": "60",
+ "maintMargin": "3",
+ "unrealizedProfit": "20",
+ "openOrderInitialMargin": "0",
+ },
+ {
+ "symbol": "ETHUSDT",
+ "positionSide": "BOTH",
+ "positionAmt": "-0.2",
+ "entryPrice": "3000",
+ "leverage": "5",
+ "isolated": True,
+ "positionInitialMargin": "120",
+ "maintMargin": "6",
+ "unrealizedProfit": "30",
+ "openOrderInitialMargin": "0",
+ },
+ ],
+ }
+
+
+def _position_risk_payload() -> list[dict[str, object]]:
+ return [
+ {
+ "symbol": "BTCUSDT",
+ "positionSide": "BOTH",
+ "positionAmt": "0.01",
+ "entryPrice": "60000",
+ "isolatedMargin": "0",
+ "marginAsset": "USDT",
+ "unRealizedProfit": "20",
+ "positionInitialMargin": "60",
+ "maintMargin": "3",
+ "openOrderInitialMargin": "0",
+ "updateTime": 1_787_664_600_000,
+ },
+ {
+ "symbol": "ETHUSDT",
+ "positionSide": "BOTH",
+ "positionAmt": "-0.2",
+ "entryPrice": "3000",
+ "isolatedMargin": "130",
+ "marginAsset": "USDT",
+ "unRealizedProfit": "30",
+ "positionInitialMargin": "120",
+ "maintMargin": "6",
+ "openOrderInitialMargin": "0",
+ "updateTime": 1_787_664_601_000,
+ },
+ ]
+
+
+class _FakeUsdMReads:
+ def __init__(
+ self,
+ account: dict[str, object] | None = None,
+ positions: list[dict[str, object]] | None = None,
+ ) -> None:
+ self.account = account if account is not None else _account_payload()
+ self.positions = positions if positions is not None else _position_risk_payload()
+ self.calls: list[str] = []
+
+ def fapiprivatev2_get_account(self) -> dict[str, object]:
+ self.calls.append("account-v2")
+ return self.account
+
+ def fapiprivatev3_get_positionrisk(self) -> list[dict[str, object]]:
+ self.calls.append("position-risk-v3")
+ return self.positions
+
+
+def _usdm_config(**changes: object) -> bn.BinanceConfig:
+ payload = {
+ "api_key": "key",
+ "api_secret": "secret",
+ "profile": "live-readonly",
+ "market_type": "usdm",
+ }
+ payload.update(changes)
+ return bn.BinanceConfig.from_mapping(payload)
+
+
+def test_usdm_config_reuses_live_readonly_profile_and_futures_host() -> None:
+ config = bn.BinanceConfig.from_mapping({"profile": "live-readonly", "market_type": "usdm"})
+
+ assert config.market_type == "usdm"
+ assert config.host == "https://fapi.binance.com"
+ assert config.is_testnet is False
+
+ with pytest.raises(bn.BinanceConfigError, match="live-readonly"):
+ bn.BinanceConfig.from_mapping({"profile": "live", "market_type": "usdm"})
+ with pytest.raises(bn.BinanceConfigError, match="market_type"):
+ bn.BinanceConfig.from_mapping({"profile": "live-readonly", "market_type": "coinm"})
+ with pytest.raises(bn.BinanceConfigError, match="observation_absolute_tolerance"):
+ _usdm_config(observation_absolute_tolerance=-1)
+
+
+def test_usdm_exchange_uses_binanceusdm_and_validates_private_hosts(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ captured: dict[str, object] = {}
+
+ class FakeUsdM:
+ def __init__(self, config: dict[str, object]) -> None:
+ captured["config"] = config
+ self.urls = {
+ "api": {
+ "fapiPrivateV2": "https://fapi.binance.com/fapi/v2",
+ "fapiPrivateV3": "https://fapi.binance.com/fapi/v3",
+ }
+ }
+
+ def set_sandbox_mode(self, enabled: bool) -> None:
+ captured["sandbox"] = enabled
+
+ class UnexpectedSpot:
+ def __init__(self, _config: dict[str, object]) -> None:
+ raise AssertionError("USD-M read must not build the spot client")
+
+ monkeypatch.setattr(
+ bn,
+ "_require_ccxt",
+ lambda: SimpleNamespace(binance=UnexpectedSpot, binanceusdm=FakeUsdM),
+ )
+ monkeypatch.setattr(bn, "getproxies", lambda: {})
+
+ exchange = bn._exchange(
+ bn.BinanceConfig.from_mapping(
+ {
+ "api_key": "key",
+ "api_secret": "secret",
+ "profile": "live-readonly",
+ "market_type": "usdm",
+ }
+ )
+ )
+
+ assert isinstance(exchange, FakeUsdM)
+ assert captured["sandbox"] is False
+ assert captured["config"]["options"] == {
+ "adjustForTimeDifference": True,
+ "recvWindow": 10_000,
+ }
+
+
+ "bad_url",
+ [
+ "https://example.invalid/fapi/v2",
+ "http://fapi.binance.com/fapi/v2",
+ "https://fapi.binance.com:8443/fapi/v2",
+ "https://fapi.binance.com/fapi/v1",
+ "https://fapi.binance.com/fapi/v2?redirect=1",
+ "https://fapi.binance.com/fapi/v2#fragment",
+ ],
+)
+def test_usdm_exchange_rejects_unapproved_private_endpoint(
+ monkeypatch: pytest.MonkeyPatch,
+ bad_url: str,
+) -> None:
+ class RedirectedUsdM:
+ def __init__(self, _config: dict[str, object]) -> None:
+ self.urls = {
+ "api": {
+ "fapiPrivateV2": bad_url,
+ "fapiPrivateV3": "https://fapi.binance.com/fapi/v3",
+ }
+ }
+
+ def set_sandbox_mode(self, _enabled: bool) -> None:
+ return None
+
+ monkeypatch.setattr(
+ bn,
+ "_require_ccxt",
+ lambda: SimpleNamespace(binanceusdm=RedirectedUsdM),
+ )
+ monkeypatch.setattr(bn, "getproxies", lambda: {})
+
+ with pytest.raises(bn.BinanceConfigError, match="unapproved host"):
+ bn._exchange(bn.BinanceConfig.from_mapping({"profile": "live-readonly", "market_type": "usdm"}))
+
+
+def test_trading_tools_forward_explicit_market_type_override() -> None:
+ assert "market_type" in trading_connector_tool.TRADING_COMMON_PARAMETERS
+ overrides = trading_connector_tool._overrides({"market_type": "usdm", "observation_absolute_tolerance": 0.1})
+ assert overrides["market_type"] == "usdm"
+ assert overrides["observation_absolute_tolerance"] == 0.1
+
+
+def test_usdm_config_cannot_reach_spot_order_methods(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ config = bn.BinanceConfig.from_mapping({"profile": "live-readonly", "market_type": "usdm"})
+ exchange_calls = 0
+
+ def unexpected_exchange(_config: bn.BinanceConfig) -> None:
+ nonlocal exchange_calls
+ exchange_calls += 1
+ raise AssertionError("write path reached an exchange client")
+
+ monkeypatch.setattr(bn, "_exchange", unexpected_exchange)
+
+ placed = bn.place_order(
+ config,
+ symbol="BTC/USDT:USDT",
+ side="buy",
+ quantity=0.001,
+ )
+ cancelled = bn.cancel_order(config, "order-1", symbol="BTC/USDT:USDT")
+
+ expected = "Binance USD-M Shadow Account is read-only"
+ assert placed == {"status": "error", "error": expected}
+ assert cancelled == {"status": "error", "error": expected}
+ assert exchange_calls == 0
+
+
+def test_usdm_account_snapshot_combines_signed_account_and_position_reads(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ exchange = _FakeUsdMReads()
+ times = iter(
+ (
+ datetime(2026, 8, 26, 10, 0, 0, tzinfo=timezone.utc),
+ datetime(2026, 8, 26, 10, 0, 2, tzinfo=timezone.utc),
+ )
+ )
+ monkeypatch.setattr(bn, "_exchange", lambda _config: exchange)
+ monkeypatch.setattr(bn, "_utc_now", lambda: next(times), raising=False)
+
+ result = bn.get_account_snapshot(_usdm_config())
+
+ assert exchange.calls == ["account-v2", "position-risk-v3"]
+ assert result["status"] == "ok"
+ assert result["source"] == "binance-usdm"
+ assert result["source_profile"] == "binance-live-sdk-readonly"
+ assert result["market_type"] == "usdm"
+ assert result["schema_version"] == "binance-usdm-account-observation-v1"
+ assert result["observed_at"] == "2026-08-26T10:00:02+00:00"
+ assert result["observation_span_seconds"] == 2.0
+ assert len(result["configuration_hash"]) == 64
+ assert "key" not in str(result)
+ assert "secret" not in str(result)
+ assert result["account"] == {
+ "wallet_balance": 1000.0,
+ "margin_balance": 1050.0,
+ "available_balance": 700.0,
+ "total_unrealized_pnl": 50.0,
+ "total_initial_margin": 180.0,
+ "total_maintenance_margin": 9.0,
+ "open_order_initial_margin": 0.0,
+ }
+ assert result["positions"] == [
+ {
+ "symbol": "BTC-USDT-PERP",
+ "quantity": 0.01,
+ "entry_price": 60000.0,
+ "leverage": 10.0,
+ "margin_mode": "cross",
+ "isolated_margin": None,
+ "unrealized_pnl": 20.0,
+ "initial_margin": 60.0,
+ "maintenance_margin": 3.0,
+ "update_time": 1_787_664_600_000,
+ },
+ {
+ "symbol": "ETH-USDT-PERP",
+ "quantity": -0.2,
+ "entry_price": 3000.0,
+ "leverage": 5.0,
+ "margin_mode": "isolated",
+ "isolated_margin": 130.0,
+ "unrealized_pnl": 30.0,
+ "initial_margin": 120.0,
+ "maintenance_margin": 6.0,
+ "update_time": 1_787_664_601_000,
+ },
+ ]
+ assert result["fidelity_flags"] == [
+ "client_observation_time",
+ "sequential_signed_reads",
+ ]
+
+
+def test_usdm_positions_reuse_the_same_strict_observation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ exchange = _FakeUsdMReads()
+ monkeypatch.setattr(bn, "_exchange", lambda _config: exchange)
+
+ result = bn.get_positions(_usdm_config())
+
+ assert exchange.calls == ["account-v2", "position-risk-v3"]
+ assert [position["symbol"] for position in result["positions"]] == [
+ "BTC-USDT-PERP",
+ "ETH-USDT-PERP",
+ ]
+ assert result["source"] == "binance-usdm"
+
+
+def test_usdm_dynamic_tolerance_is_explicit_and_configurable(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ positions = _position_risk_payload()
+ positions[0]["unRealizedProfit"] = "20.01"
+ monkeypatch.setattr(
+ bn,
+ "_exchange",
+ lambda _config: _FakeUsdMReads(_account_payload(), positions),
+ )
+
+ with pytest.raises(bn.BinanceConfigError, match="incoherent"):
+ bn.get_account_snapshot(_usdm_config())
+
+ result = bn.get_account_snapshot(_usdm_config(observation_absolute_tolerance=0.1))
+
+ assert result["positions"][0]["unrealized_pnl"] == 20.01
+
+
+def test_usdm_status_counts_positions_not_spot_balances(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(bn, "ccxt_available", lambda: True)
+ monkeypatch.setattr(bn, "_exchange", lambda _config: _FakeUsdMReads())
+
+ result = bn.check_status(_usdm_config())
+
+ assert result["status"] == "ok"
+ assert result["account"] == {
+ "profile": "live-readonly",
+ "is_testnet": False,
+ "positions": 2,
+ }
+
+
+def test_usdm_allows_only_the_two_curated_private_read_methods() -> None:
+ assert BINANCE_TOOL_CLASS["fapiprivatev2_get_account"] is ToolClass.READ
+ assert BINANCE_TOOL_CLASS["fapiprivatev3_get_positionrisk"] is ToolClass.READ
+
+
+def test_usdm_rejects_non_shadow_read_surfaces_before_client_creation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ exchange_calls = 0
+
+ def unexpected_exchange(_config: bn.BinanceConfig) -> None:
+ nonlocal exchange_calls
+ exchange_calls += 1
+ raise AssertionError("unsupported USD-M surface reached the client")
+
+ monkeypatch.setattr(bn, "_exchange", unexpected_exchange)
+ config = _usdm_config()
+
+ for call in (
+ lambda: bn.get_open_orders(config),
+ lambda: bn.get_quote("BTC-USDT-PERP", config=config),
+ lambda: bn.get_historical_bars("BTC-USDT-PERP", config=config),
+ ):
+ with pytest.raises(bn.BinanceConfigError, match="account and position reads"):
+ call()
+ assert exchange_calls == 0
+
+
+def test_usdm_endpoint_failure_propagates_without_fallback(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class FailedRead(_FakeUsdMReads):
+ def fapiprivatev2_get_account(self) -> dict[str, object]:
+ raise RuntimeError("synthetic endpoint failure")
+
+ monkeypatch.setattr(bn, "_exchange", lambda _config: FailedRead())
+
+ with pytest.raises(RuntimeError, match="synthetic endpoint failure"):
+ bn.get_account_snapshot(_usdm_config())
+
+
+ ("mutate", "message"),
+ [
+ (
+ lambda account, _positions: account.__setitem__("multiAssetsMargin", True),
+ "multi-asset margin",
+ ),
+ (
+ lambda account, _positions: account.__setitem__("totalOpenOrderInitialMargin", "1"),
+ "open-order margin",
+ ),
+ (
+ lambda account, _positions: account["positions"][0].__setitem__("positionSide", "LONG"),
+ "one-way",
+ ),
+ (
+ lambda _account, positions: positions[0].__setitem__("marginAsset", "USDC"),
+ "USDT collateral",
+ ),
+ (
+ lambda _account, positions: positions[0].__setitem__("positionAmt", "0.02"),
+ "incoherent",
+ ),
+ (
+ lambda _account, positions: positions[0].__setitem__("openOrderInitialMargin", "1"),
+ "open-order margin",
+ ),
+ (
+ lambda _account, positions: positions[0].__setitem__("positionSide", "LONG"),
+ "one-way",
+ ),
+ (
+ lambda _account, positions: positions[0].__setitem__("isolatedMargin", "10"),
+ "cross position",
+ ),
+ (
+ lambda account, _positions: account["positions"][0].__setitem__("positionInitialMargin", "999"),
+ "incoherent",
+ ),
+ (
+ lambda account, _positions: account.__setitem__("totalPositionInitialMargin", "999"),
+ "account totals",
+ ),
+ (lambda account, _positions: account.pop("assets"), "assets"),
+ (
+ lambda account, _positions: account["assets"].append(
+ {
+ "asset": "USDC",
+ "walletBalance": "1",
+ "marginBalance": "1",
+ "availableBalance": "1",
+ "initialMargin": "0",
+ "positionInitialMargin": "0",
+ "openOrderInitialMargin": "0",
+ "maintMargin": "0",
+ "unrealizedProfit": "0",
+ }
+ ),
+ "USDT asset",
+ ),
+ (
+ lambda account, _positions: account["assets"][0].__setitem__("walletBalance", "999"),
+ "asset totals",
+ ),
+ (
+ lambda account, _positions: account["assets"].append(deepcopy(account["assets"][0])),
+ "exactly one USDT",
+ ),
+ ],
+)
+def test_usdm_observation_fails_closed_for_unsupported_or_incoherent_state(
+ monkeypatch: pytest.MonkeyPatch,
+ mutate,
+ message: str,
+) -> None:
+ account = deepcopy(_account_payload())
+ positions = deepcopy(_position_risk_payload())
+ mutate(account, positions)
+ monkeypatch.setattr(
+ bn,
+ "_exchange",
+ lambda _config: _FakeUsdMReads(account, positions),
+ )
+
+ with pytest.raises(bn.BinanceConfigError, match=message):
+ bn.get_account_snapshot(_usdm_config())