OKX CEX Trading CLI
Spot, perpetual swap, delivery futures, and options order management on OKX exchange. Place, cancel, amend, and monitor orders; query option chains and Greeks; set take-profit/stop-loss and trailing stops; manage leverage and positions. Requires API credentials.
Preflight
Before running any command, follow ../_shared/preflight.md.
Use metadata.version from this file's frontmatter as the reference for Step 2.
Prerequisites
- 1. Install
okx CLI:
npm install -g @okx_ai/okx-trade-cli
- 2. Configure credentials:
okx config init
Or set environment variables:
export OKX_API_KEY=your_key
export OKX_SECRET_KEY=your_secret
export OKX_PASSPHRASE=your_passphrase
- 3. Test with demo mode (simulated trading, no real funds):
CODEBLOCK3
Credential & Profile Check
Run this check before any authenticated command.
Step A — Verify credentials
CODEBLOCK4
- - If the command returns an error or shows no configuration: stop all operations, guide the user to run
okx config init, and wait for setup to complete before retrying. - If credentials are configured: proceed to Step B.
Step B — Confirm profile (required)
INLINECODE4 is required for all authenticated commands. Never add a profile implicitly.
| Value | Mode | Funds |
|---|
| INLINECODE5 | 实盘 | Real funds |
| INLINECODE6 |
模拟盘 | Simulated funds |
Resolution rules:
- 1. Current message intent is clear (e.g. "real" / "实盘" / "live" →
live; "test" / "模拟" / "demo" → demo) → use it and inform the user: "Using --profile live (实盘)" or INLINECODE10 - Current message has no explicit declaration → check conversation context for a previous profile:
- Found → use it, inform user:
"Continuing with --profile live (实盘) from earlier"
- Not found → ask:
"Live (实盘) or Demo (模拟盘)?" — wait for answer before proceeding
Handling 401 Authentication Errors
If any command returns a 401 / authentication error:
- 1. Stop immediately — do not retry the same command
- Inform the user: "Authentication failed (401). Your API credentials may be invalid or expired."
- Guide the user to update credentials by editing the file directly with their local editor:
~/.okx/config.toml
Update the fields
api_key,
secret_key,
passphrase under the relevant profile.
Do NOT paste the new credentials into chat.
- 4. After the user confirms the file is updated, run
okx config show to verify (output is masked) - Only then retry the original operation
Demo vs Live Mode
Profile is the single control for 实盘/模拟盘 switching:
| INLINECODE17 | Mode | Funds |
|---|
| INLINECODE18 | 实盘 | Real money — irreversible |
| INLINECODE19 |
模拟盘 | Simulated — no real funds |
Rules:
- 1.
--profile is required on every authenticated command — determined in "Credential & Profile Check" Step B - Every response after a command must append:
[profile: live] or INLINECODE22 - Do not use the
--demo flag for mode switching — use --profile instead
Skill Routing
- - For market data (prices, charts, depth, funding rates) → use INLINECODE25
- For account balance, P&L, positions, fees, transfers → use INLINECODE26
- For regular spot/swap/futures/options/algo orders → use
okx-cex-trade (this skill) - For grid and DCA trading bots → use INLINECODE28
Sz Handling for Derivatives
⚠ CRITICAL: Always verify contract face value before placing orders
Before placing any SWAP/FUTURES/OPTION order, call market_get_instruments to get ctVal (contract face value). Do NOT assume contract sizes — they vary by instrument (e.g. ETH-USDT-SWAP = 0.1 ETH/contract, BTC-USDT-SWAP = 0.01 BTC/contract).
Use ctVal to:
- - Calculate the correct number of contracts from user's intended position size
- Verify margin requirements before submitting the order
- Show the user the actual position value: INLINECODE32
SWAP and FUTURES orders
Three tgtCcy modes for USDT-denominated sizing:
| INLINECODE33 | sz meaning | Conversion formula | Example: "500U" at 10x lever |
|---|
| INLINECODE34 (default) | contract count | no conversion | 500 contracts |
| INLINECODE35 |
USDT notional value |
floor(sz / (ctVal * lastPx)) | 500 USDT notional |
|
margin | USDT margin cost |
floor(sz * lever / (ctVal * lastPx)) | 500 USDT margin = 5000 USDT notional |
When user specifies a USDT amount (e.g. "200U", "500 USDT", "$1000"):
→ AMBIGUOUS — this could mean notional value OR margin cost. You MUST ask: "您输入的 500U 是名义价值(notional value)还是保证金成本(margin cost)?名义价值模式下 500U 直接买入 500U 等值合约;保证金模式下 500U 保证金以当前杠杆计算,实际仓位 = 500U × 杠杆倍数。" Wait for the user's answer before continuing.
- - If notional value → use INLINECODE39
- If margin cost → use INLINECODE40
When user specifies contracts (e.g. "2 张", "5 contracts"):
→ First verify ctVal via market_get_instruments, then use --sz with the contract count. Confirm with user: "X contracts = X × ctVal underlying, total value ≈ $Y".
When user gives a plain number with no unit (for swap/futures):
→ Ambiguous — ask before proceeding: "您输入的 X 是合约张数、USDT 名义价值还是 USDT 保证金成本?" Wait for the user's answer before continuing.
⚠ Inverse contracts (*-USD-SWAP, *-USD-YYMMDD): tgtCcy=quote_ccy and tgtCcy=margin also work (note: quote_ccy = USD, not USDT, for inverse instruments). Always warn: "This is an inverse contract. Margin and P&L are settled in BTC, not USDT."
Option orders
When the user specifies a USDT amount for options, use --tgtCcy quote_ccy (notional) or --tgtCcy margin (margin cost) and pass the amount as --sz. The system automatically converts to contracts. Note: option contracts typically have large face values (e.g. ctVal=1 BTC ≈ $84,000), so the minimum USDT amount for 1 contract is high. For option sellers (cross/isolated tdMode), margin mode accounts for leverage automatically.
Quickstart
CODEBLOCK6
Command Index
Spot Orders (11 commands)
| # | Command | Type | Description |
|---|
| 1 | INLINECODE55 | WRITE | Place spot order (market/limit/post_only/fok/ioc) |
| 2 |
okx spot cancel | WRITE | Cancel spot order |
| 3 |
okx spot amend | WRITE | Amend spot order price or size |
| 4 |
okx spot algo place | WRITE | Place spot TP/SL algo order |
| 5 |
okx spot algo amend | WRITE | Amend spot TP/SL levels |
| 6 |
okx spot algo cancel | WRITE | Cancel spot algo order |
| 7 |
okx spot algo trail | WRITE | Place spot trailing stop order |
| 8 |
okx spot orders | READ | List open or historical spot orders |
| 9 |
okx spot get | READ | Single spot order details |
| 10 |
okx spot fills | READ | Spot trade fill history |
| 11 |
okx spot algo orders | READ | List spot TP/SL algo orders |
For full command syntax, parameter tables, and edge cases, read {baseDir}/references/spot-commands.md.
Swap / Perpetual Orders (15 commands)
| # | Command | Type | Description |
|---|
| 12 | INLINECODE67 | WRITE | Place perpetual swap order |
| 13 |
okx swap cancel | WRITE | Cancel swap order |
| 14 |
okx swap amend | WRITE | Amend swap order price or size |
| 15 |
okx swap close | WRITE | Close entire position at market |
| 16 |
okx swap leverage | WRITE | Set leverage for an instrument |
| 17 |
okx swap algo place | WRITE | Place swap TP/SL algo order |
| 18 |
okx swap algo trail | WRITE | Place swap trailing stop order |
| 19 |
okx swap algo amend | WRITE | Amend swap algo order |
| 20 |
okx swap algo cancel | WRITE | Cancel swap algo order |
| 21 |
okx swap positions | READ | Open perpetual swap positions |
| 22 |
okx swap orders | READ | List open or historical swap orders |
| 23 |
okx swap get | READ | Single swap order details |
| 24 |
okx swap fills | READ | Swap trade fill history |
| 25 |
okx swap get-leverage | READ | Current leverage settings |
| 26 |
okx swap algo orders | READ | List swap algo orders |
For full command syntax, parameter tables, and edge cases, read {baseDir}/references/swap-commands.md.
Futures / Delivery Orders (15 commands)
| # | Command | Type | Description |
|---|
| 27 | INLINECODE83 | WRITE | Place delivery futures order |
| 28 |
okx futures cancel | WRITE | Cancel delivery futures order |
| 29 |
okx futures amend | WRITE | Amend delivery futures order price or size |
| 30 |
okx futures close | WRITE | Close entire futures position at market |
| 31 |
okx futures leverage | WRITE | Set leverage for a futures instrument |
| 32 |
okx futures algo place | WRITE | Place futures TP/SL algo order |
| 33 |
okx futures algo trail | WRITE | Place futures trailing stop order |
| 34 |
okx futures algo amend | WRITE | Amend futures algo order |
| 35 |
okx futures algo cancel | WRITE | Cancel futures algo order |
| 36 |
okx futures orders | READ | List delivery futures orders |
| 37 |
okx futures positions | READ | Open delivery futures positions |
| 38 |
okx futures fills | READ | Delivery futures fill history |
| 39 |
okx futures get | READ | Single delivery futures order details |
| 40 |
okx futures get-leverage | READ | Current futures leverage settings |
| 41 |
okx futures algo orders | READ | List futures algo orders |
For full command syntax, parameter tables, and edge cases, read {baseDir}/references/futures-commands.md.
Options Orders (10 commands)
| # | Command | Type | Description |
|---|
| 42 | INLINECODE99 | READ | Option chain: list available contracts for an underlying |
| 43 |
okx option greeks | READ | Implied volatility + Greeks (delta/gamma/theta/vega) by underlying |
| 44 |
okx option place | WRITE | Place option order (call or put, buyer or seller) |
| 45 |
okx option cancel | WRITE | Cancel unfilled option order |
| 46 |
okx option amend | WRITE | Amend option order price or size |
| 47 |
okx option batch-cancel | WRITE | Batch cancel up to 20 option orders |
| 48 |
okx option orders | READ | List option orders (live / history / archive) |
| 49 |
okx option get | READ | Single option order details |
| 50 |
okx option positions | READ | Open option positions with live Greeks |
| 51 |
okx option fills | READ | Option trade fill history |
For full command syntax, USDT-to-contracts conversion formula, tdMode rules, and edge cases, read {baseDir}/references/options-commands.md.
Operation Flow
Step 0 — Credential & Profile Check
Before any authenticated command: see Credential & Profile Check. Determine profile (live or demo) before executing.
After every command result: append [profile: live] or [profile: demo].
Step 1 — Identify instrument type and action
Spot (instId format: BTC-USDT):
- - Place/cancel/amend order → INLINECODE115
- TP/SL conditional → INLINECODE116
- Trailing stop → INLINECODE117
- Query → INLINECODE118
Swap/Perpetual (instId format: BTC-USDT-SWAP):
- - Place/cancel/amend order → INLINECODE120
- Close position → INLINECODE121
- Leverage →
okx swap leverage / INLINECODE123 - TP/SL conditional → INLINECODE124
- Trailing stop → INLINECODE125
- Query → INLINECODE126
Futures/Delivery (instId format: BTC-USDT-<YYMMDD>):
- - Place/cancel/amend order → INLINECODE128
- Close position → INLINECODE129
- Leverage →
okx futures leverage / INLINECODE131 - TP/SL conditional → INLINECODE132
- Trailing stop → INLINECODE133
- Query → INLINECODE134
Options (instId format: BTC-USD-250328-95000-C or ...-P):
- - Step 1 (required): find valid instId → INLINECODE137
- Step 2 (recommended): check IV and Greeks → INLINECODE138
- Place/cancel/amend → INLINECODE139
- Batch cancel → INLINECODE140
- Query → INLINECODE141
- tdMode:
cash for buyers; cross or isolated for sellers
For cross-skill workflows and step-by-step examples, read {baseDir}/references/workflows.md.
Step 2 — Confirm profile, then confirm write parameters
Read commands (orders, positions, fills, get, get-leverage, algo orders): run immediately.
- -
--history flag: defaults to active/open; use --history only if user explicitly asks for history - INLINECODE148 for algo:
conditional = single TP or SL; oco = both TP and SL together - INLINECODE151 for swap/futures:
cross or isolated; spot always uses cash (set automatically) - INLINECODE155 for hedge mode:
long or short; omit in net mode
Write commands (place, cancel, amend, close, leverage, algo): confirm the key order details once before executing:
- - Spot place: confirm
--instId, --side, --ordType, --sz (and --tgtCcy quote_ccy if quote-currency amount) - Swap/Futures place: confirm
--instId, --side, --sz, --tdMode, and explicitly confirm order mode when user specifies a USDT amount: --tgtCcy quote_ccy (notional value, sz = position value) or --tgtCcy margin (margin cost, actual position = sz * leverage). Always state which mode is being used. - Option place: confirm
--instId, --side, --sz, --tdMode (and --tgtCcy quote_ccy or --tgtCcy margin if USDT amount — system auto-converts); do NOT attach TP/SL - Swap/Futures close: confirm
--instId, --mgnMode, INLINECODE177 - Leverage: confirm new leverage and impact on existing positions
- Algo place (TP/SL): confirm trigger prices; use
--tpOrdPx=-1 for market execution - Algo trail: confirm
--callbackRatio (e.g., 0.02 = 2%) or INLINECODE181
For full parameter details per command, read the relevant reference file.
Step 3 — Verify after writes
- - After
spot place: run okx spot orders to confirm order is live or okx spot fills if market order - After
swap place: run okx swap orders or okx swap positions to confirm - After
swap close: run okx swap positions to confirm position size is 0 - After
futures place: run okx futures orders or okx futures positions to confirm - After
futures close: run okx futures positions to confirm position size is 0 - After spot algo place/trail: run
okx spot algo orders to confirm algo is active - After swap algo place/trail: run
okx swap algo orders to confirm algo is active - After futures algo place/trail: run
okx futures algo orders to confirm algo is active - After cancel: run
okx spot orders / okx swap orders / okx futures orders to confirm order is gone
Global Notes
- - All write commands require valid credentials in
~/.okx/config.toml or env vars - INLINECODE202 is required for all authenticated commands
- INLINECODE203 returns the raw OKX API v5 response by default. Add
--env to wrap the output as {"env": "<live|demo>", "profile": "<name>", "data": <response>} — useful when you need to know the active environment and credential profile - Rate limit: 60 order operations per 2 seconds per UID
- Batch operations (batch cancel, batch amend) are available via MCP tools directly if needed
- Position mode (
net vs long_short_mode) affects whether --posSide is required - Network errors: If commands fail with a connection error, prompt user to check VPN: INLINECODE209
For MCP tool reference, output conventions, and order amount safety rules, read {baseDir}/references/templates.md.
OKX CEX 交易命令行工具
在OKX交易所进行现货、永续合约、交割合约及期权订单管理。支持下单、撤单、改单及监控订单;查询期权链和希腊值;设置止盈止损和追踪止损;管理杠杆和仓位。需要API凭证。
前置检查
在执行任何命令之前,请遵循../_shared/preflight.md中的说明。
使用本文档前置元数据中的metadata.version作为步骤2的参考。
前提条件
- 1. 安装okx命令行工具:
bash
npm install -g @okx_ai/okx-trade-cli
- 2. 配置凭证:
bash
okx config init
或设置环境变量:
bash
export OKXAPIKEY=your_key
export OKXSECRETKEY=your_secret
export OKXPASSPHRASE=yourpassphrase
- 3. 使用模拟模式测试(模拟交易,不涉及真实资金):
bash
okx --profile demo spot orders
凭证与配置文件检查
在执行任何需要认证的命令前运行此检查。
步骤A — 验证凭证
bash
okx config show # 查看配置状态(输出已脱敏)
- - 如果命令返回错误或显示未配置:停止所有操作,引导用户运行okx config init,等待设置完成后再重试。
- 如果凭证已配置:继续执行步骤B。
步骤B — 确认配置文件(必需)
所有需要认证的命令必须使用--profile参数。切勿隐式添加配置文件。
模拟盘 | 模拟资金 |
判断规则:
- 1. 当前消息意图明确(如real/实盘/live → live;test/模拟/demo → demo)→ 使用该配置并告知用户:使用 --profile live(实盘) 或 使用 --profile demo(模拟盘)
- 当前消息未明确声明 → 检查对话上下文中是否有之前的配置文件:
- 有 → 使用该配置,告知用户:继续使用之前的 --profile live(实盘)
- 无 → 询问:实盘(Live)还是模拟盘(Demo)? — 等待用户回答后再继续
处理401认证错误
如果任何命令返回401/认证错误:
- 1. 立即停止 — 不要重试同一命令
- 告知用户:认证失败(401)。您的API凭证可能无效或已过期。
- 引导用户通过本地编辑器直接编辑文件来更新凭证:
~/.okx/config.toml
更新相关配置文件下的apikey、secretkey、passphrase字段。
请勿在聊天中粘贴新凭证。
- 4. 用户确认文件已更新后,运行okx config show验证(输出已脱敏)
- 然后重试原始操作
模拟盘与实盘模式
配置文件是控制实盘/模拟盘切换的唯一方式:
| --profile | 模式 | 资金 |
|---|
| live | 实盘 | 真实资金 — 不可逆 |
| demo |
模拟盘 | 模拟资金 — 无真实资金 |
规则:
- 1. 每个需要认证的命令必须使用--profile参数 — 在凭证与配置文件检查步骤B中确定
- 每个命令的响应后必须附加:[profile: live] 或 [profile: demo]
- 不要使用--demo标志进行模式切换 — 应使用--profile
技能路由
- - 市场数据(价格、图表、深度、资金费率)→ 使用okx-cex-market
- 账户余额、盈亏、仓位、费用、转账 → 使用okx-cex-portfolio
- 常规现货/合约/交割/期权/策略委托 → 使用okx-cex-trade(本技能)
- 网格和DCA交易机器人 → 使用okx-cex-bot
衍生品的数量处理
⚠ 关键:下单前务必验证合约面值
在下任何合约/交割/期权订单前,调用marketgetinstruments获取ctVal(合约面值)。不要假设合约大小 — 不同品种各不相同(例如ETH-USDT-SWAP = 0.1 ETH/合约,BTC-USDT-SWAP = 0.01 BTC/合约)。
使用ctVal来:
- - 根据用户预期的头寸规模计算正确的合约数量
- 在提交订单前验证保证金要求
- 向用户展示实际头寸价值:数量 × ctVal × 价格
合约和交割订单
USDT计价规模的三种tgtCcy模式:
| --tgtCcy | 数量含义 | 转换公式 | 示例:500U 10倍杠杆 |
|---|
| baseccy(默认) | 合约数量 | 无需转换 | 500张合约 |
| quoteccy |
USDT名义价值 | floor(数量 / (ctVal * 最新价)) | 500 USDT名义价值 |
| margin | USDT保证金成本 | floor(数量
杠杆 / (ctVal 最新价)) | 500 USDT保证金 = 5000 USDT名义价值 |
当用户指定USDT金额时(如200U、500 USDT、$1000):
→ 存在歧义 — 这可能表示名义价值或保证金成本。您必须询问:您输入的500U是名义价值(notional value)还是保证金成本(margin cost)?名义价值模式下500U直接买入500U等值合约;保证金模式下500U保证金以当前杠杆计算,实际仓位 = 500U × 杠杆倍数。 等待用户回答后再继续。
- - 如果是名义价值 → 使用--tgtCcy quote_ccy
- 如果是保证金成本 → 使用--tgtCcy margin
当用户指定合约张数时(如2张、5 contracts):
→ 首先通过marketgetinstruments验证ctVal,然后使用合约张数作为--sz。向用户确认:X张合约 = X × ctVal 标的物,总价值约$Y。
当用户给出不带单位的纯数字时(针对合约/交割):
→ 存在歧义 — 在继续前询问:您输入的X是合约张数、USDT名义价值还是USDT保证金成本? 等待用户回答后再继续。
⚠ 反向合约(-USD-SWAP、-USD-YYMMDD):tgtCcy=quoteccy和tgtCcy=margin同样适用(注意:反向合约的quoteccy = USD,而非USDT)。始终警告:这是反向合约。保证金和盈亏以BTC结算,而非USDT。
期权订单
当用户为期权指定USDT金额时,使用--tgtCcy quote_ccy(名义价值)或--tgtCcy margin(保证金成本),并将金额作为--sz传入。系统会自动转换为合约数量。注意:期权合约通常面值较大(如ctVal=1 BTC ≈ $84,000),因此1张合约的最低USDT金额较高。对于期权卖方(cross/isolated tdMode),margin模式会自动考虑杠杆。
快速入门
bash
市价买入0.01 BTC(现货)
okx spot place --instId BTC-USDT --side buy --ordType market --sz 0.01
买入10美元等值SOL(现货,USDT金额)
okx spot place --instId SOL-USDT --side buy --ordType market --sz 10 --tgtCcy quote_ccy
限价卖出0.01 BTC,价格$100,000(现货)
okx spot place --instId BTC-USDT --side sell --ordType limit --sz 0.01 --px 100000
做多1张BTC永续合约(全仓)
okx swap place --instId BTC-USDT-SWAP --side buy --ordType market --sz 1 \
--tdMode cross --posSide long
做多1000 USDT名义价值的BTC永续合约(自动转换为合约张数)
okx swap place --instId BTC-USDT-SWAP --side buy --ordType market --sz 1000 \
--tgtCcy quote_ccy --tdMode cross --posSide long
使用500 USDT保证金以当前杠杆做多(如10倍 → 5000 USDT名义价值)