劳暄美 发表于 前天 22:59

美股市场股票数据API对接文档

本文档提供StockTV美股市场数据API的完整对接指南,涵盖实时行情、历史数据、公司信息、财务指标等核心功能
一、接口概览

1.1 支持交易所

交易所代码交易所名称主要上市公司NYSE纽约证券交易所蓝筹股、传统行业巨头NASDAQ纳斯达克交易所科技股、成长型公司AMEX美国证券交易所中小型公司、ETF1.2 数据特性


[*]实时行情:毫秒级延迟(WebSocket)
[*]历史数据:支持最长20年历史数据
[*]基本面数据:完整财务指标、分析师评级
[*]多维度数据:分时K线、盘前盘后、期权数据
[*]数据格式:统一JSON格式
二、接入准备

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 /us/quote请求参数:
参数必选说明示例值symbol是股票代码AAPL响应示例:
{
"code": 200,
"data": {
    "symbol": "AAPL",
    "name": "Apple Inc.",
    "exchange": "NASDAQ",
    "price": 175.43,         // 最新价
    "prevClose": 173.75,       // 前收盘
    "open": 174.20,            // 开盘价
    "high": 175.85,            // 最高价
    "low": 173.90,             // 最低价
    "volume": 58439210,      // 成交量
    "marketCap": 2735000000000,// 市值(美元)
    "peRatio": 28.7,         // 市盈率
    "eps": 6.11,               // 每股收益
    "dividendYield": 0.55,   // 股息率
    "beta": 1.23,            // Beta值
    "lastUpdated": 1725008213// 最后更新时间戳
}
}3.2 批量查询行情

获取多只股票实时数据
接口地址:
POST /us/batch-quotes请求体:
{
"symbols": ["AAPL", "MSFT", "GOOGL"]
}响应示例:
{
"code": 200,
"data": {
    "AAPL": {
      "price": 175.43,
      "change": 1.68,
      "changePercent": 0.97
    },
    "MSFT": {
      "price": 342.54,
      "change": -0.86,
      "changePercent": -0.25
    },
    "GOOGL": {
      "price": 143.28,
      "change": 2.15,
      "changePercent": 1.52
    }
}
}3.3 历史K线数据

获取股票历史价格
接口地址:
GET /us/historical请求参数:
参数必选说明示例值symbol是股票代码AAPLperiod否时间周期1d, 1w, 1m, 3m, 6m, 1y, 5yinterval否时间粒度1m, 5m, 15m, 30m, 1h, 1dstart否开始日期(YYYYMMDD)20230901end否结束日期(YYYYMMDD)20230930响应示例:
{
"code": 200,
"data": [
    {
      "date": "2023-09-01",
      "open": 174.20,
      "high": 175.85,
      "low": 173.90,
      "close": 175.43,
      "volume": 58439210,
      "adjClose": 175.43
    },
    {
      "date": "2023-08-31",
      "open": 173.15,
      "high": 174.25,
      "low": 172.80,
      "close": 173.75,
      "volume": 52387125,
      "adjClose": 173.75
    }
]
}3.4 公司基本信息

获取公司概况
接口地址:
GET /us/company请求参数:
参数必选说明示例值symbol是股票代码AAPL响应示例:
{
"code": 200,
"data": {
    "symbol": "AAPL",
    "name": "Apple Inc.",
    "description": "全球领先的科技公司,设计、制造和销售智能手机、个人电脑、平板电脑、可穿戴设备和配件...",
    "sector": "Technology",
    "industry": "Consumer Electronics",
    "ceo": "Tim Cook",
    "employees": 164000,
    "headquarters": "Cupertino, California",
    "website": "https://www.apple.com",
    "ipoDate": "1980-12-12"
}
}3.5 财务数据

获取财务指标
接口地址:
GET /us/financials请求参数:
参数必选说明示例值symbol是股票代码AAPLperiod否年度/季度annual, quarterly响应示例:
{
"code": 200,
"data": {
    "symbol": "AAPL",
    "financials": {
      "2023": {
      "revenue": 383285000000,   // 营收
      "grossProfit": 169148000000, // 毛利润
      "netIncome": 96950000000,   // 净利润
      "eps": 6.11,               // 每股收益
      "dividend": 0.96            // 每股股息
      },
      "2022": {
      "revenue": 365817000000,
      "grossProfit": 152836000000,
      "netIncome": 99803000000,
      "eps": 6.05,
      "dividend": 0.92
      }
    }
}
}四、高级数据接口

4.1 分时数据

