sammchardy / python-binance

Binance Exchange API python implementation for automated trading
https://python-binance.readthedocs.io/en/latest/
MIT License
6.02k stars 2.2k forks source link

feature/asyncio: Unclosed client session #421

Closed sapph1re closed 4 years ago

sapph1re commented 5 years ago

Describe the bug I simply instantiate AsyncClient like demonstrated in readme, and its usage is always followed with an "Unclosed client session" error.

To Reproduce

import asyncio
from binance import AsyncClient

async def main():
    client = await AsyncClient.create()
    print(await client.get_server_time())

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

Output:

Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000029492976A58>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x000002949290DE88>, 3463537.656)]']
connector: <aiohttp.connector.TCPConnector object at 0x0000029492976AC8>
{'serverTime': 1566977521778}

Expected behavior Expected not to have errors. Should I somehow gracefully close/destroy AsyncClient?

Environment (please complete the following information):

zenflip commented 5 years ago

Yep same here. There's no AsyncClient and also the DepthCacheManager and BinanceSocketManager are elsewhere.

from binance.depthcache import DepthCacheManager
from binance.websockets import BinanceSocketManager

...perhaps?

sapph1re commented 5 years ago

Apparently, it's an error of aiohttp, which is used here. Its ClientSession is recommended to be run in a context manager: https://stackoverflow.com/questions/46112848/python-package-aiohttp-has-a-warning-message-unclosed-client-session

Another way is closing the aiohttp.ClientSession explicitly: await self.session.close() but I'm not sure where exactly it would be good to do it. Make a special class method for that, like stop()? What would be the best approach?

matze19999 commented 4 years ago

@sapph1re did you find a fix / workaround for this?

sapph1re commented 4 years ago

@sapph1re did you find a fix / workaround for this?

sorry, my previous (deleted) answer was misleading. I made a stop() method in the exchange wrapper class, which explicitly calls await self._client.session.close() where self._client is the AsyncClient instance.

gorkem2020 commented 2 years ago

I'm still getting this error. I guess it has not been fixed.

Gorgosaurus commented 2 years ago

I still get the error

difrankode commented 1 year ago

You need close conection

async def main():
    client = await AsyncClient.create()
    print(await client.get_server_time())
    # all code here
    await client.close_connection() # <--- you need this line. insert it in the end of main function