references/derivatives-commands.md
# 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.
references/indicator-commands.md
# Technical Indicator Command Reference
## Discover Supported Indicators
```bash
okx market indicator list # print all supported indicator names and descriptions
okx market indicator list --json # machine-readable format
```
Use this before calling `market_get_indicator` (MCP) or `okx market indicator` (CLI) to confirm a name is supported. The API returns empty data silently for unknown indicator names.
---
## Command Syntax
```bash
okx market indicator <indicator> <instId> [--bar <bar>] [--params <n1,n2,...>] [--list] [--limit <n>] [--backtest-time <ms>] [--json]
```
> Argument order: `<indicator>` comes **before** `<instId>` — e.g., `okx market indicator rsi BTC-USDT`, not the reverse.
| Param | Required | Default | Description |
|---|---|---|---|
| `indicator` | Yes | - | Indicator name (case-insensitive). Run `okx market indicator list` to see all. |
| `instId` | Yes | - | Instrument ID (e.g., `BTC-USDT`, `ETH-USDT-SWAP`) |
| `--bar` | No | `1H` | Timeframe. See supported values below. |
| `--params` | No | indicator default | Comma-separated numeric params, no spaces — e.g., `--params 14` or `--params 5,20` |
| `--list` | No | false | Return historical series instead of latest value only |
| `--limit` | No | 10 | Number of records when `--list` is set (max 100) |
| `--backtest-time` | No | - | Unix timestamp in ms; omit for real-time. Used for backtesting point-in-time values. |
### `--bar` Supported Values
`3m` `5m` `15m` `1H` `4H` `12Hutc` `1Dutc` `3Dutc` `1Wutc`
> These differ from candle `--bar` values: daily is `1Dutc` not `1D`, weekly is `1Wutc` not `1W`.
---
## Supported Indicators
Run `okx market indicator list` for the authoritative full list. Common indicators by category:
| Category | Indicator name | Default `--params` | Notes |
|---|---|---|---|
| **Moving Average** | `ma` | `5,20,60` | Simple moving averages; one or more periods |
| **Moving Average** | `ema` | `5,20` | Exponential moving averages |
| **Moving Average** | `wma` | — | Weighted Moving Average |
| **Moving Average** | `dema` | — | Double Exponential Moving Average |
| **Moving Average** | `tema` | — | Triple Exponential Moving Average |
| **Moving Average** | `zlema` | — | Zero-Lag Exponential Moving Average |
| **Moving Average** | `hma` | — | Hull Moving Average |
| **Moving Average** | `kama` | — | Kaufman Adaptive Moving Average |
| **Trend** | `macd` | `12,26,9` | fast, slow, signal |
| **Trend** | `sar` | — | Parabolic SAR |
| **Trend** | `adx` | — | Average Directional Index |
| **Trend** | `aroon` | — | Aroon Indicator |
| **Trend** | `cci` | — | Commodity Channel Index |
| **Trend** | `dpo` | — | Detrended Price Oscillator |
| **Trend** | `supertrend` | `10,3` | period, multiplier |
| **Trend** | `alphatrend` | — | No params needed |
| **Trend** | `halftrend` | — | No params needed |
| **Trend** | `envelope` | `20,0.1` | period, deviation |
| **Trend** | `pmax` | — | No params needed |
| **Momentum** | `rsi` | `14` | Period (default 14) |
| **Momentum** | `stoch-rsi` | `14` | Stochastic RSI |
| **Momentum** | `stoch` | — | Stochastic Oscillator |
| **Momentum** | `kdj` | `9,3,3` | K, D, J periods |
| **Momentum** | `roc` | — | Rate of Change |
| **Momentum** | `mom` | — | Momentum |
| **Momentum** | `ppo` | — | Price Percentage Oscillator |
| **Momentum** | `trix` | — | TRIX |
| **Momentum** | `ao` | — | Awesome Oscillator |
| **Momentum** | `uo` | — | Ultimate Oscillator |
| **Momentum** | `wr` | — | Williams %R |
| **Momentum** | `tdi` | — | Traders Dynamic Index |
| **Momentum** | `qqe` | — | QQE Mod |
| **Volatility** | `bb` (or `boll`) | `20,2` | period, stddev multiplier — Bollinger Bands |
| **Volatility** | `bbwidth` | — | Bollinger Band Width |
| **Volatility** | `bbpct` | — | Bollinger Band %B |
| **Volatility** | `atr` | — | Average True Range |
| **Volatility** | `keltner` | — | Keltner Channel |
| **Volatility** | `donchian` | — | Donchian Channel |
| **Volatility** | `hv` | — | Historical Volatility |
| **Volatility** | `stddev` | — | Standard Deviation |
| **Volatility** | `range-filter` | — | Range Filter |
| **Volatility** | `waddah` | — | Waddah Attar Explosion |
| **Volume** | `obv` | — | On-Balance Volume |
| **Volume** | `vwap` | — | Volume Weighted Average Price |
| **Volume** | `mvwap` | — | Moving VWAP |
| **Volume** | `cmf` | — | Chaikin Money Flow |
| **Volume** | `mfi` | — | Money Flow Index |
| **Volume** | `ad` | — | Accumulation/Distribution |
| **Statistical** | `lr` | — | Linear Regression |
| **Statistical** | `slope` | — | Linear Regression Slope |
| **Statistical** | `angle` | — | Linear Regression Angle |
| **Statistical** | `variance` | — | Variance |
| **Statistical** | `meandev` | — | Mean Deviation |
| **Statistical** | `sigma` | — | Sigma |
| **Statistical** | `stderr` | — | Standard Error |
| **Custom** | `kdj` | `9,3,3` | KDJ Stochastic Oscillator |
| **Custom** | `supertrend` | `10,3` | Supertrend |
| **Ichimoku** | `tenkan` | — | Tenkan-sen (Conversion Line) |
| **Ichimoku** | `kijun` | — | Kijun-sen (Base Line) |
| **Ichimoku** | `senkoa` | — | Senkou Span A (Leading Span A) |
| **Ichimoku** | `senkob` | — | Senkou Span B (Leading Span B) |
| **Ichimoku** | `chikou` | — | Chikou Span (Lagging Span) |
| **Candlestick** | `doji` | — | Doji pattern |
| **Candlestick** | `bull-engulf` | — | Bullish Engulfing |
| **Candlestick** | `bear-engulf` | — | Bearish Engulfing |
| **Candlestick** | `bull-harami` | — | Bullish Harami |
| **Candlestick** | `bear-harami` | — | Bearish Harami |
| **Candlestick** | `bull-harami-cross` | — | Bullish Harami Cross |
| **Candlestick** | `bear-harami-cross` | — | Bearish Harami Cross |
| **Candlestick** | `three-soldiers` | — | Three White Soldiers |
| **Candlestick** | `three-crows` | — | Three Black Crows |
| **Candlestick** | `hanging-man` | — | Hanging Man |
| **Candlestick** | `inverted-hammer` | — | Inverted Hammer |
| **Candlestick** | `shooting-star` | — | Shooting Star |
| **BTC On-Chain** | `ahr999` | — | **BTC-USDT only.** <0.45 accumulate · 0.45–1.2 DCA · >1.2 bubble warning |
| **BTC On-Chain** | `rainbow` | — | **BTC-USDT only.** BTC Rainbow Chart valuation band |
| **Other** | `fisher` | — | Fisher Transform |
| **Other** | `nvi-pvi` | — | Negative/Positive Volume Index (returns both) |
| **Other** | `cho` | — | Chande Momentum Oscillator |
| **Other** | `tr` | — | True Range |
| **Other** | `tp` | — | Typical Price |
| **Other** | `mp` | — | Median Price |
| **Other** | `top-long-short` | — | Top Trader Long/Short Ratio (timeframe-independent) |
> `boll` is accepted as an alias for `bb`.
> BTC On-Chain indicators only work with `BTC-USDT`; applying to other assets returns no data.
---
## Return Fields
All indicators return `ts` (Unix ms timestamp) plus indicator-specific fields:
| Indicator | Return fields |
|---|---|
| `ma` | `ma5`, `ma20`, `ma60` (based on `--params`) |
| `ema` | `ema5`, `ema20` (based on `--params`) |
| `rsi` | `rsi` |
| `macd` | `dif`, `dea`, `macd` (histogram) |
| `kdj` | `k`, `d`, `j` |
| `bb` / `boll` | `upper`, `middle`, `lower` |
| `supertrend` | `supertrend`, `direction` (`buy`/`sell`) |
| `ahr999` | `ahr999` |
| `rainbow` | `band` (valuation zone label) |
---
## Examples
```bash
# Discover all supported indicator names first
okx market indicator list
# Latest RSI on 4H
okx market indicator rsi BTC-USDT --bar 4H --params 14
# EMA 5 and EMA 20 trend check on 1H
okx market indicator ema BTC-USDT --bar 1H --params 5,20
# ts: 3/20/2026, 10:00 AM | ema5: 87420.5 | ema20: 86910.2
# MACD on daily
okx market indicator macd BTC-USDT --bar 1Dutc
# Bollinger Bands on 1H
okx market indicator bb ETH-USDT --bar 1H
# upper: 2050 | middle: 2000 | lower: 1950
# SuperTrend direction signal
okx market indicator supertrend BTC-USDT --bar 4H
# supertrend: 84200 | direction: buy
# Historical RSI series (last 20 values)
okx market indicator rsi ETH-USDT --bar 1H --params 14 --list --limit 20
# → table: ts, rsi (20 rows, newest first)
# BTC on-chain cycle check
okx market indicator ahr999 BTC-USDT
# ahr999: 0.87 (DCA zone: 0.45–1.2)
okx market indicator rainbow BTC-USDT
# band: "HODL"
# Backtesting point-in-time value
okx market indicator rsi BTC-USDT --bar 4H --params 14 --backtest-time 1711008000000
```
---
## BTC On-Chain Interpretation Guide
| Indicator | Zone / Value | Interpretation |
|---|---|---|
| `ahr999` | < 0.45 | Accumulate zone |
| `ahr999` | 0.45 – 1.2 | DCA zone |
| `ahr999` | > 1.2 | Bubble warning |
| `rainbow` | band label | See OKX Rainbow Chart legend for zone |
references/instrument-commands.md
# Instrument Discovery Commands
## instruments — List Tradeable Instruments
```bash
okx market instruments --instType <type> [--instId <id>] [--uly <uly>] [--instFamily <fam>] [--seriesId <id>] [--json]
```
| Param | Required | Default | Description |
|---|---|---|---|
| `--instType` | Yes | - | `SPOT` `SWAP` `FUTURES` `OPTION` `EVENTS` |
| `--instId` | No | - | Filter to a single instrument |
| `--uly` | Cond. | - | Required for `OPTION` (e.g., `--uly BTC-USD`) |
| `--instFamily` | Cond. | - | Alternative to `--uly` for `OPTION` (e.g., `--instFamily BTC-USD`) |
| `--seriesId` | Cond. | - | Required for `EVENTS` (e.g., `--seriesId BTC-ABOVE-DAILY`) |
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
okx market instruments --instType OPTION --instFamily BTC-USD
okx market instruments --instType EVENTS --seriesId BTC-ABOVE-DAILY
```
> **OPTION instruments cannot be listed without `--uly` or `--instFamily`**. If the underlying is unknown, use `open-interest --instType OPTION` first to discover active instIds, then query instruments with the known underlying.
> **EVENTS instruments cannot be listed without `--seriesId`**. Use `okx event series` to discover valid series IDs (e.g. `BTC-ABOVE-DAILY`, `ETH-ABOVE-DAILY`).
---
## 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.
references/price-data-commands.md
# 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.
references/workflows.md
# 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.
SKILL.md
---
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). Do NOT use when the user wants to TRADE a directional view as an event contract — that is okx-cex-trade. Merely ASKING which way an asset's price is moving is a market-data question and belongs here."
license: MIT
metadata:
author: okx
version: "1.4.6"
homepage: "https://www.okx.com"
agent:
requires:
bins: ["okx"]
install:
- id: npm
kind: node
package: "@okx_ai/okx-trade-cli@1.4.6"
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`
- **Trading a directional view as an event contract** → `okx-cex-trade`
- Market sentiment / most bullish-bearish coins → `okx-sentiment-tracker`
- 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>] [--uly <uly>] [--instFamily <fam>] [--seriesId <id>]` | List instruments (instId, ctVal, lotSz, minSz, tickSz, state); OPTION requires `--uly` or `--instFamily`; EVENTS requires `--seriesId` |
| 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). Prints `Total: N` + a ranked table of matching instruments (`No results` only when nothing matches). Add `--json` for the raw OKX API v5 response (structurally unchanged). |
| 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. For period-based indicators (ema/ma/wma/rsi/macd/bb/…) the CLI applies a sensible default period when `--params` is omitted (e.g. EMA/RSI → `14`, MACD → `12,26,9`, BB → `20,2`) so values render without you specifying params; explicit `--params` always wins. If no values come back, the CLI prints a visible hint (`try --params …`) — never silent. |
| 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` |
**Event contracts are not served by this skill.**
| User asks | Do |
|---|---|
| Which way an asset is moving — "is BTC going up", "what's the 15m trend" | **Answer here** with candles / indicators |
| Direction *and* whether they can trade it | Answer the data half here, then name `okx-cex-trade` for the trade half |
| To trade an event contract — "buy YES/NO on …" | **Route to `okx-cex-trade`**, serve nothing here |
Never substitute another product for an event contract — not a perp, not a futures position,
not market data presented as the contract they asked for. If you cannot load
`okx-cex-trade`, say so and stop.
### 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` or `--instFamily BTC-USD`; if unknown, run `open-interest --instType OPTION` first to discover active instIds
- **EVENTS listing**: `instruments --instType EVENTS` requires `--seriesId` (e.g. `--seriesId BTC-ABOVE-DAILY`); run `okx event series` first to discover valid series IDs
- **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`. For period-based indicators (ema/ma/wma/rsi/macd/bb/…) omitting `--params` makes the CLI substitute a default period (EMA/MA/WMA/RSI → `14`, MACD → `12,26,9`, BB → `20,2`) so the table is populated instead of empty; pass `--params` explicitly to override the default. (CLI-only convenience — the MCP `market_get_indicator` raw-data path still requires an explicit `paramList`.)
- **indicator no values returned**: the CLI never prints nothing — if a query yields no values (e.g. a non-period indicator, or a period indicator with no default), it prints a visible hint: `No indicator values returned. This indicator may require a period — try --params (e.g. --params 14).`
- **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