Skill: numpy0001/okx-cex-market (version 1.3.5)

--- name: okx-cex-market description: "Use this skill when the user asks for: price of any asset, ticker, order book, candles, OHLCV, funding rate, open interest, OI change scanner, market screener (top movers, high-volume, newly listed), mark price, index price, recent trades, instrument list, stock tokens, metals prices (gold, XAU, XAG), commodities (oil, OIL), forex rates (EUR/USD, EURUSDT), bond instruments, non-crypto assets, or any technical indicator query (RSI, MACD, EMA, Bollinger Bands, KDJ, SuperTrend, AHR999, BTC rainbow, and 70+ more). All commands are read-only and do NOT require API credentials. Do NOT use for account balance/positions (okx-cex-portfolio), placing/cancelling orders (okx-cex-trade), or bots (okx-cex-bot)." license: MIT metadata: author: okx version: "1.3.5" homepage: "https://www.okx.com" agent: requires: bins: ["okx"] install: - id: npm kind: node package: "@okx_ai/okx-trade-cli@1.3.3" bins: ["okx"] label: "Install okx CLI (npm)" --- # OKX CEX Market Data CLI > **Compliance notice**: This skill provides raw market data only. No strategy, recommendation, or optimization logic is embedded. All indicator outputs are objective numerical values; interpretation and trading decisions remain solely with the user. Public market data for OKX: prices, order books, candles, funding rates, open interest, instrument info, and technical indicators. All commands are **read-only** and require **no API credentials**. **Skill routing** - Market data / indicators → `okx-cex-market` (this skill) - Account balance / positions → `okx-cex-portfolio` - Place / cancel orders → `okx-cex-trade` - Grid / DCA bots → `okx-cex-bot` ## Preflight Before running any command, follow [`../_shared/preflight.md`](../_shared/preflight.md). Use `metadata.version` from this file's frontmatter as the reference for Step 2. ## Install ```bash npm install -g @okx_ai/okx-trade-cli okx market ticker BTC-USDT # verify ``` Market data commands return the same public data regardless of demo/live mode — no API credentials required. If the user's profile has `demo=true` set and they want live data context, they can use `--live` to confirm they are in live mode (it has no effect on public market data but clarifies environment). Always inform the user which environment is active (demo or live) when it is relevant to their query. No confirmation needed before running any market command. Add `--json` to any command for raw OKX API v5 response. Add `--env` to wrap the output as `{"env", "profile", "data"}`. --- ## Command Index | # | Command | Description | |---|---|---| | 1 | `okx market ticker <instId>` | Last price, 24h high/low/vol/change% | | 2 | `okx market tickers <instType>` | All tickers for SPOT / SWAP / FUTURES / OPTION | | 3 | `okx market instruments --instType <type> [--instId <id>]` | List instruments (instId, ctVal, lotSz, minSz, tickSz, state) | | 4 | `okx market orderbook <instId> [--sz <n>]` | Order book asks/bids (default top 5 per side, max 400) | | 5 | `okx market candles <instId> [--bar <bar>] [--limit <n>] [--after <ts>] [--before <ts>]` | OHLCV candles (default `--bar 1m`); auto-routes to historical endpoint for data back to 2021; `--after` paginates back in time, `--before` paginates forward | | 6 | `okx market index-candles <instId> [--bar <bar>] [--limit <n>] [--history]` | Index OHLCV (use `BTC-USD` not `BTC-USDT`) | | 7 | `okx market funding-rate <instId> [--history] [--limit <n>]` | Current or historical funding rate (SWAP only) | | 8 | `okx market trades <instId> [--limit <n>]` | Recent public trades | | 9 | `okx market mark-price --instType <type> [--instId <id>]` | Mark price (SWAP / FUTURES / OPTION) | | 10 | `okx market index-ticker [--instId <id>] [--quoteCcy <ccy>]` | Index price (e.g., BTC-USD) | | 11 | `okx market price-limit <instId>` | Upper/lower price limits (SWAP / FUTURES only) | | 12 | `okx market open-interest --instType <type> [--instId <id>]` | Open interest in contracts and base currency | | 13 | `okx market instruments-by-category --instCategory <3\|4\|5\|6\|7>` | Discover instruments by asset category: 3=Stock tokens (AAPL/TSLA), 4=Metals (gold/silver), 5=Commodities (oil/gas), 6=Forex (EUR/USD), 7=Bonds | | 13† | `okx market stock-tokens` | **Deprecated** — use `instruments-by-category --instCategory 3` instead | | 14 | `okx market filter --instType <SPOT\|SWAP\|FUTURES> [--sortBy <field>] [--sortOrder <asc\|desc>] [--limit <n>] [--baseCcy <ccy>] [--quoteCcy <ccy>] [--settleCcy <ccy>] [--instFamily <fam>] [--ctType <linear\|inverse>] [--minLast <n>] [--maxLast <n>] [--minChg24hPct <n>] [--maxChg24hPct <n>] [--minMarketCapUsd <n>] [--maxMarketCapUsd <n>] [--minVolUsd24h <n>] [--maxVolUsd24h <n>] [--minFundingRate <n>] [--maxFundingRate <n>] [--minOiUsd <n>] [--maxOiUsd <n>]` | Screen / rank instruments by multi-dimensional criteria (price, volume, OI, funding rate, market cap) | | 15 | `okx market oi-history <instId> [--bar <5m\|15m\|1H\|4H\|1D>] [--limit <n>] [--ts <ms>]` | OI history time series with bar-over-bar delta for a single instrument | | 16 | `okx market oi-change --instType <SWAP\|FUTURES> [--bar <5m\|15m\|1H\|4H\|1D>] [--sortBy <field>] [--sortOrder <asc\|desc>] [--limit <n>] [--minOiUsd <n>] [--minVolUsd24h <n>] [--minAbsOiDeltaPct <n>]` | Find instruments with largest OI changes (accumulation/distribution scanner) | | 17 | `okx market indicator list` | List all supported indicator names and descriptions | | 18 | `okx market indicator <indicator> <instId> [--bar] [--params] [--list] [--limit] [--backtest-time]` | Technical indicator values | | 19 | `okx market pair-spread <instIdA> <instIdB> [--bar <5m\|15m>] [--window <window>] [--backtest-time <ms>]` | Spread statistics (abs + ratio: mean/stdDev/median/min/max) over a lookback window; supports backtest mode | --- ## Operation Flow ### Step 1 — Identify data type and load reference | User intent | Reference to load | |---|---| | Price, candles, order book, recent trades | `{baseDir}/references/price-data-commands.md` | | Technical indicators (RSI, MACD, EMA, BB, KDJ, SuperTrend, AHR999, Rainbow, etc.) | `{baseDir}/references/indicator-commands.md` | | Funding rate, mark price, open interest, price limit, index ticker | `{baseDir}/references/derivatives-commands.md` | | Screen / rank instruments; find top movers, high-OI, high-volume contracts | Use `okx market filter` directly | | OI history time series for a single instrument | Use `okx market oi-history` directly | | OI change scanner; find contracts with large OI shifts | Use `okx market oi-change` directly | | Pair spread statistics; mean-reversion / pairs-trade sizing | Use `okx market pair-spread` directly | | List instruments, discover stock tokens, metals/commodities/forex/bonds, find option instIds | `{baseDir}/references/instrument-commands.md` | | Multi-step or cross-skill workflows; MCP tool names | `{baseDir}/references/workflows.md` | ### Step 2 — Run commands immediately All market data commands are read-only — no confirmation needed. ### Step 3 — No writes, no verification needed All commands in this skill are read-only. --- ## Edge Cases - **instId format**: SPOT `BTC-USDT` · SWAP `BTC-USDT-SWAP` · FUTURES `BTC-USDT-250328` · OPTION `BTC-USD-250328-95000-C` · Index `BTC-USD` · Stock token `TSLA-USDT-SWAP` · Metals/Commodities/Forex/Bonds: use `instruments-by-category` to discover valid instIds first - **OPTION listing**: `instruments --instType OPTION` requires `--uly BTC-USD`; if unknown, run `open-interest --instType OPTION` first to discover active instIds - **funding-rate / price-limit**: SWAP only · mark-price: SWAP / FUTURES / OPTION only - **candles `--bar`**: uppercase — `1H` not `1h`; use `--after <ts>` to paginate back into historical data (back to 2021); index-candles supports `--history` for extended history - **⚠️ Large historical range**: before fetching with `--after`/`--before`, estimate candle count = `time_range_ms / bar_interval_ms`. If estimate > 500, tell the user the estimated count and ask for confirmation before proceeding. This prevents silently filling the context window. - **indicator `--bar`**: uses `1Dutc` not `1D`, `1Wutc` not `1W` — different from candle bar values - **`market filter` sortBy values**: `last` `chg24hPct` `marketCapUsd` `volUsd24h` `fundingRate` `oiUsd` `listTime` — default `volUsd24h` - **`market filter` ctType**: `linear` or `inverse` (SWAP/FUTURES only); omit for SPOT - **`market filter` quoteCcy**: comma-separated list supported, e.g. `--quoteCcy USDT,USDC` - **`market filter` SPOT + quoteCcy**: when `--instType SPOT`, the API returns instruments across **all** quote currencies (USDT, USDC, BTC, ETH, etc.) mixed together — this pollutes sort order and bloats results. Always pass `--quoteCcy USDT` by default unless the user explicitly asks for other quote currencies. - **`market filter` chg24hPct**: value is a percentage number — `--minChg24hPct -5` means -5%, `--maxChg24hPct 10` means 10% - **`market oi-history` ts**: Unix ms timestamp; returns bars with ts ≤ this value for historical pagination - **`market oi-history` / `oi-change` bar**: valid values `5m` `15m` `1H` `4H` `1D` — default `1H`. Server accepts case variants (`1h` == `1H`) but prefer canonical casing. - **`market oi-history` limit**: 1–500 (default 50) - **`market oi-change` instType**: only `SWAP` or `FUTURES` supported (not SPOT) - **`market oi-change` minAbsOiDeltaPct**: filters by absolute OI change — `1.0` keeps only rows where |oiDeltaPct| ≥ 1% - **`market oi-change` sortBy values**: `oiUsd` `oiDeltaUsd` `oiDeltaPct` `absOiDeltaPct` `volUsd24h` `fundingRate` `last` — default `oiDeltaPct` (signed). Use `absOiDeltaPct` to rank by |oiDeltaPct| (largest magnitude regardless of direction). - **`market oi-change` limit**: 1–100 (default 20). For deeper than 100 rows, fetch `oi-history` per instId. - **indicator `--bar` valid values**: `3m` `5m` `15m` `1H` `4H` `12Hutc` `1Dutc` `3Dutc` `1Wutc` — `1m` is **not supported** for indicators (use `candles` for 1-minute data) - **indicator `--limit`**: 1–100 (only used with `returnList`, i.e. when a historical series is requested) - **indicator arg order**: indicator name before instId — `okx market indicator rsi BTC-USDT` - **indicator `--params`**: comma-separated, no spaces — `--params 5,20` - **BTC-only indicators**: `ahr999`, `rainbow` — BTC-USDT only - **Unknown indicator name**: returns a `ValidationError` with similar-name suggestions before the API is called — use `market_list_indicators` / `okx market indicator list` to see all valid names - **Stock token hours**: US stocks trade Mon–Fri ~09:30–16:00 ET; verify live price before acting - **No data returned**: instrument may be delisted — verify with `okx market instruments` - **`boll`** is an alias for `bb` ## Global Notes - No API key required for any command in this skill - Rate limit: 20 req / 2 s per IP - Candle data is sorted newest-first - `vol24h` is in base currency (e.g., BTC for BTC-USDT) - `--demo`/`--live` and `--profile` do not affect market data results via CLI (public endpoints); they only determine the active trading environment context

