digdigdig3 0.3.13

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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! KrakenProtocol — WsProtocol impl for Kraken WebSocket v2.
//!
//! Endpoint:      wss://ws.kraken.com/v2
//! Symbol format: BTC/USD (slash-separated, v2 uses BTC not XBT)
//! Subscribe:     {"method":"subscribe","params":{"channel":"ticker","symbol":["BTC/USD"]}}
//! Ping (JSON):   {"method":"ping"} — Kraken application-level keepalive
//! Ping interval: 30 s
//!
//! Frame routing: top-level "channel" field.
//! Control frames (method == "pong"/"subscribe"/"unsubscribe"/"heartbeat") return None
//! from extract_topic.

use std::sync::OnceLock;
use std::time::Duration;

use serde_json::{json, Value};
use url::Url;

use crate::core::rt::WsFrame;
use crate::core::traits::Credentials;
use crate::core::types::{AccountType, WebSocketError};
use crate::core::websocket::{
    KlineInterval, StreamKind, StreamSpec,
    TopicKey, TopicRegistry,
    WsProtocol,
};

use super::parser as kraken_parser;

// ─────────────────────────────────────────────────────────────────────────────
// Registry cache — Kraken is spot-only for public channels
// ─────────────────────────────────────────────────────────────────────────────

static REGISTRY: OnceLock<TopicRegistry> = OnceLock::new();

// ─────────────────────────────────────────────────────────────────────────────
// KrakenProtocol
// ─────────────────────────────────────────────────────────────────────────────

/// Declarative Kraken WS v2 protocol shim.
///
/// Public channels only. Private channels (executions, balances) require a
/// token in subscribe params — not supported in this implementation (wasm demo
/// scope is public market data only).
pub struct KrakenProtocol;

