如何接入A股实时行情API

在接入 A 股行情数据时,有一个经常被忽略但非常关键的细节:你拿到的是实时数据,还是延时数据?

我们在雪球、东方财富这类网站上看到的行情更新看起来很快,其实大多是延时数据。这在官网也会注明,比如“本页面所示行情数据为 T+0 延时15分钟,仅供参考”等。

延时行情对日常查看、趋势判断是足够的,但如果你在做以下这些事情,就会有明显影响:

  • 高频或低延迟策略开发;

  • 实盘交易系统对接;

  • 实时风控与盘口建模;

  • 多源行情同步与聚合分析。

在这些场景中,延时15秒甚至几秒钟都可能导致策略响应偏离真实市场状态。

相比之下,实时行情 API通过WebSocket 毫秒级推送最新市场数据,没有中间缓存或延迟,可以更直接地反映市场当下的状态。尤其是 Level 2 行情,还能提供更深的盘口信息,比如买卖五档、委托队列等。

这并不是说实时行情一定更好,关键在于你的应用是否真的需要它。如果你只是做中线选股或者参考日内波动,延时数据可能已经够用了;但若你需要交易决策或建模依赖市场瞬时状态,实时行情就变得必要了。

订阅K线

import asyncio
import json
import websockets

# A股行情的websocket订阅地址
WS_URL = "wss://data.infoway.io/ws?business=stock&apikey=yourApiKey"

# 请先在官网https://infoway.io 申请免费API key

async def connect_and_receive():
    async with websockets.connect(WS_URL) as websocket:
        # 发送初始化消息,这里订阅的是平安银行(000001.SZ)的1分钟K线数据
        init_message = {
            "code": 10004,
            "trace": "423afec425004bd8a5e02e1ba5f9b2b0",
            "data": {
                "arr": [
                    {
                        "type": 1,  # 1分钟K线
                        "codes": "000001.SZ"  # A股股票代码,例如 平安银行
                    }
                ]
            }
        }
        await websocket.send(json.dumps(init_message))

        async def send_ping():
            while True:
                await asyncio.sleep(30)
                ping_message = {
                    "code": 10010,
                    "trace": "423afec425004bd8a5e02e1ba5f9b2b0"
                }
                await websocket.send(json.dumps(ping_message))

        ping_task = asyncio.create_task(send_ping())

        try:
            while True:
                message = await websocket.recv()
                print(f"Message received: {message}")
        except websockets.exceptions.ConnectionClosedOK:
            print("Connection closed normally")
        finally:
            ping_task.cancel()

# 运行主函数
asyncio.run(connect_and_receive())

返回示例

{
    "c": "11.25",           // 收盘价
    "h": "11.28",           // 最高价
    "l": "11.22",           // 最低价
    "o": "11.23",           // 开盘价
    "pca": "0.02",          // 价格变化
    "pfr": "0.18%",         // 价格变化百分比
    "s": "000001.SZ",       // 股票代码
    "t": 1747550648097,     // 时间戳
    "ty": 1,                // K线类型:1 表示1分钟K线
    "v": "258400",          // 交易量(单位:股)
    "vw": "11.2458"         // 加权平均价格
}

订阅盘口数据

import asyncio
import json
import websockets

# A股行情的websocket订阅地址
WS_URL = "wss://data.infoway.io/ws?business=stock&apikey=yourApiKey"

# 请先在官网 https://infoway.io 申请免费API key

async def connect_and_receive():
    async with websockets.connect(WS_URL) as websocket:
        # 发送初始化消息,订阅的是 A股平安银行(000001.SZ)的盘口数据
        init_message = {
            "code": 10002,  # 盘口订阅的请求协议号
            "trace": "423afec425004bd8a5e02e1ba5f9b2b0",  # 可追溯ID(可随机生成)
            "data": {
                "codes": "000001.SZ"  # A股股票代码,例如平安银行
            }
        }
        await websocket.send(json.dumps(init_message))

        # 设置 ping 任务,保持连接
        async def send_ping():
            while True:
                await asyncio.sleep(30)
                ping_message = {
                    "code": 10010,
                    "trace": "423afec425004bd8a5e02e1ba5f9b2b0"
                }
                await websocket.send(json.dumps(ping_message))

        # 启动 ping 协程
        ping_task = asyncio.create_task(send_ping())

        try:
            # 持续接收消息
            while True:
                message = await websocket.recv()
                print(f"Message received: {message}")
        except websockets.exceptions.ConnectionClosedOK:
            print("Connection closed normally")
        finally:
            # 取消 ping 任务
            ping_task.cancel()

