8

I try to get data from the Binance Websocket. With python 3.9 as Interpreter it runs fine, but with 3.10 it gives me errors :(

Here is the code:

import asyncio
from binance import AsyncClient, BinanceSocketManager


async def main():
    client = await AsyncClient.create()
    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)


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

I get this error:

DeprecationWarning: There is no current event loop
  loop = asyncio.get_event_loop()

I use PyCharm as IDE.

Anyone there who can help me, please?

Max Power
  • 91
  • 1
  • 5

2 Answers2

10

This is a deprecation warning, that means the behaviour of the function get_event_loop() you called will soon change, in that it will no longer create a new event loop, but rather raise RuntimeError like get_running_loop. From the looks of it the intended way is to create a new event loop explicitly rather than implicitly.

if __name__ == "__main__":
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(main())

I am not sure if asyncio.set_event_loop(loop) is actually necessary.

Jan Christoph Terasa
  • 5,781
  • 24
  • 34
2

The recommended api for running even loop is asyncio.run (introduced in Python 3.7).

The example can be modified to adopt it:


if __name__ == "__main__":
    asyncio.run(main())
Andrew Svetlov
  • 16,730
  • 8
  • 66
  • 69
  • but if I do so in a other script I will get what I want but then I get RuntimError: Event loop is closed – Max Power Apr 07 '22 at 08:42