Files
Hermes-Skills/okx-auto-position/references/okx-raw-api-pos-parsing.md
T

1.3 KiB
Raw Blame History

OKX Raw API 持仓查询 Pitfall

问题

直接调用 OKX REST API /api/v5/account/positions 时,在 net_mode 下:

{
  "posSide": "net",   // ← 不是 "long" 或 "short"
  "pos": "10",         // ← 正数=多头,负数=空头
  "avgPx": "1764.538",
  "upl": "12.62",
  "liqPx": "1638.69"
}

错误解析方式:

side = "long" if pos_side == "long" else "short"  # ❌ net_mode 下永远是 "short"

正确解析方式:

side = "long" if float(pos) >= 0 else "short"  # ✅ 用 pos 值判断

为什么

  • posSide 在 net_mode 下固定返回 "net"(表示净头寸模式)
  • 实际方向由 pos 值的正负决定:正=多头,负=空头
  • ccxt 的 fetch_balance() 和自定义的 get_account_info() 已正确处理
  • 但直接用 curl/requests 调 API 时需要手动判断

影响

  • 误报持仓方向(多头显示为空头)
  • 可能导致错误的平仓/加仓决策

修复

所有直接调用 /api/v5/account/positions 的地方,判断方向时用 pos 而非 posSide

for p in d["data"]:
    pos_val = float(p.get("pos", 0))
    side = "long" if pos_val >= 0 else "short"
    contracts = abs(pos_val)

实测案例(2026-07-05

用户ETH持仓实际为 long 10张,但原始解析显示 "short 10张",导致误报。