digdigdig3 0.3.4

Unified async Rust API for 47 exchange connectors (REST + WebSocket). The core layer — pure ExchangeHub + connectors. Higher-level builder, persistence, replay, OB tracker live in `digdigdig3-station`.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! # Finnhub WebSocket Implementation
//!
//! WebSocket connector for Finnhub real-time data.
//!
//! ## Endpoint
//! `wss://ws.finnhub.io?token=API_KEY`
//!
//! ## Channels
//! | Channel | Subscribe type | Description |
//! |---------|---------------|-------------|
//! | Trades | `"subscribe"` | Real-time trade executions per symbol |
//! | News | `"subscribe-news"` | Company news stream |
//! | Press Releases | `"subscribe-pr"` | Press release stream |
//!
//! ## Protocol
//! Subscribe: `{"type": "subscribe", "symbol": "AAPL"}`
//! Unsubscribe: `{"type": "unsubscribe", "symbol": "AAPL"}`
//! Receive: `{"type": "trade", "data": [...], "s": "AAPL"}`
//!
//! ## Limitations
//! - 1 WebSocket connection per API key
//! - Free tier: 50 WebSocket symbols max

use std::sync::Arc;

use futures_util::{StreamExt, SinkExt};
use serde_json::{json, Value};
use tokio::sync::{broadcast, Mutex};
use tokio_tungstenite::{connect_async, tungstenite::Message, WebSocketStream, MaybeTlsStream};

use crate::core::{
    Credentials,
    ExchangeError, ExchangeResult,
    ConnectionStatus, StreamEvent,
};

use super::endpoints::FinnhubUrls;
use super::auth::FinnhubAuth;
use super::parser::FinnhubParser;

type WsStream = WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>;

// ═══════════════════════════════════════════════════════════════════════════════
// CHANNEL DEFINITIONS
// ═══════════════════════════════════════════════════════════════════════════════

/// Finnhub WebSocket channel descriptor.
///
/// Each variant describes a single subscription action.
/// Finnhub uses per-symbol granularity (no wildcard).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FinnhubChannel {
    /// Real-time trade executions (`"subscribe"` / `"unsubscribe"`).
    Trades(String),
    /// Company news stream (`"subscribe-news"` / `"unsubscribe-news"`).
    News(String),
    /// Press release stream (`"subscribe-pr"` / `"unsubscribe-pr"`).
    PressReleases(String),
}

