I've been running this setup on a VPS alongside other trading automation. This tutorial covers installation, configuration, live trading commands, and real cron job recipes you can copy-paste today.
What you'll need: A Unix-like system (Linux, macOS, WSL), Node.js 18+, and an OKX account.Why Trade from the Terminal?
Before diving into commands, here's why this approach is worth your time:
Speed. A CLI command executes in under a second. No page loads, no 2FA popups for every action, no "Are you sure?" modals. When you see a setup forming, you can go from idea to order in the time it takes to type one line. Reproducibility. Shell commands are inherently repeatable. Save them in a script, version them in git, share them with collaborators. Try doing that with "click the green button, then scroll down, then click Confirm." Automation. This is the big one. Once your orders are CLI commands, you can schedule them with cron, trigger them from webhooks, chain them with other scripts, or integrate them into a larger trading system. A CLI is a building block; a browser tab is a dead end. Auditability. Every command can be logged with timestamps. Pipe output to files, search through history withgrep, build a complete record of every trade you've ever placed. Good luck doing that with browser screenshots.
Install okx-trade-cli
One command:
npm install -g okx-trade-cli
Verify it works:
okx market ticker BTC-USDT
You should see the current BTC-USDT price, 24h volume, and spread. No API key needed for market data — authentication is only required for account and trading commands.
Market Data: No Auth Required
Before committing a single dollar, you can pull a surprising amount of data straight from the terminal.
Live Prices
okx market ticker BTC-USDT
okx market ticker ETH-USDT
Candlestick Data
okx market candles BTC-USDT --bar 4H --limit 5
okx market candles ETH-USDT --bar 1H --limit 3
The --bar flag accepts standard intervals: 1m, 5m, 15m, 1H, 4H, 1D, 1W. --limit controls how many candles to return.
Derivatives Data
For perpetual swap traders, funding rates and open interest are essential:
okx market funding-rate BTC-USDT-SWAP
okx market open-interest --instType SWAP --instId BTC-USDT-SWAP
okx market price-limit BTC-USDT-SWAP
Recent Trades
okx market trades BTC-USDT --limit 3
All market commands support --json for raw JSON output, which makes them composable with jq and shell scripts:
okx market ticker BTC-USDT --json | jq '.[0].last'
Configuration: API Keys and Profiles
To trade, you need OKX API credentials. Create them at OKX API Management (Account → API → Create API Key).
okx-trade-cli uses a TOML config file with named profiles, so you can switch between demo and live environments without juggling environment variables:
mkdir -p ~/.okx
cat > ~/.okx/config.toml << 'EOF'
default_profile = "demo"
[profiles.demo]
site = "global"
api_key = "your-demo-key"
secret_key = "your-demo-secret"
passphrase = "your-demo-passphrase"
demo = true
[profiles.live]
site = "global"
api_key = "your-live-key"
secret_key = "your-live-secret"
passphrase = 'YourPass$Special' # single quotes for special chars!
demo = false
EOF
chmod 600 ~/.okx/config.toml
Important details:
chmod 600— only your user can read the file. Non-negotiable for anything holding API secrets.- If your passphrase contains
$,!, or other shell-special characters, wrap it in single quotes in the TOML file. Double quotes will trigger shell interpolation and silently break authentication. demo = trueconnects to OKX's demo trading environment — real order flow simulation with fake money. Test here first.
Verify Connectivity
okx diagnose
This checks API connectivity, clock sync, and key permissions. Run it after any config change.
Account Commands
Once authenticated, check your balances and positions:
# Total balance across all currencies
okx account balance
# Single currency
okx account balance USDT
# Open positions (perpetual swaps)
okx account positions
# Trading fee tier
okx account fees --instType SWAP
okx account fees --instType SPOT
Note: okx account fees does not support --instId filtering — it returns fees for the entire instrument type.
Spot Trading
Place orders on spot markets:
# Market buy $10 worth of BTC
okx spot place --instId BTC-USDT --side buy --ordType market --sz 10 --tdMode cash
# Check open orders
okx spot orders --instId BTC-USDT
# Order history
okx spot orders --history
The --sz parameter means different things depending on order type:
- Market buy:
--szis the quote currency amount (USDT) you want to spend - Market sell:
--szis the base currency amount (BTC) you want to sell - Limit orders:
--szis always the base currency amount
--tdMode cash is required for spot — it means no leverage, no margin.
Perpetual Swap Trading
Swaps give you leverage and the ability to short. The CLI handles all the complexity:
# Market long 1 contract BTC-USDT-SWAP
okx swap place --instId BTC-USDT-SWAP --side buy --ordType market --sz 1 --tdMode cross
Limit Order with TP/SL
This is where the CLI really shines — setting up a complete trade with take-profit and stop-loss in a single command:
okx swap place \
--instId BTC-USDT-SWAP \
--side buy \
--ordType limit \
--sz 1 \
--px 65000 \
--tdMode cross \
--tpTriggerPx 72000 \
--tpOrdPx -1 \
--slTriggerPx 62000 \
--slOrdPx -1
Breaking this down:
--px 65000— limit entry at $65,000--tpTriggerPx 72000— take profit triggers at $72,000--tpOrdPx -1— execute TP as market order (-1= market)--slTriggerPx 62000— stop loss triggers at $62,000--slOrdPx -1— execute SL as market order
Position Management
# View open positions
okx swap positions
# Check pending orders
okx swap orders
# Close a position
okx swap close --instId BTC-USDT-SWAP --mgnMode cross
Cron Job Automation
The real power of a CLI tool is scripting. Here are three production-ready cron recipes.
Recipe 1: Dollar-Cost Averaging (DCA)
Buy $50 of BTC every 4 hours, automatically:
# Add to crontab: crontab -e
0 */4 * * * /usr/bin/okx --profile live spot place --instId BTC-USDT --side buy --ordType market --sz 50 --tdMode cash >> /var/log/okx-dca.log 2>&1
That's 6 buys per day, $300/day, spreading your entry across all market conditions. Adjust --sz and the interval to match your budget.
Recipe 2: Price Alert
Get an email when BTC drops below $65,000:
Like what you're reading? Try it yourself — this link supports ChartedTrader at no cost to you.
Try OKX →
*/5 * * * * PRICE=$(/usr/bin/okx market ticker BTC-USDT --json | jq -r '.[0].last') && [ $(echo "$PRICE < 65000" | bc) -eq 1 ] && echo "BTC below 65k: $PRICE" | mail -s "BTC Alert" you@email.com
This checks every 5 minutes. Replace mail with a curl to a Telegram bot, Discord webhook, or Slack incoming webhook for mobile notifications.
Recipe 3: Morning Portfolio Snapshot
Log your balances and positions every day at 8 AM:
0 8 * * * /usr/bin/okx account balance && /usr/bin/okx account positions >> ~/trading-log.txt
Over time, trading-log.txt becomes a full audit trail of your portfolio evolution.
Cron Tips
1. Use absolute paths. Cron runs with a minimal $PATH. Use /usr/bin/okx (find yours with which okx).
>> logfile 2>&1 captures both stdout and stderr for debugging.
3. Use --profile live explicitly. Don't rely on the default profile in cron — be explicit to avoid accidentally trading on demo.
4. Test manually first. Copy the full cron command, paste it into your terminal, and verify it works before scheduling.
JSON Output for Scripting
Every command supports --json for machine-readable output:
okx market ticker BTC-USDT --json
okx account balance --json
okx swap positions --json
This makes okx-trade-cli composable with any scripting language. A quick Python example:
import subprocess, json
result = subprocess.run(
["okx", "market", "ticker", "BTC-USDT", "--json"],
capture_output=True, text=True
)
data = json.loads(result.stdout)
price = float(data[0]["last"])
print(f"BTC: ${price:,.2f}")
Or pipe JSON through jq for quick one-liners:
# Get just the last price
okx market ticker BTC-USDT --json | jq -r '.[0].last'
# Get unrealized PnL from swap positions
okx swap positions --json | jq '.[].upl'
Advanced: Multi-Asset DCA Script
Here's a more sophisticated DCA script that buys multiple assets with different allocations:
#!/bin/bash
# multi-dca.sh — DCA into multiple assets with weighted allocation
# Total budget: $100 per run
LOG="/var/log/okx-multi-dca.log"
TIMESTAMP=$(date -u +"%Y-%m-%d %H:%M:%S UTC")
echo "=== DCA Run: $TIMESTAMP ===" >> "$LOG"
# 60% BTC, 30% ETH, 10% SOL
okx --profile live spot place --instId BTC-USDT --side buy --ordType market --sz 60 --tdMode cash >> "$LOG" 2>&1
okx --profile live spot place --instId ETH-USDT --side buy --ordType market --sz 30 --tdMode cash >> "$LOG" 2>&1
okx --profile live spot place --instId SOL-USDT --side buy --ordType market --sz 10 --tdMode cash >> "$LOG" 2>&1
echo "=== Complete ===" >> "$LOG"
Schedule it weekly:
0 9 * * 1 /home/user/scripts/multi-dca.sh
Every Monday at 9 AM, $100 gets split across three assets. Modify the allocations, add more pairs, or adjust the schedule to match your strategy.
Building a Simple Grid Bot
Combine the CLI with a bash script for a basic grid trading strategy:
#!/bin/bash
# grid-buy.sh — place limit buys at 1% intervals below current price
CURRENT=$(okx market ticker BTC-USDT --json | jq -r '.[0].last')
for i in 1 2 3 4 5; do
LEVEL=$(echo "$CURRENT * (1 - 0.01 * $i)" | bc -l | xargs printf "%.1f")
okx spot place \
--instId BTC-USDT \
--side buy \
--ordType limit \
--sz 20 \
--px "$LEVEL" \
--tdMode cash
echo "Placed buy at $LEVEL"
done
Run this daily or on a cron schedule. Each execution layers limit orders below the current price, catching dips automatically. Pair it with a matching sell script that places orders above your average entry.
Security Best Practices
Trading from the terminal means your API keys live on disk. Treat them seriously:
1. Restrict API permissions. On OKX, create keys with only the permissions you need. DCA bot? Trade permission only — no withdrawal.
2. IP whitelist. Lock your API key to your server's IP address. If someone gets your key, they still can't use it from a different machine. 3.chmod 600 your config. Already mentioned, but worth repeating.
4. Use a dedicated VPS. A $5/month VPS running your cron jobs is more reliable than your laptop — and isolates your trading keys from your daily-use machine.
5. Demo first. Always test new scripts on --profile demo before pointing them at real money. OKX's demo environment simulates the full order book.
Multi-asset DCA with SOL
SOL perpetuals are among the most liquid on OKX. Here's a multi-asset DCA that includes SOL:
#!/bin/bash
# Multi-asset DCA: BTC + ETH + SOL
for COIN in BTC ETH SOL; do
okx --profile live spot place --instId ${COIN}-USDT --side buy --ordType market --sz 20 --tdMode cash
echo "$(date): Bought $20 ${COIN}" >> ~/dca-log.txt
done
For SOL perpetual grid trading:
# SOL grid bot — range trading between support and resistance
okx bot grid create --instId SOL-USDT-SWAP --algoOrdType contract_grid \
--maxPx 120 --minPx 70 --gridNum 15 --direction long --lever 3 --sz 10
SOL's higher volatility compared to BTC makes it particularly well-suited for grid strategies.
Monitoring and Logging
For any automated trading setup, monitoring is essential. Here's a lightweight approach using the CLI itself.
Daily P&L Report
#!/bin/bash
# daily-report.sh — email yourself a portfolio summary
REPORT=$(mktemp)
echo "=== Portfolio Report $(date) ===" > "$REPORT"
echo "" >> "$REPORT"
echo "--- Balances ---" >> "$REPORT"
okx --profile live account balance >> "$REPORT" 2>&1
echo "" >> "$REPORT"
echo "--- Open Positions ---" >> "$REPORT"
okx --profile live swap positions >> "$REPORT" 2>&1
echo "" >> "$REPORT"
echo "--- Market Overview ---" >> "$REPORT"
okx market ticker BTC-USDT >> "$REPORT" 2>&1
okx market ticker ETH-USDT >> "$REPORT" 2>&1
okx market funding-rate BTC-USDT-SWAP >> "$REPORT" 2>&1
cat "$REPORT" | mail -s "Daily Crypto Report" you@email.com
rm "$REPORT"
Position Size Checker
A safety script that warns you if any position exceeds a risk threshold:
#!/bin/bash
# risk-check.sh — alert if any position is too large
MAX_NOTIONAL=5000 # $5000 max per position
POSITIONS=$(okx --profile live swap positions --json)
ALERT=$(echo "$POSITIONS" | jq -r ".[] | select((.notionalUsd | tonumber) > $MAX_NOTIONAL) | .instId")
if [ -n "$ALERT" ]; then
echo "WARNING: Oversized positions detected: $ALERT" | mail -s "Risk Alert" you@email.com
fi
Run it every 15 minutes to catch accidental over-leveraging.
Gotchas and Tips
A few things I learned the hard way:
--jsonflag outputs raw JSON suitable for piping tojq. Without it, you get human-readable formatted output.okx market orderbookuses--szfor depth, not--depth.- Demo mode can be toggled per-command with
--demoor set permanently in your profile config withdemo = true. - Rate limits exist. OKX enforces API rate limits per endpoint. A DCA bot running every 4 hours is fine. A price checker running every second will get throttled. Check OKX API docs for specific limits.
- Clock sync matters. OKX rejects requests with timestamps more than 30 seconds off. Run
ntpdorchronyon your server.okx diagnosewill warn you if your clock is skewed.
Comparison: CLI vs Web UI vs Full Bot
| Feature | OKX Web UI | okx-trade-cli | Custom Python Bot |
|---|---|---|---|
| Setup time | 0 min | 5 min | Hours to days |
| Automation | Manual only | Cron jobs | Full flexibility |
| Learning curve | Low | Medium | High |
| Maintenance | None | Minimal | Ongoing |
| Cost | Free | Free | Free (+ your time) |
| Customization | Limited | Moderate | Unlimited |
If you later need more complex logic — dynamic position sizing, multi-exchange arbitrage, ML-driven signals — the --json output means your CLI scripts can evolve into a proper codebase incrementally. Start simple, add complexity only when the simpler approach stops working.
Who This Is For
okx-trade-cli fills a specific niche: traders who are comfortable in the terminal and want to automate repetitive tasks without writing a full trading bot from scratch.
If you're already running scripts, monitoring positions via SSH, or just want to avoid the browser, this tool saves real time. The cron job recipes alone — DCA, alerts, portfolio logging — replace hours of manual work per week.
For algo traders who already have a Python or Node.js stack, okx-trade-cli is also useful as a quick manual override tool. When your bot is misbehaving at 3 AM and you need to close a position *right now*, SSH into the server and run okx swap close instead of fumbling with a mobile app on a laggy connection.
If you're interested in more advanced OKX integrations, check out our OKX Agent Trade Kit review for connecting AI agents to OKX, or the OKX withdrawal fee guide to optimize your transfer costs.
If you don't have an OKX account yet, sign up here to get started. The demo trading environment lets you test everything in this tutorial with zero risk.
---
*This article contains affiliate links. I may earn a commission if you sign up through my links, at no extra cost to you. All opinions and code examples are my own — I use these tools daily.*