Fix swap-all balance by reading OKX funding via asset/balances API.

Swap-all targets funding account but ccxt free was often empty; fall back to trading USDT for unified accounts and show balances in errors.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-07-13 09:01:37 +08:00
parent c4bac23c48
commit c4753ffb89
3 changed files with 113 additions and 5 deletions
+37
View File
@@ -439,6 +439,40 @@ def fetch_account_balances_by_type(
return out, avail
def fetch_funding_balances_via_asset_api(
ex: ccxt.okx,
) -> tuple[dict[str, float | None], dict[str, float | None]]:
"""OKX 资金账户余额(GET /api/v5/asset/balances),比 ccxt fetch_balance 更准确."""
out: dict[str, float | None] = {"USDT": None, "USDC": None, "USDG": None}
avail: dict[str, float | None] = {"USDT": None, "USDC": None, "USDG": None}
try:
resp = ex.private_get_asset_balances({})
for row in (resp or {}).get("data") or []:
if not isinstance(row, dict):
continue
ccy = str(row.get("ccy") or "").upper()
if ccy not in out:
continue
a = _safe_float(row.get("availBal"))
b = _safe_float(row.get("bal")) or _safe_float(row.get("eq"))
avail[ccy] = a
out[ccy] = b if b is not None else a
except Exception:
pass
return out, avail
def _merge_balance_maps(
primary: dict[str, float | None],
secondary: dict[str, float | None],
) -> dict[str, float | None]:
merged = dict(primary)
for ccy, val in secondary.items():
if merged.get(ccy) is None and val is not None:
merged[ccy] = val
return merged
def fetch_subaccount_asset_balances(ex: ccxt.okx, sub_acct: str) -> dict[str, float | None]:
"""子账户各币种可用余额(主/子划转「全部」用)."""
sub = (sub_acct or "").strip()
@@ -489,6 +523,9 @@ def fetch_options_balances(
return dict(cached)
funding, funding_avail = fetch_account_balances_by_type(ex, "funding")
asset_funding, asset_funding_avail = fetch_funding_balances_via_asset_api(ex)
funding = _merge_balance_maps(funding, asset_funding)
funding_avail = _merge_balance_maps(funding_avail, asset_funding_avail)
trading, trading_avail = fetch_account_balances_by_type(ex, "trading")
if trading.get("USDC") is None:
swap_bal, swap_avail = fetch_account_balances_by_type(ex, "swap")