kraken_async_rs/clients/
core_kraken_client.rs

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
//! A base implementation of [KrakenClient]
use crate::clients::errors::ClientError;
use crate::clients::errors::KrakenError;
use crate::clients::http_response_types::ResultErrorResponse;
use crate::clients::kraken_client::endpoints::*;
use crate::clients::kraken_client::KrakenClient;
use crate::crypto::nonce_provider::NonceProvider;
use crate::crypto::nonce_request::NonceRequest;
use crate::crypto::signatures::{generate_signature, Signature};
use crate::request_types::*;
use crate::response_types::*;
use crate::secrets::secrets_provider::SecretsProvider;
#[allow(unused)]
use crate::secrets::secrets_provider::StaticSecretsProvider;
use http_body_util::BodyExt;
use hyper::http::request::Builder;
use hyper::{Method, Request, Uri};
use hyper_tls::HttpsConnector;
use hyper_util::client::legacy::connect::HttpConnector;
use hyper_util::client::legacy::Client;
use hyper_util::rt::TokioExecutor;
use secrecy::ExposeSecret;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Arc;
use to_query_params::{QueryParams, ToQueryParams};
use tokio::sync::Mutex;
use tracing::{debug, trace, warn};
use url::{form_urlencoded, Url};

#[derive(QueryParams, Default)]
struct EmptyRequest {}

/// The base implementation of [KrakenClient]. It has no rate limiting, and uses whatever
/// [SecretsProvider] and [NonceProvider] it is given.
///
/// This is most useful for one-off calls, or building more complex behavior on top of.
///
/// # Example: Making a Public API Call
/// Creating a [CoreKrakenClient] is as simple as providing a [SecretsProvider] and [NonceProvider].
/// For public calls, a [StaticSecretsProvider] with empty strings will work, since there is no auth
/// required for public endpoints.
///
/// Requests follow a builder pattern, with required parameters in the `::builder()` call, if there
/// are any. Here, only the pair (optional) is provided.
///
/// ```
/// # use kraken_async_rs::clients::core_kraken_client::CoreKrakenClient;
/// # use kraken_async_rs::clients::kraken_client::KrakenClient;
/// # use kraken_async_rs::crypto::nonce_provider::{IncreasingNonceProvider, NonceProvider};
/// # use kraken_async_rs::clients::http_response_types::ResultErrorResponse;
/// # use kraken_async_rs::request_types::{StringCSV, TradableAssetPairsRequest};
/// # use kraken_async_rs::secrets::secrets_provider::StaticSecretsProvider;
/// # use std::sync::Arc;
/// # use tokio::sync::Mutex;
///
/// #[tokio::main]
/// async fn main() {
///     // credentials aren't needed for public endpoints
///     use kraken_async_rs::secrets::secrets_provider::SecretsProvider;
/// let secrets_provider: Box<Arc<Mutex<dyn SecretsProvider>>> = Box::new(Arc::new(Mutex::new(StaticSecretsProvider::new("", ""))));
///     let nonce_provider: Box<Arc<Mutex<dyn NonceProvider>>> =
///         Box::new(Arc::new(Mutex::new(IncreasingNonceProvider::new())));
///     let mut client = CoreKrakenClient::new(secrets_provider, nonce_provider);
///
///     let request = TradableAssetPairsRequest::builder()
///         .pair(StringCSV::new(vec!["BTCUSD".to_string()]))
///         .build();
///
///     let open_orders_response = client.get_tradable_asset_pairs(&request).await;
///
///     // Note that Kraken will return assets in their own naming scheme, e.g. a request for
///     // "BTCUSD" will return as "XXBTZUSD"
///     // For a reasonable understanding of their mappings, see: https://gist.github.com/brendano257/975a395d73a6d7bb53e53d292534d6af
///     if let Ok(ResultErrorResponse {
///         result: Some(tradable_assets),
///         ..
///     }) = open_orders_response
///     {
///         for (asset, details) in tradable_assets {
///             println!("{asset}: {details:?}")
///         }
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub struct CoreKrakenClient {
    pub api_url: String,
    secrets_provider: Box<Arc<Mutex<dyn SecretsProvider>>>,
    nonce_provider: Box<Arc<Mutex<dyn NonceProvider>>>,
    http_client: Client<HttpsConnector<HttpConnector>, String>,
    user_agent: Option<String>,
    trace_inbound: bool,
}

