kraken_async_rs::clients::rate_limited_kraken_client

Struct RateLimitedKrakenClient

Source
pub struct RateLimitedKrakenClient<C>
where C: KrakenClient,
{ /* private fields */ }
Expand description

A KrakenClient implementation that decorates a provided client, and applies rate limiting according to the Kraken API specs.

Loosely, this is:

  • public endpoints are limited to 1 call per second
  • private endpoints follow a token-bucket rate limiting scheme, with some endpoints having higher costs
  • trading endpoints implement the Advanced version of Kraken’s rate limiting scheme
    • this includes tracking order lifetimes and applying penalties to rapid cancels and edits of orders

The exact rate limit values and replenishment schedule are determined by a user’s verification tier. Default new methods assume an Intermediate verification, so Pro users will want to rely on methods that allow providing a custom verification tier if they want to take full advantage of their increased rate limits (e.g. new_with_verification_tier).

Calls made that violate the rate limiting policy are made to wait asynchronously, but no error handling is in place for receiving rate limit errors, these are to be handled/backed-off by the user.

Detailed documentation is available from several locations, including the overview rate-limiting page, api rate-limiting page and trading rate-limiting page. It’s worth noting that the token values used in this library are scaled to be 100x those of Kraken’s documentation to keep them as integers using semaphore permits instead of floating-point math.

RateLimitedKrakenClients are cloneable, which results in a new client that shares the same rate limiting state. This is useful for giving many services access to a client while ensuring that all will jointly respect the rate limits of the exchange.

Warning: This is not meant to be a comprehensive solution to all rate limiting, but is a best-effort attempt to match the API’s specifications. In some cases cloud providers, or server implementations may inject random errors to prevent coordinated attacks or abuse. As such, this cannot anticipate and mitigate all modes of failure.

See examples/live_retrieving_recent_trades.rs for usage that relies on rate limiting preventing request failures due to rapidly requesting public trade history.

Implementations§

Source§

impl<C> RateLimitedKrakenClient<C>
where C: KrakenClient,

Source

pub fn new_with_client( client: C, verification: VerificationTier, ) -> RateLimitedKrakenClient<C>

Create a new rate limited client that delegates calls to any type that implements KrakenClient.

Source

pub fn new_with_verification_tier( secrets_provider: Box<Arc<Mutex<dyn SecretsProvider>>>, nonce_provider: Box<Arc<Mutex<dyn NonceProvider>>>, verification: VerificationTier, ) -> Self

Create a new rate-limited client using the provided SecretsProvider and NonceProvider

Source

pub fn new_with_verification_tier_and_url( secrets_provider: Box<Arc<Mutex<dyn SecretsProvider>>>, nonce_provider: Box<Arc<Mutex<dyn NonceProvider>>>, url: String, verification: VerificationTier, ) -> Self

Create a new client, specifying the user’s verification tier and the base URL.

Source

pub fn get_private_rate_limiter( user_verification: VerificationTier, ) -> TokenBucketRateLimiter

Get a private endpoint rate limiter, depending on the user’s verification level.

This implements a more involved scheme.

Source

pub fn get_public_rate_limiter() -> SlidingWindowRateLimiter

Get a public rate limiter, which limits calls to 1 per second.

Trait Implementations§

Source§

impl<C> Clone for RateLimitedKrakenClient<C>
where C: KrakenClient + Clone,

Source§

fn clone(&self) -> RateLimitedKrakenClient<C>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<C> Debug for RateLimitedKrakenClient<C>
where C: KrakenClient + Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<C> KrakenClient for RateLimitedKrakenClient<C>
where C: KrakenClient,

Source§

async fn cancel_order_batch( &mut self, request: &CancelBatchOrdersRequest, ) -> Result<ResultErrorResponse<CancelOrder>, ClientError>

Clients can request to cancel in batches using both ref-ids produced by Kraken (Strings), or user-refs generated by the user (i64), which are known before the order is placed.

Source§

fn new( secrets_provider: Box<Arc<Mutex<dyn SecretsProvider>>>, nonce_provider: Box<Arc<Mutex<dyn NonceProvider>>>, ) -> RateLimitedKrakenClient<C>

