Async function working in .ipynb not working in .py

57 Views Asked by At

so i am trying to build a script which streams BTC data using Binance's API, similar to this. The issue however is that, when testing in an .ipynb cell, the following code works perfectly:

import asyncio
import nest_asyncio

from binance.client import Client
from binance import BinanceSocketManager

nest_asyncio.apply()

async def main():
    client = Client()
    
    bsm = BinanceSocketManager(client)

    socket = bsm.trade_socket('BTCUSDT')

    async with socket as ts:
        while True:
            print('before await')
            msg = await ts.recv()
            print(msg)

# ---

# loop = asyncio.new_event_loop()
# loop.run_until_complete(main())
asyncio.run(main())

However, when i place this code into a .py file, and try executing it, i can only reach the first print('before await') instruction, and no data is shown.

I am developing inside a .devcontainer for both the .ipynb file and the .py file, and both have the same Python and library versions installed.

I have tried using different instructions, such as running the async function with

loop = asyncio.new_event_loop()
loop.run_until_complete(main())

# instead of 
asyncio.run(main())

However in both cases it works perfectly fine in the .ipynb file but not in the .py one.

I would greatly appreciate any help, thanks! :)

1

There are 1 best solutions below

1
Milan On

Works like a charm for me on Windows 10.

Copied your code, installed the modules.

Using python virtual environment.

python 3.12.1
python-binance===1.0.19
nest_asyncio===1.5.8
def async_test():
    import asyncio
    import nest_asyncio

    from binance.client import Client
    from binance import BinanceSocketManager

    nest_asyncio.apply()

    async def main():
        client = Client()

        bsm = BinanceSocketManager(client)

        socket = bsm.trade_socket('BTCUSDT')

        async with socket as ts:
            while True:
                print('before await')
                msg = await ts.recv()
                print(msg)

    # ---

    # loop = asyncio.new_event_loop()
    # loop.run_until_complete(main())
    asyncio.run(main())

if __name__ == '__main__':
    async_test()

The output until CTRL-C

before await
{'e': 'trade', 'E': 1704466694470, 's': 'BTCUSDT', 't': 3353984451, 'p': '43563.11000000', 'q': '0.00795000', 'b': 24098103240, 'a': 24098103350, 'T': 1704466694469, 'm': True, 'M': True}

before await
{'e': 'trade', 'E': 1704466694733, 's': 'BTCUSDT', 't': 3353984452, 'p': '43563.12000000', 'q': '0.00134000', 'b': 24098103375, 'a': 24098103219, 'T': 1704466694732, 'm': False, 'M': True}

...