How to work with an API with WebSockets (example Kraken)?

  javascript, kraken.com, node.js, websocket

I am trying to update a REST API to API with Websockets and I don’t understand how to handle the responses.

With REST API and awaits is easily identify request with response.

But in WebSocket it seems that all the communication is treated in onmessage, mixed and I don’t see how to identify it.

How to identify a concrete answer without id in the request?

For example, I connect to a WebSockets API, in this case Kraken (exchange) and once the connection is open, I add an order:

ws.send(JSON.stringify({
                'event' : 'addOrder',
                'ordertype' : 'limit',
                'pair' : 'DAI/USD',
                'price' : '0.005',
                'token' : this.wsToken,
                'type' : 'buy',
                'volume' : '6',
            }));

And the response obtained in onmessage can be:

{"descr":"buy 6.00000000 DAIUSD @ limit 0.00500","event":"addOrderStatus","status":"ok","txid":"ABABC-ABABC-ABABC"}

The request has no Id, if I launch 10 requests for addOrder and other types I cannot link the request with the response.

What is the logic to work with an API in this way?

Source: Ask Javascript Questions

LEAVE A COMMENT