Skip to main content

bitvavo_api_client/
ws.rs

1//! WebSocket API client.
2//!
3//! The client pushes market data and account events into a channel.
4//! Request-response calls (for example order placement) are covered by the
5//! REST client in [`crate::rest`].
6
7use crate::ClientConfig;
8use crate::auth;
9use crate::error::{Error, Result};
10use crate::types::*;
11use futures::{SinkExt, StreamExt};
12use serde_json::json;
13use std::sync::Arc;
14use tokio::sync::mpsc;
15use tokio::time::timeout;
16use tokio_tungstenite::connect_async;
17use tokio_tungstenite::tungstenite::Error as TungsteniteError;
18use tokio_tungstenite::tungstenite::Message;
19
20/// Operation that caused a WebSocket connection error.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22#[non_exhaustive]
23pub enum WsConnectionOperation {
24    /// Reading a message from the server.
25    Read,
26    /// Writing a message to the server.
27    Write,
28}
29
30/// Event received from the WebSocket connection.
31#[derive(Debug, Clone)]
32#[non_exhaustive]
33pub enum WsEvent {
34    /// Authentication succeeded.
35    Authenticated,
36    /// Subscription confirmation with the active subscriptions.
37    Subscribed(serde_json::Value),
38    /// Unsubscription confirmation with the remaining subscriptions.
39    Unsubscribed(serde_json::Value),
40    /// Update on the `ticker` channel.
41    Ticker(TickerEvent),
42    /// Update on the `ticker24h` channel.
43    Ticker24h(Vec<Ticker24h>),
44    /// Update on the `candles` channel.
45    Candle(CandleEvent),
46    /// Update on the `trades` channel.
47    Trade(TradeEvent),
48    /// Order book delta on the `book` channel.
49    Book(BookEvent),
50    /// Order update on the `account` channel.
51    Order(OrderEvent),
52    /// Fill on the `account` channel.
53    Fill(FillEvent),
54    /// Response to a request sent over the socket, for example `getBook`.
55    Response {
56        action: String,
57        response: serde_json::Value,
58    },
59    /// Error message from the server.
60    Error { code: i64, message: String },
61    /// Transport or TLS error on an established connection.
62    ConnectionError {
63        operation: WsConnectionOperation,
64        error: Arc<TungsteniteError>,
65    },
66    /// The connection was closed and no further events will arrive.
67    Closed,
68    /// A message that did not match any known shape.
69    Unknown(serde_json::Value),
70}
71
72enum Command {
73    Send(String),
74    Close,
75}
76
77/// Handle to an open WebSocket connection.
78///
79/// Dropping the handle closes the connection.
80/// The connection does not reconnect on its own.
81/// Call [`WsClient::connect`] again and resubscribe when [`WsEvent::Closed`]
82/// arrives.
83pub struct WsClient {
84    cmd_tx: mpsc::UnboundedSender<Command>,
85    config: ClientConfig,
86}
87
88impl WsClient {
89    /// Opens a connection and returns the client handle and the event stream.
90    pub async fn connect(config: ClientConfig) -> Result<(Self, mpsc::UnboundedReceiver<WsEvent>)> {
91        crate::validate_transport_url(
92            &config.ws_url,
93            "WebSocket",
94            "wss",
95            "ws",
96            config.allow_insecure_transport,
97        )?;
98        let (stream, _) = timeout(config.timeout, connect_async(&config.ws_url))
99            .await
100            .map_err(|_| Error::WebSocketConnectTimeout(config.timeout))??;
101        let (mut write, mut read) = stream.split();
102        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel::<Command>();
103        let (event_tx, event_rx) = mpsc::unbounded_channel::<WsEvent>();
104
105        tokio::spawn(async move {
106            loop {
107                tokio::select! {
108                    command = cmd_rx.recv() => {
109                        let Some(command) = command else {
110                            break;
111                        };
112                        let (result, should_close) = match command {
113                            Command::Send(text) => {
114                                (write.send(Message::Text(text.into())).await, false)
115                            }
116                            Command::Close => {
117                                (write.send(Message::Close(None)).await, true)
118                            }
119                        };
120                        if let Err(error) = result {
121                            let _ = event_tx.send(WsEvent::ConnectionError {
122                                operation: WsConnectionOperation::Write,
123                                error: Arc::new(error),
124                            });
125                            break;
126                        }
127                        if should_close {
128                            break;
129                        }
130                    }
131                    message = read.next() => {
132                        match message {
133                            Some(Ok(Message::Text(text))) => {
134                                if event_tx.send(parse_event(&text)).is_err() {
135                                    break;
136                                }
137                            }
138                            Some(Ok(Message::Ping(payload))) => {
139                                if let Err(error) = write.send(Message::Pong(payload)).await {
140                                    let _ = event_tx.send(WsEvent::ConnectionError {
141                                        operation: WsConnectionOperation::Write,
142                                        error: Arc::new(error),
143                                    });
144                                    break;
145                                }
146                            }
147                            Some(Ok(Message::Close(_))) | None => break,
148                            Some(Err(error)) => {
149                                let _ = event_tx.send(WsEvent::ConnectionError {
150                                    operation: WsConnectionOperation::Read,
151                                    error: Arc::new(error),
152                                });
153                                break;
154                            }
155                            Some(Ok(_)) => {}
156                        }
157                    }
158                }
159            }
160            let _ = event_tx.send(WsEvent::Closed);
161        });
162
163        Ok((Self { cmd_tx, config }, event_rx))
164    }
165
166    /// Opens a connection with the default configuration for public channels.
167    pub async fn connect_public() -> Result<(Self, mpsc::UnboundedReceiver<WsEvent>)> {
168        Self::connect(ClientConfig::new()).await
169    }
170
171    fn send_json(&self, value: serde_json::Value) -> Result<()> {
172        self.cmd_tx
173            .send(Command::Send(value.to_string()))
174            .map_err(|_| Error::ConnectionClosed)
175    }
176
177    /// Authenticates the connection.
178    /// Required before subscribing to the `account` channel.
179    /// The server confirms with [`WsEvent::Authenticated`].
180    pub fn authenticate(&self) -> Result<()> {
181        let (key, secret) = self.config.credentials()?;
182        let timestamp = auth::timestamp_ms();
183        let signature = auth::sign(secret, timestamp, "GET", "/websocket", "");
184        self.send_json(json!({
185            "action": "authenticate",
186            "key": key,
187            "signature": signature,
188            "timestamp": timestamp,
189            "window": self.config.access_window_ms.to_string(),
190        }))
191    }
192
193    fn subscription(&self, action: &str, channel: serde_json::Value) -> Result<()> {
194        self.send_json(json!({ "action": action, "channels": [channel] }))
195    }
196
197    /// Subscribes to the `ticker` channel for the given markets.
198    pub fn subscribe_ticker(&self, markets: &[&str]) -> Result<()> {
199        self.subscription("subscribe", json!({ "name": "ticker", "markets": markets }))
200    }
201
202    /// Subscribes to the `ticker24h` channel for the given markets.
203    pub fn subscribe_ticker_24h(&self, markets: &[&str]) -> Result<()> {
204        self.subscription(
205            "subscribe",
206            json!({ "name": "ticker24h", "markets": markets }),
207        )
208    }
209
210    /// Subscribes to the `trades` channel for the given markets.
211    pub fn subscribe_trades(&self, markets: &[&str]) -> Result<()> {
212        self.subscription("subscribe", json!({ "name": "trades", "markets": markets }))
213    }
214
215    /// Subscribes to the `candles` channel for the given markets and interval.
216    pub fn subscribe_candles(&self, markets: &[&str], interval: &str) -> Result<()> {
217        self.subscription(
218            "subscribe",
219            json!({ "name": "candles", "interval": [interval], "markets": markets }),
220        )
221    }
222
223    /// Subscribes to the `book` channel for the given markets.
224    pub fn subscribe_book(&self, markets: &[&str]) -> Result<()> {
225        self.subscription("subscribe", json!({ "name": "book", "markets": markets }))
226    }
227
228    /// Subscribes to the `account` channel for the given markets.
229    /// Call [`WsClient::authenticate`] first and wait for
230    /// [`WsEvent::Authenticated`].
231    pub fn subscribe_account(&self, markets: &[&str]) -> Result<()> {
232        self.subscription(
233            "subscribe",
234            json!({ "name": "account", "markets": markets }),
235        )
236    }
237
238    /// Unsubscribes from a channel for the given markets.
239    pub fn unsubscribe(&self, channel: &str, markets: &[&str]) -> Result<()> {
240        self.subscription(
241            "unsubscribe",
242            json!({ "name": channel, "markets": markets }),
243        )
244    }
245
246    /// Requests an order book snapshot over the socket.
247    /// The server answers with [`WsEvent::Response`] where the action is `getBook`.
248    pub fn get_book(&self, market: &str) -> Result<()> {
249        self.send_json(json!({ "action": "getBook", "market": market }))
250    }
251
252    /// Closes the connection.
253    pub fn close(&self) {
254        let _ = self.cmd_tx.send(Command::Close);
255    }
256}
257
258impl Drop for WsClient {
259    fn drop(&mut self) {
260        let _ = self.cmd_tx.send(Command::Close);
261    }
262}
263
264/// Parses a raw text message into a typed event.
265fn parse_event(text: &str) -> WsEvent {
266    let value: serde_json::Value = match serde_json::from_str(text) {
267        Ok(value) => value,
268        Err(err) => {
269            return WsEvent::Error {
270                code: -1,
271                message: format!("invalid json: {err}"),
272            };
273        }
274    };
275
276    if let Some(code) = value.get("errorCode").and_then(|c| c.as_i64()) {
277        let message = value
278            .get("error")
279            .and_then(|e| e.as_str())
280            .unwrap_or_default()
281            .to_string();
282        return WsEvent::Error { code, message };
283    }
284
285    if let Some(event) = value.get("event").and_then(|e| e.as_str()) {
286        let typed = match event {
287            "authenticate" => Some(WsEvent::Authenticated),
288            "subscribed" => Some(WsEvent::Subscribed(
289                value.get("subscriptions").cloned().unwrap_or_default(),
290            )),
291            "unsubscribed" => Some(WsEvent::Unsubscribed(
292                value.get("subscriptions").cloned().unwrap_or_default(),
293            )),
294            "ticker" => serde_json::from_value(value.clone())
295                .ok()
296                .map(WsEvent::Ticker),
297            "ticker24h" => value
298                .get("data")
299                .cloned()
300                .and_then(|d| serde_json::from_value(d).ok())
301                .map(WsEvent::Ticker24h),
302            "candle" => serde_json::from_value(value.clone())
303                .ok()
304                .map(WsEvent::Candle),
305            "trade" => serde_json::from_value(value.clone())
306                .ok()
307                .map(WsEvent::Trade),
308            "book" => serde_json::from_value(value.clone())
309                .ok()
310                .map(WsEvent::Book),
311            "order" => serde_json::from_value(value.clone())
312                .ok()
313                .map(WsEvent::Order),
314            "fill" => serde_json::from_value(value.clone())
315                .ok()
316                .map(WsEvent::Fill),
317            _ => None,
318        };
319        return typed.unwrap_or(WsEvent::Unknown(value));
320    }
321
322    if let Some(action) = value.get("action").and_then(|a| a.as_str()) {
323        return WsEvent::Response {
324            action: action.to_string(),
325            response: value.get("response").cloned().unwrap_or_default(),
326        };
327    }
328
329    WsEvent::Unknown(value)
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335    use std::time::Duration;
336    use tokio::net::TcpListener;
337
338    #[tokio::test]
339    async fn connection_timeout_is_reported() {
340        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
341        let address = listener.local_addr().unwrap();
342        let server = tokio::spawn(async move {
343            let _connection = listener.accept().await.unwrap();
344            std::future::pending::<()>().await;
345        });
346        let config = ClientConfig::new()
347            .ws_url(format!("ws://{address}"))
348            .timeout(Duration::from_millis(50))
349            .danger_allow_insecure_transport(true);
350
351        let result = WsClient::connect(config).await;
352        server.abort();
353
354        assert!(matches!(result, Err(Error::WebSocketConnectTimeout(_))));
355    }
356
357    #[tokio::test]
358    async fn established_connection_error_is_reported_before_closed() {
359        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
360        let address = listener.local_addr().unwrap();
361        let server = tokio::spawn(async move {
362            let (stream, _) = listener.accept().await.unwrap();
363            let socket = tokio_tungstenite::accept_async(stream).await.unwrap();
364            drop(socket);
365        });
366        let config = ClientConfig::new()
367            .ws_url(format!("ws://{address}"))
368            .danger_allow_insecure_transport(true);
369
370        let (_client, mut events) = WsClient::connect(config).await.unwrap();
371        server.await.unwrap();
372
373        assert!(matches!(
374            events.recv().await,
375            Some(WsEvent::ConnectionError {
376                operation: WsConnectionOperation::Read,
377                ..
378            })
379        ));
380        assert!(matches!(events.recv().await, Some(WsEvent::Closed)));
381    }
382
383    #[test]
384    fn parse_ticker_event() {
385        let text = r#"{"event":"ticker","market":"BTC-EUR","bestBid":"9156.8","bestAsk":"9157.9","lastPrice":"9157.3"}"#;
386        match parse_event(text) {
387            WsEvent::Ticker(ticker) => {
388                assert_eq!(ticker.market, "BTC-EUR");
389                assert_eq!(ticker.best_bid.as_deref(), Some("9156.8"));
390            }
391            other => panic!("unexpected event: {other:?}"),
392        }
393    }
394
395    #[test]
396    fn parse_error_event() {
397        let text = r#"{"errorCode":105,"error":"rate limit exceeded"}"#;
398        match parse_event(text) {
399            WsEvent::Error { code, message } => {
400                assert_eq!(code, 105);
401                assert_eq!(message, "rate limit exceeded");
402            }
403            other => panic!("unexpected event: {other:?}"),
404        }
405    }
406
407    #[test]
408    fn parse_book_response() {
409        let text =
410            r#"{"action":"getBook","response":{"market":"BTC-EUR","nonce":1,"bids":[],"asks":[]}}"#;
411        match parse_event(text) {
412            WsEvent::Response { action, response } => {
413                assert_eq!(action, "getBook");
414                assert_eq!(response["market"], "BTC-EUR");
415            }
416            other => panic!("unexpected event: {other:?}"),
417        }
418    }
419
420    mod fuzz {
421        use super::*;
422        use crate::tests::arb_json;
423        use proptest::prelude::*;
424
425        proptest! {
426            #[test]
427            fn parse_event_never_panics_on_arbitrary_text(text in "\\PC*") {
428                let _ = parse_event(&text);
429            }
430
431            #[test]
432            fn parse_event_never_panics_on_arbitrary_json(value in arb_json()) {
433                let _ = parse_event(&value.to_string());
434            }
435
436            #[test]
437            fn parse_event_never_panics_on_known_events_with_arbitrary_payload(
438                event in prop_oneof![
439                    Just("authenticate"),
440                    Just("subscribed"),
441                    Just("unsubscribed"),
442                    Just("ticker"),
443                    Just("ticker24h"),
444                    Just("candle"),
445                    Just("trade"),
446                    Just("book"),
447                    Just("order"),
448                    Just("fill"),
449                ],
450                payload in arb_json(),
451            ) {
452                let mut object = serde_json::Map::new();
453                object.insert("event".to_string(), serde_json::Value::from(event));
454                object.insert("data".to_string(), payload.clone());
455                if let serde_json::Value::Object(map) = &payload {
456                    for (key, value) in map {
457                        object.insert(key.clone(), value.clone());
458                    }
459                }
460                let _ = parse_event(&serde_json::Value::Object(object).to_string());
461            }
462        }
463    }
464
465    #[test]
466    fn parse_candle_event() {
467        let text = r#"{"event":"candle","market":"BTC-EUR","interval":"1h","candle":[[1538784000000,"4999","5012","4999","5012","0.45"]]}"#;
468        match parse_event(text) {
469            WsEvent::Candle(candle) => {
470                assert_eq!(candle.market, "BTC-EUR");
471                assert_eq!(candle.candle.len(), 1);
472                assert_eq!(candle.candle[0].close, "5012");
473            }
474            other => panic!("unexpected event: {other:?}"),
475        }
476    }
477}