Creates a new instance with the given SecretsProvider and NonceProvider.
Source§

fn new_with_url( secrets_provider: Box<Arc<Mutex<dyn SecretsProvider>>>, nonce_provider: Box<Arc<Mutex<dyn NonceProvider>>>, url: String, ) -> Self

Creates a new instance, allowing a specific URL to be set. Read more
Source§

fn new_with_tracing( secrets_provider: Box<Arc<Mutex<dyn SecretsProvider>>>, nonce_provider: Box<Arc<Mutex<dyn NonceProvider>>>, trace_inbound: bool, ) -> Self

Creates a new instance with the given SecretsProvider and NonceProvider, optionally enabling tracing for inbound messages.
Source§

async fn set_user_agent(&mut self, user_agent: String)

Set the user-agent that will be sent in HTTP headers to Kraken. This is not required to be set.
Source§

async fn get_server_time( &mut self, ) -> Result<ResultErrorResponse<SystemTime>, ClientError>

Get the server time in two useful formats.
Source§

async fn get_system_status( &mut self, ) -> Result<ResultErrorResponse<SystemStatusInfo>, ClientError>

Get the status of the system, including the current server time.
Source§

async fn get_asset_info( &mut self, request: &AssetInfoRequest, ) -> Result<ResultErrorResponse<HashMap<String, AssetInfo>>, ClientError>

Get info about a particular asset, e.g. “XBT” or “ETH”.
Source§

async fn get_tradable_asset_pairs( &mut self, request: &TradableAssetPairsRequest, ) -> Result<ResultErrorResponse<HashMap<String, TradableAssetPair>>, ClientError>

Get info about tradable asset pairs, such as USDCUSD, BTCUSD, or XETHZUSD. Read more
Source§

async fn get_ticker_information( &mut self, request: &TickerRequest, ) -> Result<ResultErrorResponse<HashMap<String, RestTickerInfo>>, ClientError>

Return some or all ticker data, including the most recent bid, ask, price, and last-24h stats for each requested pair.
Source§

async fn get_ohlc( &mut self, request: &OHLCRequest, ) -> Result<ResultErrorResponse<OhlcResponse>, ClientError>

Retrieve up to the last 720 OHLC candlesticks for a given pair and interval. Read more
Source§

async fn get_orderbook( &mut self, request: &OrderbookRequest, ) -> Result<ResultErrorResponse<HashMap<String, Orderbook>>, ClientError>

Get a snapshot of the orderbook for the requested pair and depth-of-book.
Source§

async fn get_recent_trades( &mut self, request: &RecentTradesRequest, ) -> Result<ResultErrorResponse<RecentTrades>, ClientError>

Retrieve up to 1000 trades at a time from the FULL history of Kraken’s exchange for the requested pair. Read more
Source§

async fn get_recent_spreads( &mut self, request: &RecentSpreadsRequest, ) -> Result<ResultErrorResponse<RecentSpreads>, ClientError>

Get the last ~200 spread values for the requested pair. Read more
Source§

async fn get_account_balance( &mut self, ) -> Result<ResultErrorResponse<AccountBalances>, ClientError>

Get the raw balances for your account, minus any pending withdrawals.
Source§

async fn get_extended_balances( &mut self, ) -> Result<ResultErrorResponse<ExtendedBalances>, ClientError>

Get the extended balances for your account, which denotes the balance, any balance on hold, and lines of credit (if available on your account).
Source§

async fn get_trade_balances( &mut self, request: &TradeBalanceRequest, ) -> Result<ResultErrorResponse<TradeBalances>, ClientError>

Get balances relevant for futures and margin trading, including equity and margin levels.
Source§

async fn get_open_orders( &mut self, request: &OpenOrdersRequest, ) -> Result<ResultErrorResponse<OpenOrders>, ClientError>

Get all open orders for your account.
Source§

async fn get_closed_orders( &mut self, request: &ClosedOrdersRequest, ) -> Result<ResultErrorResponse<ClosedOrders>, ClientError>

Get closed orders from the full history of your account, up to 50 at a time. Read more
Source§