path: references/workflows.md
content: # Cross-Skill Workflows & MCP Tool Reference

## Cross-Skill Workflows

All market commands are read-only. Decisions and order placement remain with the user.

---

### Price lookup before order placement

```
okx market ticker BTC-USDT                    → last price, 24h range
okx-cex-portfolio: okx account balance USDT   → available funds
okx-cex-trade: okx spot place ...             → user decides px/sz
```

---

### Funding rate analysis for perp positions

```
okx market funding-rate BTC-USDT-SWAP          → current rate + next funding time
okx market funding-rate BTC-USDT-SWAP --history --limit 10  → recent trend
okx-cex-portfolio: okx account positions       → check existing exposure
```

---

### Market data lookup before grid bot setup

```
okx market candles BTC-USDT --bar 4H --limit 50   → recent OHLCV for range estimation
okx market ticker BTC-USDT                         → current price
okx market orderbook BTC-USDT --sz 20              → liquidity check
okx-cex-bot: okx bot grid create ...               → user decides minPx/maxPx
```

---

### Spot vs perp price comparison (premium check)

```
okx market ticker BTC-USDT
okx market ticker BTC-USDT-SWAP
okx market mark-price --instType SWAP --instId BTC-USDT-SWAP
```

---

### Non-crypto asset discovery before trading (Metals / Commodities / Forex / Bonds)

