0

我正在尝试连接到 Binance websocket 流。按照他们的文档,我使用以下代码建立连接:

from websocket import create_connection

ws = create_connection('wss://fstream.binance.com/')

但是,在运行它时,我收到以下错误:

WebSocketBadStatusException: Handshake status 400 Bad Request

我在网上找不到有关此错误的任何信息。

有谁知道如何解决这一问题?

4

4 回答 4

5

这一点在 Binance API-Docs 中有些不清楚。

期货的基本网址是:

  • wss://fstream.binance.com
  • wss://fstream3.binance.com

但是,如果您只是连接到这些基本 url,就会得到上述异常。您应该补充 url-strings 到

  • wss://fstream.binance.com/ws
  • wss://fstream3.binance.com/ws

这对于现货市场和所有其他 websocket 都是一样的。总是在最后加上一个“/ws”。

您也可以使用 connection-url 开始订阅,然后它看起来像这个现货市场示例:

  • wss://stream.binance.com:9443/ws/btcusdt@aggTrade

(但我认为仅使用“/ws”连接,然后按照文档中对流的解释进行实时订阅/取消订阅是更好的方法。)

于 2020-09-06T06:49:21.193 回答
3

我得说我花了很长时间才找到解决方案,但它就在这里。

应编辑 Binance API 文档,因为它缺少 fstream.binance.com 的端口

端口是 443。

所以你应该使用

“fstream.binance.com:443”而不是

“fstream.binance.com”。

希望能帮助到你。(地狱是的,它确实如此!)

于 2021-10-08T01:37:58.483 回答
0

您可以安装 python-binance 并使用 BinanceSocketManager

python -m pip 安装 python-binance

使用我在这里找到的以下代码

import time
from binance.client import Client # Import the Binance Client
from binance.websockets import BinanceSocketManager # Import the Binance Socket Manager

# Although fine for tutorial purposes, your API Keys should never be placed directly in the script like below. 
# You should use a config file (cfg or yaml) to store them and reference when needed.
PUBLIC = '<YOUR-PUBLIC-KEY>'
SECRET = '<YOUR-SECRET-KEY>'

# Instantiate a Client 
client = Client(api_key=PUBLIC, api_secret=SECRET)

# Instantiate a BinanceSocketManager, passing in the client that you instantiated
bm = BinanceSocketManager(client)

# This is our callback function. For now, it just prints messages as they come.
def handle_message(msg):
    print(msg)

# Start trade socket with 'ETHBTC' and use handle_message to.. handle the message.
conn_key = bm.start_trade_socket('ETHBTC', handle_message)
# then start the socket manager
bm.start()

# let some data flow..
time.sleep(10)

# stop the socket manager
bm.stop_socket(conn_key)
于 2020-02-23T06:06:44.377 回答
0

您缺少 websocket 连接上的路径!

查看 binance api 文档: https ://binance-docs.github.io/apidocs/futures/en/#websocket-market-streams

python-binance 不支持 websocket 到 binance 期货端点,因此您可以使用 unicorn-binance-websocket-api 代替,这里是未来端点的示例: https ://github.com/oliver-zehentleitner/unicorn-binance-websocket -api/blob/master/example_binance_futures.py

于 2020-05-02T10:49:39.203 回答