OKX API v5 Skill
Overview
OKX API v5 provides REST and WebSocket interfaces for spot trading, derivatives (perpetual swaps, futures, options), market data, and account management.
- - Base URL: INLINECODE0
- API version prefix: INLINECODE1
- Demo/sandbox: same base URL, add header INLINECODE2
- Auth: HMAC SHA256 signature (private endpoints only)
- Rate limits: public endpoints by IP; private endpoints by User ID
All examples use scripts/okx_auth.py — a reusable helper that handles credential loading, signing, and response parsing.
Configuration Setup
Store credentials in ~/.openclaw/openclaw.json under the top-level env field. OpenClaw automatically injects these into the agent environment:
CODEBLOCK0
Set OKX_DEMO=1 to use sandbox mode (paper trading). Remove or set to 0 for live trading.
You can also export these in your shell:
CODEBLOCK1
Authentication
Private endpoints require four request headers:
| Header | Value |
|---|
| INLINECODE8 | Your API key |
| INLINECODE9 |
Base64(HmacSHA256(pre-sign, secret)) |
|
OK-ACCESS-TIMESTAMP | ISO 8601 UTC timestamp with milliseconds |
|
OK-ACCESS-PASSPHRASE | Your passphrase |
|
Content-Type |
application/json (POST only) |
Signature formula:
CODEBLOCK2
- -
timestamp: e.g. INLINECODE15 - INLINECODE16 : uppercase GET or POST
- INLINECODE17 : e.g.
/api/v5/account/balance or INLINECODE19 - INLINECODE20 : JSON string for POST, empty string
"" for GET
Use scripts/okx_auth.py — it handles all of this automatically. See references/authentication.md for edge cases and error codes.
Common Operations Quick Reference
| Intent | Method | Endpoint |
|---|
| Get account balance | GET | INLINECODE24 |
| Get positions |
GET |
/api/v5/account/positions |
| Get ticker (spot price) | GET |
/api/v5/market/ticker?instId=BTC-USDT |
| Get candlestick data | GET |
/api/v5/market/candles?instId=BTC-USDT&bar=1H |
| Get order book | GET |
/api/v5/market/books?instId=BTC-USDT&sz=20 |
| Get recent trades | GET |
/api/v5/market/trades?instId=BTC-USDT |
| Place order | POST |
/api/v5/trade/order |
| Amend order | POST |
/api/v5/trade/amend-order |
| Cancel order | POST |
/api/v5/trade/cancel-order |
| Get open orders | GET |
/api/v5/trade/orders-pending |
| Get order history | GET |
/api/v5/trade/orders-history |
| Get instruments | GET |
/api/v5/public/instruments?instType=SPOT |
| Get funding rate | GET |
/api/v5/public/funding-rate?instId=BTC-USDT-SWAP |
Response Handling
All REST responses follow this envelope:
CODEBLOCK3
- -
code: "0" — success - Any other code — error; check
msg for details - INLINECODE39 is always an array (even for single objects)
Common error codes:
| Code | Meaning |
|---|
| INLINECODE40 | Rate limit exceeded — back off and retry |
| INLINECODE41 |
Invalid API key |
|
50113 | Invalid signature |
|
50114 | Timestamp out of range (±30s tolerance) |
|
51000 | Parameter error — check required fields |
|
51008 | Insufficient balance |
The make_request() function in scripts/okx_auth.py raises a RuntimeError when code != "0", so you can catch errors cleanly.
Rate Limits
OKX enforces rate limits per endpoint group:
| Category | Limit |
|---|
| Public market data | 20 req/2s per IP |
| Account endpoints |
10 req/2s per UID |
| Trade order placement | 60 req/2s per UID |
| Order cancellation | 60 req/2s per UID |
If you hit 50011, sleep 2 seconds and retry. For bulk operations, use batch endpoints:
- -
POST /api/v5/trade/batch-orders — place up to 20 orders - INLINECODE52 — cancel up to 20 orders
Place Order — Key Parameters
CODEBLOCK4
| Field | Values |
|---|
| INLINECODE53 | INLINECODE54 (spot), BTC-USDT-SWAP (perp), BTC-USD-241227 (futures) |
| INLINECODE57 |
cash (spot),
cross (cross margin),
isolated |
|
side |
buy or
sell |
|
ordType |
limit,
market,
post_only,
fok,
ioc |
|
px | Price (required for limit orders) |
|
sz | Size in base currency (spot) or contracts (derivatives) |
See examples/place-order.py for a complete working example.
WebSocket
For real-time data (prices, order updates, position changes), use WebSocket instead of polling REST.
- - Public: INLINECODE73
- Private: INLINECODE74
Subscribe to channels by sending JSON messages. Private channels require a login operation first using the same HMAC signature scheme.
See references/websocket.md and examples/websocket-ticker.py.
References
- -
references/authentication.md — Signature details, edge cases, auth error troubleshooting - INLINECODE79 — All public REST endpoints with params and response fields
- INLINECODE80 — All private REST endpoints, order types, instrument types
- INLINECODE81 — WebSocket URLs, subscription format, private channel auth, common channels
- INLINECODE82 — Fetch and display account balance
- INLINECODE83 — Ticker and candlestick data
- INLINECODE84 — Place a limit buy order
- INLINECODE85 — Real-time price subscription
- INLINECODE86 — Reusable auth/request helper (import in your scripts)
技能名称: okx-api
详细描述:
OKX API v5 技能
概述
OKX API v5 提供 REST 和 WebSocket 接口,用于现货交易、衍生品(永续合约、交割合约、期权)、市场数据和账户管理。
- - 基础 URL: https://www.okx.com
- API 版本前缀: /api/v5/
- 演示/沙箱: 相同的基础 URL,添加请求头 x-simulated-trading: 1
- 认证: HMAC SHA256 签名(仅限私有端点)
- 速率限制: 公共端点按 IP 限制;私有端点按用户 ID 限制
所有示例均使用 scripts/okx_auth.py — 一个可复用的辅助工具,用于处理凭证加载、签名和响应解析。
配置设置
将凭证存储在 ~/.openclaw/openclaw.json 的顶级 env 字段下。OpenClaw 会自动将这些注入到代理环境中:
json
{
env: {
OKXAPIKEY: your-api-key,
OKXSECRETKEY: your-secret-key,
OKX_PASSPHRASE: your-passphrase,
OKX_DEMO: 1
}
}
设置 OKX_DEMO=1 以使用沙箱模式(模拟交易)。移除或设置为 0 以进行实盘交易。
你也可以在 shell 中导出这些变量:
bash
export OKXAPIKEY=your-api-key
export OKXSECRETKEY=your-secret-key
export OKX_PASSPHRASE=your-passphrase
export OKX_DEMO=1
认证
私有端点需要四个请求头:
| 请求头 | 值 |
|---|
| OK-ACCESS-KEY | 你的 API 密钥 |
| OK-ACCESS-SIGN |
Base64(HmacSHA256(预签名, 密钥)) |
| OK-ACCESS-TIMESTAMP | 带毫秒的 ISO 8601 UTC 时间戳 |
| OK-ACCESS-PASSPHRASE | 你的密码短语 |
| Content-Type | application/json(仅限 POST) |
签名公式:
预签名 = 时间戳 + 方法 + 路径及查询参数 + 请求体
签名 = base64(hmac_sha256(预签名, 密钥))
- - 时间戳: 例如 2024-01-15T10:30:00.123Z
- 方法: 大写的 GET 或 POST
- 路径及查询参数: 例如 /api/v5/account/balance 或 /api/v5/market/ticker?instId=BTC-USDT
- 请求体: POST 请求的 JSON 字符串,GET 请求为空字符串
使用 scripts/okx_auth.py — 它会自动处理所有这些。有关边界情况和错误代码,请参阅 references/authentication.md。
常用操作快速参考
| 意图 | 方法 | 端点 |
|---|
| 获取账户余额 | GET | /api/v5/account/balance |
| 获取持仓 |
GET | /api/v5/account/positions |
| 获取行情(现货价格) | GET | /api/v5/market/ticker?instId=BTC-USDT |
| 获取K线数据 | GET | /api/v5/market/candles?instId=BTC-USDT&bar=1H |
| 获取订单簿 | GET | /api/v5/market/books?instId=BTC-USDT&sz=20 |
| 获取近期成交 | GET | /api/v5/market/trades?instId=BTC-USDT |
| 下单 | POST | /api/v5/trade/order |
| 修改订单 | POST | /api/v5/trade/amend-order |
| 撤销订单 | POST | /api/v5/trade/cancel-order |
| 获取当前委托 | GET | /api/v5/trade/orders-pending |
| 获取历史委托 | GET | /api/v5/trade/orders-history |
| 获取交易产品 | GET | /api/v5/public/instruments?instType=SPOT |
| 获取资金费率 | GET | /api/v5/public/funding-rate?instId=BTC-USDT-SWAP |
响应处理
所有 REST 响应遵循以下封装格式:
json
{
code: 0,
msg: ,
data: [...]
}
- - code: 0 — 成功
- 任何其他代码 — 错误;检查 msg 获取详细信息
- data 始终是一个数组(即使是单个对象)
常见错误代码:
| 代码 | 含义 |
|---|
| 50011 | 超出速率限制 — 等待后重试 |
| 50111 |
无效的 API 密钥 |
| 50113 | 无效的签名 |
| 50114 | 时间戳超出范围(±30秒容差) |
| 51000 | 参数错误 — 检查必填字段 |
| 51008 | 余额不足 |
scripts/okxauth.py 中的 makerequest() 函数在 code != 0 时会抛出 RuntimeError,因此你可以干净地捕获错误。
速率限制
OKX 按端点组执行速率限制:
| 类别 | 限制 |
|---|
| 公共市场数据 | 每个 IP 20 次请求/2秒 |
| 账户端点 |
每个 UID 10 次请求/2秒 |
| 交易下单 | 每个 UID 60 次请求/2秒 |
| 撤销订单 | 每个 UID 60 次请求/2秒 |
如果遇到 50011,请等待 2 秒后重试。对于批量操作,请使用批量端点:
- - POST /api/v5/trade/batch-orders — 最多下单 20 笔
- POST /api/v5/trade/cancel-batch-orders — 最多撤销 20 笔订单
下单 — 关键参数
json
{
instId: BTC-USDT,
tdMode: cash,
side: buy,
ordType: limit,
px: 42000,
sz: 0.001
}
| 字段 | 值 |
|---|
| instId | BTC-USDT(现货),BTC-USDT-SWAP(永续合约),BTC-USD-241227(交割合约) |
| tdMode |
cash(现货),cross(全仓),isolated(逐仓) |
| side | buy 或 sell |
| ordType | limit,market,post_only,fok,ioc |
| px | 价格(限价单必填) |
| sz | 以基础货币计的数量(现货)或以合约为单位的数量(衍生品) |
请参阅 examples/place-order.py 获取完整的可运行示例。
WebSocket
对于实时数据(价格、订单更新、持仓变动),请使用 WebSocket 而非轮询 REST。
- - 公共: wss://ws.okx.com:8443/ws/v5/public
- 私有: wss://ws.okx.com:8443/ws/v5/private
通过发送 JSON 消息订阅频道。私有频道需要先使用相同的 HMAC 签名方案执行 login 操作。
请参阅 references/websocket.md 和 examples/websocket-ticker.py。
参考资料
- - references/authentication.md — 签名细节、边界情况、认证错误排查
- references/market-data-endpoints.md — 所有公共 REST 端点及其参数和响应字段
- references/trading-endpoints.md — 所有私有 REST 端点、订单类型、产品类型
- references/websocket.md — WebSocket URL、订阅格式、私有频道认证、常用频道
- examples/get-balance.py — 获取并显示账户余额
- examples/get-market-data.py — 行情和K线数据
- examples/place-order.py — 下限价买单
- examples/websocket-ticker.py — 实时价格订阅
- scripts/okx_auth.py — 可复用的认证/请求辅助工具(在你的脚本中导入)