impl FinnhubChannel {
    /// Return the `type` value used in a subscribe message.
    pub fn subscribe_type(&self) -> &'static str {
        match self {
            FinnhubChannel::Trades(_) => "subscribe",
            FinnhubChannel::News(_) => "subscribe-news",
            FinnhubChannel::PressReleases(_) => "subscribe-pr",
        }
    }

    /// Return the `type` value used in an unsubscribe message.
    pub fn unsubscribe_type(&self) -> &'static str {
        match self {
            FinnhubChannel::Trades(_) => "unsubscribe",
            FinnhubChannel::News(_) => "unsubscribe-news",
            FinnhubChannel::PressReleases(_) => "unsubscribe-pr",
        }
    }

    /// Return the symbol associated with this channel.
    pub fn symbol(&self) -> &str {
        match self {
            FinnhubChannel::Trades(s)
            | FinnhubChannel::News(s)
            | FinnhubChannel::PressReleases(s) => s.as_str(),
        }
    }

    /// Build the subscribe JSON message for this channel.
    pub fn subscribe_message(&self) -> serde_json::Value {
        serde_json::json!({
            "type": self.subscribe_type(),
            "symbol": self.symbol().to_uppercase()
        })
    }

    /// Build the unsubscribe JSON message for this channel.
    pub fn unsubscribe_message(&self) -> serde_json::Value {
        serde_json::json!({
            "type": self.unsubscribe_type(),
            "symbol": self.symbol().to_uppercase()
        })
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// WEBSOCKET CONNECTOR
// ═══════════════════════════════════════════════════════════════════════════════

/// Finnhub WebSocket connector
pub struct FinnhubWebSocket {
    /// Authentication
    auth: FinnhubAuth,
    /// URLs
    urls: FinnhubUrls,
    /// WebSocket stream
    ws_stream: Arc<Mutex<Option<WsStream>>>,
    /// Event broadcast channel
    event_tx: broadcast::Sender<StreamEvent>,
    /// Connection status
    status: Arc<Mutex<ConnectionStatus>>,
}

impl FinnhubWebSocket {
    /// Create new WebSocket connector
    pub async fn new(credentials: Credentials) -> ExchangeResult<Self> {
        let auth = FinnhubAuth::new(&credentials)?;
        let urls = FinnhubUrls::MAINNET;

        // Create broadcast channel for events
        let (event_tx, _) = broadcast::channel(1000);

        Ok(Self {
            auth,
            urls,
            ws_stream: Arc::new(Mutex::new(None)),
            event_tx,
            status: Arc::new(Mutex::new(ConnectionStatus::Disconnected)),
        })
    }

    /// Connect to WebSocket
    pub async fn connect(&self) -> ExchangeResult<()> {
        // Finnhub authenticates via URL parameter
        let url = self.auth.ws_url_with_auth(self.urls.websocket_url());

        // Connect
        let (ws_stream, _) = connect_async(&url)
            .await
            .map_err(|e| ExchangeError::Network(format!("WebSocket connection failed: {}", e)))?;

        *self.ws_stream.lock().await = Some(ws_stream);
        *self.status.lock().await = ConnectionStatus::Connected;

        Ok(())
    }

    /// Subscribe to ticker (trade stream)
    pub async fn subscribe_ticker(&self, symbol: &str) -> ExchangeResult<()> {
        let sub_msg = json!({
            "type": "subscribe",
            "symbol": symbol.to_uppercase()
        });

        if let Some(ref mut ws) = *self.ws_stream.lock().await {
            ws.send(Message::Text(sub_msg.to_string()))
                .await
                .map_err(|e| ExchangeError::Network(format!("Subscribe failed: {}", e)))?;
        }

        Ok(())
    }

    /// Subscribe to company news
    pub async fn subscribe_news(&self, symbol: &str) -> ExchangeResult<()> {
        let sub_msg = json!({
            "type": "subscribe-news",
            "symbol": symbol.to_uppercase()
        });

        if let Some(ref mut ws) = *self.ws_stream.lock().await {
            ws.send(Message::Text(sub_msg.to_string()))
                .await
                .map_err(|e| ExchangeError::Network(format!("Subscribe news failed: {}", e)))?;
        }

        Ok(())
    }

    /// Subscribe to press releases
    pub async fn subscribe_press_releases(&self, symbol: &str) -> ExchangeResult<()> {
        let sub_msg = json!({
            "type": "subscribe-pr",
            "symbol": symbol.to_uppercase()
        });

        if let Some(ref mut ws) = *self.ws_stream.lock().await {
            ws.send(Message::Text(sub_msg.to_string()))
                .await
                .map_err(|e| ExchangeError::Network(format!("Subscribe press releases failed: {}", e)))?;
        }

        Ok(())
    }

    /// Unsubscribe from ticker
    pub async fn unsubscribe_ticker(&self, symbol: &str) -> ExchangeResult<()> {
        let unsub_msg = json!({
            "type": "unsubscribe",
            "symbol": symbol.to_uppercase()
        });

        if let Some(ref mut ws) = *self.ws_stream.lock().await {
            ws.send(Message::Text(unsub_msg.to_string()))
                .await
                .map_err(|e| ExchangeError::Network(format!("Unsubscribe failed: {}", e)))?;
        }

        Ok(())
    }

    /// Unsubscribe from news
    pub async fn unsubscribe_news(&self, symbol: &str) -> ExchangeResult<()> {
        let unsub_msg = json!({
            "type": "unsubscribe-news",
            "symbol": symbol.to_uppercase()
        });

        if let Some(ref mut ws) = *self.ws_stream.lock().await {
            ws.send(Message::Text(unsub_msg.to_string()))
                .await
                .map_err(|e| ExchangeError::Network(format!("Unsubscribe news failed: {}", e)))?;
        }

        Ok(())
    }

    /// Subscribe using a `FinnhubChannel` descriptor.
    ///
    /// This is the canonical channel-based subscription API.
    ///
    /// # Example
    /// ```ignore
    /// ws.subscribe_channel(&FinnhubChannel::Trades("AAPL".into())).await?;
    /// ws.subscribe_channel(&FinnhubChannel::News("TSLA".into())).await?;
    /// ```
    pub async fn subscribe_channel(&self, channel: &FinnhubChannel) -> ExchangeResult<()> {
        let msg = channel.subscribe_message();

        if let Some(ref mut ws) = *self.ws_stream.lock().await {
            ws.send(Message::Text(msg.to_string()))
                .await
                .map_err(|e| ExchangeError::Network(format!("Subscribe channel failed: {}", e)))?;
        }

        Ok(())
    }

    /// Unsubscribe using a `FinnhubChannel` descriptor.
    pub async fn unsubscribe_channel(&self, channel: &FinnhubChannel) -> ExchangeResult<()> {
        let msg = channel.unsubscribe_message();

        if let Some(ref mut ws) = *self.ws_stream.lock().await {
            ws.send(Message::Text(msg.to_string()))
                .await
                .map_err(|e| {
                    ExchangeError::Network(format!("Unsubscribe channel failed: {}", e))
                })?;
        }

        Ok(())
    }

    /// Subscribe to multiple channels in a single batch.
    ///
    /// Each channel results in a separate WebSocket message (Finnhub does not
    /// support batched subscriptions in a single frame).
    pub async fn subscribe_channels(&self, channels: &[FinnhubChannel]) -> ExchangeResult<()> {
        for channel in channels {
            self.subscribe_channel(channel).await?;
        }
        Ok(())
    }

    /// Unsubscribe from multiple channels.
    pub async fn unsubscribe_channels(&self, channels: &[FinnhubChannel]) -> ExchangeResult<()> {
        for channel in channels {
            self.unsubscribe_channel(channel).await?;
        }
        Ok(())
    }

    /// Disconnect from WebSocket
    pub async fn disconnect(&self) -> ExchangeResult<()> {
        if let Some(mut ws) = self.ws_stream.lock().await.take() {
            ws.close(None)
                .await
                .map_err(|e| ExchangeError::Network(format!("Disconnect failed: {}", e)))?;
        }

        *self.status.lock().await = ConnectionStatus::Disconnected;
        Ok(())
    }

    /// Get connection status
    pub async fn status(&self) -> ConnectionStatus {
        *self.status.lock().await
    }

    /// Get event stream receiver
    pub fn event_stream(&self) -> broadcast::Receiver<StreamEvent> {
        self.event_tx.subscribe()
    }

    /// Start receiving messages (run in background task)
    pub async fn start_receiving(&self) -> ExchangeResult<()> {
        loop {
            let msg = {
                let mut ws_guard = self.ws_stream.lock().await;
                if let Some(ref mut ws) = *ws_guard {
                    match ws.next().await {
                        Some(Ok(msg)) => msg,
                        Some(Err(e)) => {
                            *self.status.lock().await = ConnectionStatus::Disconnected;
                            return Err(ExchangeError::Network(format!("WebSocket error: {}", e)));
                        }
                        None => {
                            *self.status.lock().await = ConnectionStatus::Disconnected;
                            return Err(ExchangeError::Network("WebSocket closed".to_string()));
                        }
                    }
                } else {
                    return Err(ExchangeError::Network("WebSocket not connected".to_string()));
                }
            };

            match msg {
                Message::Text(text) => {
                    // Parse message
                    match serde_json::from_str::<Value>(&text) {
                        Ok(json_msg) => {
                            match FinnhubParser::parse_ws_message(&json_msg) {
                                Ok(events) => {
                                    for event in events {
                                        // Broadcast event (ignore send errors if no receivers)
                                        let _ = self.event_tx.send(event);
                                    }
                                }
                                Err(e) => {
                                    // Log parse error but continue
                                    eprintln!("Failed to parse WebSocket message: {}", e);
                                }
                            }
                        }
                        Err(e) => {
                            eprintln!("Failed to parse JSON: {}", e);
                        }
                    }
                }
                Message::Ping(data) => {
                    // Respond to ping with pong
                    let mut ws_guard = self.ws_stream.lock().await;
                    if let Some(ref mut ws) = *ws_guard {
                        let _ = ws.send(Message::Pong(data)).await;
                    }
                }
                Message::Close(_) => {
                    *self.status.lock().await = ConnectionStatus::Disconnected;
                    return Ok(());
                }
                _ => {}
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_websocket_creation() {
        let credentials = Credentials::new("test_api_key", "");
        let ws = FinnhubWebSocket::new(credentials).await;
        assert!(ws.is_ok());
    }

    #[test]
    fn test_subscribe_message_format() {
        let msg = json!({
            "type": "subscribe",
            "symbol": "AAPL"
        });

        assert_eq!(msg["type"], "subscribe");
        assert_eq!(msg["symbol"], "AAPL");
    }

    #[test]
    fn test_unsubscribe_message_format() {
        let msg = json!({
            "type": "unsubscribe",
            "symbol": "AAPL"
        });

        assert_eq!(msg["type"], "unsubscribe");
        assert_eq!(msg["symbol"], "AAPL");
    }

    #[test]
    fn test_channel_trades_subscribe() {
        let ch = FinnhubChannel::Trades("AAPL".into());
        let msg = ch.subscribe_message();
        assert_eq!(msg["type"], "subscribe");
        assert_eq!(msg["symbol"], "AAPL");
    }

    #[test]
    fn test_channel_trades_unsubscribe() {
        let ch = FinnhubChannel::Trades("AAPL".into());
        let msg = ch.unsubscribe_message();
        assert_eq!(msg["type"], "unsubscribe");
        assert_eq!(msg["symbol"], "AAPL");
    }

    #[test]
    fn test_channel_news_subscribe() {
        let ch = FinnhubChannel::News("TSLA".into());
        let msg = ch.subscribe_message();
        assert_eq!(msg["type"], "subscribe-news");
        assert_eq!(msg["symbol"], "TSLA");
    }

    #[test]
    fn test_channel_press_releases_subscribe() {
        let ch = FinnhubChannel::PressReleases("MSFT".into());
        let msg = ch.subscribe_message();
        assert_eq!(msg["type"], "subscribe-pr");
        assert_eq!(msg["symbol"], "MSFT");
    }

    #[test]
    fn test_channel_symbol() {
        assert_eq!(FinnhubChannel::Trades("AAPL".into()).symbol(), "AAPL");
        assert_eq!(FinnhubChannel::News("TSLA".into()).symbol(), "TSLA");
    }
}