
Okx Market
- 2 installs
- 29.6k repo stars
- Updated August 4, 2026
- hkuds/vibe-trading
Query OKX V5 public REST API for spot, swap, futures, and options market data like prices, candlesticks, funding rates, and open interest.
About
Provides an interface to the OKX V5 public REST API for retrieving crypto spot, derivatives, and index market data via Python. A developer uses it to pull real-time prices, candlesticks, funding rates, and open interest without authentication.
- Public market-data endpoints, no API key or account required
- Covers spot, perpetual swaps, futures, options, and index data
Okx Market by the numbers
- 2 all-time installs (skills.sh)
- Ranked #870 of 1,106 Finance & Trading skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/hkuds/vibe-trading --skill okx-marketAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2 |
|---|---|
| repo stars | ★ 29.6k |
| Last updated | August 4, 2026 |
| Repository | hkuds/vibe-trading ↗ |
What it does
Query OKX V5 public REST API for spot, swap, futures, and options market data like prices, candlesticks, funding rates, and open interest.
Files
OKX Market
Overview
The OKX V5 REST API provides comprehensive cryptocurrency market data covering spot, perpetual swaps, delivery futures, options, and more. All market-data endpoints are public and can be called directly without authentication. The data comes from OKX, the world's second-largest cryptocurrency exchange.
Quick Start
- Install a Python runtime (Python 3.9+ recommended) and the required
requestsdependency.
pip install requests pandas- No account registration or token configuration is required. Market-data endpoints are fully open.
- Review the endpoint documentation below and locate the interface you need.
- Use Python code to retrieve data according to the documentation. Example for the spot ticker endpoint:
import requests
import pandas as pd
BASE_URL = "https://www.okx.com/api/v5"
# Get the latest BTC-USDT market quote
resp = requests.get(f"{BASE_URL}/market/ticker", params={"instId": "BTC-USDT"})
data = resp.json()["data"][0]
print(f"BTC last price: {data['last']} 24h change: {float(data['last'])/float(data['open24h'])*100-100:.2f}%")Parameter Format Reference
- Instrument format (`instId`):
- Spot:
BTC-USDT,ETH-USDT - Perpetual swap:
BTC-USDT-SWAP,ETH-USDT-SWAP - Delivery futures:
BTC-USDT-250328(expiry date inYYMMDD) - Options:
BTC-USD-250328-95000-C(expiry-strike-C/P) - Index:
BTC-USD,ETH-USD - Candlestick interval (`bar`):
1m,3m,5m,15m,30m,1H,2H,4H,6H,12H,1D,1W,1M - Instrument type (`instType`):
SPOT(spot),SWAP(perpetual),FUTURES(delivery),OPTION(option) - Timestamp: millisecond Unix timestamp (for example
1773763200000) - Response format: JSON.
code=0indicates success, and data is returned in thedatafield
Python Script Examples
- Market data retrieval example
- Candlestick data retrieval example
Market Data Endpoint List
| ID | Endpoint Path | Title (Detailed Documentation) | Category | Description |
|---|---|---|---|---|
| 1 | /market/ticker | Single Ticker | Spot Market | Retrieve the latest market data for a single trading instrument, including last price, bid/ask, 24h volume, and more |
| 2 | /market/tickers | Batch Tickers | Spot Market | Retrieve all market data for a given instrument class (SPOT/SWAP/FUTURES/OPTION) in batch |
| 3 | /market/candles | Candlestick Data | Spot Market | Retrieve candlestick (OHLCV) data with multiple supported intervals |
| 4 | /market/trades | Recent Trades | Spot Market | Retrieve recent trade-level details |
| 5 | /public/instruments | Instrument List | Spot Market | Retrieve metadata for all tradable instruments, including minimum order size and price precision |
| 6 | /market/books | Order Book Depth | Spot Market | Retrieve bid/ask order book depth data |
| 7 | /public/funding-rate | Funding Rate | Derivatives Market | Retrieve current and historical funding rates for perpetual contracts |
| 8 | /public/funding-rate-history | Historical Funding Rate | Derivatives Market | Retrieve historical funding-rate data for perpetual contracts |
| 9 | /public/mark-price | Mark Price | Derivatives Market | Retrieve mark prices for derivatives, used for PnL and liquidation calculations |
| 10 | /public/open-interest | Open Interest | Derivatives Market | Retrieve open-interest data for derivatives |
| 11 | /public/price-limit | Price Limit | Derivatives Market | Retrieve the current maximum and minimum price limits for derivatives |
| 12 | /market/index-tickers | Index Tickers | Index Market | Retrieve index price market data |
| 13 | /market/index-candles | Index Candles | Index Market | Retrieve index candlestick data |
历史资金费率
----
接口:GET /api/v5/public/funding-rate-history 描述:获取永续合约的历史资金费率数据,用于分析费率趋势和套利机会。 限频:10次/2s
输入参数
| 名称 | 类型 | 必选 | 描述 |
|---|---|---|---|
| instId | str | Y | 永续合约ID,如 BTC-USDT-SWAP |
| after | str | N | 请求此时间戳之前的数据(毫秒) |
| before | str | N | 请求此时间戳之后的数据(毫秒) |
| limit | str | N | 返回条数,默认 100 |
输出参数
| 名称 | 类型 | 描述 |
|---|---|---|
| instId | str | 合约ID |
| instType | str | 产品类型 |
| fundingRate | str | 资金费率 |
| realizedRate | str | 实际收取费率 |
| fundingTime | str | 结算时间(毫秒) |
接口示例
import requests
import pandas as pd
BASE_URL = "https://www.okx.com/api/v5"
# 获取 BTC 永续历史资金费率
resp = requests.get(f"{BASE_URL}/public/funding-rate-history", params={
"instId": "BTC-USDT-SWAP",
"limit": "100"
})
rates = resp.json()["data"]
df = pd.DataFrame(rates)
df["fundingRate"] = df["fundingRate"].astype(float)
df["fundingTime"] = pd.to_datetime(df["fundingTime"].astype(int), unit="ms")
print(f"平均费率: {df['fundingRate'].mean():.6f}")
print(f"最大费率: {df['fundingRate'].max():.6f}")
print(f"最小费率: {df['fundingRate'].min():.6f}")
print(df[["fundingTime", "fundingRate"]].head(10))持仓量(Open Interest)
----
接口:GET /api/v5/public/open-interest 描述:获取合约持仓量数据,反映市场中未平仓合约的总量。持仓量变化是判断市场趋势的重要指标。 限频:20次/2s
输入参数
| 名称 | 类型 | 必选 | 描述 |
|---|---|---|---|
| instType | str | Y | 产品类型:SWAP、FUTURES、OPTION |
| instId | str | N | 产品ID(可选过滤) |
输出参数
| 名称 | 类型 | 描述 |
|---|---|---|
| instType | str | 产品类型 |
| instId | str | 产品ID |
| oi | str | 持仓量(合约张数) |
| oiCcy | str | 持仓量(币) |
| ts | str | 时间戳(毫秒) |
接口示例
import requests
import pandas as pd
BASE_URL = "https://www.okx.com/api/v5"
# 获取所有永续合约持仓量
resp = requests.get(f"{BASE_URL}/public/open-interest", params={"instType": "SWAP"})
oi_data = resp.json()["data"]
df = pd.DataFrame(oi_data)
df["oiCcy"] = df["oiCcy"].astype(float)
df = df.sort_values("oiCcy", ascending=False)
print(df[["instId", "oi", "oiCcy"]].head(10))标记价格
----
接口:GET /api/v5/public/mark-price 描述:获取合约的标记价格。标记价格用于计算未实现盈亏和强制平仓,比最新成交价更稳定。 限频:20次/2s
输入参数
| 名称 | 类型 | 必选 | 描述 |
|---|---|---|---|
| instType | str | Y | 产品类型:SWAP、FUTURES、OPTION |
| instId | str | N | 产品ID(可选过滤) |
输出参数
| 名称 | 类型 | 描述 |
|---|---|---|
| instType | str | 产品类型 |
| instId | str | 产品ID |
| markPx | str | 标记价格 |
| ts | str | 时间戳(毫秒) |
接口示例
import requests
BASE_URL = "https://www.okx.com/api/v5"
# 获取 BTC 永续标记价格
resp = requests.get(f"{BASE_URL}/public/mark-price", params={
"instType": "SWAP",
"instId": "BTC-USDT-SWAP"
})
data = resp.json()["data"][0]
print(f"BTC 永续标记价格: {data['markPx']}")
# 获取所有永续合约标记价格
resp = requests.get(f"{BASE_URL}/public/mark-price", params={"instType": "SWAP"})
all_marks = resp.json()["data"]
print(f"合约数量: {len(all_marks)}")资金费率
----
接口:GET /api/v5/public/funding-rate 描述:获取永续合约的当前资金费率及下次结算时间。资金费率是永续合约的核心机制,反映多空力量对比。 限频:20次/2s
输入参数
| 名称 | 类型 | 必选 | 描述 |
|---|---|---|---|
| instId | str | Y | 永续合约ID,如 BTC-USDT-SWAP |
输出参数
| 名称 | 类型 | 描述 |
|---|---|---|
| instId | str | 合约ID |
| instType | str | 产品类型(SWAP) |
| fundingRate | str | 当前资金费率 |
| fundingTime | str | 下次结算时间(毫秒) |
| nextFundingRate | str | 预测下期资金费率(可能为空) |
| nextFundingTime | str | 下下次结算时间(毫秒) |
| settFundingRate | str | 上次已结算资金费率 |
| settState | str | 结算状态:settled(已结算)/ processing(结算中) |
| prevFundingTime | str | 上次结算时间(毫秒) |
| maxFundingRate | str | 最大资金费率 |
| minFundingRate | str | 最小资金费率 |
| ts | str | 数据时间戳(毫秒) |
接口示例
import requests
from datetime import datetime
BASE_URL = "https://www.okx.com/api/v5"
# 获取 BTC 永续资金费率
resp = requests.get(f"{BASE_URL}/public/funding-rate", params={"instId": "BTC-USDT-SWAP"})
data = resp.json()["data"][0]
rate = float(data["fundingRate"])
next_time = datetime.fromtimestamp(int(data["fundingTime"]) / 1000)
print(f"当前资金费率: {rate:.6f} ({rate*100:.4f}%)")
print(f"下次结算时间: {next_time}")
print(f"年化费率: {rate * 3 * 365 * 100:.2f}%") # 每8小时结算一次合约限价
----
接口:GET /api/v5/public/price-limit 描述:获取合约的当前最高和最低限价。超出限价范围的订单会被拒绝。 限频:20次/2s
输入参数
| 名称 | 类型 | 必选 | 描述 |
|---|---|---|---|
| instId | str | Y | 合约ID,如 BTC-USDT-SWAP |
输出参数
| 名称 | 类型 | 描述 |
|---|---|---|
| instType | str | 产品类型 |
| instId | str | 产品ID |
| buyLmt | str | 买入限价(最高可买价) |
| sellLmt | str | 卖出限价(最低可卖价) |
| ts | str | 时间戳(毫秒) |
接口示例
import requests
BASE_URL = "https://www.okx.com/api/v5"
resp = requests.get(f"{BASE_URL}/public/price-limit", params={"instId": "BTC-USDT-SWAP"})
data = resp.json()["data"][0]
print(f"买入上限: {data['buyLmt']}")
print(f"卖出下限: {data['sellLmt']}")指数K线
----
接口:GET /api/v5/market/index-candles 描述:获取指数的K线数据,用于分析基准价格走势。 限频:20次/2s
输入参数
| 名称 | 类型 | 必选 | 描述 |
|---|---|---|---|
| instId | str | Y | 指数ID,如 BTC-USD |
| bar | str | N | K线周期,默认 1m。可选:1m/3m/5m/15m/30m/1H/2H/4H/6H/12H/1D/1W/1M |
| after | str | N | 请求此时间戳之前的数据(毫秒) |
| before | str | N | 请求此时间戳之后的数据(毫秒) |
| limit | str | N | 返回条数,默认 100,最大 100 |
输出参数
返回二维数组,每条数据:
| 索引 | 描述 |
|---|---|
| 0 | 开盘时间(毫秒时间戳) |
| 1 | 开盘价 |
| 2 | 最高价 |
| 3 | 最低价 |
| 4 | 收盘价 |
| 5 | K线状态:0=未完结,1=已完结 |
接口示例
import requests
import pandas as pd
BASE_URL = "https://www.okx.com/api/v5"
# 获取 BTC 指数日K
resp = requests.get(f"{BASE_URL}/market/index-candles", params={
"instId": "BTC-USD",
"bar": "1D",
"limit": "30"
})
candles = resp.json()["data"]
columns = ["ts", "open", "high", "low", "close", "confirm"]
df = pd.DataFrame(candles, columns=columns)
df["ts"] = pd.to_datetime(df["ts"].astype(int), unit="ms")
for col in ["open", "high", "low", "close"]:
df[col] = df[col].astype(float)
print(df[["ts", "open", "high", "low", "close"]].head())指数行情
----
接口:GET /api/v5/market/index-tickers 描述:获取指数价格行情。指数价格由多家交易所现货价格加权计算,用于衍生品定价基准。 限频:20次/2s
输入参数
| 名称 | 类型 | 必选 | 描述 |
|---|---|---|---|
| instId | str | N | 指数ID,如 BTC-USD、ETH-USD(与 quoteCcy 二选一) |
| quoteCcy | str | N | 计价货币,如 USD(获取所有 USD 指数) |
输出参数
| 名称 | 类型 | 描述 |
|---|---|---|
| instId | str | 指数ID |
| idxPx | str | 最新指数价格 |
| high24h | str | 24小时最高 |
| low24h | str | 24小时最低 |
| open24h | str | 24小时开盘价 |
| sodUtc0 | str | UTC 0点开盘价 |
| sodUtc8 | str | UTC+8 0点开盘价 |
| ts | str | 时间戳(毫秒) |
接口示例
import requests
BASE_URL = "https://www.okx.com/api/v5"
# 获取 BTC 指数价格
resp = requests.get(f"{BASE_URL}/market/index-tickers", params={"instId": "BTC-USD"})
data = resp.json()["data"][0]
print(f"BTC 指数价格: {data['idxPx']}")
# 获取所有 USD 指数
resp = requests.get(f"{BASE_URL}/market/index-tickers", params={"quoteCcy": "USD"})
indexes = resp.json()["data"]
for idx in indexes[:10]:
print(f" {idx['instId']:15s} {idx['idxPx']:>10s}")K线数据(OHLCV)
----
接口:GET /api/v5/market/candles 描述:获取K线数据,支持从1分钟到1月多种周期。最多返回1440条历史数据。可通过 after/before 参数翻页获取更早数据。 限频:40次/2s
输入参数
| 名称 | 类型 | 必选 | 描述 |
|---|---|---|---|
| instId | str | Y | 交易产品ID,如 BTC-USDT |
| bar | str | N | K线周期,默认 1m。可选:1m/3m/5m/15m/30m/1H/2H/4H/6H/12H/1D/1W/1M |
| after | str | N | 请求此时间戳之前的数据(毫秒),用于翻页 |
| before | str | N | 请求此时间戳之后的数据(毫秒) |
| limit | str | N | 返回条数,默认 100,最大 300 |
输出参数
返回二维数组,每条数据按以下顺序排列:
| 索引 | 描述 |
|---|---|
| 0 | 开盘时间(毫秒时间戳) |
| 1 | 开盘价(Open) |
| 2 | 最高价(High) |
| 3 | 最低价(Low) |
| 4 | 收盘价(Close) |
| 5 | 成交量(币) |
| 6 | 成交额(计价货币) |
| 7 | 成交额(报价货币) |
| 8 | K线状态:0=未完结,1=已完结 |
接口示例
import requests
import pandas as pd
BASE_URL = "https://www.okx.com/api/v5"
# 获取 BTC-USDT 日线,最近30根
resp = requests.get(f"{BASE_URL}/market/candles", params={
"instId": "BTC-USDT",
"bar": "1D",
"limit": "30"
})
candles = resp.json()["data"]
# 转为 DataFrame
columns = ["ts", "open", "high", "low", "close", "vol", "volCcy", "volCcyQuote", "confirm"]
df = pd.DataFrame(candles, columns=columns)
df["ts"] = pd.to_datetime(df["ts"].astype(int), unit="ms")
for col in ["open", "high", "low", "close", "vol"]:
df[col] = df[col].astype(float)
print(df[["ts", "open", "high", "low", "close", "vol"]].head())
# 获取 ETH-USDT 4小时K线
resp = requests.get(f"{BASE_URL}/market/candles", params={
"instId": "ETH-USDT",
"bar": "4H",
"limit": "50"
})数据样例
{
"code": "0",
"data": [
["1773763200000", "73915.5", "74800", "71966", "72144.3", "5129.27", "377618988.24", "377618988.24", "0"],
["1773676800000", "73269.1", "76011.8", "73158", "73917.4", "8631.72", "642101158.54", "642101158.54", "1"],
["1773590400000", "71478.1", "74500", "71300", "73269.1", "8461.09", "620450708.74", "620450708.74", "1"]
]
}交易产品列表
----
接口:GET /api/v5/public/instruments 描述:获取所有可交易产品的基础信息,包括交易对名称、最小下单量、价格精度、合约面值等。 限频:20次/2s
输入参数
| 名称 | 类型 | 必选 | 描述 |
|---|---|---|---|
| instType | str | Y | 产品类型:SPOT、SWAP、FUTURES、OPTION |
| instId | str | N | 产品ID,如 BTC-USDT(可选过滤) |
输出参数
| 名称 | 类型 | 描述 |
|---|---|---|
| instType | str | 产品类型 |
| instId | str | 产品ID |
| baseCcy | str | 基础货币(如 BTC) |
| quoteCcy | str | 计价货币(如 USDT) |
| tickSz | str | 最小价格变动(价格精度) |
| lotSz | str | 最小交易数量(下单精度) |
| minSz | str | 最小下单量 |
| ctVal | str | 合约面值(仅合约) |
| lever | str | 最大杠杆(仅合约) |
| listTime | str | 上市时间 |
| state | str | 状态:live(交易中)/ suspend(暂停) |
接口示例
import requests
import pandas as pd
BASE_URL = "https://www.okx.com/api/v5"
# 获取所有现货交易对
resp = requests.get(f"{BASE_URL}/public/instruments", params={"instType": "SPOT"})
instruments = resp.json()["data"]
print(f"现货交易对数量: {len(instruments)}")
# 筛选 USDT 交易对
usdt_pairs = [i for i in instruments if i["quoteCcy"] == "USDT"]
df = pd.DataFrame(usdt_pairs)[["instId", "baseCcy", "minSz", "tickSz", "lotSz"]]
print(df.head(10))
# 获取所有永续合约
resp = requests.get(f"{BASE_URL}/public/instruments", params={"instType": "SWAP"})
swaps = resp.json()["data"]
print(f"永续合约数量: {len(swaps)}")最近成交
----
接口:GET /api/v5/market/trades 描述:获取产品最近的成交明细数据。 限频:20次/2s
输入参数
| 名称 | 类型 | 必选 | 描述 |
|---|---|---|---|
| instId | str | Y | 交易产品ID,如 BTC-USDT |
| limit | str | N | 返回条数,默认 100,最大 500 |
输出参数
| 名称 | 类型 | 描述 |
|---|---|---|
| instId | str | 交易产品ID |
| tradeId | str | 成交ID |
| px | str | 成交价格 |
| sz | str | 成交数量 |
| side | str | 成交方向:buy(买入)/ sell(卖出) |
| ts | str | 成交时间(毫秒) |
接口示例
import requests
BASE_URL = "https://www.okx.com/api/v5"
# 获取 BTC-USDT 最近成交
resp = requests.get(f"{BASE_URL}/market/trades", params={"instId": "BTC-USDT", "limit": "10"})
trades = resp.json()["data"]
for t in trades:
print(f"{t['side']:4s} {t['px']:>10s} {t['sz']:>12s}")单个产品行情
----
接口:GET /api/v5/market/ticker 描述:获取单个交易产品的最新行情快照,包括最新成交价、买一卖一价、24小时成交量等核心数据。 限频:20次/2s
输入参数
| 名称 | 类型 | 必选 | 描述 |
|---|---|---|---|
| instId | str | Y | 交易产品ID,如 BTC-USDT、BTC-USDT-SWAP |
输出参数
| 名称 | 类型 | 描述 |
|---|---|---|
| instType | str | 产品类型(SPOT/SWAP/FUTURES/OPTION) |
| instId | str | 交易产品ID |
| last | str | 最新成交价 |
| lastSz | str | 最新成交量 |
| askPx | str | 卖一价 |
| askSz | str | 卖一量 |
| bidPx | str | 买一价 |
| bidSz | str | 买一量 |
| open24h | str | 24小时开盘价 |
| high24h | str | 24小时最高价 |
| low24h | str | 24小时最低价 |
| vol24h | str | 24小时成交量(币) |
| volCcy24h | str | 24小时成交额(计价货币) |
| sodUtc0 | str | UTC 0点开盘价 |
| sodUtc8 | str | UTC+8 0点开盘价 |
| ts | str | 数据时间戳(毫秒) |
接口示例
import requests
BASE_URL = "https://www.okx.com/api/v5"
# 获取 BTC-USDT 现货行情
resp = requests.get(f"{BASE_URL}/market/ticker", params={"instId": "BTC-USDT"})
data = resp.json()["data"][0]
print(f"最新价: {data['last']}, 24h量: {data['vol24h']}")
# 获取 ETH-USDT 永续合约行情
resp = requests.get(f"{BASE_URL}/market/ticker", params={"instId": "ETH-USDT-SWAP"})
data = resp.json()["data"][0]
print(f"ETH永续最新价: {data['last']}")数据样例
{
"code": "0",
"data": [{
"instType": "SPOT",
"instId": "BTC-USDT",
"last": "72159",
"lastSz": "0.00005196",
"askPx": "72157.1",
"askSz": "1.44548635",
"bidPx": "72157",
"bidSz": "0.1012",
"open24h": "73554.5",
"high24h": "74883",
"low24h": "71966",
"volCcy24h": "443213018.596221053",
"vol24h": "6013.17760207",
"ts": "1773842459809",
"sodUtc0": "73904.3",
"sodUtc8": "73915.5"
}]
}批量产品行情
----
接口:GET /api/v5/market/tickers 描述:批量获取某个产品类型下所有产品的行情数据。例如获取所有现货交易对的行情。 限频:20次/2s
输入参数
| 名称 | 类型 | 必选 | 描述 |
|---|---|---|---|
| instType | str | Y | 产品类型:SPOT(现货)、SWAP(永续)、FUTURES(交割)、OPTION(期权) |
输出参数
与单个行情接口相同,返回数组包含该类型下所有产品行情。
接口示例
import requests
import pandas as pd
BASE_URL = "https://www.okx.com/api/v5"
# 获取所有现货行情
resp = requests.get(f"{BASE_URL}/market/tickers", params={"instType": "SPOT"})
tickers = resp.json()["data"]
# 转为 DataFrame,按24h成交额排序
df = pd.DataFrame(tickers)
df["volCcy24h"] = df["volCcy24h"].astype(float)
df = df.sort_values("volCcy24h", ascending=False)
print(df[["instId", "last", "volCcy24h"]].head(10))
# 获取所有永续合约行情
resp = requests.get(f"{BASE_URL}/market/tickers", params={"instType": "SWAP"})
swaps = resp.json()["data"]
print(f"永续合约数量: {len(swaps)}")数据样例
返回结构与单个行情相同,data 为数组形式,包含该类型下全部产品。
深度数据(Orderbook)
----
接口:GET /api/v5/market/books 描述:获取交易产品的买卖盘口深度数据,可指定返回深度档位数。 限频:40次/2s
输入参数
| 名称 | 类型 | 必选 | 描述 |
|---|---|---|---|
| instId | str | Y | 交易产品ID,如 BTC-USDT |
| sz | str | N | 深度档位数,默认 1,最大 400 |
输出参数
| 名称 | 类型 | 描述 |
|---|---|---|
| asks | list | 卖盘数组,每档 [价格, 数量, 已废弃, 订单数] |
| bids | list | 买盘数组,每档 [价格, 数量, 已废弃, 订单数] |
| ts | str | 时间戳(毫秒) |
接口示例
import requests
BASE_URL = "https://www.okx.com/api/v5"
# 获取 BTC-USDT 前5档深度
resp = requests.get(f"{BASE_URL}/market/books", params={"instId": "BTC-USDT", "sz": "5"})
book = resp.json()["data"][0]
print("== 卖盘(Asks)==")
for ask in book["asks"]:
print(f" 价格: {ask[0]:>10s} 数量: {ask[1]:>12s}")
print("== 买盘(Bids)==")
for bid in book["bids"]:
print(f" 价格: {bid[0]:>10s} 数量: {bid[1]:>12s}")#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""加密货币K线数据获取示例脚本。"""
from typing import Optional
import requests
import pandas as pd
from datetime import datetime
BASE_URL = "https://www.okx.com/api/v5"
CANDLE_COLUMNS = ["ts", "open", "high", "low", "close", "vol", "volCcy", "volCcyQuote", "confirm"]
INDEX_CANDLE_COLUMNS = ["ts", "open", "high", "low", "close", "confirm"]
def get_candles(inst_id: str, bar: str = "1D", limit: int = 100) -> Optional[pd.DataFrame]:
"""获取K线数据并转为 DataFrame。
Args:
inst_id: 交易产品ID,如 BTC-USDT。
bar: K线周期,如 1m/5m/1H/4H/1D/1W。
limit: 返回条数,最大300。
Returns:
DataFrame (ts, open, high, low, close, vol),失败返回 None。
"""
try:
resp = requests.get(f"{BASE_URL}/market/candles", params={
"instId": inst_id, "bar": bar, "limit": str(limit)
})
data = resp.json()
if data["code"] != "0":
print(f"API错误: {data['msg']}")
return None
df = pd.DataFrame(data["data"], columns=CANDLE_COLUMNS)
df["ts"] = pd.to_datetime(df["ts"].astype("int64"), unit="ms")
for col in ["open", "high", "low", "close", "vol"]:
df[col] = df[col].astype(float)
df = df.sort_values("ts").reset_index(drop=True)
return df
except Exception as e:
print(f"获取K线失败: {e}")
return None
def get_index_candles(inst_id: str, bar: str = "1D", limit: int = 100) -> Optional[pd.DataFrame]:
"""获取指数K线数据。
Args:
inst_id: 指数ID,如 BTC-USD。
bar: K线周期。
limit: 返回条数,最大100。
Returns:
DataFrame (ts, open, high, low, close),失败返回 None。
"""
try:
resp = requests.get(f"{BASE_URL}/market/index-candles", params={
"instId": inst_id, "bar": bar, "limit": str(limit)
})
data = resp.json()
if data["code"] != "0":
print(f"API错误: {data['msg']}")
return None
df = pd.DataFrame(data["data"], columns=INDEX_CANDLE_COLUMNS)
df["ts"] = pd.to_datetime(df["ts"].astype("int64"), unit="ms")
for col in ["open", "high", "low", "close"]:
df[col] = df[col].astype(float)
df = df.sort_values("ts").reset_index(drop=True)
return df
except Exception as e:
print(f"获取指数K线失败: {e}")
return None
def main():
"""主函数。"""
print("===== OKX K线数据获取示例 =====\n")
# BTC 日线
print("--- BTC-USDT 日线 (最近10天) ---")
df = get_candles("BTC-USDT", "1D", 10)
if df is not None:
print(df[["ts", "open", "high", "low", "close", "vol"]].to_string(index=False))
# ETH 4小时线
print("\n--- ETH-USDT 4H线 (最近10根) ---")
df = get_candles("ETH-USDT", "4H", 10)
if df is not None:
print(df[["ts", "open", "high", "low", "close", "vol"]].to_string(index=False))
# BTC 指数日K
print("\n--- BTC-USD 指数日线 (最近10天) ---")
df = get_index_candles("BTC-USD", "1D", 10)
if df is not None:
print(df[["ts", "open", "high", "low", "close"]].to_string(index=False))
if __name__ == "__main__":
main()
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""加密货币行情数据获取示例脚本。"""
from typing import Optional
import requests
import pandas as pd
from datetime import datetime
BASE_URL = "https://www.okx.com/api/v5"
def get_ticker(inst_id: str) -> Optional[dict]:
"""获取单个产品的实时行情。
Args:
inst_id: 交易产品ID,如 BTC-USDT。
Returns:
行情数据字典,失败返回 None。
"""
try:
resp = requests.get(f"{BASE_URL}/market/ticker", params={"instId": inst_id})
data = resp.json()
if data["code"] != "0":
print(f"API错误: {data['msg']}")
return None
ticker = data["data"][0]
last = float(ticker["last"])
open24h = float(ticker["open24h"])
chg = (last / open24h - 1) * 100
print(f"{inst_id} 最新价: {last} 24h涨跌: {chg:+.2f}% 24h量: {ticker['vol24h']}")
return ticker
except Exception as e:
print(f"获取行情失败: {e}")
return None
def get_top_tickers(inst_type: str = "SPOT", top_n: int = 10) -> Optional[pd.DataFrame]:
"""获取成交额排名前N的交易对。
Args:
inst_type: 产品类型,SPOT/SWAP/FUTURES/OPTION。
top_n: 返回前N名。
Returns:
DataFrame,失败返回 None。
"""
try:
resp = requests.get(f"{BASE_URL}/market/tickers", params={"instType": inst_type})
tickers = resp.json()["data"]
df = pd.DataFrame(tickers)
df["volCcy24h"] = df["volCcy24h"].astype(float)
df["last"] = df["last"].astype(float)
df = df.sort_values("volCcy24h", ascending=False).head(top_n)
print(f"\n{inst_type} 成交额 TOP {top_n}:")
print(df[["instId", "last", "volCcy24h"]].to_string(index=False))
return df
except Exception as e:
print(f"获取批量行情失败: {e}")
return None
def get_funding_rates(symbols: Optional[list] = None) -> Optional[pd.DataFrame]:
"""获取永续合约资金费率。
Args:
symbols: 合约ID列表,如 ['BTC-USDT-SWAP']。默认获取主流币种。
Returns:
DataFrame,失败返回 None。
"""
if symbols is None:
symbols = ["BTC-USDT-SWAP", "ETH-USDT-SWAP", "SOL-USDT-SWAP", "DOGE-USDT-SWAP"]
rows = []
for sym in symbols:
try:
resp = requests.get(f"{BASE_URL}/public/funding-rate", params={"instId": sym})
data = resp.json()["data"][0]
rate = float(data["fundingRate"])
annual = rate * 3 * 365 * 100
rows.append({"instId": sym, "fundingRate": rate, "annualized": f"{annual:.2f}%"})
except Exception as e:
print(f"获取 {sym} 资金费率失败: {e}")
if rows:
df = pd.DataFrame(rows)
print("\n永续合约资金费率:")
print(df.to_string(index=False))
return df
return None
def main():
"""主函数。"""
print("===== OKX 加密货币行情获取示例 =====\n")
# 获取主流币种行情
for symbol in ["BTC-USDT", "ETH-USDT", "SOL-USDT"]:
get_ticker(symbol)
# 获取现货成交额 TOP 10
get_top_tickers("SPOT", 10)
# 获取资金费率
get_funding_rates()
if __name__ == "__main__":
main()