```
# Step 1 — discover valid instIds for the asset class
okx market instruments-by-category --instCategory 4   → Metals: find XAUUSDT-USDT-SWAP, XAGUSDT-USDT-SWAP
okx market instruments-by-category --instCategory 5   → Commodities: find OIL-USDT-SWAP, GAS-USDT-SWAP
okx market instruments-by-category --instCategory 6   → Forex: find EURUSDT-USDT-SWAP, GBPUSDT-USDT-SWAP
okx market instruments-by-category --instCategory 7   → Bonds: find US30Y-USDT-SWAP

# Step 2 — verify live price and check trading session is open
okx market ticker XAUUSDT-USDT-SWAP                   → last price, 24h range (state must show active)
okx market orderbook XAUUSDT-USDT-SWAP                → bid/ask spread and liquidity

# Step 3 — get instrument specs for order sizing
okx market instruments --instType SWAP --instId XAUUSDT-USDT-SWAP --json
                                                       → ctVal, minSz, lotSz for quantity conversion

# okx-cex-trade: user places order after confirming market is open
```

> **Important**: non-crypto instruments have trading-hour restrictions. Always confirm `state=live` in the instruments response and a non-zero last price in `ticker` before proceeding to order placement.

---

### Stock token discovery before trading

```
okx market instruments-by-category --instCategory 3            → list instIds and specs (preferred)
okx market ticker TSLA-USDT-SWAP                               → current price and 24h range
okx market instruments --instType SWAP --instId TSLA-USDT-SWAP --json
                                                                → ctVal, minSz, lotSz for sz conversion
```