获取当日分时数据
接口地址:
GET /us/intraday请求参数:
参数必选说明示例值symbol是股票代码AAPLinterval否时间粒度(1m, 5m)5m响应示例:
{
"code": 200,
"data": [
    {
      "timestamp": 1725004800000, // 时间戳(毫秒)
      "price": 174.32,
      "volume": 125432
    },
    {
      "timestamp": 1725005100000,
      "price": 174.56,
      "volume": 143256
    }
]
}4.2 盘前盘后数据

获取盘前盘后交易数据
接口地址:
GET /us/prepost请求参数:
参数必选说明示例值symbol是股票代码AAPL响应示例:
{
"code": 200,
"data": {
    "preMarket": {
      "lastPrice": 176.20,
      "change": 0.77,
      "changePercent": 0.44,
      "volume": 1254321,
      "time": "07:45:23"
    },
    "postMarket": {
      "lastPrice": 175.80,
      "change": 0.37,
      "changePercent": 0.21,
      "volume": 876543,
      "time": "18:32:11"
    }
}
}4.3 期权数据

获取期权合约信息
接口地址:
GET /us/options请求参数:
参数必选说明示例值symbol是股票代码AAPLexpiration否到期日期(YYYYMMDD)20231215响应示例:
{
"code": 200,
"data": {
    "symbol": "AAPL",
    "expirations": ["2023-12-15", "2024-01-19", "2024-03-15"],
    "options": [
      {
      "contractId": "AAPL231215C00175000",
      "strike": 175.00,       // 行权价
      "lastPrice": 6.45,      // 最后成交价
      "bid": 6.40,            // 买价
      "ask": 6.50,            // 卖价
      "volume": 1245,         // 成交量
      "openInterest": 5423,   // 未平仓合约
      "impliedVolatility": 0.35, // 隐含波动率
      "type": "call"          // 看涨/看跌
      }
    ]
}
}五、实时数据推送

5.1 WebSocket连接

wss://ws-api.stocktv.top/us?key=YOUR_API_KEY5.2 订阅消息

{
"action": "subscribe",
"symbols": ["AAPL", "MSFT", "TSLA"]
}5.3 实时数据格式

{
"symbol": "AAPL",       // 股票代码
"price": 175.43,      // 最新价
"change": 1.68,         // 涨跌额
"changePercent": 0.97,// 涨跌幅%
"volume": 58439210,   // 成交量
"bid": 175.42,          // 买一价
"ask": 175.44,          // 卖一价
"bidSize": 125,         // 买一量
"askSize": 85,          // 卖一量
"timestamp": 1725008213 // 时间戳
}5.4 心跳机制

客户端需每30秒发送心跳消息:
{"action": "ping"}六、代码示例

6.1 Python获取股票数据

import requests

def get_stock_quote(symbol):
    url = "https://api.stocktv.top/us/quote"
    params = {"symbol": symbol}
    headers = {
      "X-Api-Key": "YOUR_API_KEY",
      "Content-Type": "application/json"
    }
   
    response = requests.get(url, params=params, headers=headers)
    if response.status_code == 200:
      data = response.json()
      if data["code"] == 200:
            return data["data"]
    return None

# 获取苹果股票数据
aapl = get_stock_quote("AAPL")
if aapl:
    print(f"{aapl['name']} ({aapl['symbol']})")
    print(f"价格: ${aapl['price']} ({aapl['changePercent']}%)")
    print(f"市值: ${aapl['marketCap']/1e9:.2f}B")6.2 Node.js实时数据订阅

const WebSocket = require('ws');
const ws = new WebSocket('wss://ws-api.stocktv.top/us?key=YOUR_API_KEY');

ws.on('open', () => {
console.log('Connected to US Stock API');

// 订阅股票
ws.send(JSON.stringify({
    action: "subscribe",
    symbols: ["AAPL", "MSFT", "TSLA"]
}));
});

ws.on('message', (data) => {
const message = JSON.parse(data);
if(message.symbol) {
    const arrow = message.change >= 0 ? '↑' : '↓';
    console.log(`[${message.symbol}] ${message.price} ${arrow} ${message.changePercent}%`);
}
});

// 心跳维持
setInterval(() => {
ws.send(JSON.stringify({action: "ping"}));
}, 30000);6.3 Java获取历史数据

