Binance期货市价实时更新WebSocket配置报错求助
解决Binance期货WebSocket标记价格订阅问题
问题原因
你同时使用了两种订阅逻辑导致冲突:
- 在WebSocket URL中直接指定了
btcusdt_perpetual@markPrice流路径 - 又在
on_open回调里发送了SUBSCRIBE订阅指令
Binance服务器因此返回{"id":1,"result":null},属于无效/重复订阅操作。
方案1:通用连接+订阅指令
使用通用期货WebSocket地址,保留订阅指令的方式:
import websocket import json import threading import time def on_message(ws, message): data = json.loads(message) if 'data' in data: market_price = data['data']['markPrice'] print("Market Price:", market_price) def on_error(ws, error): print("Error:", error) def on_close(ws, close_status_code, close_msg): print("WebSocket closed") def on_open(ws): print("WebSocket connected") subscription_message = { "method": "SUBSCRIBE", "params": ["btcusdt_perpetual@markPrice"], "id": 1 } ws.send(json.dumps(subscription_message)) def run_websocket(): websocket.enableTrace(True) ws = websocket.WebSocketApp( "wss://fstream.binance.com/ws", on_message=on_message, on_error=on_error, on_close=on_close ) ws.on_open = on_open ws.run_forever() if __name__ == "__main__": websocket_thread = threading.Thread(target=run_websocket) websocket_thread.start() while True: time.sleep(1)
方案2:直接连接指定流(无需订阅指令)
删除on_open中的订阅发送逻辑,直接使用带流路径的URL,注意数据结构无外层data字段:
import websocket import json import threading import time def on_message(ws, message): data = json.loads(message) market_price = data['markPrice'] print("Market Price:", market_price) def on_error(ws, error): print("Error:", error) def on_close(ws, close_status_code, close_msg): print("WebSocket closed") def on_open(ws): print("WebSocket connected") def run_websocket(): websocket.enableTrace(True) ws = websocket.WebSocketApp( "wss://fstream.binance.com/ws/btcusdt_perpetual@markPrice", on_message=on_message, on_error=on_error, on_close=on_close ) ws.on_open = on_open ws.run_forever() if __name__ == "__main__": websocket_thread = threading.Thread(target=run_websocket) websocket_thread.start() while True: time.sleep(1)
关键提示
- 两种订阅方式二选一,不要混合使用
- 直接连接流的方式返回的是原始标记价格对象,无需解析外层
data字段
内容的提问来源于stack exchange,提问作者user1246950
相关产品推荐
相关产品推荐

