digdigdig3 0.1.30

Unified async Rust API for 44 exchange connectors — crypto, stocks, forex. REST + WebSocket.
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
//! # Kraken Endpoints
//!
//! URL's and endpoint enum for Kraken API.

use crate::core::types::AccountType;

// ═══════════════════════════════════════════════════════════════════════════════
// URLs
// ═══════════════════════════════════════════════════════════════════════════════

/// URL's for Kraken API
#[derive(Debug, Clone)]
pub struct KrakenUrls {
    pub spot_rest: &'static str,
    pub futures_rest: &'static str,
    pub spot_ws: &'static str,
    pub futures_ws: &'static str,
}

impl KrakenUrls {
    /// Production URLs
    pub const MAINNET: Self = Self {
        spot_rest: "https://api.kraken.com",
        futures_rest: "https://futures.kraken.com",
        spot_ws: "wss://ws.kraken.com/v2",
        futures_ws: "wss://futures.kraken.com/ws/v1",
    };

    /// Sandbox URLs (Kraken doesn't have official testnet, use demo futures)
    pub const TESTNET: Self = Self {
        spot_rest: "https://api.kraken.com", // No testnet for spot
        futures_rest: "https://demo-futures.kraken.com",
        spot_ws: "wss://ws.kraken.com/v2",
        futures_ws: "wss://demo-futures.kraken.com/ws/v1",
    };

    /// Get REST base URL for account type
    pub fn rest_url(&self, account_type: AccountType) -> &str {
        match account_type {
            AccountType::Spot | AccountType::Margin => self.spot_rest,
            AccountType::FuturesCross | AccountType::FuturesIsolated => self.futures_rest,
            _ => self.spot_rest,
        }
    }