import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class StockHistoryFetcher {
    private static final String API_KEY = "YOUR_API_KEY";
    private static final ObjectMapper mapper = new ObjectMapper();

    public static void main(String[] args) throws Exception {
      String symbol = "AAPL";
      String url = "https://api.stocktv.top/us/historical?symbol=" + symbol + "&period=1y";
      
      OkHttpClient client = new OkHttpClient();
      Request request = new Request.Builder()
                .url(url)
                .addHeader("X-Api-Key", API_KEY)
                .build();
      
      try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String json = response.body().string();
                JsonNode root = mapper.readTree(json);
                if (root.path("code").asInt() == 200) {
                  JsonNode data = root.path("data");
                  System.out.println("AAPL Historical Data:");
                  data.forEach(day -> {
                        System.out.printf("%s: Open=%.2f, Close=%.2f, Volume=%d%n",
                              day.path("date").asText(),
                              day.path("open").asDouble(),
                              day.path("close").asDouble(),
                              day.path("volume").asLong());
                  });
                }
            }
      }
    }
}七、最佳实践

7.1 数据缓存策略

from cachetools import TTLCache
import time

class StockDataCache:
    def __init__(self, maxsize=100, ttl=60):
      self.cache = TTLCache(maxsize=maxsize, ttl=ttl)
   
    def get_quote(self, symbol):
      if symbol in self.cache:
            return self.cache
      
      # 从API获取
      quote = api_get_quote(symbol)# 实际API调用函数
      if quote:
            self.cache = quote
      return quote

# 使用示例
cache = StockDataCache()
aapl = cache.get_quote("AAPL")7.2 批量请求优化

async function fetchBatchQuotes(symbols, batchSize=10) {
const results = {};

for (let i = 0; i < symbols.length; i += batchSize) {
    const batch = symbols.slice(i, i + batchSize);
    const response = await fetch('https://api.stocktv.top/us/batch-quotes', {
      method: 'POST',
      headers: {
      'X-Api-Key': API_KEY,
      'Content-Type': 'application/json'
      },
      body: JSON.stringify({ symbols: batch })
    });
   
    const data = await response.json();
    if (data.code === 200) {
      Object.assign(results, data.data);
    }
   
    // 避免请求过快
    await new Promise(resolve => setTimeout(resolve, 300));
}

return results;
}7.3 实时数据批处理

class RealTimeProcessor:
    def __init__(self, batch_size=10, batch_interval=0.5):
      self.buffer = {}
      self.batch_size = batch_size
      self.batch_interval = batch_interval
      self.last_process_time = time.time()
   
    def add_update(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):
      data_points = self.buffer.get(symbol, [])
      if not data_points:
            return
      
      # 计算平均价格、总成交量等
      prices = for d in data_points]
      avg_price = sum(prices) / len(prices)
      total_volume = sum(d['volume'] for d in data_points)
      
      print(f"{symbol} 批次统计: {len(data_points)}次更新")
      print(f"平均价格: {avg_price:.2f}, 总成交量: {total_volume}")
      
      # 清空缓冲区
      self.buffer = []7.4 错误处理与重试

public JsonNode fetchWithRetry(String url, int maxRetries) {
    int retries = 0;
    while (retries < maxRetries) {
      try {
            Request request = new Request.Builder()
                  .url(url)
                  .addHeader("X-Api-Key", API_KEY)
                  .build();
            
            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful()) {
                  return mapper.readTree(response.body().string());
                } else if (response.code() == 429) {
                  // 请求过多,等待后重试
                  int waitTime = 30; // 默认等待30秒
                  String retryAfter = response.header("Retry-After");
                  if (retryAfter != null) {
                        waitTime = Integer.parseInt(retryAfter);
                  }
                  Thread.sleep(waitTime * 1000);
                }
            }
      } catch (Exception e) {
            // 记录错误
      }
      retries++;
    }
    return null; // 达到最大重试次数
}八、数据字典

8.1 美股主要指数

代码指数名称包含公司.DJI道琼斯工业平均指数30家大型企业.IXIC纳斯达克综合指数所有纳斯达克上市公司.INX标普500指数500家大型公司.RUT罗素2000指数2000家小型公司8.2 交易时间

交易时段美东时间北京时间盘前交易04:00-09:3016:00-21:30常规交易09:30-16:0021:30-04:00(+1)盘后交易16:00-20:0004:00-08:00(+1)十、附录

10.1 常见问题解答

Q: 如何获取历史分时数据?
A: 使用/us/intraday接口,设置interval参数为1m
Q: 是否支持分页?
A: 对于列表接口(如历史数据),使用page和size参数控制数据范围
10.2 错误代码表

错误码含义解决方案400请求参数错误检查请求参数401未授权检查API Key404资源不存在检查请求路径429请求过于频繁降低请求频率500服务器错误联系技术支持本文档版本:v3.0.1
最后更新:2025年9月5日
下载PDF版本:https://stocktv.top/
示例代码库:https://github.com/cryptorzz/

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: 美股市场股票数据API对接文档