OKX CEX Bot Trading
Grid and DCA (Spot & Contract Martingale) bot management on OKX. All bots are native OKX server-side — they run on OKX and do not require a local process.
Preflight
Before running any command, follow ../_shared/preflight.md.
Use metadata.version from this file's frontmatter as the reference for Step 2.
Prerequisites
Security: NEVER accept credentials in chat. Guide users to
okx config initfor setup.
Credential & Profile Check
Run before every authenticated command. The auth method is detected during preflight Step 2 and remembered for the session.
Step A — Verify credentials
Run both commands — the apiKey field from okx auth status --json is the auth-binary's internal state and is always false regardless of whether ~/.okx/config.toml has an API-key profile. okx config show --json is the only authoritative source for API-key presence.
Apply in this order — first match wins:
config show --jsonhas any profile with a non-emptyapi_keyfield → API Key mode. Proceed to Step B.- No API-key profile AND
auth status --jsonreturns"status":"logged_in"→ OAuth mode. Proceed to Step B. - No API-key profile AND
"status":"pending"— login is in progress, wait for it to complete. - No API-key profile AND
"status":"not_logged_in"— stop, loadokx-cex-authskill and follow login steps, wait for completion.
Step B — Confirm trading mode
Resolution:
- User intent is clear ("real"/"实盘"/"live" → live; "test"/"模拟"/"demo" → demo) → use it, inform user
- No explicit declaration → check conversation context for previous choice → reuse if found
- Nothing found → ask: "Live (实盘) or Demo (模拟盘)?" — wait before proceeding
How to apply the mode depends on auth method (detected in Step A):
- API Key users: run
okx config show --jsonto discover available profile names and theirdemosettings. - OAuth users: omit flags for live; add
--demofor simulated trading.
After every command: append [mode: live] or [mode: demo]
Handling 401 Errors
Authentication error (error contains "401", "Session expired", or "Run okx auth login first"):
- Stop immediately
- Load
okx-cex-authskill and follow re-authentication steps - Retry original command
Skill Routing
Command Index
Grid Bot
DCA Bot (Spot & Contract)
Operation Flow
Step 1 — Identify bot type and action
Parse user request → determine module (Grid / DCA) and action (create / stop / list / details).
Step 2 — Execute
READ commands (orders, details, sub-orders): run immediately after profile confirmation.
WRITE commands (create, amend, stop): confirm key parameters with user once before executing.
Step 3 — Verify after writes
- After create → run the corresponding
orderscommand to confirm active - After amend → run
bot grid detailsto confirm updated config - After stop → run
orders --historyto confirm stopped
Key Rules
- Never auto-transfer funds. If balance is insufficient for bot creation, report the shortfall (current available vs required) and ask the user how to proceed: (1) transfer funds manually, (2) reduce size, or (3) cancel.
algoIdis the bot's algo order ID (from create or list output). It is NOT a normalordId. Never fabricate — always obtain from a prior command.algoOrdTypefor grid must match the bot's actual type. Always use the value frombot grid orders— do not infer from user description alone. Mismatch causes error50016.- When operating on existing bots, always list first to get correct IDs, unless the user provides them explicitly.
- TP/SL constraints:
tpTriggerPx/tpRatioandslTriggerPx/slRatioare mutually exclusive pairs.
CLI Command Reference
Grid Bot — Create
Grid Bot — Amend
Supports two modes that can be combined in one call:
Price-range mode — triggered when --maxPx is provided:
TP/SL mode — triggered when at least one TP/SL param is provided; --instId is also required:
Note:
tpTriggerPx/tpRatioare mutually exclusive. Same forslTriggerPx/slRatio.
Grid Bot — Stop
--algoIdand--algoOrdTypemust come frombot grid ordersoutput. ThealgoOrdTypemust match the bot's actual type — do not guess.
Workflow:
- Run
bot grid details --algoId <id> --algoOrdType <type>and check thestatefield. - If
state=running: call stop with--stopType 1(default, clean exit) or--stopType 2(keep assets). - If
state=no_close_position(user previously stopped with stopType=2): call stop again with--stopType 1to close the remaining open position.
Grid Bot — Positions
Returns open contract-grid positions: liquidation price (liqPx), margin ratio (mgnRatio), and unrealized PnL (upl). Only applicable to contract_grid bots.
Grid Bot — Liquidation Price
Estimates the liquidation price for a contract-grid bot. Use before creating a bot to assess liquidation risk. The estimate needs the full intended config — the backend requires instId, sz, lever, the grid range (maxPx/minPx/gridNum) and direction (use neutral for a neutral bot); omitting any of them fails fast with the list of what's missing. runType defaults to 1 (arithmetic; 2=geometric) and triggerStrategy is optional.
Grid Bot — Close Position
Closes the remaining open position of a contract-grid bot that was stopped with stopType='2'. The close mode is required (no default, because it moves funds): pass --mktClose for a market close (immediate), or --no-mktClose --sz <size> --px <price> for a limit close order. Omitting both is rejected.
Grid Bot — List Orders
Grid Bot — Details
Returns: bot config, current PnL (pnlRatio), grid range, number of grids, state, position info.
Grid Bot — Sub-Orders
DCA Bot — Create (Spot & Contract)
Conditional required logic:
- Always required:
--algoOrdType,--instId,--direction,--initOrdAmt,--maxSafetyOrds,--tpPct - When
algoOrdType=contract_dca: also required--lever - When
maxSafetyOrds > 0: also required--safetyOrdAmt,--pxSteps,--pxStepsMult,--volMult --slPctand--slModemust be both set or both omitted
DCA Bot — Stop
Workflow:
- Run
bot dca details --algoId <id> --algoOrdType <type>and check thestatefield. - If
state=running: call stop (with--stopTypefor spot_dca). - If
state=no_close_position(user previously stopped with stopType=2): call stop again with--stopType 1to close the remaining open position.
DCA Bot — List Orders
DCA Bot — Details
Returns: avgPx, upl, liqPx, sz, tpPx, slPx, initPx, fundingFee, fee, fillSafetyOrds, algoClOrdId, baseSz, quoteSz, tradeQuoteCcy.
DCA Bot — Sub-Orders
Quickstart
Cross-Skill Workflows
Spot Grid Bot
User: "Start a BTC grid bot between $90k and $100k with 10 grids, invest 1000 USDT"
Contract DCA Bot
User: "Start a long DCA bot on BTC perp, 3x leverage, $200 initial, 3% TP"
Spot DCA Bot
User: "帮我在现货上 DCA BTC,首单 100 USDT,5% 止盈"
Edge Cases
Grid Bot
- Price out of range:
--minPxmust be < current price <--maxPx; check withokx-cex-marketfirst - Insufficient balance: check
okx-cex-portfolio→account balancebefore creating. If insufficient, do NOT auto-transfer — report the shortfall and ask the user for instructions - Contract grid direction:
long(buys more at lower prices),short(sells at higher),neutral(both). Direction is required for contract grid - Contract grid basePos: defaults to
true— long/short grids automatically open a base position at creation. Neutral direction ignores this. Pass--no-basePosto disable - Contract grid --sz: investment margin in USDT (USDT-M) or coin (coin-M), not number of contracts
- Coin-margined grids: use inverse instruments (e.g.,
BTC-USD-SWAP). Margin unit is the base coin (BTC), not USDT - Stop type:
stopType 1sells/closes all (default);stopType 2keeps assets as-is (spot grid) or leaves position open for manual close (contract grid) - TP/SL:
tpTriggerPx/tpRatioandslTriggerPx/slRatioare mutually exclusive pairs. Ratio-based TP/SL is contract grid only - Amend — at least one mode required: must provide either price-range params (
--maxPx+--minPx+--gridNum) or TP/SL params; providing neither returns a validation error - Amend — combined mode: price-range and TP/SL can be combined in one call (two sequential API requests internally)
- Amend — clear TP/SL: pass
--tpTriggerPx=-1or--slTriggerPx=-1(use=syntax for negative values, not--flag -1) - Amend — contract grid topUpAmt: if new range requires more margin, provide
--topUpAmt; omit to auto-use the minimum required - Amend — spot grid topUpAmt: not supported; omit
--topUpAmtfor spot grids - Already stopped bot: stop returns error — check
bot grid orders --historyfirst to confirm state - Insufficient margin (51340): extract required minimum from error, check balance via
okx-cex-portfolio, report shortfall to user — do NOT auto-transfer - Demo mode:
okx --demo bot grid create ...(OAuth) orokx --profile <demo-profile> bot grid create ...(API Key) — safe for testing, no real funds - algoClOrdId duplicate: if the same
algoClOrdIdalready exists, the API returns error code51065
DCA Bot
- Spot DCA direction: must always be
long. If user says "short spot DCA", explain that spot DCA only supports long direction - Spot DCA stopType: always ask user whether to sell all tokens (
1) or keep them (2) when stopping - Contract DCA lever: required. If missing, the tool returns a validation error
- pxStepsMult:
1.0= equal spacing;>1.0= widen gaps between successive safety orders - volMult:
1.0= equal sizes;>1.0= increase per safety order (Martingale scaling) - triggerStrategy:
instantstarts immediately;pricewaits for trigger price (contract_dca only);rsiwaits for RSI condition (both spot_dca and contract_dca) - Already stopped bot: stop returns error — check
bot dca orders --historyfirst - Demo mode:
okx --demo bot dca create ...(OAuth) orokx --profile <demo-profile> bot dca create ...(API Key) — safe testing, no real funds - INVALID_PRICE_STEPS_MULTIPLIER error: adjust
slPct. Recalculate MPD = Σ(pxSteps × pxStepsMult^i) for i = 0..maxSafetyOrds−1, then setslPct> MPD - algoClOrdId duplicate: error code
51065
Communication Guidelines
- Grid/DCA: use "bot" not "strategy" (e.g., "grid bot", "DCA bot")
- DCA: always say "DCA" or "Martingale" — DCA supports both Spot DCA and Contract DCA
- Chinese: Grid = "网格", Spot DCA = "现货马丁", Contract DCA = "合约马丁"
- Use natural language for parameters — "What price range?" not "Enter minPx and maxPx"
- If the user already provides values, map directly — don't re-ask
Parameter Display Names
{base}and{quote}: extract frominstIdby splitting on-. E.g.,BTC-USDT-SWAP→ base=BTC, quote=USDT.
Grid Bot — Spot (algoOrdType=grid)
Grid Bot — Contract (algoOrdType=contract_grid)
DCA Bot (Spot & Contract)
slPctstop-loss logic:
- Long: stop-loss price = initial fill price × (1 − slPct)
- Short: stop-loss price = initial fill price × (1 + slPct) When triggered and position fully closed, the bot ends.
Global Notes
- All bots run on OKX servers — stopping the CLI does not affect them
- Auth method and trading mode are determined in "Credential & Profile Check"; see that section for parameter rules
--jsonreturns the raw OKX API v5 response by default. Add--envto wrap the output as{"env": "<live|demo>", "profile": "<name>", "data": <response>}- Rate limit: 20 requests per 2 seconds per UID
- Grid
--gridNumrange: 2–100

