You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用Binance WebSocket API遇WinError 10060等错误求助

问题解决指南

错误1:连接超时(WinError 10060)

这是网络层面的连接失败,可尝试以下方案修复:

  • 验证网络连通性:确认本地网络能访问Binance的WebSocket服务,可用支持WebSocket的工具测试 wss://stream.binance.com:9443/ws/btcusdt@trade
  • 关闭防火墙/杀毒软件:这类工具可能拦截WebSocket连接请求
  • 配置代理(若使用代理网络):在run_forever()中添加代理参数,示例:
    ws.run_forever(proxy_type="http", http_proxy_host="你的代理地址", http_proxy_port=代理端口)
    

错误2:on_close参数不匹配

websocket库的on_close回调要求接收3个参数:ws、close_status_code和close_msg,你的代码仅定义了1个参数,导致参数不匹配报错。修改后的on_close函数:

def on_close(ws, close_status_code, close_msg):
    print('close connection')
    # 可选:打印关闭详情
    if close_status_code or close_msg:
        print(f"关闭状态码: {close_status_code}, 关闭信息: {close_msg}")

API密钥疑问

调用Binance的公共WebSocket流(比如你使用的btcusdt@trade交易推送)不需要API密钥,只有访问私有数据(如账户资产、订单状态)时,才需要创建API密钥并完成鉴权。你当前的场景无需创建密钥。

修改后的完整代码

import websocket

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

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

def on_close(ws, close_status_code, close_msg):
    print('close connection')
    if close_status_code or close_msg:
        print(f"关闭状态码: {close_status_code}, 关闭信息: {close_msg}")

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

def on_error(ws, error):
    print('error detected')
    print(error)

websocket.enableTrace(True)
ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message, on_error=on_error)
# 若需代理,取消注释并配置参数
# ws.run_forever(proxy_type="http", http_proxy_host="127.0.0.1", http_proxy_port=1080)
ws.run_forever()

内容的提问来源于stack exchange,提问作者RandomGuy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 14:06:06