Les_Grosman
Les_Grosman

Reputation: 57

Get data from Binance in Python

I am trying to use BinanceSocketManager from https://python-binance.readthedocs.io/en/latest/websockets.html and do not understand what I'm doing wrong?

import asyncio
from binance import AsyncClient, BinanceSocketManager
from setting import API_KEY, SECRET_KEY



async def main():
    client = await AsyncClient.create(API_KEY, SECRET_KEY)
    bm = BinanceSocketManager(client)
    # start any sockets here, i.e a trade socket
    ts = bm.trade_socket('BNBBTC')
    # 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())

and get this error

TypeError: As of 3.10, the *loop* parameter was removed from Queue() since it is no longer necessary
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000020624729F60>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x000002062482B340>, 287815.875)]']
connector: <aiohttp.connector.TCPConnector object at 0x000002062472A0B0>

I understand that I have two issues, with Python 3.10 and with the closing session. But even VSCode highlight

  await client.close_connection()

as "This code is unreachable". Please help to fix this code. Thnx.

Upvotes: 2

Views: 1364

Answers (2)

Stephen Sanwo
Stephen Sanwo

Reputation: 123

You are getting the error because of an incompatibility with python 3.10

TypeError: As of 3.10, the *loop* parameter was removed from Queue() since it is no longer necessary

Downgrade to python3.8 and try again

Upvotes: 0

Abdelaziz IMGHARNE
Abdelaziz IMGHARNE

Reputation: 41

You can use websocket-client package on python and this snippet of code

def on_open(ws):
    print('WS binance opened !!')

def on_message3_binance(ws, message):
    tokens = json.loads(message)
    

def on_error_binance(ws, error):
    print(error)

def on_close_binance(ws, close_status_code, close_msg):
    print("### closed  ###")
    


socket = f'wss://stream.binance.com:9443/ws/!ticker@arr'
ws = websocket.WebSocketApp(socket,on_open=on_open, on_message=on_message3_binance, on_error=on_error_binance,
                            on_close=on_close_binance)
ws.run_forever()

The was URL used in this example is for getting prices, you can change it to whatever URL available in WS binance docs

Upvotes: 1

Related Questions