# 运行主函数
asyncio.run(connect_and_receive())

返回示例

{
    "a": [
        [
            "11.25",    // 卖盘价格1
            "11.26",    // 卖盘价格2
            "11.27",    // 卖盘价格3
            "11.28",    // 卖盘价格4
            "11.29"     // 卖盘价格5
        ],
        [
            "23000",    // 卖盘数量1
            "18000",    // 卖盘数量2
            "9500",     // 卖盘数量3
            "6000",     // 卖盘数量4
            "7200"      // 卖盘数量5
        ]
    ],
    "b": [
        [
            "11.24",    // 买盘价格1
            "11.23",    // 买盘价格2
            "11.22",    // 买盘价格3
            "11.21",    // 买盘价格4
            "11.20"     // 买盘价格5
        ],
        [
            "26000",    // 买盘数量1
            "20000",    // 买盘数量2
            "10000",    // 买盘数量3
            "7500",     // 买盘数量4
            "8500"      // 买盘数量5
        ]
    ],
    "s": "000001.SZ",         // A股股票代码(平安银行)
    "t": 1747553102161        // 时间戳
}

### 回答1: 以下代码可以用来获取A实时行情:import requestsurl = "http://hq.sinajs.cn/list=sz000001"response = requests.get(url)data = response.text.split('"')[1].split(',')name = data[0]open_price = float(data[1])pre_close = float(data[2])current_price = float(data[3])high_price = float(data[4])low_price = float(data[5]) ### 回答2: 获取A实时行情的代码可以使用Python编程语言来实现。以下是一个简单的示例代码: ```python import requests def get_realtime_quote(stock_code): url = f"https://hq.sinajs.cn/list={stock_code}" response = requests.get(url) data = response.text.split("=")[1].split(",") stock_name = data[0].split('"')[1] # 票名称 opening_price = float(data[1]) # 开盘价 closing_price = float(data[3]) # 收盘价 current_price = float(data[2]) # 当前价 highest_price = float(data[4]) # 最高价 lowest_price = float(data[5]) # 最低价 return { "stock_name": stock_name, "opening_price": opening_price, "closing_price": closing_price, "current_price": current_price, "highest_price": highest_price, "lowest_price": lowest_price } # 示例用法 stock_code = "sh000001" # 示例为上证指数,可以替换为任意A票代码 quote = get_realtime_quote(stock_code) print("票名称:", quote["stock_name"]) print("开盘价:", quote["opening_price"]) print("收盘价:", quote["closing_price"]) print("当前价:", quote["current_price"]) print("最高价:", quote["highest_price"]) print("最低价:", quote["lowest_price"]) ``` 这段代码使用requests库发送HTTP请求,并使用字符串处理将返回的数据解析成字典形式,包含票名称、开盘价、收盘价、当前价、最高价和最低价等实时行情数据。 ### 回答3: 要获取A实时行情,可以使用Python编程语言,并借助tushare库来实现。 首先,需要在Python环境中安装tushare库。可以使用以下命令来安装: ``` pip install tushare ``` 然后,在Python代码中引入tushare库,并设置tushare的Token,以便获取数据: ```python import tushare as ts # 设置tushare的Token ts.set_token('your_token_here') ``` 需要替换上述代码中的 `your_token_here` 为你在tushare官网(https://tushare.pro/)获取的个人Token。 接下来,可以使用tushare提供的`pro_api()`方法来创建一个API连接,并通过`query()`方法查询A实时行情数据: ```python # 创建API连接 api = ts.pro_api() # 查询A实时行情数据 data = api.query('stock_basic', exchange='SSE', list_status='L', fields='ts_code,symbol,name,area,industry,list_date') ``` 上述代码通过`query()`方法调用了tushare的`stock_basic`接口,获取了上交所(SSE)的所有上市票的基本信息数据,包括票代码、票名称、所在地区、所属行业及上市日期等。 最后,我们可以打印输出获取到的票数据: ```python # 打印输出获取到的票数据 print(data) ``` 以上代码实现了获取A实时行情的基本过程。当然,根据具体需求,你还可以进一步使用tushare库提供的其他方法来获取更详细的A实时行情数据,以及进行数据分析和处理等操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值