Kucoin / kucoin-python-sdk

MIT License
40 stars 11 forks source link

Class implementing websocket feeds ran in separate threads - Error with conda batch #92

Open kheil117 opened 1 year ago

kheil117 commented 1 year ago

Hi all,

I am implementing a class with the possibility to start various websockets in different threads to retrieve market data/orders/balances and update class attributes with websocket inputs. The below works fine in spyder, however when I set my script to run via a conda batch on the same environment it fails with the following errors over and over, do you have any idea why ?

Python 3.9.13 | Spyder 5.3.3 | Spyder kernel 2.3.3 | websocket 0.2.1 | nest-asyncio 1.5.6 | kucoin-python 1.0.11

<Task finished name='Task-4' coro=<ConnectWebsocket._run() done,> defined at > path\lib\site-packages\kucoin\websocket\websocket.py:33>> exception=RuntimeError("can't register atexit after shutdown")> got an> exception can't register atexit after shutdown pending <Task pending> name='Task-3' coro=<ConnectWebsocket._recover_topic_req_msg() running> at> path\lib\site-packages\kucoin\websocket\websocket.py:127>> wait_for=> cancel ok.> _reconnect over.

<Task finished name='Task-7' coro=<ConnectWebsocket._run() done, defined at>> path\lib\site-packages\kucoin\websocket\websocket. py:33>> exception=RuntimeError("can't register atexit after shutdown")> got an> exception can't register atexit after shutdown pending name='Task-6' coro=<ConnectWebsocket._recover_topic_req_msg() running> at path\lib\site-packages\kucoin\websocket\websocket.py:127>> wait_for=> cancel ok.> _reconnect over.

import asyncio
import nest_asyncio
nest_asyncio.apply()
from kucoin.client import WsToken
from kucoin.ws_client import KucoinWsClient
from threading import Thread

class class_X():
    def __init__(self):
        self.msg= ""

    async def main(self):
        async def book_msg(msg):
                self.msg = msg
        client = WsToken()
        ws_client = await KucoinWsClient.create(None, client, book_msg, private=False)
        await ws_client.subscribe(f'/market/level2:BTC-USDT')
        while True:
            await asyncio.sleep(20)

    def launch(self):
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            loop.run_until_complete(self.main())

instance = class_X()
t = Thread(target=instance.launch)
t.start()    

Batch


call path\anaconda3\Scripts\activate myENV
python "path1\main.py"
conda deactivate
quantokenizer commented 7 months ago

You need to add a t.join() after t.start(). Have a look here: https://stackoverflow.com/questions/65467329/server-in-a-thread-python3-9-0aiohttp-runtimeerror-cant-register-atexit-a