OKX Exchange Skill
Quantitative trading agent for OKX exchange via the official V5 API.
API Docs: https://www.okx.com/docs-v5/en/
Setup (First Time)
CODEBLOCK0
Important: OKX_SIMULATED=1 = paper trading (safe). Set to 0 for live trading.
Session Init
On every session, load credentials first:
CODEBLOCK1
Unified CLI (Recommended)
Use okx.py as the single entry point for all commands:
CODEBLOCK2
All individual scripts remain usable directly, but okx.py is preferred for agent use.
Instrument ID Format
| Type | Format | Example |
|---|
| Spot | INLINECODE4 | INLINECODE5 |
| Perpetual Swap |
{BASE}-{QUOTE}-SWAP |
BTC-USDT-SWAP |
| Futures |
{BASE}-{QUOTE}-{EXPIRY} |
BTC-USDT-250328 |
INLINECODE10 : cash (spot), cross (cross-margin), isolated (isolated-margin)
Account & Portfolio
CODEBLOCK3
Trading Mode (Live / Demo)
CODEBLOCK4
Live credentials use separate env vars:
CODEBLOCK5
Order Execution
CODEBLOCK6
Skip confirmation prompt (for automation):
CODEBLOCK7
Algo Orders (Standalone TP/SL — for existing positions)
Use when a position is already open and you want to add a stop-loss or take-profit separately.
Unlike --tp/--sl flags (which attach to the entry order), algo orders are independent.
CODEBLOCK8
When to use which:
- -
--tp/--sl at order time → atomic, guaranteed to attach, best for new entries - INLINECODE16 → add/replace TP+SL after entry, or adjust levels mid-trade
Strategies
Trend Following (MA + RSI + MACD)
CODEBLOCK9
Signal logic:
- - BUY: MAfast > MAslow + RSI < 70 + MACD histogram > 0
- SELL: MAfast < MAslow + RSI > 30 + MACD histogram < 0
Grid Trading
CODEBLOCK10
Spot-Futures Arbitrage
CODEBLOCK11
Snapshot Report
Fetches live data from the API on every run, persists the snapshot, and outputs a full report with a real historical tracking table.
CODEBLOCK12
Output includes:
- - Total equity, initial capital, % change (relative to first snapshot)
- Available USDT, major holdings
- Contract positions (entry price, mark price, unrealized PnL, liquidation distance)
- Historical tracking table (from
memory/okx-monitor-snapshots.json, up to 48 entries)
All figures are sourced directly from the OKX API — no estimates or fabricated values.
Automated Monitoring (Cron)
CODEBLOCK13
Cron jobs:
- -
okx-sl-tp — periodically runs snapshot + monitor sl-tp, reports live data - INLINECODE21 — periodically runs
monitor scan, reports strategy signals
Adjust cron interval (via user instruction)
If the user asks to change the monitoring frequency (e.g. "change to every 10 minutes"):
CODEBLOCK14
Manual monitor run
CODEBLOCK15
CRITICAL: Cron reporting rules
Every cron report MUST call the scripts first. NEVER fabricate, estimate, or reuse previous numbers.
Recommended single command for cron:
CODEBLOCK16
INLINECODE23 automatically saves the snapshot and generates a report with historical tracking. Forward the output verbatim — do not add, remove, or rephrase any content.
Report only what the scripts actually output. If a script returns an error, report the error — do not substitute with previously seen values.
Why this matters: Each cron run is an isolated session with no memory of previous runs. Any numbers not fetched from the API in this session are either fabricated or stale.
Performance Report
CODEBLOCK17
Output includes: trade count, win rate, total P&L, best/worst trade, and top-5 coin breakdown.
Configuration
View or update preferences without editing JSON directly:
CODEBLOCK18
Full preferences schema (~/.openclaw/workspace/memory/okx-trading-preferences.json):
CODEBLOCK19
| Parameter | Default | Description |
|---|
| INLINECODE25 | 100 | Max USD per single order |
| INLINECODE26 |
10 | Max allowed leverage |
|
price_impact_warn | 0.005 | Warn if market order impact > 0.5% |
|
price_impact_abort | 0.01 | Abort if market order impact > 1% |
|
require_confirm | true | Prompt before placing orders |
|
stop_loss_pct | 5.0 | Auto stop-loss at -X% unrealized PnL |
|
take_profit_pct | 10.0 | Auto take-profit at +X% unrealized PnL |
|
auto_trade | false | Execute trades automatically (no confirmation) |
|
max_position_usd | 100 | Max USD per position |
|
max_daily_trades | 10 | Max auto-trades per day |
|
default_sz | "0.01" | Default size for auto-trading |
|
strategies | ["trend"] | Active strategies: trend / arbitrage |
|
watchlist | [...] | Instruments for monitor scan |
Environment Variables
| Variable | Default | Description |
|---|
| INLINECODE38 | — | Demo API key |
| INLINECODE39 |
— | Demo API secret |
|
OKX_PASSPHRASE | — | Demo API passphrase |
|
OKX_API_KEY_LIVE | — | Live API key (used when
mode=live) |
|
OKX_SECRET_KEY_LIVE | — | Live API secret |
|
OKX_PASSPHRASE_LIVE | — | Live API passphrase |
|
OKX_SIMULATED |
0 | Set
1 for paper trading (demo account) |
|
OKX_WS |
0 | Set
1 to enable WebSocket feed (real-time cache for tickers/candles/account/positions) |
|
OKX_API_URL |
https://www.okx.com | Override API base URL |
|
OKX_LOG_LEVEL |
INFO |
DEBUG /
INFO /
WARNING /
ERROR |
|
OKX_LOG_FORMAT |
text |
text or
json (structured logging) |
|
OKX_CRON_MODE |
0 | Set
1 to suppress INFO output (for cron) |
WebSocket Mode (OKX_WS=1)
When enabled, a background thread maintains real-time caches:
- - Public feed: tickers, candles —
OKXClient.ticker() / candles() read from cache first - Private feed: account balances, positions, orders —
balance() / positions() read from cache first - REST API is used as fallback when cache is empty or WS is disabled
Trading Rules
Before making any buy/sell decision, read and apply the principles in:
CODEBLOCK20
These rules define how to observe the market, weigh signals, size positions, and learn from outcomes.
They do not prescribe a fixed strategy — the agent is expected to adapt its approach based on what the market is actually showing.
Safety Rules
- 1. Always confirm before placing orders unless
auto_trade=true or INLINECODE72 - Price impact check: abort if >1%, warn if >0.5%
- Start with
OKX_SIMULATED=1 — validate everything before going live - Never print or log credentials — load via
source .env only - Set stop-loss on every position — meme coins and leveraged positions can move fast
- Daily trade limit — auto-trading will stop when
max_daily_trades is reached
Memory Files
| File | Purpose |
|---|
| INLINECODE76 | Strategy config, risk parameters, and trading mode |
| INLINECODE77 |
Runtime state (daily trade count, last scan) |
|
memory/okx-trading-journal.json | Trade history from monitor (SL/TP closures, auto-entries) |
|
memory/okx-trade-journal.json | Trade history from learning system (signal analysis) |
|
memory/okx-learning-model.json | Learning model (win rates by coin/regime, optimal params) |
|
memory/okx-grid-{inst_id}.json | Grid state per instrument |
Kill Switch
CODEBLOCK21
OKX交易所技能
通过官方V5 API进行OKX交易所的量化交易代理。
API文档: https://www.okx.com/docs-v5/en/
初始设置(首次使用)
bash
1. 将凭证添加到.env文件
cat >> ~/.openclaw/workspace/.env << EOF
OKX
APIKEY=your_key
OKX
SECRETKEY=your_secret
OKX
PASSPHRASE=yourpassphrase
OKX_SIMULATED=1
EOF
2. 运行设置脚本
cd ~/.openclaw/workspace/skills/okx-exchange/scripts
python setup.py
重要提示: OKX_SIMULATED=1 = 模拟交易(安全)。设置为0进行实盘交易。
会话初始化
每次会话时,首先加载凭证:
bash
source ~/.openclaw/workspace/.env
cd ~/.openclaw/workspace/skills/okx-exchange/scripts
统一命令行界面(推荐)
使用okx.py作为所有命令的单一入口点:
bash
python3 okx.py help # 显示所有命令
python3 okx.py account # 投资组合概览
python3 okx.py buy BTC-USDT market 0.01
python3 okx.py trend analyze BTC-USDT-SWAP
所有单独的脚本仍然可以直接使用,但代理使用时推荐使用okx.py。
交易品种ID格式
| 类型 | 格式 | 示例 |
|---|
| 现货 | {基础币种}-{计价币种} | BTC-USDT |
| 永续合约 |
{基础币种}-{计价币种}-SWAP | BTC-USDT-SWAP |
| 交割合约 | {基础币种}-{计价币种}-{到期日} | BTC-USDT-250328 |
tdMode:cash(现货),cross(全仓),isolated(逐仓)
账户与投资组合
bash
python3 okx.py account # 完整投资组合摘要
python3 okx.py account balance # 仅余额
python3 okx.py account balance USDT # 特定币种
python3 okx.py account positions # 所有持仓
python3 okx.py account orders # 挂单
python3 okx.py account history # 已成交订单历史(现货)
python3 okx.py account history SWAP # 永续合约订单历史
python3 okx.py account history SPOT BTC-USDT # 特定交易对的历史
交易模式(实盘/模拟)
bash
python3 okx.py mode # 显示当前模式
python3 okx.py mode demo # 切换到模拟交易(安全)
python3 okx.py mode live # 切换到实盘交易(需要确认+实盘凭证)
实盘凭证使用独立的环境变量:
OKXAPIKEYLIVE / OKXSECRETKEYLIVE / OKXPASSPHRASELIVE
订单执行
bash
现货市价买入
python3 okx.py buy BTC-USDT market 0.01
现货限价卖出
python3 okx.py sell BTC-USDT limit 0.01 --px 50000
永续合约 — 开多并设置止盈止损(附加到订单)
python3 okx.py buy BTC-USDT-SWAP market 1 --td cross --pos long --tp 55000 --sl 42000
永续合约 — 开空
python3 okx.py sell BTC-USDT-SWAP market 1 --td cross --pos short
平仓(仅减仓)
python3 okx.py sell BTC-USDT-SWAP market 1 --td cross --pos long --reduce
取消订单
python3 okx.py cancel BTC-USDT <订单ID>
取消交易对的所有订单
python3 okx.py cancel-all BTC-USDT
设置杠杆
python3 okx.py leverage BTC-USDT-SWAP 10 --td cross
账户间转账(6=资金账户,18=交易账户)
python3 okx.py transfer USDT 500 funding trading # 资金账户 → 交易账户
python3 okx.py transfer USDT 500 trading funding # 交易账户 → 资金账户
跳过确认提示(用于自动化):
bash
python3 okx.py buy BTC-USDT market 0.01 --no-confirm
算法订单(独立止盈止损 — 用于已有持仓)
当已有持仓且需要单独添加止损或止盈时使用。
与--tp/--sl标志(附加到入场订单)不同,算法订单是独立的。
bash
OCO:止盈+止损同时设置 — 任一触发则取消另一个
python3 okx.py algo oco BTC-USDT-SWAP 1 --tp 55000 --sl 45000 --td cross --pos long --reduce
条件单:仅单一止损
python3 okx.py algo stop BTC-USDT-SWAP 1 --sl 45000 --td cross --reduce
列出所有待处理的算法订单
python3 okx.py algo list
python3 okx.py algo list BTC-USDT-SWAP # 按交易品种筛选
取消特定算法订单
python3 okx.py algo cancel BTC-USDT-SWAP <算法ID>
何时使用哪种方式:
- - 下单时使用--tp/--sl → 原子操作,保证附加,最适合新开仓
- algo oco → 入场后添加/替换止盈止损,或在交易中调整水平
策略
趋势跟踪(MA + RSI + MACD)
bash
仅分析(不交易)
python3 okx.py trend analyze BTC-USDT-SWAP --bar 1H
运行并自动执行
python3 okx.py trend run BTC-USDT-SWAP 1 --bar 4H --tp 0.05 --sl 0.03 --td cross --pos long
模拟运行(仅分析,不交易)
python3 okx.py trend run BTC-USDT-SWAP 1 --dry
信号逻辑:
- - 买入:快MA > 慢MA + RSI < 70 + MACD柱状图 > 0
- 卖出:快MA < 慢MA + RSI > 30 + MACD柱状图 < 0
网格交易
bash
设置网格:BTC-USDT,范围40000-50000,10个网格,总计1000 USDT
python3 okx.py grid setup BTC-USDT 40000 50000 10 1000
检查并重新平衡已成交订单(定期运行)
python3 okx.py grid check BTC-USDT
停止并取消所有网格订单
python3 okx.py grid stop BTC-USDT
现货-合约套利
bash
扫描所有交易对寻找机会
python3 okx.py arb scan
检查特定交易对基差
python3 okx.py arb basis BTC-USDT BTC-USDT-SWAP
开立套利仓位(买入现货+做空合约)
python3 okx.py arb open BTC-USDT BTC-USDT-SWAP 1000 --min-basis 0.1
基差收敛时平仓套利仓位
python3 okx.py arb close BTC-USDT BTC-USDT-SWAP 0.01 1 --max-basis 0.02
快照报告
每次运行时从API获取实时数据,持久化保存快照,并输出包含真实历史跟踪表的完整报告。
bash
python3 okx.py snapshot
输出包括:
- - 总权益、初始资金、变化百分比(相对于首次快照)
- 可用USDT、主要持仓
- 合约持仓(入场价、标记价、未实现盈亏、爆仓距离)
- 历史跟踪表(来自memory/okx-monitor-snapshots.json,最多48条记录)
所有数据直接来自OKX API — 无估算或虚构值。
自动监控(定时任务)
bash
默认:每5分钟止盈止损检查,每30分钟扫描
bash scripts/cron_setup.sh setup
自定义间隔(动态参数)
bash scripts/cron_setup.sh setup 1m # 每1分钟止盈止损检查
bash scripts/cron_setup.sh setup 10m 1h # 每10分钟止盈止损检查,每1小时扫描
停止所有任务
bash scripts/cron_setup.sh teardown
显示状态
bash scripts/cron_setup.sh status
定时任务:
- - okx-sl-tp — 定期运行snapshot + monitor sl-tp,报告实时数据
- okx-s