This guide is different. We actually run an AI agent (OpenClaw) connected to OKX sub-accounts for automated crypto trading. Real money, real commands, real lessons. Every command in this article has been tested on okx-trade-cli v1.2.3 and verified working.
By the end, you'll have a complete pipeline: market data flowing into your AI agent, trade execution through CLI, and automated bots — all without writing a single line of exchange API code.
Why CLI-First AI Trading Beats REST APIs
If you've tried building trading bots the traditional way — writing Python wrappers around REST endpoints, handling HMAC signatures, parsing nested JSON responses — you know the pain. Half your code is authentication and error handling, not trading logic.
The CLI-first approach flips this. Instead of your AI agent making HTTP requests and parsing responses, it runs shell commands and gets structured output. This matters because:
- AI agents are better at shell commands than HTTP. Every major LLM can generate and execute bash commands reliably. Constructing properly signed API requests with correct headers? Much more error-prone.
- CLI tools handle auth, retries, and formatting. The complexity is abstracted away.
- Testing is trivial. Copy a command, paste it in your terminal, verify the output. No Postman, no curl with 8 headers.
What Is the OKX Agent Trade Kit?
The OKX Agent Trade Kit consists of two npm packages:
- okx-trade-cli — A full-featured command-line interface for OKX trading (market data, account management, spot/swap trading, grid bots, DCA bots)
- okx-trade-mcp — A Model Context Protocol server that connects AI coding assistants (Claude Desktop, Cursor, Claude Code) directly to OKX
Why does this matter? Because the biggest bottleneck in AI trading isn't the AI — it's the plumbing. Parsing REST APIs, handling authentication, managing rate limits, formatting order parameters. The Agent Trade Kit eliminates all of that.
Prerequisites
Before we start, you'll need:
- Node.js 18+ installed
- An OKX account (we strongly recommend starting with a demo account)
- Basic terminal/command-line comfort
- (Optional) OpenClaw installed for full AI agent automation
Step 1: Install the CLI and MCP Server
npm install -g okx-trade-mcp okx-trade-cli
That's it. Both packages install globally, giving you the okx command and okx-trade-mcp server.
Step 2: Pull Market Data (No API Key Needed)
Here's what makes the Agent Trade Kit immediately useful: market data requires zero authentication. You can start pulling live data right now.
Get a price ticker
okx market ticker BTC-USDT
Returns the current BTC-USDT price, 24h volume, bid/ask spread — everything you need for a quick market check.
Pull candlestick data
okx market candles ETH-USDT --bar 1H --limit 5
This fetches the last 5 hourly candles for ETH-USDT. Change --bar to 1D, 4H, 15m, or any OKX-supported interval.
Check the order book
okx market orderbook BTC-USDT --sz 5
Shows the top 5 levels of bid/ask depth. Note: use --sz for the depth parameter, not --depth.
Funding rates and open interest
okx market funding-rate BTC-USDT-SWAP
okx market open-interest --instType SWAP --instId BTC-USDT-SWAP
Funding rates tell you whether longs or shorts are paying. Open interest shows how much capital is in the market. Both are critical for timing entries on perpetual swaps.
Recent trades
okx market trades BTC-USDT --limit 5
This is already powerful on its own. You can pipe these commands into scripts, cron jobs, or AI agent workflows — no API key, no rate limit hassles for public data.
Combining commands for analysis
Here's where an AI agent shines. It can chain these commands together to build context:
1. Check the ticker for current price and volume
2. Pull hourly candles to identify the trend 3. Check funding rate to gauge market sentiment 4. Look at open interest for positioning dataA human would open four browser tabs. An AI agent runs four commands in sequence and synthesizes the results in seconds. This is the core loop that drives our automated analysis.
Check SOL market data
okx market ticker SOL-USDT
okx market candles SOL-USDT --bar 4H --limit 5
okx market funding-rate SOL-USDT-SWAP
okx market open-interest --instType SWAP --instId SOL-USDT-SWAP
SOL perpetuals on OKX have deep liquidity and tight spreads — the same commands work for any supported instrument. SOL's funding rate tends to be more volatile than BTC's, which creates opportunities for funding arbitrage strategies.
Step 3: Configure API Authentication
To trade, you need API credentials. Here's the setup:
mkdir -p ~/.okx && vim ~/.okx/config.toml
Use this format:
default_profile = "demo"
[profiles.demo]
site = "global"
api_key = "your-demo-api-key"
secret_key = "your-demo-secret-key"
passphrase = "your-demo-passphrase"
demo = true
Important notes:
- Start with
demo = true. OKX's demo trading environment uses real market data with fake money — perfect for testing. - If your passphrase contains special characters (like
$), wrap it in single quotes in shell commands to prevent variable expansion. - You can create multiple profiles (e.g.,
demo,live,sub-account) and switch between them.
Setting up multiple profiles
The config supports multiple profiles for different environments. Here's a more complete example:
default_profile = "demo"
[profiles.demo]
site = "global"
api_key = "your-demo-api-key"
secret_key = "your-demo-secret-key"
passphrase = "your-demo-passphrase"
demo = true
[profiles.live]
site = "global"
api_key = "your-live-api-key"
secret_key = "your-live-secret-key"
passphrase = "your-live-passphrase"
demo = false
[profiles.agent]
site = "global"
api_key = "your-sub-account-api-key"
secret_key = "your-sub-account-secret-key"
passphrase = "your-sub-account-passphrase"
demo = false
Set default_profile to whichever you use most. This prevents accidentally trading on the wrong account — a mistake that's surprisingly easy to make at 2 AM when your bot alerts you to a signal.
Pro tip: Use sub-accounts for AI trading
We run our AI agent on an OKX sub-account, not the main account. This gives you:
1. Isolated risk — The agent can only access funds you transfer to the sub-account
2. Separate API keys — Revoke agent access without affecting your main account 3. Clean P&L tracking — Every trade in the sub-account is from the agentCreate a sub-account in OKX settings, generate API keys for it, and add it as a separate profile in your config.
Step 4: Account Management
Once authenticated, check your account status:
okx account balance
okx account positions
okx account config
Check trading fees
okx account fees --instType SWAP
Note: The fees command takes --instType (SWAP, SPOT, FUTURES, etc.), not --instId. This is a common gotcha.
Review recent activity
okx account bills --instType SWAP --limit 5
Check maximum order size
okx account max-size --instId ETH-USDT-SWAP --tdMode cross
Like what you're reading? Try it yourself — this link supports ChartedTrader at no cost to you.
Try OKX →This tells you the maximum position size you can open given your current balance and margin mode — essential before placing large orders.
Step 5: Execute Trades
Now for the real action. The okx swap subcommand handles perpetual swap trading.
Check positions and orders
okx swap positions ETH-USDT-SWAP
okx swap orders
okx swap fills --instId ETH-USDT-SWAP
Check leverage settings
okx swap get-leverage --instId ETH-USDT-SWAP --mgnMode cross
Place an order with TP/SL
This is where it gets interesting. A single command to open a position with take-profit and stop-loss:
okx swap place \
--instId ETH-USDT-SWAP \
--side buy \
--ordType market \
--sz 1 \
--tdMode cross \
--tpTriggerPx 2500 \
--tpOrdPx -1 \
--slTriggerPx 1900 \
--slOrdPx -1
Breaking this down:
--side buy— Long position--ordType market— Execute immediately at market price--sz 1— 1 contract--tdMode cross— Cross margin mode--tpTriggerPx 2500 --tpOrdPx -1— Take profit at 2500, market order execution (-1means market)--slTriggerPx 1900 --slOrdPx -1— Stop loss at 1900, market order execution
Close a position
okx swap close --instId ETH-USDT-SWAP --mgnMode cross
Trailing stop
okx swap algo trail \
--instId ETH-USDT-SWAP \
--side sell \
--sz 1 \
--callbackRatio 0.03 \
--reduceOnly
A 3% trailing stop that only reduces your position. This is the kind of order that's painful to set up via raw API but trivial with the CLI.
Step 6: Automated Bots
Beyond individual trades, the Agent Trade Kit provides direct access to OKX's algorithmic trading bots. These are the same bots available in the OKX web interface, but controllable from the command line — which means your AI agent can create, monitor, and manage them programmatically.
This is particularly useful for strategies that run 24/7 without human intervention. Grid bots and DCA bots handle the repetitive work of buying low and selling high within a range, while your AI agent can focus on higher-level decisions like when to start or stop a bot, or how to adjust parameters based on market conditions.
Contract Grid Bot
okx bot grid create \
--instId ETH-USDT-SWAP \
--algoOrdType contract_grid \
--maxPx 2500 \
--minPx 1800 \
--gridNum 10 \
--direction long \
--lever 2 \
--sz 1
This creates a 10-level grid between $1,800 and $2,500 on ETH-USDT-SWAP with 2x leverage, biased long. The bot automatically places buy orders at each grid level and sells when price moves up.
Check bot status
okx bot grid orders --algoOrdType contract_grid
DCA (Dollar-Cost Averaging) Bot
okx bot dca create \
--instId BTC-USDT-SWAP \
--lever 2 \
--direction long \
--initOrdAmt 100 \
--maxSafetyOrds 3 \
--tpPct 5
This DCA bot starts with a $100 initial order, allows up to 3 safety orders if price drops, and takes profit at 5% gain. Leveraged DCA on perpetuals — a strategy that's surprisingly effective in ranging markets.
Step 7: Connect AI Agents via MCP
This is where the OKX Agent Trade Kit becomes truly powerful. The MCP (Model Context Protocol) server lets AI assistants call OKX functions directly.
One-command setup
okx-trade-mcp setup --client claude-desktop
okx-trade-mcp setup --client cursor
okx-trade-mcp setup --client claude-code
Each command auto-configures the respective AI client to connect to OKX through the MCP server.
#Trade SOL perpetuals
okx swap place --instId SOL-USDT-SWAP --side buy --ordType market --sz 10 --tdMode cross
okx swap algo trail --instId SOL-USDT-SWAP --side sell --sz 10 --callbackRatio 0.03 --reduceOnly
SOL supports all the same order types: market, limit, TP/SL, trailing stop, and grid bots. For a grid bot on SOL:
okx bot grid create --instId SOL-USDT-SWAP --algoOrdType contract_grid --maxPx 120 --minPx 70 --gridNum 15 --direction long --lever 3 --sz 10
Security controls
# Market data only — no trading
okx-trade-mcp --modules market
# Read-only mode — can view positions but not trade
okx-trade-mcp --read-only
These flags are critical for production use. Start with --read-only until you trust your agent's behavior, then graduate to full access.
How We Use This with OpenClaw
OpenClaw is an open-source AI agent framework that can run shell commands, browse the web, manage files, and interact with messaging platforms. It's the "brain" that decides when and how to trade, while the OKX Agent Trade Kit is the "hands" that execute.
Here's our actual setup — not theory, but what we run daily:
1. OpenClaw acts as the orchestration layer. It receives market signals, evaluates conditions, and decides when to trade.
2. OKX sub-account isolates the AI's trading capital. We transfer a fixed amount and let the agent operate within that boundary. 3. okx-trade-cli executes the actual orders. OpenClaw calls CLI commands through its shell execution capability. 4. MCP server provides a structured interface when we want Claude or other AI models to analyze positions and suggest adjustments.The workflow looks like this:
Market Signal → OpenClaw evaluates → CLI executes order → Monitor position → Trailing stop or TP/SL hit
What we learned from running this:
- Sub-accounts are non-negotiable. Never give an AI agent access to your main account. Isolate, isolate, isolate.
- Start with demo mode. We ran the full pipeline on OKX demo for two weeks before touching real funds. The demo environment uses live market data, so your strategy testing is realistic.
- Use
--read-onlyMCP first. Let your AI agent observe and analyze for a few days before enabling trade execution. - Log everything. Every CLI command, every response. When something goes wrong (and it will), you need the audit trail.
- Set position limits. Don't let your agent size positions based on available balance. Hard-code maximum position sizes in your agent's logic. A bug that opens a 100x leveraged position with your entire balance will ruin your week.
- Monitor funding rates. Our agent checks funding rates before entering any perpetual swap position. Paying 0.1% every 8 hours on a position you hold for days adds up fast — and it's a cost that many trading bots ignore.
Security Best Practices
Running AI agents with exchange access requires serious security hygiene:
1. API key permissions — Create keys with only the permissions you need. If the agent only trades swaps, don't enable withdrawal permissions.
2. IP whitelisting — Lock API keys to your server's IP address. 3. Sub-account isolation — Transfer only what you're willing to risk. 4. Config file permissions —chmod 600 ~/.okx/config.toml. Nobody else should read your credentials.
5. Passphrase handling — Use single quotes for special characters. Never put credentials in shell history.
Choosing Your Architecture: CLI vs MCP vs Both
The Agent Trade Kit gives you two integration paths, and choosing the right one depends on your use case:
CLI-only works best when your agent runs on a server with shell access (like OpenClaw). The agent executesokx commands directly, parses the output, and makes decisions. This is the simplest setup and the one we use most.
MCP-only is ideal when you're using AI coding assistants (Claude Desktop, Cursor) for interactive analysis. You ask your AI assistant about market conditions or positions, and it queries OKX through the MCP protocol. Great for research and manual decision-making augmented by AI.
Both is the power-user setup. The MCP server handles structured queries and analysis, while CLI commands handle execution. Your AI agent uses MCP to understand the market, then switches to CLI for order placement.
For most people starting out, CLI-only is the right choice. Add MCP later when you want AI-assisted analysis alongside automated execution.
Common Pitfalls
After running this setup for several weeks, here are the mistakes we made so you don't have to:
| Mistake | Fix |
|---|---|
Using --depth for orderbook | Use --sz instead |
Passing --instId to fees command | Use --instType only (SWAP, SPOT, etc.) |
Passphrase with $ in double quotes | Use single quotes: 'my$pass' |
| Running on main account | Always use sub-accounts for AI agents |
| Skipping demo testing | Run demo for at least a week first |
What's Next
The OKX Agent Trade Kit turns the hardest part of AI trading — exchange integration — into a solved problem. Install two packages, configure one file, and your AI agent has full access to one of the largest crypto exchanges.
Whether you're building a custom trading bot, connecting an AI assistant to your portfolio, or just want faster CLI access to OKX, this toolkit delivers.
Try OKX with a demo account, install the Agent Trade Kit, and start with market data. Once you're comfortable, move to demo trading, then — carefully — to live execution.The future of trading isn't manual. It's agents and automation, with humans setting the guardrails. This toolkit is how you get there.
*Disclosure: This article contains affiliate links. We use OKX for our own trading and believe in the platform, but always do your own research before trading. Crypto trading involves significant risk of loss.*