> `okx market stock-tokens` is deprecated — use `instruments-by-category --instCategory 3` instead.

---

### Option discovery and pricing

```
okx market open-interest --instType OPTION --instId BTC-USD    → find active option instIds
okx market ticker BTC-USD-250328-95000-C                       → option last price and stats
okx market orderbook BTC-USD-250328-95000-C                    → bid/ask spread
```

---

### Multi-indicator trend analysis

Run in parallel — no ordering dependency:

```
okx market indicator ema BTC-USDT --bar 4H --params 5,20       → EMA5 vs EMA20 alignment
okx market indicator macd BTC-USDT --bar 4H                    → MACD histogram + DIF/DEA cross
okx market indicator rsi BTC-USDT --bar 4H --params 14         → RSI overbought/oversold
okx market indicator bb BTC-USDT --bar 4H                      → Bollinger Bands position
okx market indicator supertrend BTC-USDT --bar 4H              → direction signal (buy/sell)
```

---

### BTC macro cycle analysis

Run in parallel — no ordering dependency:

```
okx market indicator ahr999 BTC-USDT    → accumulate / DCA / bubble zone
okx market indicator rainbow BTC-USDT   → Rainbow Chart valuation band
```

---

## MCP Tool Reference

When using MCP tools directly (instead of CLI), the tool names map as follows:

| CLI subcommand | MCP tool name |
|---|---|
| `market ticker` | `market_get_ticker` |
| `market tickers` | `market_get_tickers` |
| `market instruments` | `market_get_instruments` |
| `market orderbook` | `market_get_orderbook` |
| `market candles` | `market_get_candles` |
| `market index-candles` | `market_get_index_candles` |
| `market funding-rate` | `market_get_funding_rate` |
| `market trades` | `market_get_trades` |
| `market mark-price` | `market_get_mark_price` |
| `market index-ticker` | `market_get_index_ticker` |
| `market price-limit` | `market_get_price_limit` |
| `market open-interest` | `market_get_open_interest` |
| `market stock-tokens` | `market_get_stock_tokens` |
| `market instruments-by-category` | `market_get_instruments_by_category` |
| `market indicator list` | `market_list_indicators` |
| `market indicator <name> <instId>` | `market_get_indicator` |

> **`demo` parameter (MCP only)**: All market MCP tools (except `market_list_indicators` and `market_get_indicator`) accept an optional `demo: true` parameter to query OKX's simulated trading market data environment. Default is `false` (live data). CLI equivalent: `--demo` global flag.


path: references/price-data-commands.md
content: # Price & Market Data Commands

## ticker — Single Instrument

```bash
okx market ticker <instId> [--json]
```

| Param | Required | Description |
|---|---|---|
| `instId` | Yes | Instrument ID (e.g., `BTC-USDT`, `BTC-USDT-SWAP`) |

Returns: `last` · `high24h` · `low24h` · `vol24h` (base currency) · `sodUtc8` (24h change %)

```bash
okx market ticker BTC-USDT
# instId: BTC-USDT | last: 95000.5 | 24h change%: +1.2% | high: 96000 | low: 93000
```

---

## tickers — All Instruments of a Type

```bash
okx market tickers <instType> [--json]
```

| Param | Required | Values |
|---|---|---|
| `instType` | Yes | `SPOT` `SWAP` `FUTURES` `OPTION` |

Returns table: `instId` · `last` · `high24h` · `low24h` · `vol24h`

```bash
okx market tickers SWAP
# → table of all perpetual contracts
```

---

## orderbook — Order Book Depth

```bash
okx market orderbook <instId> [--sz <n>] [--json]
```

| Param | Required | Default | Description |
|---|---|---|---|
| `instId` | Yes | - | Instrument ID |
| `--sz` | No | 5 | Depth levels per side (1–400) |

Returns: top asks (ascending) and bids (descending) with price and size. Display shows top 5 per side regardless of `--sz`.

```bash
okx market orderbook BTC-USDT-SWAP --sz 20
# Asks: 95100.0 / 2.5 · 95050.0 / 1.2 ...
# Bids: 95000.0 / 3.1 · 94950.0 / 0.8 ...
```

---

## trades — Recent Public Trades

```bash
okx market trades <instId> [--limit <n>] [--json]
```

| Param | Required | Default |
|---|---|---|
| `instId` | Yes | - |
| `--limit` | No | 100 |

Returns: `tradeId` · `px` · `sz` · `side` (`buy`/`sell`) · `ts`

```bash
okx market trades BTC-USDT --limit 20
```

---

## candles — OHLCV Candlestick Data

```bash
okx market candles <instId> [--bar <bar>] [--limit <n>] [--after <ts>] [--before <ts>] [--json]
```

| Param | Required | Default | Description |
|---|---|---|---|
| `instId` | Yes | - | Instrument ID |
| `--bar` | No | `1m` | Time granularity (see values below) |
| `--limit` | No | 100 | Number of candles |
| `--after` | No | - | Return candles **before** this timestamp (ms) — paginate backward in time |
| `--before` | No | - | Return candles **after** this timestamp (ms) — paginate forward in time |

`--bar` values: `1m` `3m` `5m` `15m` `30m` `1H` `2H` `4H` `6H` `12H` `1D` `1W` `1M`

> Use uppercase for hour/day/week/month — `1H` not `1h`.