async fn query_orders_info( &mut self, request: &OrderRequest, ) -> Result<ResultErrorResponse<HashMap<String, Order>>, ClientError>

Get the information for up to 50 orders at a time.
Source§

async fn get_order_amends( &mut self, request: &OrderAmendsRequest, ) -> Result<ResultErrorResponse<OrderAmends>, ClientError>

Source§

async fn get_trades_history( &mut self, request: &TradesHistoryRequest, ) -> Result<ResultErrorResponse<TradesHistory>, ClientError>

Get trades from the full history your account, up to 50 at a time. Read more
Source§

async fn query_trades_info( &mut self, request: &TradeInfoRequest, ) -> Result<ResultErrorResponse<TradesInfo>, ClientError>

Get trade details for up to 20 specific trades by id at a time.
Source§

async fn get_open_positions( &mut self, request: &OpenPositionsRequest, ) -> Result<ResultErrorResponse<OpenPositions>, ClientError>

Get information about open margin positions.
Source§

async fn get_ledgers_info( &mut self, request: &LedgersInfoRequest, ) -> Result<ResultErrorResponse<LedgerInfo>, ClientError>

Get ledger entries for the full history of your account, up to 50 at a time. Read more
Source§

async fn query_ledgers( &mut self, request: &QueryLedgerRequest, ) -> Result<ResultErrorResponse<QueryLedgerInfo>, ClientError>

Get ledger information for up to 20 ids at a time.
Source§

async fn get_trade_volume( &mut self, request: &TradeVolumeRequest, ) -> Result<ResultErrorResponse<TradeVolume>, ClientError>

Get the 30-day trading volume for your account, and fee information for any pairs (if requested).
Source§

async fn request_export_report( &mut self, request: &ExportReportRequest, ) -> Result<ResultErrorResponse<ExportReport>, ClientError>

Request a report for ledgers or trades to be generated asynchronously.
Source§

async fn get_export_report_status( &mut self, request: &ExportReportStatusRequest, ) -> Result<ResultErrorResponse<Vec<ExportReportStatus>>, ClientError>

Get the status of a report that was requested.
Source§

async fn retrieve_export_report( &mut self, request: &RetrieveExportReportRequest, ) -> Result<Vec<u8>, ClientError>

Retrieve an export report once generated.
Source§

async fn delete_export_report( &mut self, request: &DeleteExportRequest, ) -> Result<ResultErrorResponse<DeleteExportReport>, ClientError>

Request for an export report to be deleted.
Source§

async fn add_order( &mut self, request: &AddOrderRequest, ) -> Result<ResultErrorResponse<AddOrder>, ClientError>

Add an order of any type (market, limit, trailing stop, etc).
Source§

async fn add_order_batch( &mut self, request: &AddBatchedOrderRequest, ) -> Result<ResultErrorResponse<AddOrderBatch>, ClientError>

Add up to 15 orders for a single pair at once. Orders that fail to place are dropped from processing and will be returned with errors in the response’s Vec.
Source§

async fn amend_order( &mut self, request: &AmendOrderRequest, ) -> Result<ResultErrorResponse<AmendOrder>, ClientError>

Source§

async fn edit_order( &mut self, request: &EditOrderRequest, ) -> Result<ResultErrorResponse<OrderEdit>, ClientError>

Edit the volume or price of an existing order, excluding contingent orders like stop/profit orders.
Source§

async fn cancel_order( &mut self, request: &CancelOrderRequest, ) -> Result<ResultErrorResponse<CancelOrder>, ClientError>

Cancel an existing order by ref-id or user-ref.
Source§

async fn cancel_all_orders( &mut self, ) -> Result<ResultErrorResponse<CancelOrder>, ClientError>

Cancel all active orders.
Source§

async fn cancel_all_orders_after( &mut self, request: &CancelAllOrdersAfterRequest, ) -> Result<ResultErrorResponse<CancelAllOrdersAfter>, ClientError>

Submit a “Dead Man’s Switch” that will cancel all orders if not repeatedly updated over time.
Source§

async fn get_deposit_methods( &mut self, request: &DepositMethodsRequest, ) -> Result<ResultErrorResponse<Vec<DepositMethod>>, ClientError>