impl KrakenClient for CoreKrakenClient {
    fn new(
        secrets_provider: Box<Arc<Mutex<dyn SecretsProvider>>>,
        nonce_provider: Box<Arc<Mutex<dyn NonceProvider>>>,
    ) -> Self {
        if cfg!(feature = "debug-inbound") {
            warn!("Feature `debug-inbound` is deprecated - use `new_with_tracing` method to set tracing flag")
        }

        let https = HttpsConnector::new();
        let http_client: Client<HttpsConnector<HttpConnector>, String> =
            Client::builder(TokioExecutor::new()).build(https);
        CoreKrakenClient {
            api_url: KRAKEN_BASE_URL.into(),
            secrets_provider,
            nonce_provider,
            http_client,
            user_agent: None,
            trace_inbound: false,
        }
    }

    fn new_with_url(
        secrets_provider: Box<Arc<Mutex<dyn SecretsProvider>>>,
        nonce_provider: Box<Arc<Mutex<dyn NonceProvider>>>,
        url: String,
    ) -> Self {
        let https = HttpsConnector::new();
        let http_client = Client::builder(TokioExecutor::new()).build(https);
        CoreKrakenClient {
            api_url: url,
            secrets_provider,
            nonce_provider,
            http_client,
            user_agent: None,
            trace_inbound: false,
        }
    }

    fn new_with_tracing(
        secrets_provider: Box<Arc<Mutex<dyn SecretsProvider>>>,
        nonce_provider: Box<Arc<Mutex<dyn NonceProvider>>>,
        trace_inbound: bool,
    ) -> Self {
        let https = HttpsConnector::new();
        let http_client = Client::builder(TokioExecutor::new()).build(https);
        CoreKrakenClient {
            api_url: KRAKEN_BASE_URL.into(),
            secrets_provider,
            nonce_provider,
            http_client,
            user_agent: None,
            trace_inbound,
        }
    }

    async fn set_user_agent(&mut self, user_agent: String) {
        self.user_agent = Some(user_agent);
    }

    #[tracing::instrument(ret, err(Debug), skip(self))]
    async fn get_server_time(&mut self) -> Result<ResultErrorResponse<SystemTime>, ClientError> {
        let url = Url::from_str(&self.api_url(TIME_ENDPOINT))?;
        let body = self.body_from_url(Method::GET, &url, "".into()).await?;
        Ok(serde_json::from_str(&body)?)
    }