The command automatically routes to the historical endpoint when `--after` is older than ~2 days, supporting data back to 2021.

> **OKX API pagination direction**: `--after <ts>` returns candles with timestamp **earlier** than `ts` (go further back in time). `--before <ts>` returns candles with timestamp **later** than `ts` (go toward the present).

Returns columns: `time` · `open` · `high` · `low` · `close` · `vol` (base currency). Sorted newest-first.

```bash
okx market candles BTC-USDT --bar 4H --limit 30
okx market candles ETH-USDT-SWAP --bar 1H --limit 100
okx market candles BTC-USDT --bar 1D --after 1672531200000   # candles before 2023-01-01
```

---

## index-candles — Index OHLCV

```bash
okx market index-candles <instId> [--bar <bar>] [--limit <n>] [--history] [--json]
```

Same params as `candles`. Use index instrument IDs: `BTC-USD` (not `BTC-USDT`).

`--history`: return historical candles beyond the default 1440-candle window.

Returns: same columns as `candles`.

```bash
okx market index-candles BTC-USD --bar 1Dutc --limit 50
okx market index-candles BTC-USD --bar 1Wutc --history --limit 200
```

> **Demo market data**: All commands above support `--demo` (CLI) or `demo: true` (MCP) to query OKX's simulated trading market data. Default is live data.


path: references/derivatives-commands.md
content: # Derivatives & Contract Data Commands

These commands apply to SWAP, FUTURES, and/or OPTION instruments. Not applicable to SPOT unless noted.

---

## funding-rate — Funding Rate

```bash
okx market funding-rate <instId> [--history] [--limit <n>] [--json]
```

| Param | Required | Default | Description |
|---|---|---|---|
| `instId` | Yes | - | Perpetual swap instrument ID, **must end with `-SWAP`** (e.g., `BTC-USDT-SWAP`). Spot IDs like `BTC-USDT` will be rejected. |
| `--history` | No | false | Return historical funding rates |
| `--limit` | No | 100 | Number of historical records (only with `--history`) |

**Current rate** (no `--history`):
Returns: `fundingRate` · `nextFundingRate` · `fundingTime` · `nextFundingTime`

**Historical** (`--history`):
Returns table: `fundingRate` · `realizedRate` · `fundingTime`

```bash
okx market funding-rate BTC-USDT-SWAP
okx market funding-rate BTC-USDT-SWAP --history --limit 10
```

> **IMPORTANT**: `instId` must end with `-SWAP` (e.g., `BTC-USDT-SWAP`). Spot IDs like `BTC-USDT` are **NOT** valid and will be rejected. Funding rate applies only to perpetual swap instruments.

---

## mark-price — Mark Price

```bash
okx market mark-price --instType <type> [--instId <id>] [--json]
```

| Param | Required | Values |
|---|---|---|
| `--instType` | Yes | `SWAP` `FUTURES` `OPTION` |
| `--instId` | No | Filter to a single instrument |

Returns: `instId` · `instType` · `markPx` · `ts`

Used for liquidation price calculation and contract fair-value reference.

```bash
okx market mark-price --instType SWAP --instId BTC-USDT-SWAP
okx market mark-price --instType FUTURES
```

---

## price-limit — Upper / Lower Price Limits

```bash
okx market price-limit <instId> [--json]
```

Returns: `buyLmt` (max buy price) · `sellLmt` (min sell price)

Applies to SWAP and FUTURES only. Used to check whether a limit order price is within allowed range.

```bash
okx market price-limit BTC-USDT-SWAP
```

---

## open-interest — Open Interest

```bash
okx market open-interest --instType <type> [--instId <id>] [--json]
```

| Param | Required | Values |
|---|---|---|
| `--instType` | Yes | `SWAP` `FUTURES` `OPTION` |
| `--instId` | No | Filter to a single instrument |

Returns: `instId` · `oi` (contracts) · `oiCcy` (base currency amount) · `ts`

```bash
okx market open-interest --instType SWAP --instId BTC-USDT-SWAP
okx market open-interest --instType SWAP
```

