# Send OKX Exchange to your agent
Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.
## Fast path
- Download the package from Yavira.
- Extract it into a folder your agent can access.
- Paste one of the prompts below and point your agent at the extracted folder.
## Suggested prompts
### New install

```text
I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete.
```
### Upgrade existing

```text
I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run.
```
## Machine-readable fields
```json
{
  "schemaVersion": "1.0",
  "item": {
    "slug": "okx-exchange",
    "name": "OKX Exchange",
    "source": "tencent",
    "type": "skill",
    "category": "AI 智能",
    "sourceUrl": "https://clawhub.ai/lk2023060901/okx-exchange",
    "canonicalUrl": "https://clawhub.ai/lk2023060901/okx-exchange",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadUrl": "/downloads/okx-exchange",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=okx-exchange",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "packageFormat": "ZIP package",
    "primaryDoc": "SKILL.md",
    "includedAssets": [
      "README.md",
      "README_ZH.md",
      "SKILL.md",
      "docs/decision-engine-guide.md",
      "docs/learning-system-data-management.md",
      "docs/trading-rules.md"
    ],
    "downloadMode": "redirect",
    "sourceHealth": {
      "source": "tencent",
      "slug": "okx-exchange",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-05-02T19:41:16.009Z",
      "expiresAt": "2026-05-09T19:41:16.009Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=okx-exchange",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=okx-exchange",
        "contentDisposition": "attachment; filename=\"okx-exchange-1.0.1.zip\"",
        "redirectLocation": null,
        "bodySnippet": null,
        "slug": "okx-exchange"
      },
      "scope": "item",
      "summary": "Item download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this item.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/okx-exchange"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    }
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/okx-exchange",
    "downloadUrl": "https://openagent3.xyz/downloads/okx-exchange",
    "agentUrl": "https://openagent3.xyz/skills/okx-exchange/agent",
    "manifestUrl": "https://openagent3.xyz/skills/okx-exchange/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/okx-exchange/agent.md"
  }
}
```
## Documentation

### 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)

# 1. Add credentials to .env
cat >> ~/.openclaw/workspace/.env << 'EOF'
OKX_API_KEY=your_key
OKX_SECRET_KEY=your_secret
OKX_PASSPHRASE=your_passphrase
OKX_SIMULATED=1
EOF

# 2. Run setup
cd ~/.openclaw/workspace/skills/okx-exchange/scripts
python setup.py

Important: OKX_SIMULATED=1 = paper trading (safe). Set to 0 for live trading.

### Session Init

On every session, load credentials first:

source ~/.openclaw/workspace/.env
cd ~/.openclaw/workspace/skills/okx-exchange/scripts

### Unified CLI (Recommended)

Use okx.py as the single entry point for all commands:

python3 okx.py help           # Show all commands
python3 okx.py account        # Portfolio overview
python3 okx.py buy BTC-USDT market 0.01
python3 okx.py trend analyze BTC-USDT-SWAP

All individual scripts remain usable directly, but okx.py is preferred for agent use.

### Instrument ID Format

TypeFormatExampleSpot{BASE}-{QUOTE}BTC-USDTPerpetual Swap{BASE}-{QUOTE}-SWAPBTC-USDT-SWAPFutures{BASE}-{QUOTE}-{EXPIRY}BTC-USDT-250328

tdMode: cash (spot), cross (cross-margin), isolated (isolated-margin)

### Account & Portfolio

python3 okx.py account                          # Full portfolio summary
python3 okx.py account balance                  # Balances only
python3 okx.py account balance USDT             # Specific currency
python3 okx.py account positions                # All positions
python3 okx.py account orders                   # Pending orders
python3 okx.py account history                  # Filled order history (SPOT)
python3 okx.py account history SWAP             # Perpetual swap order history
python3 okx.py account history SPOT BTC-USDT    # History for specific symbol

### Trading Mode (Live / Demo)

python3 okx.py mode           # Show current mode
python3 okx.py mode demo      # Switch to paper trading (safe)
python3 okx.py mode live      # Switch to live trading (requires confirmation + LIVE credentials)

Live credentials use separate env vars:

OKX_API_KEY_LIVE / OKX_SECRET_KEY_LIVE / OKX_PASSPHRASE_LIVE

### Order Execution

# Spot market buy
python3 okx.py buy BTC-USDT market 0.01

# Spot limit sell
python3 okx.py sell BTC-USDT limit 0.01 --px 50000

# Perpetual swap — long with TP/SL (attached to the order)
python3 okx.py buy BTC-USDT-SWAP market 1 --td cross --pos long --tp 55000 --sl 42000

