Kucoin / kucoin-python-sdk

MIT License
45 stars 15 forks source link

ConnectWebsocket _run() never completes #13

Closed nkhalsa closed 1 month ago

nkhalsa commented 3 years ago

I'm using python 3.8.6. Upon connecting to the websocket and subscribing, I am getting no output. It seems the problem is websocket.py. I added some print statements to ConnectWebsocket's _run() to demonstrate the issue:


async def _run(self):
        keep_alive = True
        self._last_ping = time.time()  # record last ping
        self._ws_details = None
        self._ws_details = self._client.get_ws_token(self._private)
        print('this prints')
        async with websockets.connect(self.get_ws_endpoint(), ssl=self.get_ws_encryption()) as socket:
            print('this never prints')
            self._socket = socket
            self._reconnect_num = 0
            try:
                while keep_alive:
                    if time.time() - self._last_ping > self.get_ws_pingtimeout():
                        await self.send_ping()
                    try:
                        _msg = await asyncio.wait_for(self._socket.recv(), timeout=self.get_ws_pingtimeout())
                    except asyncio.TimeoutError:
                        await self.send_ping()
                    except asyncio.CancelledError:
                        await self._socket.ping()
                    else:
                        try:
                            msg = json.loads(_msg)
                        except ValueError:
                            pass
                        else:
                            await self._callback(msg)
            except websockets.ConnectionClosed:
                print('this never prints')
                await self._reconnect()
            except Exception as e:
                print('this never prints')
                await self._reconnect()

As far as I know, self.get_ws_endpoint(), ssl=self.get_ws_encryption() both have valid return values. get_ws_endpoint() returns a URL and get_ws_encryption() returns a Boolean. I didn't check the URL though to make sure it's good.

Does anyone have a solution? Currently, I cannot receive any messages from the socket.

Thank you for the help!!

nkhalsa commented 3 years ago

I just copied your source code in this repo and it worked, so ended up just refactoring my code to use it...probably had to do with the loop I was running it inside of

1bazinga25 commented 3 years ago

Yes, for sure it's synchronous with the loop, you could run with the example code.

nkhalsa commented 3 years ago

Another similar error, after pretty much copying and pasting the documentation code:

import config
from colorama import init, Fore, Style
import asyncio
from kucoin.client import WsToken
from kucoin.ws_client import KucoinWsClient

class KucoinListener():
    def __init__(self, private_subscriptions, public_subscriptions, callback):
        self.private_subscriptions = private_subscriptions
        self.public_subscriptions = public_subscriptions
        self.callback=callback

    async def start_listening(self):
        async def deal_msg(msg):
            try:
                self.callback(msg)
                print('done with callback')
            except Exception as e:
                os.system('say there was an exception')
                print(Fore.RED + str(e) + Style.RESET_ALL)

        client = WsToken(config.kucoin['key'], config.kucoin['secret'], config.kucoin['passphrase'], is_sandbox=False)#, url='')

        pub_client = await KucoinWsClient.create(None, client, deal_msg, private=False)
        priv_client = await KucoinWsClient.create(None, client, deal_msg, private=True)

        for sub in self.private_subscriptions:
            await priv_client.subscribe(sub)
        for sub in self.public_subscriptions:
            await pub_client.subscribe(sub)

        while True:
            await asyncio.sleep(60, loop=self.loop)

    def run(self):
        self.loop = asyncio.get_event_loop()
        self.loop.run_until_complete(self.start_listening())

It's definitely a problem with my callback function but there's no output to tell me what the problem is, and no exception is thrown. I'm 100% sure it's a problem with my callback function, as it works indefinitely with a simple print statement instead of the callback, which causes it to stop after a while. Yet the final output is (before it stays like this without returning):

this runs
onupdate check 2
True
onupdate check 4
done with callback

Do you have any idea how the callback can finish and still cause this?

Thanks for the help!!

nkhalsa commented 3 years ago

I think it's something server-side that my code triggers. It turns out, it's still getting pongs after it finishes the messages. It just isn't getting any other messages. Sometimes the connection is also closed and it fails to reconnect.

Perhaps there is a rate limit I am somehow exceeding? If so, it would be nice to have a message saying so! Any other ideas? Thanks again

ISAAC-XXYYZZ commented 1 month ago

Since this issue has had no updates for a long time, we will now close it. Please try updating to the latest version of the SDK and modify your code to try again. If you encounter any issues, feel free to provide feedback.