> For OPTION: use `--instId BTC-USD` (underlying, not a specific strike/expiry) to list all active option series OI.

---

## index-ticker — Index Price

```bash
okx market index-ticker [--instId <id>] [--quoteCcy <ccy>] [--json]
```

| Param | Required | Default | Description |
|---|---|---|---|
| `--instId` | Cond. | - | Index ID (e.g., `BTC-USD`). Either this or `--quoteCcy` required. |
| `--quoteCcy` | Cond. | - | Filter all indices by quote currency (e.g., `USD`, `USDT`) |

Returns: `instId` · `idxPx` · `high24h` · `low24h`

> Use `BTC-USD` format for index IDs (not `BTC-USDT`).

```bash
okx market index-ticker --instId BTC-USD
okx market index-ticker --quoteCcy USD
```

## Pair Spread

`okx market pair-spread` — spread statistics between two instruments.

| Param | Required | Default | Description |
|---|---|---|---|
| `<instIdA>` | Yes | - | First instrument (positional), e.g. `BTC-USDT-SWAP` |
| `<instIdB>` | Yes | - | Second instrument (positional); must differ from instIdA |
| `--bar` | No | `15m` | Bar size: `5m` or `15m` (1m not supported) |
| `--window` | No | `1W` | Lookback window. Format `<n><unit>`, units m/H/D/W (case-sensitive), max 1W |
| `--backtest-time` | No | - | Anchor timestamp (ms epoch) for backtest mode; omits realtime block |

Returns: `mode` · `realtime` (lastPriceA/B, spreadAbs, spreadRatio) · `statistics` (absolute + ratio: mean/stdDev/median/min/max) · `meta` (requestedBars, alignedBars, droppedBars, truncated)

```bash
# Live spread between two perpetuals, default bar=15m, window=1W
okx market pair-spread BTC-USDT-SWAP ETH-USDT-SWAP

# Tight window for fast mean-reversion setups
okx market pair-spread BTC-USDT-SWAP BTC-USDT --bar 5m --window 4H

# Backtest anchor (ms epoch). When set, realtime block is omitted.
okx market pair-spread BTC-USDT-SWAP ETH-USDT-SWAP --bar 15m --window 1D --backtest-time 1715000000000 --json
```

> Constraints: bar must be 5m or 15m; window ≤ 1W (units case-sensitive: m/H/D/W); requires ≥80% bar coverage (otherwise returns error 41020).

> **Demo market data**: All commands above support `--demo` (CLI) or `demo: true` (MCP) to query OKX's simulated trading market data. Default is live data.


path: references/instrument-commands.md
content: # Instrument Discovery Commands

## instruments — List Tradeable Instruments

```bash
okx market instruments --instType <type> [--instId <id>] [--json]
```

| Param | Required | Default | Description |
|---|---|---|---|
| `--instType` | Yes | - | `SPOT` `SWAP` `FUTURES` `OPTION` |
| `--instId` | No | - | Filter to a single instrument |
| `--uly` | Cond. | - | Required for `OPTION` (e.g., `--uly BTC-USD`) |

Returns: `instId` · `ctVal` · `lotSz` · `minSz` · `tickSz` · `state`. Displays up to 50 rows.

```bash
okx market instruments --instType SPOT
okx market instruments --instType SWAP --instId BTC-USDT-SWAP --json
okx market instruments --instType OPTION --uly BTC-USD
```

> **OPTION instruments cannot be listed without `--uly`**. If the underlying is unknown, use `open-interest --instType OPTION` first to discover active instIds, then query instruments with the known underlying.

---

## stock-tokens — List All Stock Token Perpetuals *(Deprecated)*

> **Deprecated**: use `okx market instruments-by-category --instCategory 3` instead. This command is kept for backward compatibility and will be removed in a future major version.

```bash
okx market stock-tokens [--json]
```

Returns: `instId` · `ctVal` · `lotSz` · `minSz` · `tickSz` · `state` for all active stock token SWAP instruments (`instCategory=3`).

