自学内容网 自学内容网

如何使用Websocket订阅实时股票价格

WebSocket和HTTP请求在工作原理和使用场景上存在显著区别。首先,HTTP是一种无状态的协议,客户端发起请求,服务器响应后,连接通常会关闭。如果客户端需要再次获取数据,必须发起新的请求。这种"请求-响应"模型适用于大多数网络应用,如网页浏览和API交互,但不适合需要实时、持续通信的场景。

WebSocket则是一种全双工通信协议,它允许客户端和服务器在建立初始连接后,保持连接持续打开。通过这个连接,双方可以随时发送数据,而无需客户端不断发起新请求。这使WebSocket成为处理实时数据的理想选择,如股票价格、聊天应用、游戏服务器等。在WebSocket连接建立后,数据的传输效率更高,因为它不需要每次通信都包含完整的HTTP头部信息。

WebSocket在订阅实时股价时具有显著优势。传统的HTTP请求通常依赖于轮询(polling)机制,即客户端定期向服务器发送请求以获取最新数据,这不仅增加了网络负载,还引入了延迟,无法实现真正的实时更新。而WebSocket则通过建立持续的全双工连接,使服务器能够在有新的股价数据时立即推送给客户端,无需轮询。这种方式极大地减少了延迟,确保用户能够实时获取股价波动。

此外,WebSocket的效率更高。与HTTP相比,WebSocket在初次连接后不会在每次通信时重新发送冗长的请求头信息,数据传输更加轻量化,节省了带宽。在需要处理高频率、大量数据的金融交易平台和量化交易中,WebSocket能够支持实时、高效的市场数据传输,让交易系统快速响应市场变化,从而为投资者提供更精确的决策支持。

因此,使用WebSocket订阅实时股价不仅降低了延迟,还优化了网络资源的使用,为高频率交易和数据密集型应用提供了理想的解决方案。

通过Websocket订阅股票价格的方法

import json
import websocket    # pip install websocket-client
 
'''
# 特别注意:
# github: https://github.com/alltick/free-quote
# token申请:https://alltick.co
# 把下面url中的testtoken替换为您自己的token
# 外汇,数字币,贵金属的api址:
# wss://quote.tradeswitcher.com/quote-b-ws-api
# 港美股api地址:
# wss://quote.tradeswitcher.com/quote-stock-b-ws-api
'''
 
class Feed(object):
 
    def __init__(self):
        self.url = 'wss://quote.tradeswitcher.com/quote-stock-b-ws-api?token=testtoken'  # 这里输入websocket的url
        self.ws = None
 
    def on_open(self, ws):
        """
        Callback object which is called at opening websocket.
        1 argument:
        @ ws: the WebSocketApp object
        """
        print('A new WebSocketApp is opened!')
 
        # 开始订阅(举个例子)
        sub_param = {
            "cmd_id": 22002, 
            "seq_id": 123,
            "trace":"3baaa938-f92c-4a74-a228-fd49d5e2f8bc-1678419657806",
            "data":{
                "symbol_list":[
                    {
                        "code": "700.HK",
                        "depth_level": 5,
                    },
                    {
                        "code": "UNH.US",
                        "depth_level": 5,
                    }
                ]
            }
        }
        
        #如果希望长时间运行,除了需要发送订阅之外,还需要修改代码,定时发送心跳,避免连接断开,具体查看接口文档
        sub_str = json.dumps(sub_param)
        ws.send(sub_str)
        print("depth quote are subscribed!")
 
    def on_data(self, ws, string, type, continue_flag):
        """
        4 argument.
        The 1st argument is this class object.
        The 2nd argument is utf-8 string which we get from the server.
        The 3rd argument is data type. ABNF.OPCODE_TEXT or ABNF.OPCODE_BINARY will be came.
        The 4th argument is continue flag. If 0, the data continue
        """
 
    def on_message(self, ws, message):
        """
        Callback object which is called when received data.
        2 arguments:
        @ ws: the WebSocketApp object
        @ message: utf-8 data received from the server
        """
        # 对收到的message进行解析
        result = eval(message)
        print(result)
 
    def on_error(self, ws, error):
        """
        Callback object which is called when got an error.
        2 arguments:
        @ ws: the WebSocketApp object
        @ error: exception object
        """
        print(error)
 
    def on_close(self, ws, close_status_code, close_msg):
        """
        Callback object which is called when the connection is closed.
        2 arguments:
        @ ws: the WebSocketApp object
        @ close_status_code
        @ close_msg
        """
        print('The connection is closed!')
 
    def start(self):
        self.ws = websocket.WebSocketApp(
            self.url,
            on_open=self.on_open,
            on_message=self.on_message,
            on_data=self.on_data,
            on_error=self.on_error,
            on_close=self.on_close,
        )
        self.ws.run_forever()
 
 
if __name__ == "__main__":
    feed = Feed()
    feed.start()

解析推送数据

{
    "cmd_id":22998,
    "data":{
"code": "1288.HK",
        "seq": "1605509068000001",
        "tick_time": "1605509068",
        "price": "651.12",
        "volume": "300",
        "turnover": "12345.6",
        "trade_direction": 1,
    }
}

5档行情数据

{
    "cmd_id":22999,
    "data":{
"code": "1288.HK",
        "seq": "1605509068000001",
        "tick_time": "1605509068",
        "bids": [
            {
                "pric": "9.12",
                "volume": "9.12",
            },
            {
                "pric": "9.12",
                "volume": "9.12",
            },
            {
                "pric": "9.12",
                "volume": "9.12",
            },
            {
                "pric": "9.12",
                "volume": "9.12",
            },
            {
                "pric": "9.12",
                "volume": "9.12",
            }
        ],
        "asks": [
            {
                "price": "147.12",
                "volume": "147.12",
            },
            {
                "price": "147.12",
                "volume": "147.12",
            },
            {
                "price": "147.12",
                "volume": "147.12",
            },
            {
                "price": "147.12",
                "volume": "147.12",
            },
            {
                "price": "147.12",
                "volume": "147.12",
            }
        ],
    }
}


原文地址:https://blog.csdn.net/qq_34102871/article/details/142953586

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!