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
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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
//! # Gemini Connector
//!
//! Реализация всех core трейтов для Gemini.
//!
//! ## Core трейты
//! - `ExchangeIdentity` - идентификация биржи
//! - `MarketData` - рыночные данные
//! - `Trading` - торговые операции
//! - `Account` - информация об аккаунте
//! - `Positions` - futures позиции
//!
//! ## Extended методы
//! Дополнительные Gemini-специфичные методы как методы структуры.

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use async_trait::async_trait;
use serde_json::{json, Value};

use crate::core::{
    HttpClient, Credentials,
    ExchangeId, AccountType, Symbol,
    ExchangeError, ExchangeResult,
    Price, Kline, Ticker, OrderBook,
    Order, OrderSide, OrderType, Balance, AccountInfo,
    Position, FundingRate,
    OrderRequest, CancelRequest, CancelScope,
    BalanceQuery, PositionQuery, PositionModification,
    OrderHistoryFilter, PlaceOrderResponse, FeeInfo,
    CancelAllResponse, CancelAll, CustodialFunds,
    DepositAddress, WithdrawResponse, FundsRecord,
};
use crate::core::types::SymbolInfo;
use crate::core::traits::{
    ExchangeIdentity, MarketData, Trading, Account, Positions,
};
use crate::core::{MarketDataCapabilities, TradingCapabilities, AccountCapabilities};
use crate::core::types::ConnectorStats;
use crate::core::types::{WithdrawRequest, FundsHistoryFilter, FundsRecordType};
use crate::core::types::{UserTrade, UserTradeFilter};
use crate::core::utils::{RuntimeLimiter, RateLimitMonitor, RateLimitPressure};
use crate::core::types::{RateLimitCapabilities, LimitModel, RestLimitPool, WsLimits, EndpointWeight};
use crate::core::utils::PrecisionCache;

use super::endpoints::{GeminiUrls, GeminiEndpoint, format_symbol, normalize_symbol, map_kline_interval};
use super::auth::GeminiAuth;
use super::parser::GeminiParser;

// ═══════════════════════════════════════════════════════════════════════════════
// RATE LIMIT CAPABILITIES
// ═══════════════════════════════════════════════════════════════════════════════

static GEMINI_POOLS: &[RestLimitPool] = &[
    RestLimitPool {
        name: "public",
        max_budget: 120,
        window_seconds: 60,
        is_weight: false,
        has_server_headers: false,
        server_header: None,
        header_reports_used: false,
    },
    RestLimitPool {
        name: "private",
        max_budget: 600,
        window_seconds: 60,
        is_weight: false,
        has_server_headers: false,
        server_header: None,
        header_reports_used: false,
    },
];

static GEMINI_RATE_CAPS: RateLimitCapabilities = RateLimitCapabilities {
    model: LimitModel::Group,
    rest_pools: GEMINI_POOLS,
    decaying: None,
    endpoint_weights: &[] as &[EndpointWeight],
    ws: WsLimits {
        max_connections: None,
        max_subs_per_conn: None,
        max_msg_per_sec: None,
        max_streams_per_conn: None,
    },
};

// ═══════════════════════════════════════════════════════════════════════════════
// CONNECTOR
// ═══════════════════════════════════════════════════════════════════════════════

/// Gemini коннектор
pub struct GeminiConnector {
    /// HTTP клиент
    http: HttpClient,
    /// Аутентификация (None для публичных методов)
    auth: Option<GeminiAuth>,
    /// URL'ы (mainnet/testnet)
    urls: GeminiUrls,
    /// Testnet mode
    testnet: bool,
    /// Runtime rate limiter (Group model: public 120/60s + private 600/60s)
    limiter: Arc<Mutex<RuntimeLimiter>>,
    /// Pressure monitor
    monitor: Arc<Mutex<RateLimitMonitor>>,
    /// Per-symbol precision cache for safe price/qty formatting
    precision: PrecisionCache,
}

impl GeminiConnector {
    /// Создать новый коннектор
    pub async fn new(credentials: Option<Credentials>, testnet: bool) -> ExchangeResult<Self> {
        let urls = if testnet {
            GeminiUrls::TESTNET
        } else {
            GeminiUrls::MAINNET
        };

        let http = HttpClient::new(30_000)?; // 30 sec timeout

        let auth = credentials
            .as_ref()
            .map(GeminiAuth::new)
            .transpose()?;

        let limiter = Arc::new(Mutex::new(RuntimeLimiter::from_caps(&GEMINI_RATE_CAPS)));
        let monitor = Arc::new(Mutex::new(RateLimitMonitor::new("Gemini")));

        Ok(Self {
            http,
            auth,
            urls,
            testnet,
            limiter,
            monitor,
            precision: PrecisionCache::new(),
        })
    }

