kraken_async_rs/clients/
kraken_client.rs

1//! Common trait and endpoints
2#[allow(unused)]
3use crate::clients::core_kraken_client::CoreKrakenClient;
4use crate::clients::errors::ClientError;
5use crate::clients::http_response_types::ResultErrorResponse;
6#[allow(unused)]
7use crate::clients::rate_limited_kraken_client::RateLimitedKrakenClient;
8use crate::crypto::nonce_provider::NonceProvider;
9use crate::request_types::*;
10use crate::response_types::*;
11use crate::secrets::secrets_provider::SecretsProvider;
12use std::collections::HashMap;
13use std::future::Future;
14use std::sync::Arc;
15use tokio::sync::Mutex;
16
17pub mod endpoints {
18    pub const KRAKEN_BASE_URL: &str = "https://api.kraken.com";
19
20    pub const TIME_ENDPOINT: &str = "/0/public/Time";
21    pub const STATUS_ENDPOINT: &str = "/0/public/SystemStatus";
22    pub const ASSET_INFO_ENDPOINT: &str = "/0/public/Assets";
23    pub const TRADABLE_ASSET_PAIRS_ENDPOINT: &str = "/0/public/AssetPairs";
24    pub const TICKER_INFO_ENDPOINT: &str = "/0/public/Ticker";
25    pub const OHLC_ENDPOINT: &str = "/0/public/OHLC";
26    pub const ORDER_BOOK_ENDPOINT: &str = "/0/public/Depth";
27    pub const RECENT_TRADES_ENDPOINT: &str = "/0/public/Trades";
28    pub const RECENT_SPREADS_ENDPOINT: &str = "/0/public/Spread";
29
30    pub const ACCOUNT_BALANCE_ENDPOINT: &str = "/0/private/Balance";
31    pub const ACCOUNT_BALANCE_EXTENDED_ENDPOINT: &str = "/0/private/BalanceEx";
32    pub const TRADE_BALANCE_ENDPOINT: &str = "/0/private/TradeBalance";
33    pub const OPEN_ORDERS_ENDPOINT: &str = "/0/private/OpenOrders";
34    pub const CLOSED_ORDERS_ENDPOINT: &str = "/0/private/ClosedOrders";
35    pub const QUERY_ORDERS_ENDPOINT: &str = "/0/private/QueryOrders";
36    pub const ORDER_AMENDS_ENDPOINT: &str = "/0/private/OrderAmends";
37    pub const TRADES_HISTORY_ENDPOINT: &str = "/0/private/TradesHistory";
38    pub const QUERY_TRADES_ENDPOINT: &str = "/0/private/QueryTrades";
39    pub const OPEN_POSITIONS_ENDPOINT: &str = "/0/private/OpenPositions";
40    pub const LEDGERS_ENDPOINT: &str = "/0/private/Ledgers";
41    pub const QUERY_LEDGERS_ENDPOINT: &str = "/0/private/QueryLedgers";
42    pub const TRADE_VOLUME_ENDPOINT: &str = "/0/private/TradeVolume";
43    pub const ADD_EXPORT_ENDPOINT: &str = "/0/private/AddExport";
44    pub const EXPORT_STATUS_ENDPOINT: &str = "/0/private/ExportStatus";
45    pub const RETRIEVE_EXPORT_ENDPOINT: &str = "/0/private/RetrieveExport";
46    pub const REMOVE_EXPORT_ENDPOINT: &str = "/0/private/RemoveExport";
47
48    pub const ADD_ORDER_ENDPOINT: &str = "/0/private/AddOrder";
49    pub const ADD_ORDER_BATCH_ENDPOINT: &str = "/0/private/AddOrderBatch";
50    pub const AMEND_ORDER_ENDPOINT: &str = "/0/private/AmendOrder";
51    pub const EDIT_ORDER_ENDPOINT: &str = "/0/private/EditOrder";
52    pub const CANCEL_ORDER_ENDPOINT: &str = "/0/private/CancelOrder";
53    pub const CANCEL_ALL_ORDERS_ENDPOINT: &str = "/0/private/CancelAll";
54    pub const CANCEL_ALL_ORDERS_AFTER_ENDPOINT: &str = "/0/private/CancelAllOrdersAfter";
55    pub const CANCEL_ORDER_BATCH_ENDPOINT: &str = "/0/private/CancelOrderBatch";
56
57    pub const DEPOSIT_METHODS_ENDPOINT: &str = "/0/private/DepositMethods";
58    pub const DEPOSIT_ADDRESSES_ENDPOINT: &str = "/0/private/DepositAddresses";
59    pub const DEPOSIT_STATUS_ENDPOINT: &str = "/0/private/DepositStatus";
60
61    pub const WITHDRAW_METHODS_ENDPOINT: &str = "/0/private/WithdrawMethods";
62    pub const WITHDRAW_ADDRESSES_ENDPOINT: &str = "/0/private/WithdrawAddresses";
63    pub const WITHDRAW_INFO_ENDPOINT: &str = "/0/private/WithdrawInfo";
64    pub const WITHDRAW_ENDPOINT: &str = "/0/private/Withdraw";
65    pub const WITHDRAW_STATUS_ENDPOINT: &str = "/0/private/WithdrawStatus";
66    pub const WITHDRAW_CANCEL_ENDPOINT: &str = "/0/private/WithdrawCancel";
67
68    pub const WALLET_TRANSFER_ENDPOINT: &str = "/0/private/WalletTransfer";
69
70    pub const CREATE_SUB_ACCOUNT_ENDPOINT: &str = "/0/private/CreateSubaccount";
71    pub const ACCOUNT_TRANSFER_ENDPOINT: &str = "/0/private/AccountTransfer";
72
73    pub const EARN_ALLOCATE_ENDPOINT: &str = "/0/private/Earn/Allocate";
74    pub const EARN_DEALLOCATE_ENDPOINT: &str = "/0/private/Earn/Deallocate";
75    pub const EARN_ALLOCATE_STATUS_ENDPOINT: &str = "/0/private/Earn/AllocateStatus";
76    pub const EARN_DEALLOCATE_STATUS_ENDPOINT: &str = "/0/private/Earn/DeallocateStatus";
77    pub const EARN_STRATEGIES_ENDPOINT: &str = "/0/private/Earn/Strategies";
78    pub const EARN_ALLOCATIONS_ENDPOINT: &str = "/0/private/Earn/Allocations";
79
80    pub const GET_WS_TOKEN_ENDPOINT: &str = "/0/private/GetWebSocketsToken";
81}
82
83/// The common trait shared by implementations like [CoreKrakenClient] and [RateLimitedKrakenClient]
84///
85pub trait KrakenClient: Send + Sync {
86    /// Creates a new instance with the given [SecretsProvider] and [NonceProvider].
87    fn new(
88        secrets_provider: Box<Arc<Mutex<dyn SecretsProvider>>>,
89        nonce_provider: Box<Arc<Mutex<dyn NonceProvider>>>,
90    ) -> Self;
91
92    /// Creates a new instance, allowing a specific URL to be set.
93    ///
94    /// Useful if using a proxy, testing with a mock-server, or if the URL changes from the default
95    /// used in this library.
96    fn new_with_url(
97        secrets_provider: Box<Arc<Mutex<dyn SecretsProvider>>>,
98        nonce_provider: Box<Arc<Mutex<dyn NonceProvider>>>,
99        url: impl ToString,
100    ) -> Self;
101
102    /// Creates a new instance with the given [SecretsProvider] and [NonceProvider], optionally
103    /// enabling tracing for inbound messages.
104    fn new_with_tracing(
105        secrets_provider: Box<Arc<Mutex<dyn SecretsProvider>>>,
106        nonce_provider: Box<Arc<Mutex<dyn NonceProvider>>>,
107        trace_inbound: bool,
108    ) -> Self;
109
110    /// Set the user-agent that will be sent in HTTP headers to Kraken. This is not required to be
111    /// set.
112    fn set_user_agent(&mut self, user_agent: impl ToString) -> impl Future<Output = ()>;
113
114    /// Get the server time in two useful formats.
115    fn get_server_time(
116        &mut self,
117    ) -> impl Future<Output = Result<ResultErrorResponse<SystemTime>, ClientError>> + Send;
118
119    /// Get the status of the system, including the current server time.
120    fn get_system_status(
121        &mut self,
122    ) -> impl Future<Output = Result<ResultErrorResponse<SystemStatusInfo>, ClientError>>;
123
124    /// Get info about a particular asset, e.g. "XBT" or "ETH".
125    fn get_asset_info(
126        &mut self,
127        request: &AssetInfoRequest,
128    ) -> impl Future<Output = Result<ResultErrorResponse<HashMap<String, AssetInfo>>, ClientError>>;
129
130    /// Get info about tradable asset pairs, such as USDCUSD, BTCUSD, or XETHZUSD.
131    ///
132    /// Returns all the information needed to place correctly formatted order volumes, prices, and pairs.
133    fn get_tradable_asset_pairs(
134        &mut self,
135        request: &TradableAssetPairsRequest,
136    ) -> impl Future<Output = Result<ResultErrorResponse<HashMap<String, TradableAssetPair>>, ClientError>>;
137
138    /// Return some or all ticker data, including the most recent bid, ask, price, and last-24h
139    /// stats for each requested pair.
140    fn get_ticker_information(
141        &mut self,
142        request: &TickerRequest,
143    ) -> impl Future<Output = Result<ResultErrorResponse<HashMap<String, RestTickerInfo>>, ClientError>>;
144
145    /// Retrieve up to the last 720 OHLC candlesticks for a given pair and interval.
146    ///
147    /// The `since` request parameter allows for getting only data since some timestamp
148    /// (the `last` response), but does not allow pagination.
149    fn get_ohlc(
150        &mut self,
151        request: &OHLCRequest,
152    ) -> impl Future<Output = Result<ResultErrorResponse<OhlcResponse>, ClientError>>;
153
154    /// Get a snapshot of the orderbook for the requested pair and depth-of-book.
155    fn get_orderbook(
156        &mut self,
157        request: &OrderbookRequest,
158    ) -> impl Future<Output = Result<ResultErrorResponse<HashMap<String, Orderbook>>, ClientError>>;
159
160    /// Retrieve up to 1000 trades at a time from the FULL history of Kraken's exchange for the
161    /// requested pair.
162    ///
163    /// The `since` and `count` parameters allow complete pagination starting from the exchange's
164    /// first-ever trade in each pair.
165    ///
166    /// See /examples/live_retrieving_recent_trades.rs for a full example of pagination with rate
167    /// limiting.
168    fn get_recent_trades(
169        &mut self,
170        request: &RecentTradesRequest,
171    ) -> impl Future<Output = Result<ResultErrorResponse<RecentTrades>, ClientError>>;
172
173    /// Get the last ~200 spread values for the requested pair.
174    ///
175    /// The `since` parameter allows getting incremental updates, but does not paginate the request
176    /// historically.
177    fn get_recent_spreads(
178        &mut self,
179        request: &RecentSpreadsRequest,
180    ) -> impl Future<Output = Result<ResultErrorResponse<RecentSpreads>, ClientError>>;
181
182    /// Get the raw balances for your account, minus any pending withdrawals.
183    fn get_account_balance(
184        &mut self,
185    ) -> impl Future<Output = Result<ResultErrorResponse<AccountBalances>, ClientError>>;
186
187    /// Get the extended balances for your account, which denotes the balance, any balance on hold,
188    /// and lines of credit (if available on your account).
189    fn get_extended_balances(
190        &mut self,
191    ) -> impl Future<Output = Result<ResultErrorResponse<ExtendedBalances>, ClientError>>;
192
193    /// Get balances relevant for futures and margin trading, including equity and margin levels.
194    fn get_trade_balances(
195        &mut self,
196        request: &TradeBalanceRequest,
197    ) -> impl Future<Output = Result<ResultErrorResponse<TradeBalances>, ClientError>>;
198
199    /// Get all open orders for your account.
200    fn get_open_orders(
201        &mut self,
202        request: &OpenOrdersRequest,
203    ) -> impl Future<Output = Result<ResultErrorResponse<OpenOrders>, ClientError>>;
204
205    /// Get closed orders from the full history of your account, up to 50 at a time.
206    ///
207    /// Pagination is done using the `start`, `end`, `ofs` (offset) parameters.
208    fn get_closed_orders(
209        &mut self,
210        request: &ClosedOrdersRequest,
211    ) -> impl Future<Output = Result<ResultErrorResponse<ClosedOrders>, ClientError>>;
212
213    /// Get the information for up to 50 orders at a time.
214    fn query_orders_info(
215        &mut self,
216        request: &OrderRequest,
217    ) -> impl Future<Output = Result<ResultErrorResponse<HashMap<String, Order>>, ClientError>>;
218
219    fn get_order_amends(
220        &mut self,
221        request: &OrderAmendsRequest,
222    ) -> impl Future<Output = Result<ResultErrorResponse<OrderAmends>, ClientError>>;
223
224    /// Get trades from the full history your account, up to 50 at a time.
225    ///
226    /// Pagination is done using the `start`, `end` and `ofs` (offset) parameters.
227    fn get_trades_history(
228        &mut self,
229        request: &TradesHistoryRequest,
230    ) -> impl Future<Output = Result<ResultErrorResponse<TradesHistory>, ClientError>>;
231
232    /// Get trade details for up to 20 specific trades by id at a time.
233    fn query_trades_info(
234        &mut self,
235        request: &TradeInfoRequest,
236    ) -> impl Future<Output = Result<ResultErrorResponse<TradesInfo>, ClientError>>;
237
238    /// Get information about open margin positions.
239    fn get_open_positions(
240        &mut self,
241        request: &OpenPositionsRequest,
242    ) -> impl Future<Output = Result<ResultErrorResponse<OpenPositions>, ClientError>>;
243
244    /// Get ledger entries for the full history of your account, up to 50 at a time.
245    ///
246    /// Pagination is done using the `start`, `end`, `ofs` (offset) parameters.
247    fn get_ledgers_info(
248        &mut self,
249        request: &LedgersInfoRequest,
250    ) -> impl Future<Output = Result<ResultErrorResponse<LedgerInfo>, ClientError>>;
251
252    /// Get ledger information for up to 20 ids at a time.
253    fn query_ledgers(
254        &mut self,
255        request: &QueryLedgerRequest,
256    ) -> impl Future<Output = Result<ResultErrorResponse<QueryLedgerInfo>, ClientError>>;
257
258    /// Get the 30-day trading volume for your account, and fee information for any pairs (if requested).
259    fn get_trade_volume(
260        &mut self,
261        request: &TradeVolumeRequest,
262    ) -> impl Future<Output = Result<ResultErrorResponse<TradeVolume>, ClientError>>;
263
264    /// Request a report for ledgers or trades to be generated asynchronously.
265    fn request_export_report(
266        &mut self,
267        request: &ExportReportRequest,
268    ) -> impl Future<Output = Result<ResultErrorResponse<ExportReport>, ClientError>>;
269
270    /// Get the status of a report that was requested.
271    fn get_export_report_status(
272        &mut self,
273        request: &ExportReportStatusRequest,
274    ) -> impl Future<Output = Result<ResultErrorResponse<Vec<ExportReportStatus>>, ClientError>>;
275
276    /// Retrieve an export report once generated.
277    fn retrieve_export_report(
278        &mut self,
279        request: &RetrieveExportReportRequest,
280    ) -> impl Future<Output = Result<Vec<u8>, ClientError>>;
281
282    /// Request for an export report to be deleted.
283    fn delete_export_report(
284        &mut self,
285        request: &DeleteExportRequest,
286    ) -> impl Future<Output = Result<ResultErrorResponse<DeleteExportReport>, ClientError>>;
287
288    /// Add an order of any type (market, limit, trailing stop, etc).
289    fn add_order(
290        &mut self,
291        request: &AddOrderRequest,
292    ) -> impl Future<Output = Result<ResultErrorResponse<AddOrder>, ClientError>>;
293
294    /// Add up to 15 orders *for a single pair* at once. Orders that fail to place are dropped from
295    /// processing and will be returned with errors in the response's `Vec`.
296    fn add_order_batch(
297        &mut self,
298        request: &AddBatchedOrderRequest,
299    ) -> impl Future<Output = Result<ResultErrorResponse<AddOrderBatch>, ClientError>>;
300
301    fn amend_order(
302        &mut self,
303        request: &AmendOrderRequest,
304    ) -> impl Future<Output = Result<ResultErrorResponse<AmendOrder>, ClientError>>;
305
306    /// Edit the volume or price of an existing order, excluding contingent orders like stop/profit orders.
307    fn edit_order(
308        &mut self,
309        request: &EditOrderRequest,
310    ) -> impl Future<Output = Result<ResultErrorResponse<OrderEdit>, ClientError>>;
311
312    /// Cancel an existing order by ref-id or user-ref.
313    fn cancel_order(
314        &mut self,
315        request: &CancelOrderRequest,
316    ) -> impl Future<Output = Result<ResultErrorResponse<CancelOrder>, ClientError>>;
317
318    /// Cancel all active orders.
319    fn cancel_all_orders(
320        &mut self,
321    ) -> impl Future<Output = Result<ResultErrorResponse<CancelOrder>, ClientError>>;
322
323    /// Submit a "Dead Man's Switch" that will cancel all orders if not repeatedly updated over time.
324    fn cancel_all_orders_after(
325        &mut self,
326        request: &CancelAllOrdersAfterRequest,
327    ) -> impl Future<Output = Result<ResultErrorResponse<CancelAllOrdersAfter>, ClientError>>;
328
329    /// Cancel up to 50 orders in a batch by id or user-ref.
330    fn cancel_order_batch(
331        &mut self,
332        request: &CancelBatchOrdersRequest,
333    ) -> impl Future<Output = Result<ResultErrorResponse<CancelOrder>, ClientError>>;
334
335    /// Get all methods of depositing a specific asset.
336    fn get_deposit_methods(
337        &mut self,
338        request: &DepositMethodsRequest,
339    ) -> impl Future<Output = Result<ResultErrorResponse<Vec<DepositMethod>>, ClientError>>;
340
341    /// Get all available addresses for a given asset and method.
342    fn get_deposit_addresses(
343        &mut self,
344        request: &DepositAddressesRequest,
345    ) -> impl Future<Output = Result<ResultErrorResponse<Vec<DepositAddress>>, ClientError>>;
346
347    /// Get the status of recent deposits.
348    ///
349    /// Pagination is done using the `start`, `end`, `cursor` and `limit` parameters.
350    fn get_status_of_recent_deposits(
351        &mut self,
352        request: &StatusOfDepositWithdrawRequest,
353    ) -> impl Future<Output = Result<ResultErrorResponse<DepositWithdrawResponse>, ClientError>>;
354
355    /// Get all withdrawal methods, optionally for a given asset.
356    fn get_withdrawal_methods(
357        &mut self,
358        request: &WithdrawalMethodsRequest,
359    ) -> impl Future<Output = Result<ResultErrorResponse<Vec<WithdrawMethod>>, ClientError>>;
360
361    /// Get all withdrawal addresses, optionally for a specific asset or method.
362    fn get_withdrawal_addresses(
363        &mut self,
364        request: &WithdrawalAddressesRequest,
365    ) -> impl Future<Output = Result<ResultErrorResponse<Vec<WithdrawalAddress>>, ClientError>>;
366
367    /// Get details about a particular withdrawal.
368    fn get_withdrawal_info(
369        &mut self,
370        request: &WithdrawalInfoRequest,
371    ) -> impl Future<Output = Result<ResultErrorResponse<Withdrawal>, ClientError>>;
372
373    /// Request a withdrawal for the provided asset and key.
374    fn withdraw_funds(
375        &mut self,
376        request: &WithdrawFundsRequest,
377    ) -> impl Future<Output = Result<ResultErrorResponse<ConfirmationRefId>, ClientError>>;
378
379    /// Get the status of recent withdrawals.
380    ///
381    /// Pagination is done using the `start`, `end`, `cursor` and `limit` parameters.
382    fn get_status_of_recent_withdrawals(
383        &mut self,
384        request: &StatusOfDepositWithdrawRequest,
385    ) -> impl Future<Output = Result<ResultErrorResponse<Vec<DepositWithdrawal>>, ClientError>>;
386
387    /// Request to cancel a particular withdrawal if it has not been fully processed.
388    fn request_withdrawal_cancellation(
389        &mut self,
390        request: &WithdrawCancelRequest,
391    ) -> impl Future<Output = Result<ResultErrorResponse<bool>, ClientError>>;
392
393    /// Request to transfer from the default Spot wallet to a Futures wallet if available.
394    fn request_wallet_transfer(
395        &mut self,
396        request: &WalletTransferRequest,
397    ) -> impl Future<Output = Result<ResultErrorResponse<ConfirmationRefId>, ClientError>>;
398
399    /// Create a linked sub-account for the given username and email (Institutional Clients only).
400    fn create_sub_account(
401        &mut self,
402        request: &CreateSubAccountRequest,
403    ) -> impl Future<Output = Result<ResultErrorResponse<bool>, ClientError>>;
404
405    /// Request to transfer a given asset between sub-accounts (Institutional Clients only).
406    fn account_transfer(
407        &mut self,
408        request: &AccountTransferRequest,
409    ) -> impl Future<Output = Result<ResultErrorResponse<AccountTransfer>, ClientError>>;
410
411    /// Allocate available funds to a given earn strategy.
412    fn allocate_earn_funds(
413        &mut self,
414        request: &AllocateEarnFundsRequest,
415    ) -> impl Future<Output = Result<ResultErrorResponse<bool>, ClientError>>;
416
417    /// De-allocate funds from a given earn strategy.
418    fn deallocate_earn_funds(
419        &mut self,
420        request: &AllocateEarnFundsRequest,
421    ) -> impl Future<Output = Result<ResultErrorResponse<bool>, ClientError>>;
422
423    /// Get the status for the only pending earn allocation request if there is one.
424    fn get_earn_allocation_status(
425        &mut self,
426        request: &EarnAllocationStatusRequest,
427    ) -> impl Future<Output = Result<ResultErrorResponse<AllocationStatus>, ClientError>>;
428
429    /// Get the status for the only pending earn de-allocation if there is one.
430    fn get_earn_deallocation_status(
431        &mut self,
432        request: &EarnAllocationStatusRequest,
433    ) -> impl Future<Output = Result<ResultErrorResponse<AllocationStatus>, ClientError>>;
434
435    /// List all earn strategies.
436    ///
437    /// Pagination is supported through the cursor and limit parameters.
438    fn list_earn_strategies(
439        &mut self,
440        request: &ListEarnStrategiesRequest,
441    ) -> impl Future<Output = Result<ResultErrorResponse<EarnStrategies>, ClientError>>;
442
443    /// List all current earn allocations.
444    fn list_earn_allocations(
445        &mut self,
446        request: &ListEarnAllocationsRequest,
447    ) -> impl Future<Output = Result<ResultErrorResponse<EarnAllocations>, ClientError>>;
448
449    /// Get a token for connecting to private websockets.
450    ///
451    /// Tokens are valid for 15 minutes for their first use, but do not require being refreshed
452    /// once a connection is established.
453    fn get_websockets_token(
454        &mut self,
455    ) -> impl Future<Output = Result<ResultErrorResponse<WebsocketToken>, ClientError>>;
456}