1. 查询股票基础信息
这个接口用来查询股票的基础信息,比如流通股本、每股盈利等信息:
import requests
url = "https://data.infoway.io/common/basic/symbols/info?symbols=000001.SZ%2C000002.SZ&type=STOCK_CN"
# API Key申请: www.infoway.io
headers = {
'User-Agent': 'Mozilla/5.0',
'Accept': 'application/json',
'apiKey': 'yourApikey'
}
response = requests.get(url, headers=headers)
print(response.text)
1.1 返回示例
{
"ret": 200,
"msg": "success",
"traceId": "52327ed3-e96a-4e9a-a591-e910a0fcc563",
"data": [
{
"symbol": "000001.SZ", #股票代码
"market": "CN", #上市国家
"name_cn": "平安银行", #股票中文名
"name_en": "PAB", #股票英文名
"name_hk": "平安銀行", #繁体名
"exchange": "SZSE", #交易所
"currency": "CNY", #结算货币
"lot_size": 100, #每手股数
"total_shares": 19405918198, #总股本
"circulating_shares": 19405762053, #流通股本
"hk_shares": 0, #港股股本 (仅港股)
"eps": "2.2935271367158012", #每股盈利
"eps_ttm": "2.2504474951615995", #每股盈利TTM
"bps": "22.4755662447835698", #每股净资产
"dividend_yield": "0.9649999999963929", #股息
"stock_derivatives": "", #可提供的衍生品行情类型
"board": "SZMainConnect" #所属板块
},
]
}
2. 查询最新成交价
顾名思义,查最新一笔的成交明细,可以通过HTTP批量查询:
import requests
url = "https://data.infoway.io/stock/batch_trade/002594.SZ%2C00285.HK%2CTSLA.US%2CAUDCAD%2CHK50%2CXNIUSD"
# 申请API Key: www.infoway.io
headers = {
'User-Agent': 'Mozilla/5.0',
'Accept': 'application/json',
'apiKey': 'yourApikey'
}
response = requests.get(url, headers=headers)
print(response.text)
2.1 返回示例
{
"ret": 200,
"msg": "success",
"traceId": "c49a0866-c551-4951-927e-fe6a55c9fa53",
"data": [
{
"s": "00285.HK",
"t": 1750147730935,
"p": "31.350",
"v": "171500",
"vw": "5376525.000",
"td": 0
},
{
"s": "TSLA.US",
"t": 1750177279200,
"p": "320.960",
"v": "100",
"vw": "32096.000",
"td": 0
},
{
"s": "002594.SZ",
"t": 1750143600999,
"p": "343.74",
"v": "1395",
"vw": "479517.30",
"td": 1
}
]
}
3. 查询股票K线
这个接口也支持批量查询,下面演示的是同时查询A股、港股和美股的K线:
import requests
url = "https://data.infoway.io/stock/batch_kline/1/10/002594.SZ%2C00285.HK%2CTSLA.US"
# 设置请求头
# 申请API Key: www.infoway.io
headers = {
'User-Agent': 'Mozilla/5.0',
'Accept': 'application/json',
'apiKey': 'yourApikey'
}
response = requests.get(url)
print(response.text)
K线可以选择不同的周期:
https://data.infoway.io/stock/batch_kline/{klineType}/{klineNum}/{codes}
# {klineType} 是K线的时间
# 1 = 1分钟k线
# 2 = 5分钟k线
# 3 = 15分钟k线
# 4 = 30分钟k线
# 5 = 1小时k线
# 6 = 2小时k线
# 7 = 4小时k线
# 8 = 1日k线
# 9 = 1周k线
# 10 = 1月k线
# 11 = 1季k线
# 12 = 1年k线
# {klineNum}是需要返回的K线数量,最大支持一次性返回500根K线
3.1 返回示例
{
"code": 0,
"data": {
"0700.HK": [
{
"date": "2025-06-25",
"open": 390.0,
"close": 398.6,
"high": 400.2,
"low": 388.1,
"volume": 12034500
},
...
],
"0005.HK": [
{
"date": "2025-06-25",
"open": 62.0,
"close": 63.2,
"high": 63.8,
"low": 61.5,
"volume": 8100000
},
...
]
}
}
4 WebSocket行情推送
以上介绍的是HTTP的请求方式,这种适合低频查询,如果需要高频次查询,或者对行情的实时性要求特别高,需要使用WebSocket长连接的方式。
import json
import time
import schedule
import threading
import websocket
from loguru import logger
# 申请API Key: www.infoway.io
class WebsocketExample:
def __init__(self):
self.session = None
self.ws_url = "wss://data.infoway.io/ws?business=crypto&apikey=yourApikey"
self.reconnecting = False
def connect_all(self):
"""建立WebSocket连接并启动自动重连机制"""
try:
self.connect(self.ws_url)
self.start_reconnection(self.ws_url)
except Exception as e:
logger.error(f"Failed to connect to {self.ws_url}: {str(e)}")
def start_reconnection(self, url):
"""启动定时重连检查"""
def check_connection():
if not self.is_connected():
logger.debug("Reconnection attempt...")
self.connect(url)
# 使用线程定期检查连接状态
threading.Thread(target=lambda: schedule.every(10).seconds.do(check_connection), daemon=True).start()
def is_connected(self):
"""检查WebSocket连接状态"""
return self.session and self.session.connected
def connect(self, url):
"""建立WebSocket连接"""
try:
if self.is_connected():
self.session.close()
self.session = websocket.WebSocketApp(
url,
on_open=self.on_open,
on_message=self.on_message,
on_error=self.on_error,
on_close=self.on_close
)
# 启动WebSocket连接(非阻塞模式)
threading.Thread(target=self.session.run_forever, daemon=True).start()
except Exception as e:
logger.error(f"Failed to connect to the server: {str(e)}")
def on_open(self, ws):
"""WebSocket连接建立成功后的回调"""
logger.info(f"Connection opened")
try:
# 发送实时成交明细订阅请求
trade_send_obj = {
"code": 10000,
"trace": "01213e9d-90a0-426e-a380-ebed633cba7a",
"data": {"codes": "BTCUSDT"}
}
self.send_message(trade_send_obj)
# 不同请求之间间隔一段时间
time.sleep(5)
# 发送实时盘口数据订阅请求
depth_send_obj = {
"code": 10003,
"trace": "01213e9d-90a0-426e-a380-ebed633cba7a",
"data": {"codes": "BTCUSDT"}
}
self.send_message(depth_send_obj)
# 不同请求之间间隔一段时间
time.sleep(5)
# 发送实时K线数据订阅请求
kline_data = {
"arr": [
{
"type": 1,
"codes": "BTCUSDT"
}
]
}
kline_send_obj = {
"code": 10006,
"trace": "01213e9d-90a0-426e-a380-ebed633cba7a",
"data": kline_data
}
self.send_message(kline_send_obj)
# 启动定时心跳任务
threading.Thread(target=lambda: schedule.every(30).seconds.do(self.ping), daemon=True).start()
except Exception as e:
logger.error(f"Error sending initial messages: {str(e)}")
def on_message(self, ws, message):
"""接收消息的回调"""
try:
logger.info(f"Message received: {message}")
except Exception as e:
logger.error(f"Error processing message: {str(e)}")
def on_close(self, ws, close_status_code, close_msg):
"""连接关闭的回调"""
logger.info(f"Connection closed: {close_status_code} - {close_msg}")
def on_error(self, ws, error):
"""错误处理的回调"""
logger.error(f"WebSocket error: {str(error)}")
def send_message(self, message_obj):
"""发送消息到WebSocket服务器"""
if self.is_connected():
try:
self.session.send(json.dumps(message_obj))
except Exception as e:
logger.error(f"Error sending message: {str(e)}")
else:
logger.warning("Cannot send message: Not connected")
def ping(self):
"""发送心跳包"""
ping_obj = {
"code": 10010,
"trace": "01213e9d-90a0-426e-a380-ebed633cba7a"
}
self.send_message(ping_obj)
# 使用示例
if __name__ == "__main__":
ws_client = WebsocketExample()
ws_client.connect_all()
# 保持主线程运行
try:
while True:
schedule.run_pending()
time.sleep(1)
except KeyboardInterrupt:
logger.info("Exiting...")
if ws_client.is_connected():
ws_client.session.close()