    /// Создать коннектор только для публичных методов
    pub async fn public(testnet: bool) -> ExchangeResult<Self> {
        Self::new(None, testnet).await
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // HTTP HELPERS
    // ═══════════════════════════════════════════════════════════════════════════

    /// Wait for rate limit if needed.
    ///
    /// Routes to "public" or "private" group. Non-essential (public) requests are
    /// dropped at >= 90% utilization. Returns `true` if acquired, `false` if dropped.
    async fn rate_limit_wait(&self, is_private: bool) -> bool {
        let group = if is_private { "private" } else { "public" };
        let essential = is_private;
        loop {
            let wait_time = {
                let mut limiter = self.limiter.lock().expect("limiter poisoned");
                let pressure = self.monitor.lock().expect("monitor poisoned").check(&mut limiter);
                if pressure >= RateLimitPressure::Cutoff && !essential {
                    return false;
                }
                if limiter.try_acquire(group, 1) {
                    return true;
                }
                limiter.time_until_ready(group, 1)
            };
            if wait_time > Duration::ZERO {
                tokio::time::sleep(wait_time).await;
            }
        }
    }

    /// GET запрос
    async fn get(
        &self,
        endpoint: GeminiEndpoint,
        path_params: &[(&str, &str)],
    ) -> ExchangeResult<Value> {
        // Public GET = non-essential; private GET = essential
        if !self.rate_limit_wait(endpoint.requires_auth()).await {
            return Err(ExchangeError::RateLimitExceeded {
                retry_after: None,
                message: "Rate limit budget >= 90% used; market data request dropped".to_string(),
            });
        }

        let base_url = self.urls.rest_url(AccountType::Spot);
        let mut path = endpoint.path().to_string();

        // Replace path parameters
        for (key, value) in path_params {
            path = path.replace(&format!("{{{}}}", key), value);
        }

        let url = format!("{}{}", base_url, path);

        let response = self.http.get(&url, &HashMap::new()).await?;
        GeminiParser::check_error(&response)?;
        Ok(response)
    }

    /// POST запрос (всегда требует auth)
    async fn post(
        &self,
        endpoint: GeminiEndpoint,
        params: HashMap<String, Value>,
        path_params: &[(&str, &str)],
    ) -> ExchangeResult<Value> {
        // POST is always private + essential
        self.rate_limit_wait(true).await;

        let base_url = self.urls.rest_url(AccountType::Spot);
        let mut path = endpoint.path().to_string();

        // Replace path parameters
        for (key, value) in path_params {
            path = path.replace(&format!("{{{}}}", key), value);
        }

        let url = format!("{}{}", base_url, path);

        // Auth headers
        let auth = self.auth.as_ref()
            .ok_or_else(|| ExchangeError::Auth("Authentication required".to_string()))?;
        let headers = auth.sign_request(&path, params)?;

        // Gemini POST requests have empty body, everything in headers
        let response = self.http.post(&url, &json!({}), &headers).await?;
        GeminiParser::check_error(&response)?;
        Ok(response)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// EXCHANGE IDENTITY
// ═══════════════════════════════════════════════════════════════════════════════

impl ExchangeIdentity for GeminiConnector {
    fn exchange_id(&self) -> ExchangeId {
        ExchangeId::Gemini
    }

    fn metrics(&self) -> ConnectorStats {
        let (http_requests, http_errors, last_latency_ms) = self.http.stats();
        let (rate_used, rate_max, rate_groups) = if let Ok(mut limiter) = self.limiter.lock() {
            let (used, max) = limiter.primary_stats();
            let groups = limiter.group_stats();
            (used, max, groups)
        } else {
            (0, 0, Vec::new())
        };
        ConnectorStats {
            http_requests,
            http_errors,
            last_latency_ms,
            rate_used,
            rate_max,
            rate_groups,
            ws_ping_rtt_ms: 0,
        }
    }

    fn rate_limit_capabilities(&self) -> RateLimitCapabilities {
        GEMINI_RATE_CAPS
    }

    fn is_testnet(&self) -> bool {
        self.testnet
    }

    fn supported_account_types(&self) -> Vec<AccountType> {
        vec![
            AccountType::Spot,
            AccountType::FuturesCross,
        ]
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// MARKET DATA
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl MarketData for GeminiConnector {
    async fn get_price(&self, symbol: Symbol, account_type: AccountType) -> ExchangeResult<Price> {
        let symbol_str = normalize_symbol(&format_symbol(&symbol.base, &symbol.quote, account_type));

        let response = self.get(
            GeminiEndpoint::Ticker,
            &[("symbol", &symbol_str)],
        ).await?;

        let ticker = GeminiParser::parse_ticker(&response, &symbol_str)?;
        Ok(ticker.last_price)
    }

    async fn get_ticker(&self, symbol: Symbol, account_type: AccountType) -> ExchangeResult<Ticker> {
        let symbol_str = normalize_symbol(&format_symbol(&symbol.base, &symbol.quote, account_type));

        let response = self.get(
            GeminiEndpoint::TickerV2,
            &[("symbol", &symbol_str)],
        ).await?;

        GeminiParser::parse_ticker(&response, &symbol_str)
    }

    async fn get_orderbook(
        &self,
        symbol: Symbol,
        _depth: Option<u16>,
        account_type: AccountType,
    ) -> ExchangeResult<OrderBook> {
        let symbol_str = normalize_symbol(&format_symbol(&symbol.base, &symbol.quote, account_type));

        let response = self.get(
            GeminiEndpoint::OrderBook,
            &[("symbol", &symbol_str)],
        ).await?;

        GeminiParser::parse_orderbook(&response)
    }

    async fn get_klines(
        &self,
        symbol: Symbol,
        interval: &str,
        _limit: Option<u16>,
        account_type: AccountType,
        _end_time: Option<i64>,
    ) -> ExchangeResult<Vec<Kline>> {
        let symbol_str = normalize_symbol(&format_symbol(&symbol.base, &symbol.quote, account_type));
        let time_frame = map_kline_interval(interval);

        // Use DerivativeCandles endpoint for futures
        let endpoint = if matches!(account_type, AccountType::FuturesCross | AccountType::FuturesIsolated) {
            GeminiEndpoint::DerivativeCandles
        } else {
            GeminiEndpoint::Candles
        };

        let response = self.get(
            endpoint,
            &[("symbol", &symbol_str), ("time_frame", time_frame)],
        ).await?;

        GeminiParser::parse_candles(&response)
    }

    async fn ping(&self) -> ExchangeResult<()> {
        // Gemini doesn't have a dedicated ping endpoint, use symbols as health check
        self.get(GeminiEndpoint::Symbols, &[]).await?;
        Ok(())
    }

    async fn get_exchange_info(&self, account_type: AccountType) -> ExchangeResult<Vec<SymbolInfo>> {
        // Fetch all symbols first, then get details for each
        let symbols_response = self.get(GeminiEndpoint::Symbols, &[]).await?;
        let symbols = GeminiParser::parse_symbols(&symbols_response)?;

        let mut result = Vec::with_capacity(symbols.len());

        for symbol_lower in &symbols {
            // Skip non-spot/perpetual symbols (e.g. contain digits like options)
            // Only process lowercase alpha symbols
            if !symbol_lower.chars().all(|c| c.is_alphabetic()) {
                continue;
            }

            match self.get(GeminiEndpoint::SymbolDetails, &[("symbol", symbol_lower)]).await {
                Ok(details) => {
                    if let Some(info) = GeminiParser::parse_symbol_details(&details, symbol_lower, account_type) {
                        result.push(info);
                    }
                }
                Err(_) => continue, // Skip symbols where details fetch fails
            }
        }

        self.precision.load_from_symbols(&result);
        Ok(result)
    }

    fn market_data_capabilities(&self, account_type: AccountType) -> MarketDataCapabilities {
        let is_futures = !matches!(account_type, AccountType::Spot | AccountType::Margin);

        MarketDataCapabilities {
            // Gemini has no dedicated ping endpoint; we use /v1/symbols as health check
            has_ping: true,
            // Both spot and perpetuals work with /v1/pubticker/{symbol}
            has_price: true,
            // Both work with /v2/ticker/{symbol}; TickerV2 accepts perp symbols
            has_ticker: true,
            has_orderbook: true,
            // Both work: spot uses /v2/candles, futures uses /v2/derivatives/candles
            has_klines: true,
            // /v1/symbols + /v1/symbols/details is spot-oriented; perpetuals not listed there
            has_exchange_info: !is_futures,
            // GeminiEndpoint::Trades exists but get_recent_trades is not implemented
            // on the MarketData trait — the inherent endpoint is unused here
            has_recent_trades: false,
            // Both Candles and DerivativeCandles support the same time frames
            supported_intervals: &["1m", "5m", "15m", "30m", "1h", "6h", "1d"],
            // Gemini returns all available candles per time-frame; no limit param in either API
            max_kline_limit: None,
            // l2_updates channel carries orderbook deltas; ticker is approximated via l2 bid/ask.
            has_ws_ticker: true,
            has_ws_trades: true,
            // l2 channel provides full L2 orderbook stream.
            has_ws_orderbook: true,
            // candles_{interval} channel provides kline updates.
            has_ws_klines: true,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TRADING
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl Trading for GeminiConnector {
    async fn place_order(&self, req: OrderRequest) -> ExchangeResult<PlaceOrderResponse> {
        let symbol = req.symbol.clone();
        let side = req.side;
        let quantity = req.quantity;
        let account_type = req.account_type;
        let symbol_str = normalize_symbol(&format_symbol(&symbol.base, &symbol.quote, account_type));

        match req.order_type {
            OrderType::Market => {
                let mut params = HashMap::new();
                params.insert("symbol".to_string(), json!(symbol_str));
                params.insert("amount".to_string(), json!(self.precision.qty(&symbol_str, quantity)));
                params.insert("side".to_string(), json!(match side {
                    OrderSide::Buy => "buy",
                    OrderSide::Sell => "sell",
                }));
                params.insert("type".to_string(), json!("exchange market"));

                let response = self.post(GeminiEndpoint::NewOrder, params, &[]).await?;
                GeminiParser::parse_order(&response).map(PlaceOrderResponse::Simple)
            }
            OrderType::Limit { price } => {
                let mut params = HashMap::new();
                params.insert("symbol".to_string(), json!(symbol_str));
                params.insert("amount".to_string(), json!(self.precision.qty(&symbol_str, quantity)));
                params.insert("price".to_string(), json!(self.precision.price(&symbol_str, price)));
                params.insert("side".to_string(), json!(match side {
                    OrderSide::Buy => "buy",
                    OrderSide::Sell => "sell",
                }));
                params.insert("type".to_string(), json!("exchange limit"));

                let response = self.post(GeminiEndpoint::NewOrder, params, &[]).await?;
                GeminiParser::parse_order(&response).map(PlaceOrderResponse::Simple)
            }
            OrderType::StopLimit { stop_price, limit_price } => {
                // Gemini: type="exchange stop limit", stop_price=trigger, price=limit
                let mut params = HashMap::new();
                params.insert("symbol".to_string(), json!(symbol_str));
                params.insert("amount".to_string(), json!(self.precision.qty(&symbol_str, quantity)));
                params.insert("price".to_string(), json!(self.precision.price(&symbol_str, limit_price)));
                params.insert("stop_price".to_string(), json!(self.precision.price(&symbol_str, stop_price)));
                params.insert("side".to_string(), json!(match side {
                    OrderSide::Buy => "buy",
                    OrderSide::Sell => "sell",
                }));
                params.insert("type".to_string(), json!("exchange stop limit"));

                let response = self.post(GeminiEndpoint::NewOrder, params, &[]).await?;
                GeminiParser::parse_order(&response).map(PlaceOrderResponse::Simple)
            }
            OrderType::PostOnly { price } => {
                // Gemini: type="exchange limit" with options=["maker-or-cancel"]
                let mut params = HashMap::new();
                params.insert("symbol".to_string(), json!(symbol_str));
                params.insert("amount".to_string(), json!(self.precision.qty(&symbol_str, quantity)));
                params.insert("price".to_string(), json!(self.precision.price(&symbol_str, price)));
                params.insert("side".to_string(), json!(match side {
                    OrderSide::Buy => "buy",
                    OrderSide::Sell => "sell",
                }));
                params.insert("type".to_string(), json!("exchange limit"));
                params.insert("options".to_string(), json!(["maker-or-cancel"]));

                let response = self.post(GeminiEndpoint::NewOrder, params, &[]).await?;
                GeminiParser::parse_order(&response).map(PlaceOrderResponse::Simple)
            }
            OrderType::Ioc { price } => {
                // Gemini: type="exchange limit" with options=["immediate-or-cancel"]
                let limit_price = price.unwrap_or(0.0);
                let mut params = HashMap::new();
                params.insert("symbol".to_string(), json!(symbol_str));
                params.insert("amount".to_string(), json!(self.precision.qty(&symbol_str, quantity)));
                params.insert("price".to_string(), json!(self.precision.price(&symbol_str, limit_price)));
                params.insert("side".to_string(), json!(match side {
                    OrderSide::Buy => "buy",
                    OrderSide::Sell => "sell",
                }));
                params.insert("type".to_string(), json!("exchange limit"));
                params.insert("options".to_string(), json!(["immediate-or-cancel"]));

                let response = self.post(GeminiEndpoint::NewOrder, params, &[]).await?;
                GeminiParser::parse_order(&response).map(PlaceOrderResponse::Simple)
            }
            OrderType::Fok { price } => {
                // Gemini: type="exchange limit" with options=["fill-or-kill"]
                let mut params = HashMap::new();
                params.insert("symbol".to_string(), json!(symbol_str));
                params.insert("amount".to_string(), json!(self.precision.qty(&symbol_str, quantity)));
                params.insert("price".to_string(), json!(self.precision.price(&symbol_str, price)));
                params.insert("side".to_string(), json!(match side {
                    OrderSide::Buy => "buy",
                    OrderSide::Sell => "sell",
                }));
                params.insert("type".to_string(), json!("exchange limit"));
                params.insert("options".to_string(), json!(["fill-or-kill"]));

                let response = self.post(GeminiEndpoint::NewOrder, params, &[]).await?;
                GeminiParser::parse_order(&response).map(PlaceOrderResponse::Simple)
            }
            _ => Err(ExchangeError::UnsupportedOperation(
                format!("{:?} order type not supported on {:?}", req.order_type, self.exchange_id())
            )),
        }
    }

    async fn get_order_history(
        &self,
        filter: OrderHistoryFilter,
        account_type: AccountType,
    ) -> ExchangeResult<Vec<Order>> {
        // Gemini uses /v1/mytrades (PastTrades) for trade history
        let mut params = HashMap::new();

        // Add symbol filter if provided
        if let Some(ref symbol) = filter.symbol {
            let symbol_str = normalize_symbol(&format_symbol(&symbol.base, &symbol.quote, account_type));
            params.insert("symbol".to_string(), json!(symbol_str));
        }

        // Limit trades returned (max 500 per Gemini docs)
        let limit = filter.limit.unwrap_or(50).min(500);
        params.insert("limit_trades".to_string(), json!(limit));

        // Timestamp filter
        if let Some(since) = filter.start_time {
            params.insert("timestamp".to_string(), json!(since / 1000)); // convert ms to sec
        }

        let response = self.post(GeminiEndpoint::PastTrades, params, &[]).await?;
        GeminiParser::parse_past_trades(&response)
    }

    async fn cancel_order(&self, req: CancelRequest) -> ExchangeResult<Order> {
        match req.scope {
            CancelScope::Single { ref order_id } => {
                let mut params = HashMap::new();
                params.insert("order_id".to_string(), json!(order_id.parse::<i64>().unwrap_or(0)));

                let response = self.post(GeminiEndpoint::CancelOrder, params, &[]).await?;
                GeminiParser::parse_order(&response)
            }
            _ => Err(ExchangeError::UnsupportedOperation(
                format!("{:?} cancel scope not supported on {:?}", req.scope, self.exchange_id())
            )),
        }
    }

    async fn get_order(
        &self,
        _symbol: &str,
        order_id: &str,
        _account_type: AccountType,
    ) -> ExchangeResult<Order> {
        let mut params = HashMap::new();
        params.insert("order_id".to_string(), json!(order_id.parse::<i64>().unwrap_or(0)));

        let response = self.post(GeminiEndpoint::OrderStatus, params, &[]).await?;
        GeminiParser::parse_order(&response)
    }

    async fn get_open_orders(
        &self,
        _symbol: Option<&str>,
        _account_type: AccountType,
    ) -> ExchangeResult<Vec<Order>> {
        let response = self.post(GeminiEndpoint::ActiveOrders, HashMap::new(), &[]).await?;
        GeminiParser::parse_orders(&response)
    }

    async fn get_user_trades(
        &self,
        filter: UserTradeFilter,
        account_type: AccountType,
    ) -> ExchangeResult<Vec<UserTrade>> {
        let mut params = HashMap::new();

        // Symbol is required for Gemini /v1/mytrades.
        // If not provided, we attempt with no symbol (Gemini accepts it for some account types).
        if let Some(ref symbol_str) = filter.symbol {
            let sym_normalized = if symbol_str.contains('/') {
                let parts: Vec<&str> = symbol_str.splitn(2, '/').collect();
                normalize_symbol(&format_symbol(parts[0], parts.get(1).unwrap_or(&"USD"), account_type))
            } else {
                normalize_symbol(symbol_str)
            };
            params.insert("symbol".to_string(), json!(sym_normalized));
        }

        let limit = filter.limit.unwrap_or(50).min(500);
        params.insert("limit_trades".to_string(), json!(limit));

        // Gemini uses Unix timestamp in **seconds** for the `timestamp` param
        if let Some(st) = filter.start_time {
            params.insert("timestamp".to_string(), json!(st / 1000));
        }

        let response = self.post(GeminiEndpoint::PastTrades, params, &[]).await?;
        GeminiParser::parse_user_trades(&response, filter.end_time)
    }

    fn trading_capabilities(&self, account_type: AccountType) -> TradingCapabilities {
        let is_futures = !matches!(account_type, AccountType::Spot | AccountType::Margin);

        TradingCapabilities {
            has_market_order: true,
            has_limit_order: true,
            // Gemini has no stop-market (trigger-only) order type on either account type
            has_stop_market: false,
            // "exchange stop limit" is a spot-only order type; perpetuals use different flow
            has_stop_limit: !is_futures,
            // No trailing stop on Gemini REST API
            has_trailing_stop: false,
            // No bracket orders
            has_bracket: false,
            // No OCO on Gemini
            has_oco: false,
            // No order amendment endpoint
            has_amend: false,
            // No batch order placement
            has_batch: false,
            max_batch_size: None,
            // CancelAll trait is implemented via /v1/order/cancel/all
            has_cancel_all: true,
            // get_user_trades uses /v1/mytrades (works for both spot and futures trades)
            has_user_trades: true,
            // get_order_history also uses /v1/mytrades
            has_order_history: true,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ACCOUNT
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl Account for GeminiConnector {
    async fn get_balance(&self, _query: BalanceQuery) -> ExchangeResult<Vec<Balance>> {
        let response = self.post(GeminiEndpoint::Balances, HashMap::new(), &[]).await?;
        GeminiParser::parse_balances(&response)
    }

    async fn get_account_info(&self, _account_type: AccountType) -> ExchangeResult<AccountInfo> {
        // Gemini doesn't have a specific account info endpoint
        Ok(AccountInfo {
            account_type: _account_type,
            can_trade: true,
            can_withdraw: true,
            can_deposit: true,
            maker_commission: 0.0,
            taker_commission: 0.0,
            balances: vec![],
        })
    }

    async fn get_fees(&self, symbol: Option<&str>) -> ExchangeResult<FeeInfo> {
        // Use /v1/notionalvolume which returns API fee tier in basis points
        let response = self.post(GeminiEndpoint::NotionalVolume, HashMap::new(), &[]).await?;
        GeminiParser::parse_notional_volume_fees(&response, symbol)
    }

    fn account_capabilities(&self, account_type: AccountType) -> AccountCapabilities {
        let is_futures = !matches!(account_type, AccountType::Spot | AccountType::Margin);

        AccountCapabilities {
            // get_balance uses /v1/balances (works for both)
            has_balances: true,
            // get_account_info is a hardcoded stub with no real API call — reports false.
            has_account_info: false,
            // get_fees uses /v1/notionalvolume (spot fee tiers; less meaningful for futures)
            has_fees: !is_futures,
            // No AccountTransfers trait implemented — no internal transfer endpoint
            has_transfers: false,
            // No sub-account management
            has_sub_accounts: false,
            // Deposit/withdraw is a spot/custody concept; perpetuals are GUSD-settled internally
            has_deposit_withdraw: !is_futures,
            // MarginAccount exists as an extended method but no Account-level margin trait
            has_margin: false,
            // StakingBalances endpoint exists but no earn/staking Account trait is implemented
            has_earn_staking: false,
            // /v1/perpetuals/fundingPayment exists and is exposed as get_funding_payments() extended method
            has_funding_history: is_futures,
            // No ledger / transactions trait implemented
            has_ledger: false,
            // No convert/swap support
            has_convert: false,
            // Positions trait is implemented; relevant for futures account types.
            has_positions: is_futures,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// POSITIONS
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl Positions for GeminiConnector {
    async fn get_positions(&self, _query: PositionQuery) -> ExchangeResult<Vec<Position>> {
        let response = self.post(GeminiEndpoint::Positions, HashMap::new(), &[]).await?;
        GeminiParser::parse_positions(&response)
    }

    async fn get_funding_rate(
        &self,
        symbol: &str,
        _account_type: AccountType,
    ) -> ExchangeResult<FundingRate> {
        let symbol_parts: Vec<&str> = symbol.split('/').collect();
        let sym = if symbol_parts.len() == 2 {
            crate::core::Symbol::new(symbol_parts[0], symbol_parts[1])
        } else {
            crate::core::Symbol { base: symbol.to_string(), quote: String::new(), raw: Some(symbol.to_string()) }
        };

        let symbol_str = normalize_symbol(&format_symbol(&sym.base, &sym.quote, AccountType::FuturesCross));

        let response = self.get(
            GeminiEndpoint::FundingAmount,
            &[("symbol", &symbol_str)],
        ).await?;

        GeminiParser::parse_funding_rate(&response)
    }

    async fn modify_position(&self, req: PositionModification) -> ExchangeResult<()> {
        match req {
            PositionModification::SetLeverage { .. } => {
                // Gemini doesn't have a set leverage endpoint
                Err(ExchangeError::NotSupported("Set leverage not supported by Gemini".to_string()))
            }
            _ => Err(ExchangeError::UnsupportedOperation(
                format!("{:?} not supported on {:?}", req, self.exchange_id())
            )),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CANCEL ALL TRAIT
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl CancelAll for GeminiConnector {
    async fn cancel_all_orders(
        &self,
        _scope: CancelScope,
        _account_type: AccountType,
    ) -> ExchangeResult<CancelAllResponse> {
        // Gemini /v1/order/cancel/all cancels all session orders globally.
        // There is no per-symbol cancel-all in the REST API.
        let response = self.post(GeminiEndpoint::CancelAllOrders, HashMap::new(), &[]).await?;

        // Response: {"result":"ok","details":{"cancelledOrders":[...],"cancelRejects":[...]}}
        let cancelled_count = response
            .get("details")
            .and_then(|d| d.get("cancelledOrders"))
            .and_then(|arr| arr.as_array())
            .map(|arr| arr.len() as u32)
            .unwrap_or(0);

        let failed_count = response
            .get("details")
            .and_then(|d| d.get("cancelRejects"))
            .and_then(|arr| arr.as_array())
            .map(|arr| arr.len() as u32)
            .unwrap_or(0);

        Ok(CancelAllResponse {
            cancelled_count,
            failed_count,
            details: vec![],
        })
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CUSTODIAL FUNDS (optional trait)
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl CustodialFunds for GeminiConnector {
    /// Get a new deposit address for an asset.
    ///
    /// Endpoint: POST /v1/deposit/{currency}/newAddress
    /// The `network` parameter is used as the currency path segment if provided.
    async fn get_deposit_address(
        &self,
        asset: &str,
        network: Option<&str>,
    ) -> ExchangeResult<DepositAddress> {
        let currency = network.unwrap_or(asset).to_lowercase();
        let params = HashMap::new();

        let response = self.post(
            GeminiEndpoint::NewDepositAddress,
            params,
            &[("network", &currency)],
        ).await?;

        // Response: {"currency": "BTC", "address": "...", "label": "...", "timestamp": ...}
        let address = response.get("address")
            .and_then(|v| v.as_str())
            .ok_or_else(|| ExchangeError::Parse("Missing address in deposit address response".to_string()))?
            .to_string();

        let created_at = response.get("timestamp")
            .and_then(|v| v.as_i64());

        Ok(DepositAddress {
            address,
            tag: None, // Gemini doesn't return a tag/memo for standard addresses
            network: Some(currency),
            asset: asset.to_string(),
            created_at,
        })
    }

    /// Submit a withdrawal request.
    ///
    /// Endpoint: POST /v1/withdraw/{currency}
    /// Params: address, amount
    async fn withdraw(&self, req: WithdrawRequest) -> ExchangeResult<WithdrawResponse> {
        let currency = req.asset.to_lowercase();

        let mut params = HashMap::new();
        params.insert("address".to_string(), json!(req.address));
        params.insert("amount".to_string(), json!(req.amount.to_string()));

        let response = self.post(
            GeminiEndpoint::Withdraw,
            params,
            &[("currency", &currency)],
        ).await?;

        // Response: {"destination": "...", "amount": "...", "txHash": "...", "withdrawalId": "..."}
        // or on error: {"result": "error", "reason": "..."}
        let withdraw_id = response.get("withdrawalId")
            .or_else(|| response.get("id"))
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        let tx_hash = response.get("txHash")
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string());

        Ok(WithdrawResponse {
            withdraw_id,
            status: "Pending".to_string(),
            tx_hash,
        })
    }

    /// Get deposit and/or withdrawal history via the transfers endpoint.
    ///
    /// Endpoint: POST /v1/transfers
    /// Both deposits and withdrawals are returned by the same endpoint.
    /// Filtered client-side by `type` field ("Deposit" or "Withdrawal").
    async fn get_funds_history(
        &self,
        filter: FundsHistoryFilter,
    ) -> ExchangeResult<Vec<FundsRecord>> {
        let mut params = HashMap::new();

        if let Some(limit) = filter.limit {
            params.insert("limit_transfers".to_string(), json!(limit.min(50u32)));
        }

        if let Some(start) = filter.start_time {
            // Gemini uses Unix timestamp in seconds
            params.insert("timestamp".to_string(), json!(start / 1000));
        }

        let response = self.post(GeminiEndpoint::Transfers, params, &[]).await?;

        // Response is an array of transfer objects:
        // {"type": "Deposit"|"Withdrawal", "status": "...", "timestampms": ...,
        //  "eid": ..., "currency": "...", "amount": "...",
        //  "destination": "...", "txHash": "...", "feeAmount": "..."}
        let records = if let Some(arr) = response.as_array() {
            arr.iter().filter_map(|item| {
                let obj = item.as_object()?;

                let transfer_type = obj.get("type")?.as_str()?;
                let currency = obj.get("currency")?.as_str().unwrap_or("").to_uppercase();

                // Filter by asset if specified
                if let Some(ref asset_filter) = filter.asset {
                    if !currency.eq_ignore_ascii_case(asset_filter) {
                        return None;
                    }
                }

                let id = obj.get("eid").and_then(|v| v.as_i64()).map(|v| v.to_string())
                    .or_else(|| obj.get("eventId").and_then(|v| v.as_str()).map(|s| s.to_string()))
                    .unwrap_or_default();
                let amount_str = obj.get("amount").and_then(|v| v.as_str()).unwrap_or("0");
                let amount = amount_str.parse::<f64>().unwrap_or(0.0);
                let timestamp = obj.get("timestampms").and_then(|v| v.as_i64()).unwrap_or(0);
                let status = obj.get("status").and_then(|v| v.as_str()).unwrap_or("Unknown").to_string();
                let tx_hash = obj.get("txHash")
                    .and_then(|v| v.as_str())
                    .filter(|s| !s.is_empty())
                    .map(|s| s.to_string());

                match transfer_type {
                    "Deposit" | "deposit" => {
                        if matches!(filter.record_type, FundsRecordType::Deposit | FundsRecordType::Both) {
                            Some(FundsRecord::Deposit {
                                id,
                                asset: currency,
                                amount,
                                tx_hash,
                                network: None,
                                status,
                                timestamp,
                            })
                        } else {
                            None
                        }
                    }
                    "Withdrawal" | "withdrawal" => {
                        if matches!(filter.record_type, FundsRecordType::Withdrawal | FundsRecordType::Both) {
                            let address = obj.get("destination")
                                .and_then(|v| v.as_str())
                                .unwrap_or("")
                                .to_string();
                            let fee_str = obj.get("feeAmount").and_then(|v| v.as_str()).unwrap_or("0");
                            let fee = fee_str.parse::<f64>().ok().filter(|&f| f > 0.0);

                            Some(FundsRecord::Withdrawal {
                                id,
                                asset: currency,
                                amount,
                                fee,
                                address,
                                tag: None,
                                tx_hash,
                                network: None,
                                status,
                                timestamp,
                            })
                        } else {
                            None
                        }
                    }
                    _ => None,
                }
            }).collect()
        } else {
            vec![]
        };

        Ok(records)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// EXTENDED METHODS (Gemini-специфичные)
// ═══════════════════════════════════════════════════════════════════════════════

impl GeminiConnector {
    /// Get all available symbols
    pub async fn get_symbols(&self) -> ExchangeResult<Vec<String>> {
        let response = self.get(GeminiEndpoint::Symbols, &[]).await?;
        GeminiParser::parse_symbols(&response)
    }

    /// Get notional volume and fee information
    pub async fn get_notional_volume(&self) -> ExchangeResult<Value> {
        self.post(GeminiEndpoint::NotionalVolume, HashMap::new(), &[]).await
    }

    /// Get funding payment history for perpetuals
    pub async fn get_funding_payments(
        &self,
        since: Option<i64>,
        to: Option<i64>,
    ) -> ExchangeResult<Value> {
        let mut params = HashMap::new();

        if let Some(s) = since {
            params.insert("since".to_string(), json!(s));
        }
        if let Some(t) = to {
            params.insert("to".to_string(), json!(t));
        }

        self.post(GeminiEndpoint::FundingPayments, params, &[]).await
    }

    /// Get margin account summary
    pub async fn get_margin_info(&self) -> ExchangeResult<Value> {
        self.post(GeminiEndpoint::MarginAccount, HashMap::new(), &[]).await
    }
}

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

    #[tokio::test]
    async fn test_connector_creation() {
        let connector = GeminiConnector::public(false).await.unwrap();
        assert_eq!(connector.exchange_id(), ExchangeId::Gemini);
        assert!(!connector.is_testnet());
    }

    #[test]
    fn test_format_symbol() {
        let symbol = format_symbol("BTC", "USD", AccountType::Spot);
        assert_eq!(symbol, "btcusd");

        let symbol = format_symbol("ETH", "USD", AccountType::FuturesCross);
        assert_eq!(symbol, "ethgusdperp");
    }
}