我正在尝试连接到Binance Websocket流。 在their documentation之后,我使用下面的代码建立连接:
from websocket import create_connection
ws = create_connection('wss://fstream.binance.com/')
虽然运行它,但出现以下错误:
WebSocketBadStatusException: Handshake status 400 Bad Request
我在网上找不到有关此错误的任何信息。
有人知道如何解决此问题吗?
答案 0 :(得分:1)
这一点在Binance API文档中还不清楚。
期货的基本网址为:
但是,如果您仅连接到这些基本URL,则会遇到上述异常。 您应该将url-string补充到
对于现货市场和所有其他网络套接字都是相同的。始终在末尾加上“ / ws”。
您还可以开始订阅connection-url,然后看起来像下面的现货市场示例:
(但是我认为只连接“ / ws”,然后按照文档中的说明进行实时订阅/取消订阅流是更好的方法。)
答案 1 :(得分:0)
您可以安装python-binance并使用BinanceSocketManager
python -m pip安装python-binance
使用我发现的以下代码here
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)
答案 2 :(得分:0)
您缺少websocket connect上的路径!
看看binance api文档: https://binance-docs.github.io/apidocs/futures/en/#websocket-market-streams
python-binance不支持websocket来对期货端点进行币种化,因此您可以改用unicorn-binance-websocket-api,这是未来端点的示例: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/example_binance_futures.py