# Perpetual swap — short
python3 okx.py sell BTC-USDT-SWAP market 1 --td cross --pos short

# Close position (reduce-only)
python3 okx.py sell BTC-USDT-SWAP market 1 --td cross --pos long --reduce

# Cancel order
python3 okx.py cancel BTC-USDT <ord_id>

# Cancel all orders for symbol
python3 okx.py cancel-all BTC-USDT

# Set leverage
python3 okx.py leverage BTC-USDT-SWAP 10 --td cross

# Transfer funds between accounts (6=Funding, 18=Trading)
python3 okx.py transfer USDT 500 funding trading   # Funding → Trading
python3 okx.py transfer USDT 500 trading funding   # Trading → Funding

Skip confirmation prompt (for automation):

python3 okx.py buy BTC-USDT market 0.01 --no-confirm

### 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.

# OCO: TP + SL together — whichever triggers first cancels the other
python3 okx.py algo oco BTC-USDT-SWAP 1 --tp 55000 --sl 45000 --td cross --pos long --reduce

# Conditional: single stop-loss only
python3 okx.py algo stop BTC-USDT-SWAP 1 --sl 45000 --td cross --reduce

# List all pending algo orders
python3 okx.py algo list
python3 okx.py algo list BTC-USDT-SWAP   # filter by instrument

# Cancel a specific algo order
python3 okx.py algo cancel BTC-USDT-SWAP <algo_id>

When to use which:

--tp/--sl at order time → atomic, guaranteed to attach, best for new entries
algo oco → add/replace TP+SL after entry, or adjust levels mid-trade

### Trend Following (MA + RSI + MACD)

# Analyze only (no trade)
python3 okx.py trend analyze BTC-USDT-SWAP --bar 1H

# Run with auto-execution
python3 okx.py trend run BTC-USDT-SWAP 1 --bar 4H --tp 0.05 --sl 0.03 --td cross --pos long

# Dry run (analysis only, no trade)
python3 okx.py trend run BTC-USDT-SWAP 1 --dry

Signal logic:

BUY: MA_fast > MA_slow + RSI < 70 + MACD histogram > 0
SELL: MA_fast < MA_slow + RSI > 30 + MACD histogram < 0

### Grid Trading

# Setup grid: BTC-USDT, range 40000-50000, 10 grids, 1000 USDT total
python3 okx.py grid setup BTC-USDT 40000 50000 10 1000

# Check and rebalance filled orders (run periodically)
python3 okx.py grid check BTC-USDT

# Stop and cancel all grid orders
python3 okx.py grid stop BTC-USDT

### Spot-Futures Arbitrage

# Scan all pairs for opportunities
python3 okx.py arb scan

# Check specific pair basis
python3 okx.py arb basis BTC-USDT BTC-USDT-SWAP

# Open arbitrage position (buy spot + short swap)
python3 okx.py arb open BTC-USDT BTC-USDT-SWAP 1000 --min-basis 0.1

# Close arbitrage position when basis converges
python3 okx.py arb close BTC-USDT BTC-USDT-SWAP 0.01 1 --max-basis 0.02

### 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.

python3 okx.py snapshot

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)

# Default: sl-tp every 5 minutes, scan every 30 minutes
bash scripts/cron_setup.sh setup

# Custom intervals (dynamic parameters)
bash scripts/cron_setup.sh setup 1m       # sl-tp every 1 minute
bash scripts/cron_setup.sh setup 10m 1h   # sl-tp every 10 minutes, scan every 1 hour

# Stop all jobs
bash scripts/cron_setup.sh teardown

# Show status
bash scripts/cron_setup.sh status

Cron jobs:

okx-sl-tp — periodically runs snapshot + monitor sl-tp, reports live data
okx-scan  — 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"):

# Find the cron job ID first
openclaw cron list

# Then edit the interval (replace <id> with the okx-sl-tp job ID)
openclaw cron edit <id> --every 10m   # e.g. 1m, 5m, 15m, 30m, 1h

### Manual monitor run

python3 okx.py snapshot             # Full account snapshot report (with history — recommended)
python3 okx.py monitor              # SL/TP check + strategy scan + liquidation risk
python3 okx.py monitor sl-tp        # Only SL/TP check
python3 okx.py monitor scan         # Only strategy scan
python3 okx.py monitor liq-risk     # Liquidation risk check (default: alert if within 10%)
python3 okx.py monitor liq-risk 5   # Alert if mark price within 5% of liquidation price

