如何通过pyside6通过WebSocket订阅binance?

enyaitl3  于 2023-05-29  发布在  其他
关注(0)|答案(1)|浏览(240)

我可以通过以下代码获得流:

from PySide6.QtWebSockets import QWebSocket

...

self.websocket = QWebSocket()
self.websocket_base_url = 'wss://stream.binance.com:9443/ws'
self.websocket.open(self.websocket_base_url + '/btcusdt@kline_5m')
self.websocket.textMessageReceived.connect(self.on_message_received)

def on_message_received(self, msg):
    print(msg)

这可以正常接收流,但我想使用订阅,所以我写了这个:

self.websocket = QWebSocket()
self.websocket_base_url = 'wss://stream.binance.com:9443/ws'
self.websocket.open(self.websocket_base_url)

info = {
    "method": "SUBSCRIBE",
     "params":
      [
           "btcusdt@aggTrade"
       ],
       "id": 1
}

ret = self.websocket.sendTextMessage(json.dumps(info))
print(str(self.websocket.state()))
self.websocket.textMessageReceived.connect(self.on_message_received)

def on_message_received(self, msg):
    print(msg)

print()output:PySide6.QtNetwork.QAbstractSocket.SocketState.ConnectingState和self.on_message_received()未收到消息。
我不知道为什么……

zpqajqem

zpqajqem1#

您必须在连接后订阅:

import json

from PySide6.QtCore import QObject
from PySide6.QtWebSockets import QWebSocket

class Manager(QObject):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.websocket = QWebSocket()
        self.websocket.textMessageReceived.connect(self.handle_text_message_received)
        self.websocket.connected.connect(self.handle_connected)

    def start(self):
        url = "wss://stream.binance.com:9443/ws"
        self.websocket.open(url)

    def subscribe(self):
        info = {"method": "SUBSCRIBE", "params": ["btcusdt@aggTrade"], "id": 1}
        message = json.dumps(info)
        ret = self.websocket.sendTextMessage(message)
        assert ret == len(message)

    def handle_connected(self):
        self.subscribe()

    def handle_text_message_received(self, message):
        data = json.loads(message)
        print(data)

def main():
    import sys
    from PySide6.QtCore import QCoreApplication

    app = QCoreApplication(sys.argv)
    manager = Manager()
    manager.start()

    app.exec()

if __name__ == "__main__":
    main()

输出:

{'result': None, 'id': 1}
{'e': 'aggTrade', 'E': 1634398386255, 's': 'BTCUSDT', 'a': 958023628, 'p': '60999.99000000', 'q': '0.00442000', 'f': 1100891458, 'l': 1100891458, 'T': 1634398386255, 'm': True, 'M': True}
{'e': 'aggTrade', 'E': 1634398386750, 's': 'BTCUSDT', 'a': 958023629, 'p': '61000.00000000', 'q': '0.00028000', 'f': 1100891459, 'l': 1100891459, 'T': 1634398386749, 'm': False, 'M': True}
{'e': 'aggTrade', 'E': 1634398386765, 's': 'BTCUSDT', 'a': 958023630, 'p': '61000.00000000', 'q': '0.01447000', 'f': 1100891460, 'l': 1100891461, 'T': 1634398386764, 'm': False, 'M': True}

相关问题