impl KrakenProtocol {
    /// Map StreamKind → Kraken v2 wire channel name.
    ///
    /// Returns None for stream kinds that have no public channel on Kraken v2.
    pub(crate) fn channel_name(kind: &StreamKind) -> Option<&'static str> {
        match kind {
            StreamKind::Ticker => Some("ticker"),
            StreamKind::Trade => Some("trade"),
            StreamKind::Orderbook | StreamKind::OrderbookDelta => Some("book"),
            StreamKind::Kline { .. } => Some("ohlc"),
            StreamKind::MarketWarning => Some("instrument"),
            _ => None,
        }
    }

    /// Format symbol as BTC/USD (Kraken v2 uses slash, not hyphen, not XBT).
    ///
    /// CRITICAL: Kraken WS v2 uses BTC, NOT XBT. Callers must pass
    /// Symbol::new("BTC", "USD") — "XBT/USD" will be rejected by the exchange.
    fn format_symbol(spec: &StreamSpec) -> Result<String, WebSocketError> {
        let resolved = spec
            .symbol
            .resolve(crate::core::types::ExchangeId::Kraken, spec.account_type)
            .map_err(|e| {
                WebSocketError::NotSupported(format!(
                    "kraken: symbol normalization failed: {}",
                    e
                ))
            })?;
        Ok(to_kraken_ws_symbol(&resolved.to_string()))
    }

    /// Build subscribe / unsubscribe frame.
    fn build_frame(op: &str, spec: &StreamSpec) -> Result<WsFrame, WebSocketError> {
        let channel = Self::channel_name(&spec.kind).ok_or_else(|| {
            WebSocketError::NotSupported(format!(
                "Kraken v2 has no public WS channel for {:?} — use REST for this data kind",
                spec.kind
            ))
        })?;

        let symbol = Self::format_symbol(spec)?;

        // Base params — symbol is always present for public channels
        let mut params = json!({
            "channel": channel,
            "symbol": [symbol],
        });

        // Channel-specific extra parameters
        match &spec.kind {
            StreamKind::Orderbook | StreamKind::OrderbookDelta => {
                let depth = spec.depth.unwrap_or(10) as u64;
                params["depth"] = json!(depth);
            }
            StreamKind::Kline { interval } => {
                let minutes = kline_interval_to_minutes(interval);
                params["interval"] = json!(minutes);
            }
            _ => {}
        }

        let frame = json!({
            "method": op,
            "params": params,
        });

        Ok(WsFrame::Text(frame.to_string()))
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// WsProtocol impl
// ─────────────────────────────────────────────────────────────────────────────

impl WsProtocol for KrakenProtocol {
    fn name(&self) -> &'static str {
        "kraken"
    }

    fn endpoint(&self, _account_type: AccountType, _testnet: bool) -> Url {
        // Kraken has no testnet for public channels.
        // Private URL (wss://ws-auth.kraken.com/v2) is not in scope for wasm demo.
        Url::parse("wss://ws.kraken.com/v2").expect("kraken ws endpoint is valid")
    }

    /// JSON application-level ping: {"method":"ping"}.
    ///
    /// Kraken v2 responds with {"method":"pong",...}.
    /// The transport also sends native WS Ping frames for RTT measurement.
    fn ping_frame(&self) -> Option<WsFrame> {
        Some(WsFrame::Text(
            r#"{"method":"ping"}"#.to_string(),
        ))
    }

    /// 30-second ping interval — matches the bespoke loop behaviour.
    fn ping_interval(&self) -> Duration {
        Duration::from_secs(30)
    }

    fn subscribe_frame(&self, spec: &StreamSpec) -> Result<WsFrame, WebSocketError> {
        Self::build_frame("subscribe", spec)
    }

    fn unsubscribe_frame(&self, spec: &StreamSpec) -> Result<WsFrame, WebSocketError> {
        Self::build_frame("unsubscribe", spec)
    }

    /// Kraken public channels require no authentication.
    fn auth_frame(&self, _credentials: &Credentials) -> Option<Result<WsFrame, WebSocketError>> {
        None
    }

    fn is_pong(&self, raw: &Value) -> bool {
        raw.get("method").and_then(|v| v.as_str()) == Some("pong")
    }

    fn is_subscribe_ack(&self, raw: &Value) -> bool {
        let method = raw.get("method").and_then(|v| v.as_str());
        matches!(method, Some("subscribe") | Some("unsubscribe"))
    }

    /// Extract routing topic from an incoming Kraken v2 frame.
    ///
    /// Data frames carry a top-level "channel" field.
    /// Control frames carry a top-level "method" field (pong, subscribe, heartbeat, status).
    /// Returns None for all control frames; Some(channel) for data frames.
    fn extract_topic(&self, raw: &Value) -> Option<TopicKey> {
        // Control frames have a "method" field — filter them out.
        // This covers: pong, subscribe ACK, unsubscribe ACK, heartbeat, status.
        if raw.get("method").is_some() {
            return None;
        }

        let channel = raw.get("channel").and_then(|v| v.as_str())?;

        // Filter server-side control channels that carry no market data.
        match channel {
            "heartbeat" | "status" => None,
            _ => Some(TopicKey::new(channel)),
        }
    }

    fn topic_registry(&self, _account_type: AccountType) -> &TopicRegistry {
        REGISTRY.get_or_init(build_registry)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Registry builder
// ─────────────────────────────────────────────────────────────────────────────

fn build_registry() -> TopicRegistry {
    let at = AccountType::Spot;
    TopicRegistry::builder()
        // ticker → Ticker
        .register(StreamKind::Ticker, at, "ticker", kraken_parser::parse_ws_ticker)
        // trade → Trade
        .register(StreamKind::Trade, at, "trade", kraken_parser::parse_ws_trade)
        // book → OrderbookSnapshot OR OrderbookDelta (same parser, branches on raw["type"])
        // Registered under both Orderbook and OrderbookDelta so both StreamKind subscriptions
        // are satisfied. The parser returns the appropriate variant per frame.
        .register(StreamKind::Orderbook, at, "book", kraken_parser::parse_ws_book)
        .register(StreamKind::OrderbookDelta, at, "book", kraken_parser::parse_ws_book)
        // ohlc → Kline
        .register(
            StreamKind::Kline { interval: KlineInterval::new("") },
            at,
            "ohlc",
            kraken_parser::parse_ws_ohlc,
        )
        // instrument → MarketWarning (only when status != "online")
        .register(StreamKind::MarketWarning, at, "instrument", kraken_parser::parse_ws_instrument)
        .build()
}

// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Convert a symbol string to Kraken WS v2 slash format.
///
/// Kraken WS v2 requires `"BTC/USD"` (slash, BTC not XBT). The REST API uses the
/// concat form `"XBTUSD"`. This function normalises both forms to the WS format so
/// that consumers using `SymbolNormalizer::to_exchange` (REST) still work correctly
/// when their symbol is forwarded to the WS connector.
///
/// Rules:
/// - Already contains '/' → returned as-is (idempotent).
/// - Otherwise: split a known quote suffix off the right, map XBT→BTC on the base,
///   then join with '/'.
/// - Unknown suffix: return unchanged (safe fallback — Kraken will NAK the subscribe
///   rather than silently drop data).
pub(crate) fn to_kraken_ws_symbol(sym: &str) -> String {
    // Idempotent: already in WS slash form.
    if sym.contains('/') {
        return sym.to_string();
    }

    // Known Kraken quote currencies (longest first to avoid prefix ambiguity).
    const KNOWN_QUOTES: &[&str] = &["USDT", "USDC", "EUR", "USD", "GBP", "AUD", "CHF", "JPY"];

    for q in KNOWN_QUOTES {
        if let Some(base) = sym.to_uppercase().strip_suffix(*q) {
            if !base.is_empty() {
                // XBT is Kraken's legacy REST code for Bitcoin; WS v2 uses BTC.
                let ws_base = if base == "XBT" { "BTC" } else { base };
                return format!("{}/{}", ws_base, q);
            }
        }
    }

    // No known quote matched — return unchanged so the caller gets a clear NAK.
    sym.to_string()
}

/// Convert KlineInterval to Kraken ohlc interval in minutes.
fn kline_interval_to_minutes(interval: &KlineInterval) -> u32 {
    match interval.as_str() {
        "1m" => 1,
        "5m" => 5,
        "15m" => 15,
        "30m" => 30,
        "1h" => 60,
        "4h" => 240,
        "1d" => 1440,
        "1w" => 10080,
        _ => 1,
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::types::OwnedSymbolInput;
    use crate::core::websocket::StreamSpec;

    fn make_spec(kind: StreamKind, sym: &str) -> StreamSpec {
        StreamSpec {
            kind,
            symbol: OwnedSymbolInput::Raw(sym.to_string()),
            account_type: AccountType::Spot,
            depth: None,
            speed_ms: None,
        }
    }

    // ── subscribe_frame ───────────────────────────────────────────────────────

    #[test]
    fn subscribe_frame_ticker() {
        let proto = KrakenProtocol;
        let spec = make_spec(StreamKind::Ticker, "BTC/USD");
        let frame = proto.subscribe_frame(&spec).expect("subscribe frame");
        if let WsFrame::Text(s) = frame {
            let v: Value = serde_json::from_str(&s).expect("valid json");
            assert_eq!(v["method"], "subscribe");
            assert_eq!(v["params"]["channel"], "ticker");
            assert_eq!(v["params"]["symbol"][0], "BTC/USD");
        } else {
            panic!("expected Text frame");
        }
    }

    #[test]
    fn subscribe_frame_trade() {
        let proto = KrakenProtocol;
        let spec = make_spec(StreamKind::Trade, "BTC/USD");
        let frame = proto.subscribe_frame(&spec).expect("subscribe frame");
        if let WsFrame::Text(s) = frame {
            let v: Value = serde_json::from_str(&s).expect("valid json");
            assert_eq!(v["params"]["channel"], "trade");
        } else {
            panic!("expected Text frame");
        }
    }

    #[test]
    fn subscribe_frame_book_includes_depth() {
        let proto = KrakenProtocol;
        let mut spec = make_spec(StreamKind::Orderbook, "BTC/USD");
        spec.depth = Some(25);
        let frame = proto.subscribe_frame(&spec).expect("subscribe frame");
        if let WsFrame::Text(s) = frame {
            let v: Value = serde_json::from_str(&s).expect("valid json");
            assert_eq!(v["params"]["channel"], "book");
            assert_eq!(v["params"]["depth"], 25);
        } else {
            panic!("expected Text frame");
        }
    }

    #[test]
    fn subscribe_frame_ohlc_includes_interval() {
        let proto = KrakenProtocol;
        let spec = make_spec(StreamKind::Kline { interval: KlineInterval::new("1h") }, "BTC/USD");
        let frame = proto.subscribe_frame(&spec).expect("subscribe frame");
        if let WsFrame::Text(s) = frame {
            let v: Value = serde_json::from_str(&s).expect("valid json");
            assert_eq!(v["params"]["channel"], "ohlc");
            assert_eq!(v["params"]["interval"], 60);
        } else {
            panic!("expected Text frame");
        }
    }

    #[test]
    fn subscribe_frame_unsupported_returns_not_supported() {
        let proto = KrakenProtocol;
        let spec = make_spec(StreamKind::Liquidation, "BTC/USD");
        let result = proto.subscribe_frame(&spec);
        assert!(
            matches!(result, Err(WebSocketError::NotSupported(_))),
            "Liquidation must return NotSupported, got {:?}",
            result
        );
    }

    // ── extract_topic ─────────────────────────────────────────────────────────

    #[test]
    fn extract_topic_ticker_data_frame() {
        let proto = KrakenProtocol;
        let raw = serde_json::json!({
            "channel": "ticker",
            "type": "snapshot",
            "data": []
        });
        assert_eq!(proto.extract_topic(&raw), Some(TopicKey::new("ticker")));
    }

    #[test]
    fn extract_topic_pong_returns_none() {
        let proto = KrakenProtocol;
        let raw = serde_json::json!({"method": "pong", "time_in": "...", "time_out": "..."});
        assert_eq!(proto.extract_topic(&raw), None);
    }

    #[test]
    fn extract_topic_subscribe_ack_returns_none() {
        let proto = KrakenProtocol;
        let raw = serde_json::json!({"method": "subscribe", "success": true});
        assert_eq!(proto.extract_topic(&raw), None);
    }

    #[test]
    fn extract_topic_heartbeat_returns_none() {
        let proto = KrakenProtocol;
        let raw = serde_json::json!({"channel": "heartbeat"});
        assert_eq!(proto.extract_topic(&raw), None);
    }

    #[test]
    fn extract_topic_status_returns_none() {
        let proto = KrakenProtocol;
        let raw = serde_json::json!({"channel": "status", "data": [{"api_version": "v2"}]});
        assert_eq!(proto.extract_topic(&raw), None);
    }

    // ── is_pong / is_subscribe_ack ────────────────────────────────────────────

    #[test]
    fn is_pong_true_for_method_pong() {
        let proto = KrakenProtocol;
        let raw = serde_json::json!({"method": "pong"});
        assert!(proto.is_pong(&raw));
    }

    #[test]
    fn is_pong_false_for_data_frame() {
        let proto = KrakenProtocol;
        let raw = serde_json::json!({"channel": "ticker", "data": []});
        assert!(!proto.is_pong(&raw));
    }

    #[test]
    fn is_subscribe_ack_true_for_subscribe() {
        let proto = KrakenProtocol;
        let raw = serde_json::json!({"method": "subscribe", "success": true});
        assert!(proto.is_subscribe_ack(&raw));
    }

    #[test]
    fn is_subscribe_ack_true_for_unsubscribe() {
        let proto = KrakenProtocol;
        let raw = serde_json::json!({"method": "unsubscribe", "success": true});
        assert!(proto.is_subscribe_ack(&raw));
    }

    // ── ping_frame ────────────────────────────────────────────────────────────

    #[test]
    fn ping_frame_is_json_ping() {
        let proto = KrakenProtocol;
        let frame = proto.ping_frame();
        assert!(frame.is_some());
        if let Some(WsFrame::Text(s)) = frame {
            let v: Value = serde_json::from_str(&s).expect("valid json");
            assert_eq!(v["method"], "ping");
        } else {
            panic!("expected Some(Text)");
        }
    }

    // ── topic_registry ────────────────────────────────────────────────────────

    #[test]
    fn topic_registry_covers_public_channels() {
        let proto = KrakenProtocol;
        let reg = proto.topic_registry(AccountType::Spot);
        let at = AccountType::Spot;
        assert!(reg.supports(&StreamKind::Ticker, at), "Ticker");
        assert!(reg.supports(&StreamKind::Trade, at), "Trade");
        assert!(reg.supports(&StreamKind::Orderbook, at), "Orderbook");
        assert!(reg.supports(&StreamKind::OrderbookDelta, at), "OrderbookDelta");
        assert!(
            reg.supports(&StreamKind::Kline { interval: KlineInterval::new("") }, at),
            "Kline"
        );
        assert!(reg.supports(&StreamKind::MarketWarning, at), "MarketWarning");
    }

    #[test]
    fn book_channel_has_two_parsers() {
        let proto = KrakenProtocol;
        let reg = proto.topic_registry(AccountType::Spot);
        let key = TopicKey::new("book");
        let parsers = reg.dispatch_all(&key);
        // Orderbook + OrderbookDelta are registered with the SAME function ptr,
        // so dispatch_all de-duplicates → 1 unique parser.
        assert_eq!(parsers.len(), 1, "book channel must have 1 unique parser (de-duped)");
    }

    // ── to_kraken_ws_symbol ───────────────────────────────────────────────────

    #[test]
    fn ws_symbol_xbtusd_to_btc_usd() {
        assert_eq!(to_kraken_ws_symbol("XBTUSD"), "BTC/USD");
    }

    #[test]
    fn ws_symbol_btcusd_to_btc_usd() {
        assert_eq!(to_kraken_ws_symbol("BTCUSD"), "BTC/USD");
    }

    #[test]
    fn ws_symbol_btc_usd_idempotent() {
        assert_eq!(to_kraken_ws_symbol("BTC/USD"), "BTC/USD");
    }

    #[test]
    fn ws_symbol_xbtusdt_to_btc_usdt() {
        assert_eq!(to_kraken_ws_symbol("XBTUSDT"), "BTC/USDT");
    }

    #[test]
    fn ws_symbol_ethusdt_to_eth_usdt() {
        assert_eq!(to_kraken_ws_symbol("ETHUSDT"), "ETH/USDT");
    }

    #[test]
    fn ws_symbol_ethusd_to_eth_usd() {
        assert_eq!(to_kraken_ws_symbol("ETHUSD"), "ETH/USD");
    }

    #[test]
    fn ws_symbol_unknown_passthrough() {
        // No known quote suffix — returned unchanged so Kraken gives a clear NAK.
        assert_eq!(to_kraken_ws_symbol("BTCXXX"), "BTCXXX");
    }

    // ── subscribe_frame uses WS symbol format ─────────────────────────────────

    #[test]
    fn subscribe_frame_ticker_xbtusd_normalised() {
        // When a consumer passes the REST format "XBTUSD" as raw, the connector
        // must normalise it to "BTC/USD" before sending to Kraken WS v2.
        let proto = KrakenProtocol;
        let spec = make_spec(StreamKind::Ticker, "XBTUSD");
        let frame = proto.subscribe_frame(&spec).expect("subscribe frame");
        if let WsFrame::Text(s) = frame {
            let v: Value = serde_json::from_str(&s).expect("valid json");
            assert_eq!(
                v["params"]["symbol"][0], "BTC/USD",
                "XBTUSD must be normalised to BTC/USD for Kraken WS v2"
            );
        } else {
            panic!("expected Text frame");
        }
    }

    // ── kline interval mapping ────────────────────────────────────────────────

    #[test]
    fn kline_interval_to_minutes_coverage() {
        assert_eq!(kline_interval_to_minutes(&KlineInterval::new("1m")), 1);
        assert_eq!(kline_interval_to_minutes(&KlineInterval::new("5m")), 5);
        assert_eq!(kline_interval_to_minutes(&KlineInterval::new("15m")), 15);
        assert_eq!(kline_interval_to_minutes(&KlineInterval::new("30m")), 30);
        assert_eq!(kline_interval_to_minutes(&KlineInterval::new("1h")), 60);
        assert_eq!(kline_interval_to_minutes(&KlineInterval::new("4h")), 240);
        assert_eq!(kline_interval_to_minutes(&KlineInterval::new("1d")), 1440);
        assert_eq!(kline_interval_to_minutes(&KlineInterval::new("1w")), 10080);
        // Unknown → 1 (default)
        assert_eq!(kline_interval_to_minutes(&KlineInterval::new("2m")), 1);
    }
}