如何使用Autobahn与Asyncio连接到Binance Websocket服务



我正在尝试通过:

连接到Binance服务
wss://stream.binance.com:9443/ws/bnbbtc@kline_1m

我知道它有效,因为已经尝试使用在线网络服务检查器,并且它注册了服务器并收到100万蜡烛而没有问题。

我已经看到问题到主机的路径时出现。如果我不添加路径"/ws/bnbbtc@kline_1m",它将连接但带有错误:

WebSocket connection closed: connection was closed uncleanly (WebSocket connection upgrade failed (400 - BadRequest))

这是我使用的代码,主要从示例中提取:

from autobahn.asyncio.websocket import WebSocketClientProtocol, WebSocketClientFactory
class MyClientProtocol(WebSocketClientProtocol):
    def onConnect(self, response):
        print("Server connected: {0}".format(response.peer))
    def onOpen(self):
        print("WebSocket connection open.")
    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
        else:
            print("Text message received: {0}".format(payload.decode('utf8')))
    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))

if __name__ == '__main__':
    import asyncio
    factory = WebSocketClientFactory()
    factory.protocol = MyClientProtocol
    loop = asyncio.get_event_loop()
    coro = loop.create_connection(factory,"stream.binance.com/ws/bnbbtc@kline_1m", 9443)
    loop.run_until_complete(coro)
    loop.run_forever()
loop.close()

使用此信息,我从getAddrinfo中获得以下错误:

for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11003] getaddrinfo failed

我真的很坚持这个,如果有人能提供帮助,我真的很感激。

好吧,经过几个小时的修复很明显,我将在这里留下代码,以便任何人检查他们是否需要:

factory = WebSocketClientFactory("wss://stream.binance.com:9443/ws/bnbbtc@kline_1m")
factory.protocol = MyClientProtocol
loop = asyncio.get_event_loop()
coro = loop.create_connection(factory,"stream.binance.com", 9443, ssl=True)
loop.run_until_complete(coro)
loop.run_forever()

我缺少ssl = true零件。

我知道,这也很晚,但这也可以解决问题,您必须使用4行代码:

$ pip安装Unicorn-Binance-websocket-api

from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager import BinanceWebSocketApiManager
from unicorn_binance_websocket_api_process_streams import BinanceWebSocketApiProcessStreams
binance_websocket_api_manager = BinanceWebSocketApiManager(BinanceWebSocketApiProcessStreams.process_stream_data)
binance_websocket_api_manager.create_stream('kline_1m', 'bnbbtc')

您使用" create_stream"创建的每个Websocket都将在单独的线程中创建,并用Asyncio编写为Coroutine。

要处理收到的数据,您可以使用此模板:https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api/blob/blob/blob/master/unicorn_binance_websocke_websocke_api_api_api_process_process_process_process_process_pystreams.py/p>

最新更新