Get all methods of depositing a specific asset.
Source§

async fn get_deposit_addresses( &mut self, request: &DepositAddressesRequest, ) -> Result<ResultErrorResponse<Vec<DepositAddress>>, ClientError>

Get all available addresses for a given asset and method.
Source§

async fn get_status_of_recent_deposits( &mut self, request: &StatusOfDepositWithdrawRequest, ) -> Result<ResultErrorResponse<DepositWithdrawResponse>, ClientError>

Get the status of recent deposits. Read more
Source§

async fn get_withdrawal_methods( &mut self, request: &WithdrawalMethodsRequest, ) -> Result<ResultErrorResponse<Vec<WithdrawMethod>>, ClientError>

Get all withdrawal methods, optionally for a given asset.
Source§

async fn get_withdrawal_addresses( &mut self, request: &WithdrawalAddressesRequest, ) -> Result<ResultErrorResponse<Vec<WithdrawalAddress>>, ClientError>

Get all withdrawal addresses, optionally for a specific asset or method.
Source§

async fn get_withdrawal_info( &mut self, request: &WithdrawalInfoRequest, ) -> Result<ResultErrorResponse<Withdrawal>, ClientError>

Get details about a particular withdrawal.
Source§

async fn withdraw_funds( &mut self, request: &WithdrawFundsRequest, ) -> Result<ResultErrorResponse<ConfirmationRefId>, ClientError>

Request a withdrawal for the provided asset and key.
Source§

async fn get_status_of_recent_withdrawals( &mut self, request: &StatusOfDepositWithdrawRequest, ) -> Result<ResultErrorResponse<Vec<DepositWithdrawal>>, ClientError>

Get the status of recent withdrawals. Read more
Source§

async fn request_withdrawal_cancellation( &mut self, request: &WithdrawCancelRequest, ) -> Result<ResultErrorResponse<bool>, ClientError>

Request to cancel a particular withdrawal if it has not been fully processed.
Source§

async fn request_wallet_transfer( &mut self, request: &WalletTransferRequest, ) -> Result<ResultErrorResponse<ConfirmationRefId>, ClientError>

Request to transfer from the default Spot wallet to a Futures wallet if available.
Source§

async fn create_sub_account( &mut self, request: &CreateSubAccountRequest, ) -> Result<ResultErrorResponse<bool>, ClientError>

Create a linked sub-account for the given username and email (Institutional Clients only).
Source§

async fn account_transfer( &mut self, request: &AccountTransferRequest, ) -> Result<ResultErrorResponse<AccountTransfer>, ClientError>

Request to transfer a given asset between sub-accounts (Institutional Clients only).
Source§

async fn allocate_earn_funds( &mut self, request: &AllocateEarnFundsRequest, ) -> Result<ResultErrorResponse<bool>, ClientError>

Allocate available funds to a given earn strategy.
Source§

async fn deallocate_earn_funds( &mut self, request: &AllocateEarnFundsRequest, ) -> Result<ResultErrorResponse<bool>, ClientError>

De-allocate funds from a given earn strategy.
Source§

async fn get_earn_allocation_status( &mut self, request: &EarnAllocationStatusRequest, ) -> Result<ResultErrorResponse<AllocationStatus>, ClientError>

Get the status for the only pending earn allocation request if there is one.
Source§

async fn get_earn_deallocation_status( &mut self, request: &EarnAllocationStatusRequest, ) -> Result<ResultErrorResponse<AllocationStatus>, ClientError>

Get the status for the only pending earn de-allocation if there is one.
Source§

async fn list_earn_strategies( &mut self, request: &ListEarnStrategiesRequest, ) -> Result<ResultErrorResponse<EarnStrategies>, ClientError>

List all earn strategies. Read more
Source§

async fn list_earn_allocations( &mut self, request: &ListEarnAllocationsRequest, ) -> Result<ResultErrorResponse<EarnAllocations>, ClientError>

List all current earn allocations.
Source§

async fn get_websockets_token( &mut self, ) -> Result<ResultErrorResponse<WebsocketToken>, ClientError>

Get a token for connecting to private websockets. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T