Cas*_*no 7 python binance binance-api-client
每当有订单事件(订单执行、取消等)时,我需要监听用户数据流,我希望能够监听这些事件并创建通知。
所以我得到了我的“listenKey”,我不确定它是否以正确的方式完成,但我执行了这段代码,它给了我类似listenKey的东西。
获取listenKey的代码:
def get_listen_key_by_REST(binance_api_key):
url = 'https://api.binance.com/api/v1/userDataStream'
response = requests.post(url, headers={'X-MBX-APIKEY': binance_api_key})
json = response.json()
return json['listenKey']
print(get_listen_key_by_REST(API_KEY))
Run Code Online (Sandbox Code Playgroud)
以及监听用户数据流的代码 - 这不起作用,我没有得到 json 响应。
socket = f"wss://fstream-auth.binance.com/ws/btcusdt@markPrice?listenKey=<listenKeyhere>"
def on_message(ws, message):
json_message = json.loads(message)
print(json_message)
def on_close(ws):
print(f"Connection Closed")
# restart()
def on_error(ws, error):
print(f"Error")
print(error)
ws = websocket.WebSocketApp(socket, on_message=on_message, on_close=on_close, on_error=on_error)
Run Code Online (Sandbox Code Playgroud)
我已阅读文档但无济于事。如果有人能指出我正确的方向,我将不胜感激。
您可以从此处的文档以及 Binance API 的其他有用信息创建基本的异步用户套接字连接。这是一个简单的例子:
import asyncio
from binance import AsyncClient, BinanceSocketManager
async def main():
client = await AsyncClient.create(api_key, api_secret, tld='us')
bm = BinanceSocketManager(client)
# start any sockets here, i.e a trade socket
ts = bm.user_socket()
# then start receiving messages
async with ts as tscm:
while True:
res = await tscm.recv()
print(res)
await client.close_connection()
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)