### CRITICAL: Cron reporting rules

Every cron report MUST call the scripts first. NEVER fabricate, estimate, or reuse previous numbers.

Recommended single command for cron:

cd ~/.openclaw/workspace/skills/okx-exchange/scripts
python3 okx.py snapshot
python3 okx.py monitor sl-tp

snapshot 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

python3 okx.py report daily    # Today's P&L summary
python3 okx.py report weekly   # Last 7 days
python3 okx.py report all      # All-time

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:

python3 okx.py prefs show
python3 okx.py prefs set auto_trade true
python3 okx.py prefs set stop_loss_pct 3.0
python3 okx.py prefs set watchlist BTC-USDT-SWAP,ETH-USDT-SWAP,SOL-USDT-SWAP

Full preferences schema (~/.openclaw/workspace/memory/okx-trading-preferences.json):

{
  "max_order_usd": 100,
  "max_leverage": 10,
  "price_impact_warn": 0.005,
  "price_impact_abort": 0.01,
  "require_confirm": true,
  "stop_loss_pct": 5.0,
  "take_profit_pct": 10.0,
  "auto_trade": false,
  "max_position_usd": 100,
  "max_daily_trades": 10,
  "default_sz": "0.01",
  "strategies": ["trend"],
  "watchlist": ["BTC-USDT-SWAP", "ETH-USDT-SWAP"]
}

ParameterDefaultDescriptionmax_order_usd100Max USD per single ordermax_leverage10Max allowed leverageprice_impact_warn0.005Warn if market order impact > 0.5%price_impact_abort0.01Abort if market order impact > 1%require_confirmtruePrompt before placing ordersstop_loss_pct5.0Auto stop-loss at -X% unrealized PnLtake_profit_pct10.0Auto take-profit at +X% unrealized PnLauto_tradefalseExecute trades automatically (no confirmation)max_position_usd100Max USD per positionmax_daily_trades10Max auto-trades per daydefault_sz"0.01"Default size for auto-tradingstrategies["trend"]Active strategies: trend / arbitragewatchlist[...]Instruments for monitor scan

### Environment Variables

VariableDefaultDescriptionOKX_API_KEY—Demo API keyOKX_SECRET_KEY—Demo API secretOKX_PASSPHRASE—Demo API passphraseOKX_API_KEY_LIVE—Live API key (used when mode=live)OKX_SECRET_KEY_LIVE—Live API secretOKX_PASSPHRASE_LIVE—Live API passphraseOKX_SIMULATED0Set 1 for paper trading (demo account)OKX_WS0Set 1 to enable WebSocket feed (real-time cache for tickers/candles/account/positions)OKX_API_URLhttps://www.okx.comOverride API base URLOKX_LOG_LEVELINFODEBUG / INFO / WARNING / ERROROKX_LOG_FORMATtexttext or json (structured logging)OKX_CRON_MODE0Set 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:

docs/trading-rules.md

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

Always confirm before placing orders unless auto_trade=true or --no-confirm
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

FilePurposememory/okx-trading-preferences.jsonStrategy config, risk parameters, and trading modememory/okx-trading-state.jsonRuntime state (daily trade count, last scan)memory/okx-trading-journal.jsonTrade history from monitor (SL/TP closures, auto-entries)memory/okx-trade-journal.jsonTrade history from learning system (signal analysis)memory/okx-learning-model.jsonLearning model (win rates by coin/regime, optimal params)memory/okx-grid-{inst_id}.jsonGrid state per instrument

### Kill Switch

# Stop all automated trading
bash scripts/cron_setup.sh teardown
# Or remove OKX_API_KEY from .env to prevent any API calls
## Trust
- Source: tencent
- Verification: Indexed source record
- Publisher: lk2023060901
- Version: 1.0.1
## Source health
- Status: healthy
- Item download looks usable.
- Yavira can redirect you to the upstream package for this item.
- Health scope: item
- Reason: direct_download_ok
- Checked at: 2026-05-02T19:41:16.009Z
- Expires at: 2026-05-09T19:41:16.009Z
- Recommended action: Download for OpenClaw
## Links
- [Detail page](https://openagent3.xyz/skills/okx-exchange)
- [Send to Agent page](https://openagent3.xyz/skills/okx-exchange/agent)
- [JSON manifest](https://openagent3.xyz/skills/okx-exchange/agent.json)
- [Markdown brief](https://openagent3.xyz/skills/okx-exchange/agent.md)
- [Download page](https://openagent3.xyz/downloads/okx-exchange)