When connecting to Deribit’s WebSocket interface, you need to do the following:
- Establish a Heartbeat.
- Respond to Heartbeat messages Deribit sends you.
After connecting to the WebSocket interface, the code establishes the heartbeat by calling the “establish_heartbeat” coroutine to send the request to Deribit. When the WebSocket connection receives a “heartbeat” from Deribit, it responds by calling the “heartbeat_response” coroutine which also sends a request to Deribit.
It is always a good idea to authenticate your WebSocket connections with Deribit. You authenticate your WebSocket connection, in the example, by calling the “ws_auth” coroutine. In response to your request to authenticate, if successful, Deribit will return a “refresh_token” which you can use as a part of a subsequent “public/auth” request to refresh the connection’s authentication. You’ll notice you only need to refresh your connections authentication every so often and this is maintained by the instantiated “ws_refresh_auth” coroutine task.
Your WebSocket connection is now ready to make both unauthenticated & authenticated requests. On line 69, you’ll notice we request to subscribe to “trades.BTC-PERPETUAL.raw” WebSocket channel. This channel will send you every trade which occurs for the “BTC-PERPETUAL” instrument on Deribit. You can subscribe to a number of WebSocket channels and then send a payload with a “method”: “public/unsubscribe” key value to unsubscribe.
WebSocket messages will flow to you in real-time without having to make subsequent requests for this data. This is different from the RESToverHTTP interface where you make [GET] or [POST] requests to Deribit.
Another cool thing to note is that you can also make requests using your WebSocket connection in a slightly faster manner than using the RESToverHTTP interface given you have already authenticated the connection. Using your WebSocket connection, you could submit a BUY LIMIT order via requesting a payload like the “/private/buy” example in the API docs.