    #[tracing::instrument(ret, err(Debug), skip(self))]
    async fn get_system_status(
        &mut self,
    ) -> Result<ResultErrorResponse<SystemStatusInfo>, ClientError> {
        let url = Url::from_str(&self.api_url(STATUS_ENDPOINT))?;
        let body = self.body_from_url(Method::GET, &url, "".into()).await?;
        Ok(serde_json::from_str(&body)?)
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_asset_info(
        &mut self,
        request: &AssetInfoRequest,
    ) -> Result<ResultErrorResponse<HashMap<String, AssetInfo>>, ClientError> {
        self.public_get(ASSET_INFO_ENDPOINT, request).await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_tradable_asset_pairs(
        &mut self,
        request: &TradableAssetPairsRequest,
    ) -> Result<ResultErrorResponse<HashMap<String, TradableAssetPair>>, ClientError> {
        self.public_get(TRADABLE_ASSET_PAIRS_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_ticker_information(
        &mut self,
        request: &TickerRequest,
    ) -> Result<ResultErrorResponse<HashMap<String, RestTickerInfo>>, ClientError> {
        self.public_get(TICKER_INFO_ENDPOINT, request).await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_ohlc(
        &mut self,
        request: &OHLCRequest,
    ) -> Result<ResultErrorResponse<OhlcResponse>, ClientError> {
        self.public_get(OHLC_ENDPOINT, request).await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_orderbook(
        &mut self,
        request: &OrderbookRequest,
    ) -> Result<ResultErrorResponse<HashMap<String, Orderbook>>, ClientError> {
        self.public_get(ORDER_BOOK_ENDPOINT, request).await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_recent_trades(
        &mut self,
        request: &RecentTradesRequest,
    ) -> Result<ResultErrorResponse<RecentTrades>, ClientError> {
        self.public_get(RECENT_TRADES_ENDPOINT, request).await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_recent_spreads(
        &mut self,
        request: &RecentSpreadsRequest,
    ) -> Result<ResultErrorResponse<RecentSpreads>, ClientError> {
        self.public_get(RECENT_SPREADS_ENDPOINT, request).await
    }

    #[tracing::instrument(ret, err(Debug), skip(self))]
    async fn get_account_balance(
        &mut self,
    ) -> Result<ResultErrorResponse<AccountBalances>, ClientError> {
        self.private_form_post(ACCOUNT_BALANCE_ENDPOINT, &EmptyRequest::default())
            .await
    }

    #[tracing::instrument(ret, err(Debug), skip(self))]
    async fn get_extended_balances(
        &mut self,
    ) -> Result<ResultErrorResponse<ExtendedBalances>, ClientError> {
        self.private_form_post(ACCOUNT_BALANCE_EXTENDED_ENDPOINT, &EmptyRequest::default())
            .await
    }

    #[tracing::instrument(ret, err(Debug), skip(self))]
    async fn get_trade_balances(
        &mut self,
        request: &TradeBalanceRequest,
    ) -> Result<ResultErrorResponse<TradeBalances>, ClientError> {
        self.private_form_post(TRADE_BALANCE_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_open_orders(
        &mut self,
        request: &OpenOrdersRequest,
    ) -> Result<ResultErrorResponse<OpenOrders>, ClientError> {
        self.private_form_post(OPEN_ORDERS_ENDPOINT, request).await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_closed_orders(
        &mut self,
        request: &ClosedOrdersRequest,
    ) -> Result<ResultErrorResponse<ClosedOrders>, ClientError> {
        self.private_form_post(CLOSED_ORDERS_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(ret, err(Debug), skip(self))]
    async fn query_orders_info(
        &mut self,
        request: &OrderRequest,
    ) -> Result<ResultErrorResponse<HashMap<String, Order>>, ClientError> {
        self.private_form_post(QUERY_ORDERS_ENDPOINT, request).await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_order_amends(
        &mut self,
        request: &OrderAmendsRequest,
    ) -> Result<ResultErrorResponse<OrderAmends>, ClientError> {
        self.private_json_post(ORDER_AMENDS_ENDPOINT, request).await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_trades_history(
        &mut self,
        request: &TradesHistoryRequest,
    ) -> Result<ResultErrorResponse<TradesHistory>, ClientError> {
        self.private_form_post(TRADES_HISTORY_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn query_trades_info(
        &mut self,
        request: &TradeInfoRequest,
    ) -> Result<ResultErrorResponse<TradesInfo>, ClientError> {
        self.private_form_post(QUERY_TRADES_ENDPOINT, request).await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_open_positions(
        &mut self,
        request: &OpenPositionsRequest,
    ) -> Result<ResultErrorResponse<OpenPositions>, ClientError> {
        self.private_form_post(OPEN_POSITIONS_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_ledgers_info(
        &mut self,
        request: &LedgersInfoRequest,
    ) -> Result<ResultErrorResponse<LedgerInfo>, ClientError> {
        self.private_form_post(LEDGERS_ENDPOINT, request).await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn query_ledgers(
        &mut self,
        request: &QueryLedgerRequest,
    ) -> Result<ResultErrorResponse<QueryLedgerInfo>, ClientError> {
        self.private_form_post(QUERY_LEDGERS_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(ret, err(Debug), skip(self))]
    async fn get_trade_volume(
        &mut self,
        request: &TradeVolumeRequest,
    ) -> Result<ResultErrorResponse<TradeVolume>, ClientError> {
        self.private_form_post(TRADE_VOLUME_ENDPOINT, request).await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn request_export_report(
        &mut self,
        request: &ExportReportRequest,
    ) -> Result<ResultErrorResponse<ExportReport>, ClientError> {
        self.private_form_post(ADD_EXPORT_ENDPOINT, request).await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_export_report_status(
        &mut self,
        request: &ExportReportStatusRequest,
    ) -> Result<ResultErrorResponse<Vec<ExportReportStatus>>, ClientError> {
        self.private_form_post(EXPORT_STATUS_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn retrieve_export_report(
        &mut self,
        request: &RetrieveExportReportRequest,
    ) -> Result<Vec<u8>, ClientError> {
        self.private_post_binary::<RetrieveExportReportRequest>(RETRIEVE_EXPORT_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn delete_export_report(
        &mut self,
        request: &DeleteExportRequest,
    ) -> Result<ResultErrorResponse<DeleteExportReport>, ClientError> {
        self.private_form_post(REMOVE_EXPORT_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(ret, err(Debug), skip(self))]
    async fn add_order(
        &mut self,
        request: &AddOrderRequest,
    ) -> Result<ResultErrorResponse<AddOrder>, ClientError> {
        self.private_form_post(ADD_ORDER_ENDPOINT, request).await
    }

    #[tracing::instrument(ret, err(Debug), skip(self))]
    async fn add_order_batch(
        &mut self,
        request: &AddBatchedOrderRequest,
    ) -> Result<ResultErrorResponse<AddOrderBatch>, ClientError> {
        self.private_json_post(ADD_ORDER_BATCH_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(ret, err(Debug), skip(self))]
    async fn amend_order(
        &mut self,
        request: &AmendOrderRequest,
    ) -> Result<ResultErrorResponse<AmendOrder>, ClientError> {
        self.private_json_post(AMEND_ORDER_ENDPOINT, request).await
    }

    #[tracing::instrument(ret, err(Debug), skip(self))]
    async fn edit_order(
        &mut self,
        request: &EditOrderRequest,
    ) -> Result<ResultErrorResponse<OrderEdit>, ClientError> {
        self.private_form_post(EDIT_ORDER_ENDPOINT, request).await
    }

    #[tracing::instrument(ret, err(Debug), skip(self))]
    async fn cancel_order(
        &mut self,
        request: &CancelOrderRequest,
    ) -> Result<ResultErrorResponse<CancelOrder>, ClientError> {
        self.private_form_post(CANCEL_ORDER_ENDPOINT, request).await
    }

    #[tracing::instrument(ret, err(Debug), skip(self))]
    async fn cancel_all_orders(&mut self) -> Result<ResultErrorResponse<CancelOrder>, ClientError> {
        self.private_form_post(CANCEL_ALL_ORDERS_ENDPOINT, &EmptyRequest::default())
            .await
    }

    #[tracing::instrument(ret, err(Debug), skip(self))]
    async fn cancel_all_orders_after(
        &mut self,
        request: &CancelAllOrdersAfterRequest,
    ) -> Result<ResultErrorResponse<CancelAllOrdersAfter>, ClientError> {
        self.private_form_post(CANCEL_ALL_ORDERS_AFTER_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(ret, err(Debug), skip(self))]
    async fn cancel_order_batch(
        &mut self,
        request: &CancelBatchOrdersRequest,
    ) -> Result<ResultErrorResponse<CancelOrder>, ClientError> {
        self.private_json_post(CANCEL_ORDER_BATCH_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_deposit_methods(
        &mut self,
        request: &DepositMethodsRequest,
    ) -> Result<ResultErrorResponse<Vec<DepositMethod>>, ClientError> {
        self.private_form_post(DEPOSIT_METHODS_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_deposit_addresses(
        &mut self,
        request: &DepositAddressesRequest,
    ) -> Result<ResultErrorResponse<Vec<DepositAddress>>, ClientError> {
        self.private_form_post(DEPOSIT_ADDRESSES_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_status_of_recent_deposits(
        &mut self,
        request: &StatusOfDepositWithdrawRequest,
    ) -> Result<ResultErrorResponse<DepositWithdrawResponse>, ClientError> {
        self.private_form_post(DEPOSIT_STATUS_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_withdrawal_methods(
        &mut self,
        request: &WithdrawalMethodsRequest,
    ) -> Result<ResultErrorResponse<Vec<WithdrawMethod>>, ClientError> {
        self.private_form_post(WITHDRAW_METHODS_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_withdrawal_addresses(
        &mut self,
        request: &WithdrawalAddressesRequest,
    ) -> Result<ResultErrorResponse<Vec<WithdrawalAddress>>, ClientError> {
        self.private_form_post(WITHDRAW_ADDRESSES_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_withdrawal_info(
        &mut self,
        request: &WithdrawalInfoRequest,
    ) -> Result<ResultErrorResponse<Withdrawal>, ClientError> {
        self.private_form_post(WITHDRAW_INFO_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn withdraw_funds(
        &mut self,
        request: &WithdrawFundsRequest,
    ) -> Result<ResultErrorResponse<ConfirmationRefId>, ClientError> {
        self.private_form_post(WITHDRAW_ENDPOINT, request).await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_status_of_recent_withdrawals(
        &mut self,
        request: &StatusOfDepositWithdrawRequest,
    ) -> Result<ResultErrorResponse<Vec<DepositWithdrawal>>, ClientError> {
        self.private_form_post(WITHDRAW_STATUS_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn request_withdrawal_cancellation(
        &mut self,
        request: &WithdrawCancelRequest,
    ) -> Result<ResultErrorResponse<bool>, ClientError> {
        self.private_form_post(WITHDRAW_CANCEL_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn request_wallet_transfer(
        &mut self,
        request: &WalletTransferRequest,
    ) -> Result<ResultErrorResponse<ConfirmationRefId>, ClientError> {
        self.private_form_post(WALLET_TRANSFER_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn create_sub_account(
        &mut self,
        request: &CreateSubAccountRequest,
    ) -> Result<ResultErrorResponse<bool>, ClientError> {
        self.private_form_post(CREATE_SUB_ACCOUNT_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn account_transfer(
        &mut self,
        request: &AccountTransferRequest,
    ) -> Result<ResultErrorResponse<AccountTransfer>, ClientError> {
        self.private_form_post(ACCOUNT_TRANSFER_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn allocate_earn_funds(
        &mut self,
        request: &AllocateEarnFundsRequest,
    ) -> Result<ResultErrorResponse<bool>, ClientError> {
        self.private_form_post(EARN_ALLOCATE_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn deallocate_earn_funds(
        &mut self,
        request: &AllocateEarnFundsRequest,
    ) -> Result<ResultErrorResponse<bool>, ClientError> {
        self.private_form_post(EARN_DEALLOCATE_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_earn_allocation_status(
        &mut self,
        request: &EarnAllocationStatusRequest,
    ) -> Result<ResultErrorResponse<AllocationStatus>, ClientError> {
        self.private_form_post(EARN_ALLOCATE_STATUS_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_earn_deallocation_status(
        &mut self,
        request: &EarnAllocationStatusRequest,
    ) -> Result<ResultErrorResponse<AllocationStatus>, ClientError> {
        self.private_form_post(EARN_DEALLOCATE_STATUS_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn list_earn_strategies(
        &mut self,
        request: &ListEarnStrategiesRequest,
    ) -> Result<ResultErrorResponse<EarnStrategies>, ClientError> {
        self.private_form_post(EARN_STRATEGIES_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn list_earn_allocations(
        &mut self,
        request: &ListEarnAllocationsRequest,
    ) -> Result<ResultErrorResponse<EarnAllocations>, ClientError> {
        self.private_form_post(EARN_ALLOCATIONS_ENDPOINT, request)
            .await
    }

    #[tracing::instrument(err(Debug), skip(self))]
    async fn get_websockets_token(
        &mut self,
    ) -> Result<ResultErrorResponse<WebsocketToken>, ClientError> {
        let url = Url::from_str(&self.api_url(GET_WS_TOKEN_ENDPOINT))?;
        let signature = self
            .get_form_signature(GET_WS_TOKEN_ENDPOINT, &EmptyRequest::default())
            .await;

        let response_body = self
            .body_from_url_and_form_with_auth(Method::POST, &url, signature)
            .await?;

        Ok(serde_json::from_str(&response_body)?)
    }
}

impl CoreKrakenClient {
    fn api_url(&self, endpoint: &str) -> String {
        format!("{}{}", self.api_url, endpoint)
    }

    fn get_user_agent(&self) -> String {
        self.user_agent
            .clone()
            .unwrap_or("KrakenAsyncRsClient".to_string())
    }

    fn add_query_params<T: ToQueryParams>(url: &mut Url, request: &T) {
        for (k, v) in request.to_query_params() {
            url.query_pairs_mut().append_pair(&k, &v);
        }
    }

    fn request_builder_from_url(method: Method, url: &Url) -> Result<Builder, ClientError> {
        let uri = url.as_str().parse::<Uri>()?;
        Ok(Request::builder().method(method).uri(uri.to_string()))
    }

    async fn public_get<T, R>(
        &self,
        url: &str,
        request: &R,
    ) -> Result<ResultErrorResponse<T>, ClientError>
    where
        T: for<'a> Deserialize<'a>,
        R: ToQueryParams,
    {
        let mut url = Url::from_str(&self.api_url(url))?;
        Self::add_query_params(&mut url, request);

        let response_body = self.body_from_url(Method::GET, &url, "".into()).await?;
        Self::parse_body_and_errors(&response_body)
    }

    async fn private_form_post<T, R>(
        &mut self,
        url: &str,
        request: &R,
    ) -> Result<ResultErrorResponse<T>, ClientError>
    where
        T: for<'a> Deserialize<'a>,
        R: ToQueryParams,
    {
        let signature = self.get_form_signature(url, request).await;
        let url = Url::from_str(&self.api_url(url))?;

        let response_body = self
            .body_from_url_and_form_with_auth(Method::POST, &url, signature)
            .await?;

        Self::parse_body_and_errors(&response_body)
    }

    async fn private_json_post<T, R>(
        &mut self,
        url: &str,
        request: &R,
    ) -> Result<ResultErrorResponse<T>, ClientError>
    where
        T: for<'a> Deserialize<'a>,
        R: Serialize,
    {
        let signature = self.get_json_signature(url, request).await?;
        let url = Url::from_str(&self.api_url(url))?;

        let response_body = self
            .body_from_url_and_json_with_auth(Method::POST, &url, signature)
            .await?;

        Self::parse_body_and_errors(&response_body)
    }

    async fn private_post_binary<R>(
        &mut self,
        url: &str,
        request: &R,
    ) -> Result<Vec<u8>, ClientError>
    where
        R: ToQueryParams,
    {
        let signature = self.get_form_signature(url, request).await;
        let url = Url::from_str(&self.api_url(url))?;

        self.body_from_url_as_data(Method::POST, &url, signature)
            .await
    }

    fn parse_body_and_errors<T>(body: &str) -> Result<ResultErrorResponse<T>, ClientError>
    where
        T: for<'a> Deserialize<'a>,
    {
        let result: ResultErrorResponse<T> = serde_json::from_str(body)?;

        if let Some(error) = result.error.first() {
            error
                .try_into()
                .map(|err: KrakenError| Err(ClientError::Kraken(err)))
                .unwrap_or(Ok(result))
        } else {
            Ok(result)
        }
    }

    async fn body_from_url(
        &self,
        method: Method,
        url: &Url,
        request_body: String,
    ) -> Result<String, ClientError> {
        let request = Self::request_builder_from_url(method, url)?
            .header("Accept", "application/json")
            .header("Content-Type", "application/x-www-form-urlencoded")
            .header("User-Agent", self.get_user_agent().as_str())
            .body(request_body)?;

        self.body_from_request(request).await
    }

    async fn body_from_url_and_form_with_auth(
        &mut self,
        method: Method,
        url: &Url,
        signature: Signature,
    ) -> Result<String, ClientError> {
        let request = self.build_form_request(method, url, signature).await?;
        self.body_from_request(request).await
    }

    async fn body_from_url_and_json_with_auth(
        &mut self,
        method: Method,
        url: &Url,
        signature: Signature,
    ) -> Result<String, ClientError> {
        let mut secrets_provider = self.secrets_provider.lock().await;
        let request = Self::request_builder_from_url(method, url)?
            .header("Accept", "application/json")
            .header("Content-Type", "application/json")
            .header("User-Agent", self.get_user_agent().as_str())
            .header(
                "API-Key",
                secrets_provider.get_secrets().key.expose_secret(),
            )
            .header("API-Sign", signature.signature)
            .body(signature.body_data)?;

        self.body_from_request(request).await
    }

    async fn body_from_url_as_data(
        &mut self,
        method: Method,
        url: &Url,
        signature: Signature,
    ) -> Result<Vec<u8>, ClientError> {
        let request = self.build_form_request(method, url, signature).await?;
        let resp = self.http_client.request(request).await?;

        let status = resp.status();
        let bytes = resp.into_body().collect().await?.to_bytes();

        if !status.is_success() {
            Err(ClientError::HttpStatus(format!(
                "HTTP Status: {}",
                status.as_u16()
            )))
        } else {
            Ok(bytes.to_vec())
        }
    }

    async fn body_from_request(&self, req: Request<String>) -> Result<String, ClientError> {
        let resp = self.http_client.request(req).await?;

        let status = resp.status();
        let bytes = resp.into_body().collect().await?.to_bytes();
        let text = String::from_utf8(bytes.to_vec()).or(Err(ClientError::Parse(
            "Failed to parse bytes from response body.",
        )))?;

        if !status.is_success() {
            Err(ClientError::HttpStatus(text))
        } else {
            if cfg!(feature = "debug-inbound") {
                debug!("Received: {}", text);
            }

            if self.trace_inbound {
                trace!("Received: {}", text);
            }

            Ok(text)
        }
    }

    async fn build_form_request(
        &mut self,
        method: Method,
        url: &Url,
        signature: Signature,
    ) -> Result<Request<String>, ClientError> {
        let mut secrets_provider = self.secrets_provider.lock().await;
        let request = Self::request_builder_from_url(method, url)?
            .header("Accept", "application/json")
            .header("Content-Type", "application/x-www-form-urlencoded")
            .header("User-Agent", self.get_user_agent().as_str())
            .header(
                "API-Key",
                secrets_provider.get_secrets().key.expose_secret(),
            )
            .header("API-Sign", signature.signature)
            .body(signature.body_data)?;
        Ok(request)
    }

    async fn get_form_signature<R>(&mut self, endpoint: &str, request: &R) -> Signature
    where
        R: ToQueryParams,
    {
        let mut secrets_provider = self.secrets_provider.lock().await;
        let mut provider = self.nonce_provider.lock().await;
        let nonce = provider.get_nonce();
        let encoded_data = self.encode_form_request(nonce, request);
        generate_signature(
            nonce,
            secrets_provider.get_secrets().secret.expose_secret(),
            endpoint,
            encoded_data,
        )
    }

    async fn get_json_signature<R>(
        &mut self,
        endpoint: &str,
        request: &R,
    ) -> Result<Signature, ClientError>
    where
        R: Serialize,
    {
        let mut secrets_provider = self.secrets_provider.lock().await;
        let mut nonce_provider = self.nonce_provider.lock().await;
        let nonce = nonce_provider.get_nonce();
        let encoded_data = self.encode_json_request(nonce, request)?;
        Ok(generate_signature(
            nonce,
            secrets_provider.get_secrets().secret.expose_secret(),
            endpoint,
            encoded_data,
        ))
    }

    fn encode_json_request<R>(&self, nonce: u64, request: &R) -> Result<String, ClientError>
    where
        R: Serialize,
    {
        let nonce_request = NonceRequest::new(nonce, request);
        Ok(serde_json::to_string(&nonce_request)?)
    }

    fn encode_form_request<R>(&self, nonce: u64, request: &R) -> String
    where
        R: ToQueryParams,
    {
        let mut query_params = form_urlencoded::Serializer::new(String::new());
        query_params.append_pair("nonce", &nonce.to_string());

        for (key, value) in request.to_query_params().iter() {
            query_params.append_pair(key, value);
        }

        query_params.finish()
    }
}

#[cfg(test)]
#[macro_export]
macro_rules! test_parse_error_matches_pattern {
    ($body: expr, $pattern: pat) => {
        let err = CoreKrakenClient::parse_body_and_errors::<AccountBalances>($body);

        println!("{:?}", err);
        assert!(err.is_err());
        assert!(matches!(err, $pattern));
    };
}

#[cfg(test)]
mod tests {
    use crate::clients::core_kraken_client::CoreKrakenClient;
    use crate::clients::errors::ClientError;
    use crate::clients::errors::KrakenError;
    use crate::response_types::AccountBalances;

    pub const ERROR_PERMISSION_DENIED: &str = r#"{"error":["EGeneral:Permission denied"]}"#;
    pub const ERROR_INVALID_KEY: &str = r#"{"error":["EAPI:Invalid key"]}"#;
    pub const ERROR_UNKNOWN_ASSET_PAIR: &str = r#"{"error":["EQuery:Unknown asset pair"]}"#;
    pub const ERROR_INVALID_ARGUMENT: &str = r#"{"error":["EGeneral:Invalid arguments:type"]}"#;

    // doc-inferred ones not from true API responses
    pub const ERROR_INVALID_SIGNATURE: &str = r#"{"error":["EAPI:Invalid signature"]}"#;
    pub const ERROR_INVALID_NONCE: &str = r#"{"error":["EAPI:Invalid nonce"]}"#;
    pub const ERROR_INVALID_SESSION: &str = r#"{"error":["ESession:Invalid session"]}"#;
    pub const ERROR_BAD_REQUEST: &str = r#"{"error":["EAPI:Bad request"]}"#;
    pub const ERROR_UNKNOWN_METHOD: &str = r#"{"error":["EGeneral:Unknown Method"]}"#;

    pub const ERROR_API_RATE_LIMIT: &str = r#"{"error":["EAPI:Rate limit exceeded"]}"#;
    pub const ERROR_ORDER_RATE_LIMIT: &str = r#"{"error":["EOrder:Rate limit exceeded"]}"#;
    pub const ERROR_RATE_LIMIT_LOCKOUT: &str = r#"{"error":["EGeneral:Temporary lockout"]}"#;
    pub const ERROR_SERVICE_UNAVAILABLE: &str = r#"{"error":["EService:Unavailable"]}"#;
    pub const ERROR_SERVICE_BUSY: &str = r#"{"error":["EService:Busy"]}"#;
    pub const ERROR_INTERNAL_ERROR: &str = r#"{"error":["EGeneral:Internal error"]}"#;
    pub const ERROR_TRADE_LOCKED: &str = r#"{"error":["ETrade:Locked"]}"#;
    pub const ERROR_FEATURE_DISABLED: &str = r#"{"error":["EAPI:Feature disabled"]}"#;

    #[test]
    fn test_parse_body_and_errors() {
        test_parse_error_matches_pattern!(
            ERROR_PERMISSION_DENIED,
            Err(ClientError::Kraken(KrakenError::PermissionDenied))
        );

        test_parse_error_matches_pattern!(
            ERROR_INVALID_KEY,
            Err(ClientError::Kraken(KrakenError::InvalidKey))
        );

        test_parse_error_matches_pattern!(
            ERROR_UNKNOWN_ASSET_PAIR,
            Err(ClientError::Kraken(KrakenError::UnknownAssetPair))
        );

        test_parse_error_matches_pattern!(
            ERROR_INVALID_ARGUMENT,
            Err(ClientError::Kraken(KrakenError::InvalidArguments(..)))
        );

        test_parse_error_matches_pattern!(
            ERROR_INVALID_SIGNATURE,
            Err(ClientError::Kraken(KrakenError::InvalidSignature))
        );

        test_parse_error_matches_pattern!(
            ERROR_INVALID_NONCE,
            Err(ClientError::Kraken(KrakenError::InvalidNonce))
        );

        test_parse_error_matches_pattern!(
            ERROR_INVALID_SESSION,
            Err(ClientError::Kraken(KrakenError::InvalidSession))
        );

        test_parse_error_matches_pattern!(
            ERROR_BAD_REQUEST,
            Err(ClientError::Kraken(KrakenError::BadRequest))
        );

        test_parse_error_matches_pattern!(
            ERROR_UNKNOWN_METHOD,
            Err(ClientError::Kraken(KrakenError::UnknownMethod))
        );

        test_parse_error_matches_pattern!(
            ERROR_API_RATE_LIMIT,
            Err(ClientError::Kraken(KrakenError::RateLimitExceeded))
        );

        test_parse_error_matches_pattern!(
            ERROR_ORDER_RATE_LIMIT,
            Err(ClientError::Kraken(KrakenError::TradingRateLimitExceeded))
        );

        test_parse_error_matches_pattern!(
            ERROR_RATE_LIMIT_LOCKOUT,
            Err(ClientError::Kraken(KrakenError::TemporaryLockout))
        );

        test_parse_error_matches_pattern!(
            ERROR_SERVICE_UNAVAILABLE,
            Err(ClientError::Kraken(KrakenError::ServiceUnavailable))
        );

        test_parse_error_matches_pattern!(
            ERROR_SERVICE_BUSY,
            Err(ClientError::Kraken(KrakenError::ServiceBusy))
        );

        test_parse_error_matches_pattern!(
            ERROR_INTERNAL_ERROR,
            Err(ClientError::Kraken(KrakenError::InternalError))
        );

        test_parse_error_matches_pattern!(
            ERROR_TRADE_LOCKED,
            Err(ClientError::Kraken(KrakenError::TradeLocked))
        );

        test_parse_error_matches_pattern!(
            ERROR_FEATURE_DISABLED,
            Err(ClientError::Kraken(KrakenError::FeatureDisabled))
        );
    }
}