altangent / ccxws

WebSocket client for 38 cryptocurrency exchanges
MIT License
619 stars 187 forks source link

All exchanges: Unsubscribe is not working #224

Closed MidoMiddle closed 3 years ago

MidoMiddle commented 3 years ago

For example on Kraken when I catch error 429 I need to unsubscribe from socket. I invoke unsubscribe methods and nothing gone change. After 15 sec I have receive 'connecting' event.

You can try it yourself

In index.js call startApp() with all pairs and small timeout, after few seconds exchange give error 429 After this I starts app with one pair

https://codesandbox.io/s/unsubscribe-error-wzj3j

Result in console

MidoMiddle commented 3 years ago

If you subscribe to a socket and the exchange issues an error, for example 429, then the connection does not occur and this._wss.isConnected = false. Which does not allow you to unsubscribe. I propose: if we get error 429 close the connection.

ccxws/src/smart-wss.js


_attemptConnect() {
    return new Promise(resolve => {
      let wssPath = this._wssPath;
      this.emit("connecting");
      this._wss = new WebSocket(wssPath, {
        perMessageDeflate: false,
        handshakeTimeout: 15000,
      });
      this._wss.on("open", () => {
        this._connected = true;
        this.emit("open"); // deprecated
        this.emit("connected");
        resolve();
      });
      this._wss.on("close", () => this._closeCallback());
      this._wss.on("error", err => {
        this.emit("error", err);
        err.toString().includes('429') ? this.close() : null;      //  <===== add this
    });
      this._wss.on("message", msg => this.emit("message", msg));
    });
  }
bmancini55 commented 3 years ago

Hi, thanks for submitting an issue.

429 is an HTTP error, which sounds like you're instantiated a large number of clients and running into rate limits (https://www.kraken.com/features/api#api-call-rate-limit) trying to establish a socket. In general, this library is designed to have a single instantiated client per exchange.

Can you confirm what your use-case is and what is happening? Thanks!

MidoMiddle commented 3 years ago

I want to have a full and complete state of all order books. Because when I subscribe to a socket, it takes 30 minutes to wait until the book is fully loaded.

bmancini55 commented 3 years ago

So you're initiating a large number of socket connections?

MidoMiddle commented 3 years ago

Yes. All active pairs.

bmancini55 commented 3 years ago

That is outside the scope of this library. This library supports subscriptions (as many as you like in most cases) via a single instantiation of a client/socket per exchange.

429 and 502 errors are socket connection issues that are caused by instantiation many clients/sockets at once. If you need that behavior, you will have to manage connection throttling and error handling in your code.