OKX DEX Market Price API Skill
Overview
This skill generates production-ready code for fetching token prices from the OKX DEX Market Price API v6. The API returns the latest price for one or more tokens on a given chain. It is a batch endpoint: you send a list of (chainIndex, tokenContractAddress) and receive a list of price results.
Key capabilities:
- Authenticated POST API requests with HMAC-SHA256 signing (prehash includes request body)
- Batch support: 1–100 tokens per request
- Multi-chain support (Ethereum, BSC, Polygon, Arbitrum, Base, Solana, etc.)
- Response includes
time (price timestamp in ms) and price (string for precision)
Prerequisites
Required Credentials
OKX_ACCESS_KEY — API key
OKX_SECRET_KEY — Secret key for HMAC signing
OKX_PASSPHRASE — Account passphrase
Environment
- Python:
requests, hmac, hashlib, base64, datetime, json (stdlib except requests)
- Node.js:
axios or node-fetch, built-in crypto
- No blockchain dependencies (read-only HTTP API)
API Endpoint
POST https://web3.okx.com/api/v6/dex/market/price
Workflow
Step 1: Validate User Input
Request body — Must be a JSON array of 1–100 objects. Each object:
chainIndex (String, required): Supported chain ID, e.g. "1" = Ethereum, "56" = BSC.
tokenContractAddress (String, required): Token contract address.
- EVM: 42-character hex, all lowercase (e.g.
0x382bb369d343125bfb2117af9c149795c6c65c50).
- Native token (ETH, BNB, etc.): use
0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee.
- Solana: base58 address.
Batch size — Between 1 and 100 (inclusive). Empty array or >100 items will result in API error.
Step 2: Construct Authentication Headers (POST)
OKX API requires HMAC-SHA256 signed requests. For POST, the body is part of the prehash.
Headers:
Content-Type: application/json
OK-ACCESS-KEY: <api_key>
OK-ACCESS-SIGN: <hmac_signature>
OK-ACCESS-PASSPHRASE: <passphrase>
OK-ACCESS-TIMESTAMP: <iso8601_timestamp>
Signing algorithm (POST):
timestamp = ISO 8601 UTC (e.g. "2025-01-15T12:00:00.000Z")
request_path = "/api/v6/dex/market/price" // no query string for this endpoint
body = exact JSON string that will be sent (e.g. '[{"chainIndex":"1","tokenContractAddress":"0x..."}]'
prehash = timestamp + "POST" + request_path + body
signature = Base64(HMAC-SHA256(secret_key, prehash))
CRITICAL for POST:
- The body must be the exact JSON string (same as sent). No extra spaces; use canonical JSON (e.g. no extra whitespace).
- Method is uppercase
"POST".
- Request path is without query string (this endpoint has no query params).
Step 3: Send Request and Parse Response
Request body example:
[
{ "chainIndex": "1", "tokenContractAddress": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" },
{ "chainIndex": "56", "tokenContractAddress": "0x382bb369d343125bfb2117af9c149795c6c65c50" }
]
Success response structure:
{
"code": "0",
"data": [
{
"chainIndex": "1",
"tokenContractAddress": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
"time": "1716892020000",
"price": "1.00012345"
}
],
"msg": ""
}
Fields:
code: "0" = success; non-zero = error (see msg).
data: Array of price objects, one per requested token (order may match request).
chainIndex, tokenContractAddress: Echo of request.
time: Price timestamp in Unix milliseconds (string).
price: Latest token price (string to preserve precision).
Step 4: Format Output for User
- Convert
price (string) to number only when needed for display/math to avoid precision loss.
- Use
time for “price as of” display (e.g. convert ms to local time).
- If
code !== "0", surface msg and do not treat as success.
Best Practices
Security
- Never hardcode API credentials; use environment variables or secure config.
- Never log secret key or raw signature.
- Validate
tokenContractAddress format (EVM hex length/case, Solana base58) before sending.
POST body and signing
- Use identical JSON string for both signing and request body (no re-pretty-print between sign and send).
- In Python:
json.dumps(payload, separators=(',', ':')) for deterministic output.
- In JavaScript:
JSON.stringify(payload) — ensure no trailing spaces.
Error handling
- Check
response["code"] == "0" before using data.
- Empty or invalid
tokenParamList (e.g. empty list or >100 items) returns param error.
- HTTP 401 = auth failure (check prehash: timestamp + "POST" + path + body).
- HTTP 429 = rate limit; implement backoff.
Rate limits
- Respect OKX rate limits; cache prices when polling frequently.
Examples
Example 1: Python — Batch get token prices
import os
import json
import hmac
import hashlib
import base64
import requests
from datetime import datetime, timezone
API_KEY = os.environ["OKX_ACCESS_KEY"]
SECRET_KEY = os.environ["OKX_SECRET_KEY"]
PASSPHRASE = os.environ["OKX_PASSPHRASE"]
BASE_URL = "https://web3.okx.com"
PRICE_PATH = "/api/v6/dex/market/price"
def get_prices(token_param_list):
# 1–100 items
if not token_param_list or len(token_param_list) > 100:
raise ValueError("token_param_list must have 1–100 items")
body = json.dumps(token_param_list, separators=(',', ':'))
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
prehash = timestamp + "POST" + PRICE_PATH + body
signature = base64.b64encode(
hmac.new(SECRET_KEY.encode(), prehash.encode(), hashlib.sha256).digest()
).decode()
headers = {
"Content-Type": "application/json",
"OK-ACCESS-KEY": API_KEY,
"OK-ACCESS-SIGN": signature,
"OK-ACCESS-PASSPHRASE": PASSPHRASE,
"OK-ACCESS-TIMESTAMP": timestamp,
}
resp = requests.post(BASE_URL + PRICE_PATH, headers=headers, data=body, timeout=30)
resp.raise_for_status()
data = resp.json()
if data.get("code") != "0":
raise Exception(f"OKX API error: {data.get('msg', 'Unknown')}")
return data.get("data", [])
# One token on Ethereum (USDC)
payload = [{"chainIndex": "1", "tokenContractAddress": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"}]
prices = get_prices(payload)
for p in prices:
print(f"{p['tokenContractAddress']} @ {p['time']}: {p['price']}")
Example 2: Node.js — POST with body in prehash
const crypto = require("crypto");
const https = require("https");
const API_KEY = process.env.OKX_ACCESS_KEY;
const SECRET_KEY = process.env.OKX_SECRET_KEY;
const PASSPHRASE = process.env.OKX_PASSPHRASE;
const BASE = "https://web3.okx.com";
const PATH = "/api/v6/dex/market/price";
function getPrices(tokenParamList) {
const body = JSON.stringify(tokenParamList);
const timestamp = new Date().toISOString();
const prehash = timestamp + "POST" + PATH + body;
const signature = crypto.createHmac("sha256", SECRET_KEY).update(prehash).digest("base64");
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"OK-ACCESS-KEY": API_KEY,
"OK-ACCESS-SIGN": signature,
"OK-ACCESS-PASSPHRASE": PASSPHRASE,
"OK-ACCESS-TIMESTAMP": timestamp,
},
};
return new Promise((resolve, reject) => {
const req = https.request(BASE + PATH, options, (res) => {
let data = "";
res.on("data", (chunk) => (data += chunk));
res.on("end", () => {
const json = JSON.parse(data);
if (json.code !== "0") reject(new Error(json.msg || "API error"));
else resolve(json.data || []);
});
});
req.on("error", reject);
req.write(body);
req.end();
});
}
Troubleshooting
| Problem |
Cause |
Solution |
| 401 Unauthorized |
Signature mismatch |
Ensure prehash = timestamp + "POST" + path + exact body; same body for sign and request. |
| tokenParamList param error |
Empty or >100 items |
Send array with 1–100 elements. |
| Invalid token address |
Wrong format or chain |
EVM: 42-char hex lowercase; use native token placeholder for ETH/BNB. |
| code non-zero |
API / param error |
Read msg; check chain support and address validity. |
| Missing price for a token |
Token not supported or no liquidity |
API may omit or fail for that pair; check supported chains/tokens. |
Reference: Common Chain IDs
| Chain |
chainIndex |
| Ethereum |
1 |
| BSC |
56 |
| Polygon |
137 |
| Arbitrum |
42161 |
| Optimism |
10 |
| Base |
8453 |
| Solana |
501 |
| Unichain |
130 |
Reference: Request/Response Summary
| Item |
Description |
| Method |
POST |
| URL |
https://web3.okx.com/api/v6/dex/market/price |
| Body |
JSON array of { "chainIndex": string, "tokenContractAddress": string }, length 1–100 |
| Success code |
"0" |
| data[] |
chainIndex, tokenContractAddress, time (ms string), price (string) |
1---
2name: okx-dex-market-price
3description: >
4 Fetch token prices from OKX DEX Market Price API (v6). Use this skill when a user wants to:
5 1. Get the latest price of one or more tokens on supported EVM/Solana chains
6 2. Batch query token prices (up to 100 tokens per request) for portfolios or UIs
7 3. Build applications that need real-time DEX market price data
8 Core value: Correct authenticated POST requests with JSON body, HMAC-SHA256 signing
9 including body in prehash, and proper handling of batch request/response.
10version: 1.0.0
11allowed_tools: [bash_tool, create_file, str_replace, view]
12required_context: [api_key, secret_key, passphrase]
13license: MIT
14author: Claude Assistant
15tags: [defi, dex, okx, market, price, web3, token, evm, solana, batch]
16metadata:
17 source: https://skillmd.com/skills/modbender/okx-dex-market-price
18---
19
20# OKX DEX Market Price API Skill
21
22## Overview
23
24This skill generates production-ready code for fetching **token prices** from the **OKX DEX Market Price API v6**. The API returns the latest price for one or more tokens on a given chain. It is a **batch endpoint**: you send a list of `(chainIndex, tokenContractAddress)` and receive a list of price results.
25
26**Key capabilities:**
27- Authenticated **POST** API requests with HMAC-SHA256 signing (prehash includes request body)
28- **Batch support**: 1–100 tokens per request
29- Multi-chain support (Ethereum, BSC, Polygon, Arbitrum, Base, Solana, etc.)
30- Response includes `time` (price timestamp in ms) and `price` (string for precision)
31
32## Prerequisites
33
34### Required Credentials
35- `OKX_ACCESS_KEY` — API key
36- `OKX_SECRET_KEY` — Secret key for HMAC signing
37- `OKX_PASSPHRASE` — Account passphrase
38
39### Environment
40- **Python**: `requests`, `hmac`, `hashlib`, `base64`, `datetime`, `json` (stdlib except `requests`)
41- **Node.js**: `axios` or `node-fetch`, built-in `crypto`
42- No blockchain dependencies (read-only HTTP API)
43
44### API Endpoint
45```
46POST https://web3.okx.com/api/v6/dex/market/price
47```
48
49## Workflow
50
51### Step 1: Validate User Input
52
531. **Request body** — Must be a **JSON array** of 1–100 objects. Each object:
54 - `chainIndex` (String, required): Supported chain ID, e.g. `"1"` = Ethereum, `"56"` = BSC.
55 - `tokenContractAddress` (String, required): Token contract address.
56 - **EVM**: 42-character hex, **all lowercase** (e.g. `0x382bb369d343125bfb2117af9c149795c6c65c50`).
57 - **Native token** (ETH, BNB, etc.): use `0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee`.
58 - Solana: base58 address.
59
602. **Batch size** — Between 1 and 100 (inclusive). Empty array or >100 items will result in API error.
61
62### Step 2: Construct Authentication Headers (POST)
63
64OKX API requires HMAC-SHA256 signed requests. For **POST**, the **body is part of the prehash**.
65
66**Headers:**
67```
68Content-Type: application/json
69OK-ACCESS-KEY: <api_key>
70OK-ACCESS-SIGN: <hmac_signature>
71OK-ACCESS-PASSPHRASE: <passphrase>
72OK-ACCESS-TIMESTAMP: <iso8601_timestamp>
73```
74
75**Signing algorithm (POST):**
76```
77timestamp = ISO 8601 UTC (e.g. "2025-01-15T12:00:00.000Z")
78request_path = "/api/v6/dex/market/price" // no query string for this endpoint
79body = exact JSON string that will be sent (e.g. '[{"chainIndex":"1","tokenContractAddress":"0x..."}]'
80prehash = timestamp + "POST" + request_path + body
81signature = Base64(HMAC-SHA256(secret_key, prehash))
82```
83
84**CRITICAL for POST:**
85- The **body** must be the **exact** JSON string (same as sent). No extra spaces; use canonical JSON (e.g. no extra whitespace).
86- Method is uppercase `"POST"`.
87- Request path is **without** query string (this endpoint has no query params).
88
89### Step 3: Send Request and Parse Response
90
91**Request body example:**
92```json
93[
94 { "chainIndex": "1", "tokenContractAddress": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" },
95 { "chainIndex": "56", "tokenContractAddress": "0x382bb369d343125bfb2117af9c149795c6c65c50" }
96]
97```
98
99**Success response structure:**
100```json
101{
102 "code": "0",
103 "data": [
104 {
105 "chainIndex": "1",
106 "tokenContractAddress": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
107 "time": "1716892020000",
108 "price": "1.00012345"
109 }
110 ],
111 "msg": ""
112}
113```
114
115**Fields:**
116- `code`: `"0"` = success; non-zero = error (see `msg`).
117- `data`: Array of price objects, one per requested token (order may match request).
118- `chainIndex`, `tokenContractAddress`: Echo of request.
119- `time`: Price timestamp in **Unix milliseconds** (string).
120- `price`: Latest token price (string to preserve precision).
121
122### Step 4: Format Output for User
123
124- Convert `price` (string) to number only when needed for display/math to avoid precision loss.
125- Use `time` for “price as of” display (e.g. convert ms to local time).
126- If `code !== "0"`, surface `msg` and do not treat as success.
127
128## Best Practices
129
130### Security
131- **Never hardcode** API credentials; use environment variables or secure config.
132- **Never log** secret key or raw signature.
133- Validate `tokenContractAddress` format (EVM hex length/case, Solana base58) before sending.
134
135### POST body and signing
136- Use **identical** JSON string for both signing and request body (no re-pretty-print between sign and send).
137- In Python: `json.dumps(payload, separators=(',', ':'))` for deterministic output.
138- In JavaScript: `JSON.stringify(payload)` — ensure no trailing spaces.
139
140### Error handling
141- Check `response["code"] == "0"` before using `data`.
142- Empty or invalid `tokenParamList` (e.g. empty list or >100 items) returns param error.
143- HTTP 401 = auth failure (check prehash: timestamp + "POST" + path + body).
144- HTTP 429 = rate limit; implement backoff.
145
146### Rate limits
147- Respect OKX rate limits; cache prices when polling frequently.
148
149## Examples
150
151### Example 1: Python — Batch get token prices
152
153```python
154import os
155import json
156import hmac
157import hashlib
158import base64
159import requests
160from datetime import datetime, timezone
161
162API_KEY = os.environ["OKX_ACCESS_KEY"]
163SECRET_KEY = os.environ["OKX_SECRET_KEY"]
164PASSPHRASE = os.environ["OKX_PASSPHRASE"]
165BASE_URL = "https://web3.okx.com"
166PRICE_PATH = "/api/v6/dex/market/price"
167
168def get_prices(token_param_list):
169 # 1–100 items
170 if not token_param_list or len(token_param_list) > 100:
171 raise ValueError("token_param_list must have 1–100 items")
172
173 body = json.dumps(token_param_list, separators=(',', ':'))
174 timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
175 prehash = timestamp + "POST" + PRICE_PATH + body
176 signature = base64.b64encode(
177 hmac.new(SECRET_KEY.encode(), prehash.encode(), hashlib.sha256).digest()
178 ).decode()
179
180 headers = {
181 "Content-Type": "application/json",
182 "OK-ACCESS-KEY": API_KEY,
183 "OK-ACCESS-SIGN": signature,
184 "OK-ACCESS-PASSPHRASE": PASSPHRASE,
185 "OK-ACCESS-TIMESTAMP": timestamp,
186 }
187 resp = requests.post(BASE_URL + PRICE_PATH, headers=headers, data=body, timeout=30)
188 resp.raise_for_status()
189 data = resp.json()
190
191 if data.get("code") != "0":
192 raise Exception(f"OKX API error: {data.get('msg', 'Unknown')}")
193 return data.get("data", [])
194
195# One token on Ethereum (USDC)
196payload = [{"chainIndex": "1", "tokenContractAddress": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"}]
197prices = get_prices(payload)
198for p in prices:
199 print(f"{p['tokenContractAddress']} @ {p['time']}: {p['price']}")
200```
201
202### Example 2: Node.js — POST with body in prehash
203
204```javascript
205const crypto = require("crypto");
206const https = require("https");
207
208const API_KEY = process.env.OKX_ACCESS_KEY;
209const SECRET_KEY = process.env.OKX_SECRET_KEY;
210const PASSPHRASE = process.env.OKX_PASSPHRASE;
211const BASE = "https://web3.okx.com";
212const PATH = "/api/v6/dex/market/price";
213
214function getPrices(tokenParamList) {
215 const body = JSON.stringify(tokenParamList);
216 const timestamp = new Date().toISOString();
217 const prehash = timestamp + "POST" + PATH + body;
218 const signature = crypto.createHmac("sha256", SECRET_KEY).update(prehash).digest("base64");
219
220 const options = {
221 method: "POST",
222 headers: {
223 "Content-Type": "application/json",
224 "OK-ACCESS-KEY": API_KEY,
225 "OK-ACCESS-SIGN": signature,
226 "OK-ACCESS-PASSPHRASE": PASSPHRASE,
227 "OK-ACCESS-TIMESTAMP": timestamp,
228 },
229 };
230
231 return new Promise((resolve, reject) => {
232 const req = https.request(BASE + PATH, options, (res) => {
233 let data = "";
234 res.on("data", (chunk) => (data += chunk));
235 res.on("end", () => {
236 const json = JSON.parse(data);
237 if (json.code !== "0") reject(new Error(json.msg || "API error"));
238 else resolve(json.data || []);
239 });
240 });
241 req.on("error", reject);
242 req.write(body);
243 req.end();
244 });
245}
246```
247
248## Troubleshooting
249
250| Problem | Cause | Solution |
251|--------|-------|----------|
252| 401 Unauthorized | Signature mismatch | Ensure prehash = timestamp + "POST" + path + **exact body**; same body for sign and request. |
253| tokenParamList param error | Empty or >100 items | Send array with 1–100 elements. |
254| Invalid token address | Wrong format or chain | EVM: 42-char hex lowercase; use native token placeholder for ETH/BNB. |
255| code non-zero | API / param error | Read `msg`; check chain support and address validity. |
256| Missing price for a token | Token not supported or no liquidity | API may omit or fail for that pair; check supported chains/tokens. |
257
258## Reference: Common Chain IDs
259
260| Chain | chainIndex |
261|----------|------------|
262| Ethereum | 1 |
263| BSC | 56 |
264| Polygon | 137 |
265| Arbitrum | 42161 |
266| Optimism | 10 |
267| Base | 8453 |
268| Solana | 501 |
269| Unichain | 130 |
270
271## Reference: Request/Response Summary
272
273| Item | Description |
274|------|-------------|
275| Method | POST |
276| URL | `https://web3.okx.com/api/v6/dex/market/price` |
277| Body | JSON array of `{ "chainIndex": string, "tokenContractAddress": string }`, length 1–100 |
278| Success code | `"0"` |
279| data[] | `chainIndex`, `tokenContractAddress`, `time` (ms string), `price` (string) |