Binance API. How to switch between spot and futures for multiplex socket using python-binance

214 views Asked by At

I want to use multiplex socket for Binance future klines using python-binance.

import asyncio
from binance import AsyncClient, BinanceSocketManager
api_key_real = '____________your api key________'
secret_key_real = '____________your secret key________'

async def process_message(msg):
    print(msg)

async def start_user_data_stream(sockets_list):
    try:
        client = await AsyncClient.create(api_key_real, secret_key_real)
        bm = BinanceSocketManager(client)
        user_data_socket = bm.multiplex_socket(sockets_list)
        async with user_data_socket as stream:
            while True:
                try:
                    res = await asyncio.wait_for(stream.recv(), timeout=5.0)
                    await process_message(res)
            
                except asyncio.TimeoutError:
                    print("Stream timeout. Restarting...")
                    await client.close_connection()
                    return await start_user_data_stream(sockets_list)

async def main():
    socket_list = ['bnbusdt@klines_1h','btcusdt@klines_1h','ethusdt@klines_1h']
    await start_user_data_stream(sockets_list)

if __name__ == "__main__":
    asyncio.run(main())

The code works perfect but gives me klines for SPOT, not for FUTURES. In official binance documentation both spot and futures have the same name , like 'bnbusdt@klines_1h', but use different clients. I've tried to add /futures to the end of the name like 'bnbusdt@klines_1h/futures'. Binance accepts it but returns the same spot data. Could anyone help me to switch from spot to futures?

1

There are 1 answers

0
Airplaaaaaane On

Use futures_multiplex_socket instead of multiplex_socket.