digdigdig3 0.1.29

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
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
//! # ConnectorAggregator - Unified High-Level API
//!
//! Provides a unified high-level API over ConnectorPool for common operations.
//!
//! ## Features
//!
//! - **Single Exchange Operations**: Get price, ticker, orderbook, klines from specific exchange
//! - **Multi-Exchange Operations**: Query multiple exchanges concurrently
//! - **Trading Operations**: Place market/limit orders, cancel orders
//! - **Account Operations**: Query balances across exchanges
//! - **Best Execution**: Find best bid/ask across multiple exchanges
//!
//! ## Architecture
//!
//! ```text
//! ConnectorAggregator
//!   ├── ConnectorPool (Arc) - thread-safe connection pool
//!   └── High-level methods - unified API with error handling
//! ```
//!
//! ## Usage
//!
//! ```ignore
//! use connectors_v5::connector_manager::{ConnectorAggregator, ConnectorPool};
//!
//! // Create aggregator
//! let pool = ConnectorPool::new();
//! let aggregator = ConnectorAggregator::new(pool);
//!
//! // Single exchange operation
//! let price = aggregator.get_price(
//!     ExchangeId::Binance,
//!     Symbol::new("BTC", "USDT"),
//!     AccountType::Spot
//! ).await?;
//!
//! // Multi-exchange operation
//! let prices = aggregator.get_prices_multi(
//!     &[ExchangeId::Binance, ExchangeId::KuCoin],
//!     Symbol::new("BTC", "USDT"),
//!     AccountType::Spot
//! ).await?;
//!
//! // Find best bid/ask across exchanges
//! let best = aggregator.get_best_bid_ask(
//!     &[ExchangeId::Binance, ExchangeId::KuCoin],
//!     Symbol::new("BTC", "USDT"),
//!     AccountType::Spot
//! ).await?;
//! ```

use std::sync::Arc;

use crate::connector_manager::ConnectorPool;
use crate::core::traits::MarketData;
use crate::core::types::{
    AccountType, ExchangeError, ExchangeId, ExchangeResult, Kline, OrderBook, Price, Symbol,
    Ticker,
};

// ═══════════════════════════════════════════════════════════════════════════════
// ConnectorAggregator - Main API
// ═══════════════════════════════════════════════════════════════════════════════

/// Unified high-level API over ConnectorPool.
///
/// Provides convenient methods for common operations across single or multiple exchanges.
/// All operations handle errors gracefully and return typed results.
#[derive(Clone)]
pub struct ConnectorAggregator {
    /// Underlying connection pool
    pool: Arc<ConnectorPool>,
}

