Two websockets with BinanceSocketManager

Question:

I’m trying to open two web sockets – depth book and user socket.

Here’s my code:

async def sockets(client):
    bm = BinanceSocketManager(client)
    ds = bm.depth_socket("BTCUSDT", depth=BinanceSocketManager.WEBSOCKET_DEPTH_5)
    
    print("Started...")

    async with ds as depth_socket:
        while True:
            res = await depth_socket.recv()
            print(res)

    await client.close_connection()

I need bm.user_socket() socket to be opened as well at the same time.

How can I have two of them opened at the same time with BinanceSocketManager?

Asked By: Cassano

||

Answers:

I’ve amended your code because it wasn’t working. My feeling is that you don’t have a good understanding of how asyncio works. I would recommend you read this tutorial on asyncio event loops.

What you need is to run multiple coroutines using asyncio‘s ensure_future module which will enable you to schedule tasks and run them asynchronously.

What we are doing in the code below is we are creating separate tasks for depth_socket and user_socket which loop indefinately but also run asynchronously so they can return data whenever it is sent by the server without waiting for the other task to finish.

I think the problem you were having is that you were trying to put both depth_socket and user_socket in the same async coroutine so looping indefinately with depth_socket meant that you could never loop through the user_socket concurrently.

There’s a section on running multiple coroutines in the tutorial link I have given you above which helped me a lot understand how this works.

Unfortunately I can’t seem to connect to the binance testnet so I haven’t been able to test if the user_socket task actually works when a user event occurs but it should as it’s not throwing an error when connected to livenet. Let me know if you are getting trade events.

You will need to input your api key and secret of course.

import asyncio
from binance import AsyncClient, BinanceSocketManager

api_key = '...'
api_secret = '...'

async def task_depth_socket():
    client = await AsyncClient.create(api_key, api_secret)
    bm = BinanceSocketManager(client)
    ds = bm.depth_socket("BTCUSDT", depth=BinanceSocketManager.WEBSOCKET_DEPTH_5)

    async with ds as depth_socket:
        while True:
            res = await depth_socket.recv()
            print(res)
    
async def task_user_socket():
    client = await AsyncClient.create(api_key, api_secret)
    bm = BinanceSocketManager(client)
    us = bm.user_socket()
    
    async with us as user_socket:
        while True:
            res = await user_socket.recv()
            print(res)    
 
loop = asyncio.get_event_loop()

try:
    asyncio.ensure_future(task_depth_socket())
    asyncio.ensure_future(task_user_socket())
    loop.run_forever()

except KeyboardInterrupt:
    pass
finally:
    print("Closing Loop")
    loop.close()
Answered By: Alex B

im new in websockets and i dont understand python doc. my issue is to get the order book completely or, at least the same 1000 data that API returns via websocket but i dont understand Binance Doc about it… how do i get the snapshot , jus with normal API ? and then…how do i pass it to be updated?
Thanks

Answered By: trapala85
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.