    /// Get WebSocket URL for account type
    pub fn ws_url(&self, account_type: AccountType) -> &str {
        match account_type {
            AccountType::Spot | AccountType::Margin => self.spot_ws,
            AccountType::FuturesCross | AccountType::FuturesIsolated => self.futures_ws,
            _ => self.spot_ws,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ENDPOINTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Kraken API endpoints
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum KrakenEndpoint {
    // === COMMON ===
    ServerTime,

    // === SPOT MARKET DATA ===
    SpotTicker,
    SpotOrderbook,
    SpotOHLC,
    SpotAssetPairs,

    // === SPOT TRADING ===
    SpotAddOrder,
    SpotCancelOrder,
    SpotCancelAll,
    SpotEditOrder,
    SpotGetOrder,
    SpotOpenOrders,
    SpotClosedOrders,

    // === SPOT ACCOUNT ===
    SpotBalance,
    SpotTradeBalance,

    // === SPOT WEBSOCKET ===
    SpotWebSocketToken,

    // === FILL/TRADE HISTORY ===
    /// POST /0/private/TradesHistory — personal trade fills (signed)
    TradesHistory,

    // === FUTURES MARKET DATA ===
    FuturesTickers,
    FuturesOrderbook,
    FuturesInstruments,
    FuturesHistory,

    // === FUTURES TRADING ===
    FuturesSendOrder,
    FuturesCancelOrder,
    FuturesBatchOrder,
    FuturesEditOrder,

    // === FUTURES ACCOUNT ===
    FuturesAccounts,
    FuturesOpenPositions,
    FuturesHistoricalFunding,

    // === FUTURES LEVERAGE ===
    FuturesSetLeverage,

    // === CUSTODIAL FUNDS (Spot) ===
    SpotDepositAddresses,   // POST /0/private/DepositAddresses
    SpotWithdraw,           // POST /0/private/Withdraw
    SpotDepositStatus,      // POST /0/private/DepositStatus
    SpotWithdrawStatus,     // POST /0/private/WithdrawStatus

    // === SUB-ACCOUNTS (Spot) ===
    SpotListSubaccounts,        // POST /0/private/ListSubaccounts
    SpotTransferToSubaccount,   // POST /0/private/TransferToSubaccount
    SpotTransferFromSubaccount, // POST /0/private/TransferFromSubaccount

    // === LEDGER (Spot) ===
    /// POST /0/private/Ledgers — full account ledger (funding + all types)
    SpotLedgers,
}

impl KrakenEndpoint {
    /// Get endpoint path
    pub fn path(&self) -> &'static str {
        match self {
            // Common
            Self::ServerTime => "/0/public/Time",

            // Spot Market Data
            Self::SpotTicker => "/0/public/Ticker",
            Self::SpotOrderbook => "/0/public/Depth",
            Self::SpotOHLC => "/0/public/OHLC",
            Self::SpotAssetPairs => "/0/public/AssetPairs",

            // Spot Trading
            Self::SpotAddOrder => "/0/private/AddOrder",
            Self::SpotCancelOrder => "/0/private/CancelOrder",
            Self::SpotCancelAll => "/0/private/CancelAll",
            Self::SpotEditOrder => "/0/private/EditOrder",
            Self::SpotGetOrder => "/0/private/QueryOrders",
            Self::SpotOpenOrders => "/0/private/OpenOrders",
            Self::SpotClosedOrders => "/0/private/ClosedOrders",

            // Spot Account
            Self::SpotBalance => "/0/private/Balance",
            Self::SpotTradeBalance => "/0/private/TradeBalance",

            // Spot WebSocket
            Self::SpotWebSocketToken => "/0/private/GetWebSocketsToken",

            // Fill/Trade History
            Self::TradesHistory => "/0/private/TradesHistory",

            // Futures Market Data
            Self::FuturesTickers => "/derivatives/api/v3/tickers",
            Self::FuturesOrderbook => "/derivatives/api/v3/orderbook",
            Self::FuturesInstruments => "/derivatives/api/v3/instruments",
            Self::FuturesHistory => "/derivatives/api/v3/history",

            // Futures Trading
            Self::FuturesSendOrder => "/derivatives/api/v3/sendorder",
            Self::FuturesCancelOrder => "/derivatives/api/v3/cancelorder",
            Self::FuturesBatchOrder => "/derivatives/api/v3/batchorder",
            Self::FuturesEditOrder => "/derivatives/api/v3/editorder",

            // Futures Account
            Self::FuturesAccounts => "/derivatives/api/v3/accounts",
            Self::FuturesOpenPositions => "/derivatives/api/v3/openpositions",
            Self::FuturesHistoricalFunding => "/derivatives/api/v4/historicalfundingrates",

            // Futures Leverage
            Self::FuturesSetLeverage => "/derivatives/api/v3/leveragepreferences",

            // Custodial Funds
            Self::SpotDepositAddresses => "/0/private/DepositAddresses",
            Self::SpotWithdraw => "/0/private/Withdraw",
            Self::SpotDepositStatus => "/0/private/DepositStatus",
            Self::SpotWithdrawStatus => "/0/private/WithdrawStatus",

            // Sub-Accounts
            Self::SpotListSubaccounts => "/0/private/ListSubaccounts",
            Self::SpotTransferToSubaccount => "/0/private/TransferToSubaccount",
            Self::SpotTransferFromSubaccount => "/0/private/TransferFromSubaccount",

            // Ledger
            Self::SpotLedgers => "/0/private/Ledgers",
        }
    }

    /// Does endpoint require authentication
    pub fn requires_auth(&self) -> bool {
        match self {
            // Public endpoints
            Self::ServerTime
            | Self::SpotTicker
            | Self::SpotOrderbook
            | Self::SpotOHLC
            | Self::SpotAssetPairs
            | Self::FuturesTickers
            | Self::FuturesOrderbook
            | Self::FuturesInstruments
            | Self::FuturesHistory => false,

            // Private endpoints
            _ => true,
        }
    }

    /// HTTP method for endpoint
    pub fn method(&self) -> &'static str {
        match self {
            // POST endpoints
            Self::SpotAddOrder
            | Self::SpotCancelOrder
            | Self::SpotCancelAll
            | Self::SpotEditOrder
            | Self::SpotGetOrder
            | Self::SpotOpenOrders
            | Self::SpotClosedOrders
            | Self::SpotBalance
            | Self::SpotTradeBalance
            | Self::SpotWebSocketToken
            | Self::FuturesSendOrder
            | Self::FuturesCancelOrder
            | Self::FuturesBatchOrder
            | Self::FuturesEditOrder
            | Self::FuturesSetLeverage
            | Self::SpotDepositAddresses
            | Self::SpotWithdraw
            | Self::SpotDepositStatus
            | Self::SpotWithdrawStatus
            | Self::SpotListSubaccounts
            | Self::SpotTransferToSubaccount
            | Self::SpotTransferFromSubaccount
            | Self::TradesHistory
            | Self::SpotLedgers => "POST",

            // GET endpoints
            _ => "GET",
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// SYMBOL FORMATTING
// ═══════════════════════════════════════════════════════════════════════════════

/// Format symbol for Kraken API
///
/// # Symbol Format Differences
///
/// ## Spot REST API
/// - Request: Simplified format (`XBTUSD`)
/// - Response: Full ISO format (`XXBTZUSD`)
/// - Use BTC → XBT mapping
/// - Prefix convention: X for crypto, Z for fiat
///
/// ## Futures API
/// - Format: `PI_{base}{quote}` for perpetual inverse
/// - Example: `PI_XBTUSD`, `PI_ETHUSD`
/// - Product prefixes:
///   - `PI_`: Perpetual Inverse (crypto collateral)
///   - `PF_`: Perpetual Forward (linear, USD collateral)
///   - `FI_`: Fixed maturity Inverse
///   - `FF_`: Fixed maturity Forward
///
/// # Examples
/// - Spot: `XBTUSD` (request) → `XXBTZUSD` (response)
/// - Spot: `ETHUSD` → `XETHZUSD`
/// - Futures: `BTC` + `USD` → `PI_XBTUSD`
pub fn format_symbol(base: &str, quote: &str, account_type: AccountType) -> String {
    match account_type {
        AccountType::Spot | AccountType::Margin => {
            // Spot uses simplified format for requests
            // BTC → XBT for Bitcoin
            let base = if base.to_uppercase() == "BTC" { "XBT" } else { base };
            format!("{}{}", base, quote)
        }
        AccountType::FuturesCross | AccountType::FuturesIsolated => {
            // Futures: PI_{BASE}{QUOTE} for perpetual inverse
            // BTC → XBT for Bitcoin
            let base = if base.to_uppercase() == "BTC" { "XBT" } else { base };
            format!("PI_{}{}", base, quote)
        }
        _ => {
            // Unsupported account types default to spot format
            let base = if base.to_uppercase() == "BTC" { "XBT" } else { base };
            format!("{}{}", base, quote)
        }
    }
}

/// Parse response symbol to extract base and quote
///
/// Kraken responses use full ISO format with prefixes:
/// - `XXBTZUSD` → (base: "XBT", quote: "USD")
/// - `XETHZUSD` → (base: "ETH", quote: "USD")
/// - `PI_XBTUSD` → (base: "XBT", quote: "USD")
#[allow(dead_code)]
pub fn parse_response_symbol(symbol: &str) -> Option<(String, String)> {
    // Futures format: PI_XBTUSD
    if symbol.starts_with("PI_") || symbol.starts_with("PF_") {
        let parts = symbol.split('_').nth(1)?;
        // Simple split: assume 3-letter base
        if parts.len() >= 6 {
            let base = &parts[0..3];
            let quote = &parts[3..];
            return Some((base.to_string(), quote.to_string()));
        }
    }

    // Spot format: XXBTZUSD, XETHZUSD
    // Strip X prefix from crypto, Z prefix from fiat
    let clean = symbol
        .strip_prefix("XX")
        .or_else(|| symbol.strip_prefix("X"))
        .unwrap_or(symbol);

    // Common pairs
    for fiat in &["ZUSD", "ZEUR", "ZGBP", "ZJPY", "ZCAD"] {
        if let Some(base) = clean.strip_suffix(fiat) {
            return Some((base.to_string(), fiat.strip_prefix("Z").expect("Fiat codes start with Z").to_string()));
        }
    }

    // Crypto pairs (e.g., XETHXXBT)
    if clean.len() >= 6 {
        let base = &clean[0..3];
        let quote = &clean[3..];
        return Some((base.to_string(), quote.to_string()));
    }

    None
}

/// Map kline interval to Kraken OHLC interval
///
/// Kraken uses integer minutes for intervals
pub fn map_ohlc_interval(interval: &str) -> u32 {
    match interval {
        "1m" => 1,
        "5m" => 5,
        "15m" => 15,
        "30m" => 30,
        "1h" => 60,
        "4h" => 240,
        "1d" => 1440,
        "1w" => 10080,
        "15d" => 21600,
        _ => 60, // default 1 hour
    }
}

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

    #[test]
    fn test_format_symbol_spot() {
        assert_eq!(format_symbol("BTC", "USD", AccountType::Spot), "XBTUSD");
        assert_eq!(format_symbol("ETH", "USD", AccountType::Spot), "ETHUSD");
        assert_eq!(format_symbol("XBT", "EUR", AccountType::Spot), "XBTEUR");
    }

    #[test]
    fn test_format_symbol_futures() {
        assert_eq!(
            format_symbol("BTC", "USD", AccountType::FuturesCross),
            "PI_XBTUSD"
        );
        assert_eq!(
            format_symbol("ETH", "USD", AccountType::FuturesCross),
            "PI_ETHUSD"
        );
    }

    #[test]
    fn test_parse_response_symbol() {
        assert_eq!(
            parse_response_symbol("XXBTZUSD"),
            Some(("XBT".to_string(), "USD".to_string()))
        );
        assert_eq!(
            parse_response_symbol("XETHZUSD"),
            Some(("ETH".to_string(), "USD".to_string()))
        );
        assert_eq!(
            parse_response_symbol("PI_XBTUSD"),
            Some(("XBT".to_string(), "USD".to_string()))
        );
    }

    #[test]
    fn test_map_ohlc_interval() {
        assert_eq!(map_ohlc_interval("1m"), 1);
        assert_eq!(map_ohlc_interval("1h"), 60);
        assert_eq!(map_ohlc_interval("1d"), 1440);
        assert_eq!(map_ohlc_interval("unknown"), 60);
    }
}