分享一个用python,使用websocket获取实时数据的例子
站点地址:脉动行情数据-全面的行情数据接口
这个站点可以获取:外汇、国际期货、国内期货、贵金属、能源、虚拟货币、股指期货、美股、台股、港股、印度股、A股、ETF等。
外汇等数据都很全,大概有100+的品种,以及相关的股指期货,恒指,德指,小道指,小纳指等等,品种非常全。
以下是Python的连接demo,可以参考下。同时也支持其他后端语言的连接,PHP、Java等。
获取品种地址: 脉动行情数据-全面的行情数据接口
import json
import websocket
# 行情对接地址:http://39.107.99.235:1008/market
try:
import thread
except ImportError:
import _thread as thread
import time
def on_data(ws, message, msg_type, flag):
# 解析接收到的数据
msg = json.loads(message)
if 'body' not in msg or not msg['body']:
return
data = msg['body'];
StockCode = data['StockCode'];
Price = data['Price'];
Open = data['Open'];
LastClose = data['LastClose'];
High = data['High'];
Low = data['Low'];
Diff = data['Diff'];
DiffRate = data['DiffRate'];
BP1 = data['BP1'];
BV1 = data['BV1'];
SP1 = data['SP1'];
SV1 = data['SV1'];
TotalVol = data['TotalVol'];
Time = data['Time'];
LastTime = data['LastTime'];
BS = data['BS'];
Depth = data['Depth'];
#处理业务逻辑.....
print(StockCode);
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
# print("open")
# 建立连接后订阅品种
data = {
'Key': 'btcusdt,ethusdt,fx_sgbpusd'
}
ws.send(json.dumps(data))
# 间隔10秒发送心跳信息
def run(*args):
while(True) :
time.sleep(10)
ping = {
'ping' : int(time.time())
}
ws.send(json.dumps(ping))
thread.start_new_thread(run, ())
if __name__ == "__main__":
# websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://39.107.99.235/ws", on_data = on_data, on_error = on_error, on_close = on_close)
ws.on_open = on_open
ws.run_forever()
返回数据结构:
最新价,最高价,最低价,收盘价,涨幅,成交量,买卖5档、实时成交等数据。
这些数据都有,有需要可以对接下
{
"body": {
"StockCode": "btcusdt",
"Price": 27206.02,
"Open": 26689.98,
"LastClose": 27206.02,
"High": 27287.74,
"Low": 26554.35,
"Time": "2023-05-28 15:43:51",
"LastTime": "1685259831",
"BP1": 27206.02,
"BV1": 0.21,
"SP1": 27206.03,
"SV1": 0.78,
"TotalVol": 2293.14,
"Depth": {
"Buy": [
{
"BP1": 27206.02,
"BV1": 0.39
},
{
"BP2": 27204.14,
"BV2": 0
},
{
"BP3": 27204.13,
"BV3": 1.28
},
{
"BP4": 27203.32,
"BV4": 0.64
},
{
"BP5": 27203.3,
"BV5": 0.68
}
],
"Sell": [
{
"SP1": 27206.03,
"SV1": 0.78
},
{
"SP2": 27206.22,
"SV2": 0.04
},
{
"SP3": 27206.96,
"SV3": 0.02
},
{
"SP4": 27208.13,
"SV4": 0.01
},
{
"SP5": 27208.14,
"SV5": 0.07
}
]
},
"BS": [
{
"time": "15:43:51",
"price": 27206.02,
"size": 0.21,
"direction": 2
},
{
"time": "15:43:51",
"price": 27206.03,
"size": 0.78,
"direction": 1
}
],
"Info": [
],
"lastSize": 0.055118,
"Diff": 516.04,
"DiffRate": 1.93
}
}