impl ConnectorAggregator {
    /// Create a new aggregator from a pool.
    ///
    /// # Arguments
    ///
    /// * `pool` - ConnectorPool instance
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let pool = ConnectorPool::new();
    /// let aggregator = ConnectorAggregator::new(pool);
    /// ```
    pub fn new(pool: ConnectorPool) -> Self {
        Self {
            pool: Arc::new(pool),
        }
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Pool Access
    // ═══════════════════════════════════════════════════════════════════════════

    /// Get reference to underlying pool.
    ///
    /// Allows direct access to pool methods for advanced use cases.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let pool = aggregator.pool();
    /// let ids = pool.ids();
    /// ```
    pub fn pool(&self) -> &ConnectorPool {
        &self.pool
    }

    /// List all exchanges available in the pool.
    ///
    /// Returns exchange IDs for all connectors currently in the pool.
    ///
    /// # Returns
    ///
    /// Vector of ExchangeIds
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let exchanges = aggregator.available_exchanges();
    /// println!("Available: {:?}", exchanges);
    /// ```
    pub fn available_exchanges(&self) -> Vec<ExchangeId> {
        self.pool.ids()
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Market Data - Single Exchange
    // ═══════════════════════════════════════════════════════════════════════════

    /// Get price from a specific exchange.
    ///
    /// # Arguments
    ///
    /// * `id` - Exchange identifier
    /// * `symbol` - Trading pair symbol
    /// * `account_type` - Account type (Spot, Futures, etc.)
    ///
    /// # Returns
    ///
    /// Current price as f64
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Exchange not in pool
    /// - Network error
    /// - API error
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let price = aggregator.get_price(
    ///     ExchangeId::Binance,
    ///     Symbol::new("BTC", "USDT"),
    ///     AccountType::Spot
    /// ).await?;
    /// ```
    pub async fn get_price(
        &self,
        id: ExchangeId,
        symbol: Symbol,
        account_type: AccountType,
    ) -> ExchangeResult<Price> {
        let connector = self
            .pool
            .get(&id)
            .ok_or_else(|| ExchangeError::NotFound(format!("Exchange {:?} not in pool", id)))?;

        connector.get_price(symbol, account_type).await
    }

    /// Get ticker from a specific exchange.
    ///
    /// # Arguments
    ///
    /// * `id` - Exchange identifier
    /// * `symbol` - Trading pair symbol
    /// * `account_type` - Account type
    ///
    /// # Returns
    ///
    /// Ticker with 24h statistics
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let ticker = aggregator.get_ticker(
    ///     ExchangeId::Binance,
    ///     Symbol::new("BTC", "USDT"),
    ///     AccountType::Spot
    /// ).await?;
    /// ```
    pub async fn get_ticker(
        &self,
        id: ExchangeId,
        symbol: Symbol,
        account_type: AccountType,
    ) -> ExchangeResult<Ticker> {
        let connector = self
            .pool
            .get(&id)
            .ok_or_else(|| ExchangeError::NotFound(format!("Exchange {:?} not in pool", id)))?;

        connector.get_ticker(symbol, account_type).await
    }

    /// Get orderbook from a specific exchange.
    ///
    /// # Arguments
    ///
    /// * `id` - Exchange identifier
    /// * `symbol` - Trading pair symbol
    /// * `account_type` - Account type
    /// * `depth` - Optional depth limit (e.g., 5, 10, 20)
    ///
    /// # Returns
    ///
    /// OrderBook with bids and asks
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let orderbook = aggregator.get_orderbook(
    ///     ExchangeId::Binance,
    ///     Symbol::new("BTC", "USDT"),
    ///     AccountType::Spot,
    ///     Some(20)
    /// ).await?;
    /// ```
    pub async fn get_orderbook(
        &self,
        id: ExchangeId,
        symbol: Symbol,
        account_type: AccountType,
        depth: Option<u16>,
    ) -> ExchangeResult<OrderBook> {
        let connector = self
            .pool
            .get(&id)
            .ok_or_else(|| ExchangeError::NotFound(format!("Exchange {:?} not in pool", id)))?;

        connector.get_orderbook(symbol, depth, account_type).await
    }

    /// Get klines (candlestick data) from a specific exchange.
    ///
    /// # Arguments
    ///
    /// * `id` - Exchange identifier
    /// * `symbol` - Trading pair symbol
    /// * `interval` - Timeframe (e.g., "1m", "5m", "1h", "1d")
    /// * `account_type` - Account type
    /// * `limit` - Optional number of klines to return
    ///
    /// # Returns
    ///
    /// Vector of Klines (OHLCV data)
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let klines = aggregator.get_klines(
    ///     ExchangeId::Binance,
    ///     Symbol::new("BTC", "USDT"),
    ///     "1h",
    ///     AccountType::Spot,
    ///     Some(100)
    /// ).await?;
    /// ```
    pub async fn get_klines(
        &self,
        id: ExchangeId,
        symbol: Symbol,
        interval: &str,
        account_type: AccountType,
        limit: Option<u16>,
        end_time: Option<i64>,
    ) -> ExchangeResult<Vec<Kline>> {
        let connector = self
            .pool
            .get(&id)
            .ok_or_else(|| ExchangeError::NotFound(format!("Exchange {:?} not in pool", id)))?;

        connector
            .get_klines(symbol, interval, limit, account_type, end_time)
            .await
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Market Data - Multi-Exchange
    // ═══════════════════════════════════════════════════════════════════════════

    /// Get prices from multiple exchanges concurrently.
    ///
    /// Queries all specified exchanges in parallel and collects successful results.
    /// Failed exchanges are skipped (not propagated as errors).
    ///
    /// # Arguments
    ///
    /// * `ids` - Exchange identifiers to query
    /// * `symbol` - Trading pair symbol
    /// * `account_type` - Account type
    ///
    /// # Returns
    ///
    /// HashMap of ExchangeId -> Price for successful queries
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let prices = aggregator.get_prices_multi(
    ///     &[ExchangeId::Binance, ExchangeId::KuCoin, ExchangeId::OKX],
    ///     Symbol::new("BTC", "USDT"),
    ///     AccountType::Spot
    /// ).await?;
    /// ```
    pub async fn get_prices_multi(
        &self,
        ids: &[ExchangeId],
        symbol: Symbol,
        account_type: AccountType,
    ) -> ExchangeResult<std::collections::HashMap<ExchangeId, Price>> {
        use futures_util::future::join_all;

        // Filter to only exchanges in pool
        let connectors: Vec<_> = ids
            .iter()
            .filter_map(|id| self.pool.get(id).map(|c| (*id, c)))
            .collect();

        if connectors.is_empty() {
            return Err(ExchangeError::NotFound(
                "No specified exchanges found in pool".to_string(),
            ));
        }

        // Query all exchanges concurrently
        let futures = connectors.into_iter().map(|(id, connector)| {
            let sym = symbol.clone();
            let acc_type = account_type;
            async move {
                connector
                    .get_price(sym, acc_type)
                    .await
                    .ok()
                    .map(|price| (id, price))
            }
        });

        let results: Vec<Option<(ExchangeId, Price)>> = join_all(futures).await;

        // Collect successful results
        let prices: std::collections::HashMap<_, _> =
            results.into_iter().flatten().collect();

        if prices.is_empty() {
            return Err(ExchangeError::NotFound(
                "All exchange queries failed".to_string(),
            ));
        }

        Ok(prices)
    }

    /// Find best bid and ask across multiple exchanges.
    ///
    /// Queries orderbooks from all specified exchanges and finds the highest bid
    /// and lowest ask, enabling best execution across exchanges.
    ///
    /// # Arguments
    ///
    /// * `ids` - Exchange identifiers to query
    /// * `symbol` - Trading pair symbol
    /// * `account_type` - Account type
    ///
    /// # Returns
    ///
    /// BestBidAsk with highest bid, lowest ask, and their sources
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let best = aggregator.get_best_bid_ask(
    ///     &[ExchangeId::Binance, ExchangeId::KuCoin],
    ///     Symbol::new("BTC", "USDT"),
    ///     AccountType::Spot
    /// ).await?;
    /// println!("Best bid: {} from {:?}", best.bid, best.bid_exchange);
    /// println!("Best ask: {} from {:?}", best.ask, best.ask_exchange);
    /// ```
    pub async fn get_best_bid_ask(
        &self,
        ids: &[ExchangeId],
        symbol: Symbol,
        account_type: AccountType,
    ) -> ExchangeResult<BestBidAsk> {
        use futures_util::future::join_all;

        // Filter to only exchanges in pool
        let connectors: Vec<_> = ids
            .iter()
            .filter_map(|id| self.pool.get(id).map(|c| (*id, c)))
            .collect();

        if connectors.is_empty() {
            return Err(ExchangeError::NotFound(
                "No specified exchanges found in pool".to_string(),
            ));
        }

        // Query all orderbooks concurrently
        let futures = connectors.into_iter().map(|(id, connector)| {
            let sym = symbol.clone();
            let acc_type = account_type;
            async move {
                connector
                    .get_orderbook(sym, Some(1), acc_type)
                    .await
                    .ok()
                    .map(|ob| (id, ob))
            }
        });

        let results: Vec<Option<(ExchangeId, OrderBook)>> = join_all(futures).await;

        // Collect successful orderbooks
        let orderbooks: Vec<_> = results.into_iter().flatten().collect();

        if orderbooks.is_empty() {
            return Err(ExchangeError::NotFound(
                "All orderbook queries failed".to_string(),
            ));
        }

        // Find best bid (highest) and best ask (lowest)
        let mut best_bid: Option<(f64, ExchangeId)> = None;
        let mut best_ask: Option<(f64, ExchangeId)> = None;

        for (id, ob) in orderbooks {
            // Check bids (highest is best)
            if let Some(bid_level) = ob.bids.first() {
                let bid_price = bid_level.price;
                match best_bid {
                    None => best_bid = Some((bid_price, id)),
                    Some((current_best, _)) if bid_price > current_best => {
                        best_bid = Some((bid_price, id))
                    }
                    _ => {}
                }
            }

            // Check asks (lowest is best)
            if let Some(ask_level) = ob.asks.first() {
                let ask_price = ask_level.price;
                match best_ask {
                    None => best_ask = Some((ask_price, id)),
                    Some((current_best, _)) if ask_price < current_best => {
                        best_ask = Some((ask_price, id))
                    }
                    _ => {}
                }
            }
        }

        let (bid, bid_exchange) = best_bid.ok_or_else(|| {
            ExchangeError::NotFound("No valid bids found in orderbooks".to_string())
        })?;

        let (ask, ask_exchange) = best_ask.ok_or_else(|| {
            ExchangeError::NotFound("No valid asks found in orderbooks".to_string())
        })?;

        Ok(BestBidAsk {
            bid,
            bid_exchange,
            ask,
            ask_exchange,
            spread: ask - bid,
            spread_percent: ((ask - bid) / bid) * 100.0,
        })
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Account Operations
    // ═══════════════════════════════════════════════════════════════════════════
    //
    // NOTE: These methods require Account trait to be implemented on AnyConnector.
    // TODO: Uncomment when Account trait is delegated in connector.rs
    //
    // /// Get balance from a specific exchange.
    // pub async fn get_balance(...) -> ExchangeResult<Vec<Balance>> { ... }
    //
    // /// Get balances from multiple exchanges concurrently.
    // pub async fn get_balances_multi(...) -> ExchangeResult<HashMap<ExchangeId, Vec<Balance>>> { ... }

    // ═══════════════════════════════════════════════════════════════════════════
    // Trading Operations
    // ═══════════════════════════════════════════════════════════════════════════
    //
    // NOTE: These methods require Trading trait to be implemented on AnyConnector.
    // TODO: Uncomment when Trading trait is delegated in connector.rs
    //
    // /// Place a market order on a specific exchange.
    // pub async fn place_market_order(...) -> ExchangeResult<Order> { ... }
    //
    // /// Place a limit order on a specific exchange.
    // pub async fn place_limit_order(...) -> ExchangeResult<Order> { ... }
    //
    // /// Cancel an order on a specific exchange.
    // pub async fn cancel_order(...) -> ExchangeResult<Order> { ... }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Builder Pattern
// ═══════════════════════════════════════════════════════════════════════════════

/// Builder for ConnectorAggregator.
///
/// Provides fluent API for constructing an aggregator instance.
pub struct ConnectorAggregatorBuilder {
    pool: ConnectorPool,
}

impl ConnectorAggregatorBuilder {
    /// Create a new builder with an empty pool.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let builder = ConnectorAggregatorBuilder::new();
    /// ```
    pub fn new() -> Self {
        Self {
            pool: ConnectorPool::new(),
        }
    }

    /// Create a builder with an existing pool.
    ///
    /// # Arguments
    ///
    /// * `pool` - Existing ConnectorPool instance
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let pool = ConnectorPool::new();
    /// let builder = ConnectorAggregatorBuilder::with_pool(pool);
    /// ```
    pub fn with_pool(pool: ConnectorPool) -> Self {
        Self { pool }
    }

    /// Build the aggregator.
    ///
    /// Consumes the builder and returns the configured aggregator.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let aggregator = ConnectorAggregatorBuilder::new()
    ///     .build();
    /// ```
    pub fn build(self) -> ConnectorAggregator {
        ConnectorAggregator::new(self.pool)
    }
}

impl Default for ConnectorAggregatorBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Helper Types
// ═══════════════════════════════════════════════════════════════════════════════

/// Result from get_best_bid_ask query.
#[derive(Debug, Clone)]
pub struct BestBidAsk {
    /// Best (highest) bid price
    pub bid: f64,
    /// Exchange with best bid
    pub bid_exchange: ExchangeId,
    /// Best (lowest) ask price
    pub ask: f64,
    /// Exchange with best ask
    pub ask_exchange: ExchangeId,
    /// Spread (ask - bid)
    pub spread: f64,
    /// Spread as percentage of bid
    pub spread_percent: f64,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Unit Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;
    use crate::connector_manager::AnyConnector;
    use crate::l3::open::crypto::cex::okx::OkxConnector;

    /// Helper to create a mock OKX connector for testing
    async fn create_mock_connector() -> Arc<AnyConnector> {
        let connector = OkxConnector::public(true).await.unwrap();
        Arc::new(AnyConnector::OKX(Arc::new(connector)))
    }

    /// Helper to create a pool with mock connectors
    async fn create_test_pool() -> ConnectorPool {
        let pool = ConnectorPool::new();
        pool.insert(ExchangeId::Binance, create_mock_connector().await);
        pool.insert(ExchangeId::KuCoin, create_mock_connector().await);
        pool
    }

    // ───────────────────────────────────────────────────────────────────────────
    // Constructor Tests
    // ───────────────────────────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_new_aggregator() {
        let pool = ConnectorPool::new();
        let aggregator = ConnectorAggregator::new(pool);
        assert!(aggregator.available_exchanges().is_empty());
    }

    #[tokio::test]
    async fn test_aggregator_with_pool() {
        let pool = create_test_pool().await;
        let aggregator = ConnectorAggregator::new(pool);
        assert_eq!(aggregator.available_exchanges().len(), 2);
    }

    // ───────────────────────────────────────────────────────────────────────────
    // Builder Tests
    // ───────────────────────────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_builder_new() {
        let aggregator = ConnectorAggregatorBuilder::new().build();
        assert!(aggregator.available_exchanges().is_empty());
    }

    #[tokio::test]
    async fn test_builder_with_pool() {
        let pool = create_test_pool().await;
        let aggregator = ConnectorAggregatorBuilder::with_pool(pool).build();
        assert_eq!(aggregator.available_exchanges().len(), 2);
    }

    #[tokio::test]
    async fn test_builder_default() {
        let aggregator = ConnectorAggregatorBuilder::default().build();
        assert!(aggregator.available_exchanges().is_empty());
    }

    // ───────────────────────────────────────────────────────────────────────────
    // Pool Access Tests
    // ───────────────────────────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_pool_access() {
        let pool = create_test_pool().await;
        let aggregator = ConnectorAggregator::new(pool);

        let pool_ref = aggregator.pool();
        assert_eq!(pool_ref.len(), 2);
    }

    #[tokio::test]
    async fn test_available_exchanges() {
        let pool = create_test_pool().await;
        let aggregator = ConnectorAggregator::new(pool);

        let exchanges = aggregator.available_exchanges();
        assert_eq!(exchanges.len(), 2);
        assert!(exchanges.contains(&ExchangeId::Binance));
        assert!(exchanges.contains(&ExchangeId::KuCoin));
    }

    // ───────────────────────────────────────────────────────────────────────────
    // Single Exchange Operations - Error Handling
    // ───────────────────────────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_get_price_exchange_not_in_pool() {
        let pool = ConnectorPool::new();
        let aggregator = ConnectorAggregator::new(pool);

        let result = aggregator
            .get_price(
                ExchangeId::Binance,
                Symbol::new("BTC", "USDT"),
                AccountType::Spot,
            )
            .await;

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), ExchangeError::NotFound(_)));
    }

    #[tokio::test]
    async fn test_get_ticker_exchange_not_in_pool() {
        let pool = ConnectorPool::new();
        let aggregator = ConnectorAggregator::new(pool);

        let result = aggregator
            .get_ticker(
                ExchangeId::Binance,
                Symbol::new("BTC", "USDT"),
                AccountType::Spot,
            )
            .await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_get_orderbook_exchange_not_in_pool() {
        let pool = ConnectorPool::new();
        let aggregator = ConnectorAggregator::new(pool);

        let result = aggregator
            .get_orderbook(
                ExchangeId::Binance,
                Symbol::new("BTC", "USDT"),
                AccountType::Spot,
                Some(20),
            )
            .await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_get_klines_exchange_not_in_pool() {
        let pool = ConnectorPool::new();
        let aggregator = ConnectorAggregator::new(pool);

        let result = aggregator
            .get_klines(
                ExchangeId::Binance,
                Symbol::new("BTC", "USDT"),
                "1h",
                AccountType::Spot,
                Some(100),
                None,
            )
            .await;

        assert!(result.is_err());
    }

    // ───────────────────────────────────────────────────────────────────────────
    // Multi-Exchange Operations - Error Handling
    // ───────────────────────────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_get_prices_multi_no_exchanges() {
        let pool = ConnectorPool::new();
        let aggregator = ConnectorAggregator::new(pool);

        let result = aggregator
            .get_prices_multi(
                &[ExchangeId::Binance, ExchangeId::KuCoin],
                Symbol::new("BTC", "USDT"),
                AccountType::Spot,
            )
            .await;

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), ExchangeError::NotFound(_)));
    }

    #[tokio::test]
    async fn test_get_prices_multi_empty_list() {
        let pool = create_test_pool().await;
        let aggregator = ConnectorAggregator::new(pool);

        let result = aggregator
            .get_prices_multi(&[], Symbol::new("BTC", "USDT"), AccountType::Spot)
            .await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_get_best_bid_ask_no_exchanges() {
        let pool = ConnectorPool::new();
        let aggregator = ConnectorAggregator::new(pool);

        let result = aggregator
            .get_best_bid_ask(
                &[ExchangeId::Binance],
                Symbol::new("BTC", "USDT"),
                AccountType::Spot,
            )
            .await;

        assert!(result.is_err());
    }

    // ───────────────────────────────────────────────────────────────────────────
    // Helper Types Tests
    // ───────────────────────────────────────────────────────────────────────────

    #[test]
    fn test_best_bid_ask_spread_calculation() {
        let best = BestBidAsk {
            bid: 50000.0,
            bid_exchange: ExchangeId::Binance,
            ask: 50100.0,
            ask_exchange: ExchangeId::KuCoin,
            spread: 100.0,
            spread_percent: 0.2,
        };

        assert_eq!(best.spread, 100.0);
        assert_eq!(best.spread_percent, 0.2);
    }

    // ───────────────────────────────────────────────────────────────────────────
    // Aggregator Clone Tests
    // ───────────────────────────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_aggregator_clone() {
        let pool = create_test_pool().await;
        let aggregator1 = ConnectorAggregator::new(pool);

        // Clone the aggregator
        let aggregator2 = aggregator1.clone();

        // Both should share the same pool
        assert_eq!(aggregator1.available_exchanges().len(), 2);
        assert_eq!(aggregator2.available_exchanges().len(), 2);
    }
}