首页 > 解决方案 > web-socket 客户端不会连接到 API

问题描述

在网上搜索了几个小时并在 Reddit 上提出了同样的问题但没有成功后,我决定注册 Stack Overflow 并在这里提出问题。

我目前正在关注一个教程以了解有关 API 的更多信息。该特定教程正在使用 Binance API 尝试每分钟收集一次有关 BTC 价格的数据(以美元计)。为此,我导入了 WebSocket-client 以保持稳定的连接并每分钟收集一次新的数据点,但是每当我运行我的代码时,什么都没有发生。控制台打印“进程以退出代码 0 完成”,而不是实际连接到服务器并收集数据。

这是我的代码:

import websocket

SOCKET = "wss://stream.binance.com:9443/ws/btcusdt@kline_1m"

def on_open(ws):
    print('connection: successful')

def on_close(ws):
    print('connection: lost')

def on_message(ws, message):
    print('message')

ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message)
ws.run_forever()

起初,我以为我安装了错误的 WebSocket 库(而不是我认为我使用的 WebSocket-client。常规的 WebSocket 库)但是,我没有。然后我认为可能是 PyCharm 有问题,所以我在 Visual Studio Code、Sublime Text、终端和 Jupyter notebook 中运行了代码,但它们都没有工作。

我的代码有什么问题吗?我尝试了无数次编辑,但到目前为止都没有奏效。

币安 API 文档:https ://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md

我正在关注的教程:https ://youtu.be/GdlFhF6gjKo?t= 1112(到 18:32 左右查看他的代码)。

附言。我是一名新程序员,刚刚完成我的第一个项目(a* 寻路算法),所以不要太苛刻:)。

标签: pythonwebsocketcryptocurrency

解决方案


假设这是普遍存在的 SSL 错误,然后执行以下操作:-

import websocket
import ssl

SOCKET = "wss://stream.binance.com:9443/ws/btcusdt@kline_1m"


def on_open(ws):
    print('connection: successful')

def on_close(ws, *args):
    print('connection: lost')

def on_message(ws, message):
    print('message')

def on_error(ws, message):
    print(message)

ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message, on_error=on_error)
ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})

推荐阅读