黄金、原油期货数据API对接文档
本文档提供StockTV期货市场数据API的完整对接指南,包含全球主要期货交易所的实时行情、历史数据、合约信息等核心功能一、接口概览
1.1 支持期货交易所
交易所代码交易所名称主要期货品种CME芝加哥商品交易所股指、利率、农产品NYMEX纽约商品交易所能源、金属COMEX纽约金属交易所贵金属ICE洲际交易所能源、农产品LME伦敦金属交易所工业金属TOCOM东京商品交易所能源、贵金属SGX新加坡交易所铁矿石、外汇SHFE上海期货交易所金属、能源、化工DCE大连商品交易所农产品、化工CZCE郑州商品交易所农产品1.2 数据特性
[*]实时行情:毫秒级延迟
[*]历史数据:支持最长10年历史K线
[*]合约信息:完整合约规格、到期日等
[*]多维度数据:主力合约、连续合约、跨期价差
[*]数据格式:统一JSON格式
[*]货币单位:多种货币支持(USD、CNY等)
二、接入准备
2.1 获取API Key
联系官方获取密钥:https://t.me/CryptoRzz
2.2 请求基础URL
https://api.stocktv.top2.3 请求头设置
X-Api-Key: YOUR_API_KEY
Content-Type: application/json三、核心接口说明
3.1 期货市场列表
获取所有可用期货品种的概要信息
接口地址:
GET /futures/list请求参数:
参数必选说明示例值category否品种类别energy, metal, agricultureexchange否交易所代码CME, NYMEX, SHFE响应示例:
{
"code": 200,
"data": [
{
"symbol": "CL", // 交易代码
"name": "WTI原油", // 品种名称
"exchange": "NYMEX", // 交易所
"lastPrice": 82.45, // 最新价
"change": 0.87, // 涨跌额
"changePercent": 1.07, // 涨跌幅%
"openInterest": 185432,// 持仓量
"volume": 245832, // 成交量
"updateTime": "2024-09-02T10:15:30Z" // 更新时间
},
{
"symbol": "GC",
"name": "黄金",
"exchange": "COMEX",
"lastPrice": 1956.80,
"change": -5.20,
"changePercent": -0.27,
"openInterest": 452189,
"volume": 124170,
"updateTime": "2024-09-02T10:15:32Z"
}
]
}3.2 查询指定期货行情
获取单个期货品种的详细行情
接口地址:
GET /futures/querySymbol请求参数:
参数必选说明示例值symbol是期货代码CL, GC, SI响应示例:
{
"code": 200,
"data": {
"symbol": "CL",
"name": "WTI原油",
"exchange": "NYMEX",
"lastPrice": 82.45,
"open": 81.80, // 开盘价
"high": 82.60, // 最高价
"low": 81.25, // 最低价
"prevClose": 81.58, // 前收盘
"volume": 245832, // 成交量
"openInterest": 185432,// 持仓量
"settlement": 81.55, // 结算价
"bid": 82.44, // 买一价
"ask": 82.46, // 卖一价
"bidSize": 85, // 买一量
"askSize": 120, // 卖一量
"tradingHours": "00:00-24:00", // 交易时段
"expiryDate": "2024-10-20", // 到期日
"contractSize": "1000 barrels", // 合约规模
"tickSize": 0.01, // 最小变动价位
"tickValue": 10.00 // 最小变动价值
}
}3.3 获取期货K线数据
获取历史K线数据
接口地址:
GET /futures/kline请求参数:
参数必选说明示例值symbol是期货代码CLinterval是时间粒度1m, 5m, 15m, 1h, 4h, 1dfrom否开始时间(YYYYMMDDHHmm)202409010000to否结束时间(YYYYMMDDHHmm)202409022359响应示例:
{
"code": 200,
"data": [
{
"timestamp": 1725004800000, // 时间戳(ms)
"open": 82.12, // 开盘价
"high": 82.48, // 最高价
"low": 82.05, // 最低价
"close": 82.32, // 收盘价
"volume": 12452, // 成交量
"openInterest": 185120 // 持仓量
},
{
"timestamp": 1725004860000,
"open": 82.33,
"high": 82.40,
"low": 82.28,
"close": 82.35,
"volume": 8560,
"openInterest": 185150
}
]
}3.4 获取合约信息
获取期货合约详细信息
接口地址:
GET /futures/contract请求参数:
参数必选说明示例值symbol是期货代码CLmonth否合约月份202410响应示例:
{
"code": 200,
"data": {
"symbol": "CL",
"contractMonth": "2024-10",
"firstTradingDate": "2024-09-10",
"lastTradingDate": "2024-10-20",
"firstNoticeDate": "2024-10-05",
"lastNoticeDate": "2024-10-15",
"firstDeliveryDate": "2024-10-21",
"lastDeliveryDate": "2024-10-25",
"contractSize": "1000 barrels",
"priceQuotation": "USD per barrel",
"tickSize": 0.01,
"tickValue": 10.00,
"tradingHours": "00:00-24:00",
"productCode": "CL",
"exchange": "NYMEX"
}
}四、高级数据接口
4.1 主力合约与连续合约
获取主力合约和连续合约数据
接口地址:
GET /futures/continuous请求参数:
参数必选说明示例值symbol是期货代码CLtype是合约类型main(主力), continuous(连续)响应示例:
{
"code": 200,
"data": {
"symbol": "CL",
"type": "main",
"currentContract": "CL2024V4", // 当前主力合约
"nextContract": "CL2024X4", // 下一个主力合约
"rolloverDate": "2024-09-15",// 换月日期
"historicalContracts": [ // 历史主力合约
"CL2024U4",
"CL2024Q4",
"CL2024N4"
]
}
}4.2 价差交易数据
获取跨期价差数据
接口地址:
GET /futures/spread请求参数:
参数必选说明示例值symbol1是第一个合约CL2024V4symbol2是第二个合约CL2024X4响应示例:
{
"code": 200,
"data": {
"symbol1": "CL2024V4",
"symbol2": "CL2024X4",
"price1": 82.45,
"price2": 82.20,
"spread": 0.25, // 价差
"spreadPercent": 0.30, // 价差百分比
"volume": 1245, // 价差交易量
"openInterest": 8560, // 价差持仓量
"historicalSpreads": [ // 历史价差
{
"timestamp": 1725004800000,
"spread": 0.22
},
{
"timestamp": 1725004860000,
"spread": 0.24
}
]
}
}4.3 持仓报告
获取交易所持仓报告数据
接口地址:
GET /futures/cot请求参数:
参数必选说明示例值symbol是期货代码CLreportDate否报告日期(YYYYMMDD)20240901响应示例:
{
"code": 200,
"data": {
"symbol": "CL",
"reportDate": "2024-09-01",
"commercialLong": 452189, // 商业多头
"commercialShort": 245832, // 商业空头
"nonCommercialLong": 185432, // 非商业多头
"nonCommercialShort": 124170,// 非商业空头
"nonReportableLong": 8560, // 非报告多头
"nonReportableShort": 12452,// 非报告空头
"openInterest": 892000, // 总持仓量
"change": 12450 // 持仓变化
}
}五、实时数据推送
5.1 WebSocket连接
wss://ws-api.stocktv.top/connect?key=YOUR_API_KEY5.2 订阅消息
{
"action": "subscribe",
"channels": ["futures:CL", "futures:GC"]
}5.3 实时数据格式
{
"channel": "futures:CL",
"data": {
"symbol": "CL",
"last": 82.46, // 最新价
"change": 0.88, // 涨跌额
"changePercent": 1.08,// 涨跌幅
"volume": 245901, // 成交量
"openInterest": 185450, // 持仓量
"bid": 82.45, // 买一价
"ask": 82.47, // 卖一价
"bidSize": 85, // 买一量
"askSize": 120, // 卖一量
"high": 82.60, // 最高价
"low": 81.25, // 最低价
"open": 81.80, // 开盘价
"prevClose": 81.58, // 前收盘
"settlement": 81.55, // 结算价
"timestamp": 1725008213 // 时间戳
}
}5.4 心跳机制
客户端需每30秒发送心跳消息:
{"action": "ping"}六、代码示例
6.1 Python获取期货数据
import requests
def get_futures_list(category=None):
"""获取期货市场列表"""
url = "https://api.stocktv.top/futures/list"
params = {"key": "YOUR_API_KEY"}
if category:
params["category"] = category
try:
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json()
if data["code"] == 200:
for futures in data["data"]:
print(f"{futures['symbol']}: {futures['name']} - {futures['lastPrice']}")
else:
print(f"API Error: {data['message']}")
else:
print(f"Request failed with status: {response.status_code}")
except Exception as e:
print(f"Error fetching futures list: {str(e)}")
# 获取能源类期货
get_futures_list(category="energy")6.2 Java获取K线数据
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONObject;
public class FuturesKline {
public static void main(String[] args) throws Exception {
OkHttpClient client = new OkHttpClient();
String symbol = "CL";
String url = "https://api.stocktv.top/futures/kline?symbol=" + symbol + "&interval=1h&key=YOUR_API_KEY";
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
JSONObject json = new JSONObject(response.body().string());
if (json.getInt("code") == 200) {
JSONArray data = json.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject kline = data.getJSONObject(i);
System.out.println("Time: " + kline.getLong("timestamp") +
" | Close: " + kline.getDouble("close"));
}
}
}
}
}
}6.3 Node.js实时数据订阅
const WebSocket = require('ws');
const wsUrl = 'wss://ws-api.stocktv.top/connect?key=YOUR_API_KEY';
const ws = new WebSocket(wsUrl);
ws.on('open', () => {
console.log('Connected to Futures API');
// 订阅WTI原油和黄金
ws.send(JSON.stringify({
action: 'subscribe',
channels: ['futures:CL', 'futures:GC']
}));
// 心跳机制
setInterval(() => {
ws.send(JSON.stringify({action: 'ping'}));
}, 30000);
});
ws.on('message', (data) => {
const message = JSON.parse(data);
if (message.channel) {
const symbol = message.channel.split(':');
console.log(`[${symbol}] ${message.data.last} (${message.data.changePercent}%)`);
}
});
ws.on('close', () => {
console.log('Disconnected from Futures API');
});七、最佳实践
7.1 数据缓存策略
from cachetools import TTLCache
import time
# 创建缓存,有效期5秒
futures_cache = TTLCache(maxsize=100, ttl=5)
def get_futures_quote(symbol):
"""获取期货行情(带缓存)"""
# 检查缓存
if symbol in futures_cache:
return futures_cache
# 调用API获取数据
quote = fetch_from_api(symbol)
# 存入缓存
if quote:
futures_cache = quote
return quote7.2 错误处理与重试
import requests
import time
def fetch_with_retry(url, params, max_retries=3):
"""带重试机制的API请求"""
for attempt in range(max_retries):
try:
response = requests.get(url, params=params, timeout=5)
if response.status_code == 200:
data = response.json()
if data.get("code") == 200:
return data
elif data.get("code") == 429:# 请求过多
retry_after = int(data.get("retryAfter", 10))
print(f"请求过于频繁,等待 {retry_after} 秒后重试...")
time.sleep(retry_after)
else:
print(f"API返回错误: {data.get('message')}")
else:
print(f"请求失败,状态码: {response.status_code}")
except Exception as e:
print(f"请求异常: {str(e)}")
if attempt < max_retries - 1:
wait = 2 ** attempt# 指数退避
print(f"等待 {wait} 秒后重试 (尝试 {attempt+1}/{max_retries})")
time.sleep(wait)
print(f"请求失败,已达最大重试次数 {max_retries}")
return None7.3 实时数据批处理
class FuturesDataProcessor:
def __init__(self, batch_size=10, batch_interval=0.5):
self.batch_size = batch_size
self.batch_interval = batch_interval
self.buffer = {}
self.last_process_time = time.time()
def add_data(self, symbol, data):
"""添加实时数据到缓冲区"""
if symbol not in self.buffer:
self.buffer = []
self.buffer.append(data)
# 检查是否达到批处理条件
current_time = time.time()
if (len(self.buffer) >= self.batch_size or
current_time - self.last_process_time >= self.batch_interval):
self.process_batch(symbol)
self.last_process_time = current_time
def process_batch(self, symbol):
"""处理缓冲区的数据"""
if symbol not in self.buffer or not self.buffer:
return
data_points = self.buffer
# 计算统计指标
prices = for d in data_points]
volumes = for d in data_points]
oi_changes =
avg_price = sum(prices) / len(prices)
max_price = max(prices)
min_price = min(prices)
total_volume = sum(volumes)
total_oi_change = sum(oi_changes)
print(f"\n{symbol} 实时数据统计 (最近 {len(data_points)} 个更新):")
print(f"平均价格: {avg_price:.2f}, 最高: {max_price:.2f}, 最低: {min_price:.2f}")
print(f"总成交量: {total_volume}, 总持仓变化: {total_oi_change}")
# 清空缓冲区
self.buffer = []八、数据字典
8.1 主要期货品种
代码品种名称交易所合约规模CLWTI原油NYMEX1000桶GC黄金COMEX100金衡盎司SI白银COMEX5000金衡盎司NG天然气NYMEX10000MMBtuZS大豆CBOT5000蒲式耳ZC玉米CBOT5000蒲式耳ZW小麦CBOT5000蒲式耳6E欧元期货CME125,000欧元ES标普500指数期货CME$50×指数NQ纳斯达克100指数期货CME$20×指数十、附录
10.1 常见问题解答
Q: 如何获取不同到期日的合约数据?
A: 使用完整合约代码,例如CL2024V4表示2024年10月WTI原油合约
Q: 支持哪些历史数据粒度?
A: 支持1分钟、5分钟、15分钟、30分钟、1小时、4小时、日线、周线、月线
10.2 错误代码表
错误码含义解决方案400请求参数错误检查请求参数401未授权检查API Key403禁止访问确认账户权限404资源不存在检查请求路径500服务器错误联系技术支持
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页:
[1]