Examples: `TSLA-USDT-SWAP`, `NVDA-USDT-SWAP`, `AAPL-USDT-SWAP`, `MSFT-USDT-SWAP`

```bash
okx market stock-tokens
```

> **Fallback** (if command not yet available):
> ```bash
> okx market instruments --instType SWAP --json | jq '[.[] | select(.instCategory == "3")]'
> ```
> Requires `jq` installed.

---

## instruments-by-category — Discover Metals, Commodities, Forex, and Bond Instruments

OKX supports non-crypto asset categories distinguished by the `instCategory` field:

| instCategory | Asset Class | Examples |
|---|---|---|
| `3` | Stock tokens | Apple (AAPL-USDT-SWAP), Tesla (TSLA-USDT-SWAP), Nvidia (NVDA-USDT-SWAP) |
| `4` | Metals | Gold (XAUUSDT-USDT-SWAP), Silver (XAGUSDT-USDT-SWAP) |
| `5` | Commodities | Crude Oil (OIL-USDT-SWAP), Natural Gas (GAS-USDT-SWAP) |
| `6` | Forex | EUR/USD (EURUSDT-USDT-SWAP), GBP/USD (GBPUSDT-USDT-SWAP) |
| `7` | Bonds | US 30Y Treasury (US30Y-USDT-SWAP) |

```bash
okx market instruments-by-category --instCategory <3|4|5|6|7> [--instType <SPOT|SWAP>] [--instId <id>] [--json]
```

| Param | Required | Default | Description |
|---|---|---|---|
| `--instCategory` | Yes | - | `3`=Stock tokens `4`=Metals `5`=Commodities `6`=Forex `7`=Bonds |
| `--instType` | No | SWAP | `SPOT` or `SWAP` |
| `--instId` | No | - | Filter to a specific instrument |

Returns: `instId` · `instCategory` · `ctVal` · `lotSz` · `minSz` · `tickSz` · `state`.

```bash
# Discover stock token perpetuals (replaces the deprecated stock-tokens command)
okx market instruments-by-category --instCategory 3

# Discover all gold/silver instruments
okx market instruments-by-category --instCategory 4

# Discover all forex perpetuals
okx market instruments-by-category --instCategory 6

# Discover commodities
okx market instruments-by-category --instCategory 5

# Inspect a specific bond instrument
okx market instruments-by-category --instCategory 7 --instId US30Y-USDT-SWAP --json
```

> **Fallback** (if command not yet available):
> ```bash
> okx market instruments --instType SWAP --json | jq '[.[] | select(.instCategory == "3")]'
> ```
> Replace `"3"` with `"4"`, `"5"`, `"6"`, or `"7"` as needed. Requires `jq` installed.

> **Discovery workflow**: always run `instruments-by-category` first to get valid instIds, then use `ticker` / `orderbook` / `candles` to get price data.

### Trading Hours Notes

- **Forex** (category 6): follows FX market hours (Mon 00:00 – Fri 22:00 UTC, closed weekends)
- **Metals** (category 4): generally trades with FX hours; verify with `ticker` before placing orders
- **Commodities** (category 5): session-based hours; check `state=live` in instruments list
- **Bonds** (category 7): US bond instruments follow US market hours

Always run `okx market ticker <instId>` to confirm a live last price before placing any order on these instruments.

---

## Notes

- `ctVal` — contract value (e.g., 0.01 BTC per contract for BTC-USDT-SWAP). Required for sz ↔ coin quantity conversion.
- `lotSz` — order size increment. sz must be a multiple of lotSz.
- `minSz` — minimum order size.
- `tickSz` — minimum price increment.
- `state` — `live` means currently tradeable.

### Stock Token Trading Hours

Stock tokens follow underlying exchange hours:
- US stocks (TSLA, NVDA, AAPL, etc.): Mon–Fri ~09:30–16:00 ET
- Orders outside trading hours may be queued or rejected

Always run `okx market ticker <instId>` to confirm a live last price before placing any stock token order.

> **Demo market data**: All commands above support `--demo` (CLI) or `demo: true` (MCP) to query OKX's simulated trading market data. Default is live data.


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)