Skip to main content

BinanceHistoricalClient

Struct BinanceHistoricalClient 

Source
pub struct BinanceHistoricalClient { /* private fields */ }
Expand description

REST client for Binance historical klines on a single surface (spot or futures-continuous). Construct with spot or futures; both bake in the surface’s host, page cap, and a conservative default pre-pace.

§Pre-pacing

A fixed, bounded delay is applied between pages so a single backfill stays within Binance’s weight budget without tripping 429/418. It is tracing-observable (logged at debug) and caller-overridable via with_pace. This is proactive courtesy only — it never inspects a 429, never retries, and never adapts to retry_after; the surface-RateLimited-and-end contract is unchanged.

Implementations§

Source§

impl BinanceHistoricalClient

Source

pub fn spot() -> Self

Create a client for the spot surface (/api/v3/klines, max 1000/page, default pace ~20ms).

Source

pub fn futures() -> Self

Create a client for the USD-M futures continuous surface (/fapi/v1/continuousKlines, contractType=PERPETUAL, max 1500/page, default pace ~250ms).

This is the surface that unlocks Sec1 on futures; /fapi/v1/klines rejects it with 400 Invalid interval.

Source

pub fn with_pace(self, pace: Duration) -> Self

Override the inter-page pre-pace.

Use a smaller value on a higher API weight tier, or Duration::ZERO to disable pacing entirely (the caller then owns staying within the weight budget). The default is sized to the surface’s public weight budget.

Source

pub fn with_base_url(self, base_url: impl Into<String>) -> Self

Override the REST base URL (for tests against a mock server).

Source

pub fn with_client(self, client: Client) -> Self

Inject a pre-built reqwest::Client.

By default each constructor builds its own Client (one connection pool per client). Pass a shared Client here to reuse a single pool across, e.g., a spot and a futures client, or to apply custom transport configuration (proxy, TLS).

Note: a 30-second per-request timeout is always applied at request level regardless of any client-level timeout configured on the injected Client, so a shorter client-level timeout will not take effect.

Source

pub fn fetch_candles<'a>( &'a self, symbol: &'a str, interval: CandleInterval, start: DateTime<Utc>, end: DateTime<Utc>, ) -> impl Stream<Item = Result<Candle, BinanceDataError>> + 'a

Fetch historical candles for symbol at interval, paginating automatically across the surface’s page cap.

Returns a Stream that processes each page as it arrives (does not buffer the whole range in memory — a 90d 1s backfill is millions of candles). For a convenience Vec see collect_candles.

§Range contract

Yields exactly the candles whose close_time falls in [start, end] (both inclusive), matched on close_time — the field consumers receive. Binance filters by the bar’s open time, so this method maps both bounds from close_time to open_time (lower bound widens to capture the candle whose close_time == start, i.e. open == start − interval; upper bound narrows to open == end − interval) and trims by close_time, consistent with the library’s other historical fetches.

close_time is computed library-side as the exclusive period-end boundary (open_time + interval) — Binance’s raw wire closeTime (period-end − 1ms) is discarded (see Candle::close_time).

Zero-trade periods are not dropped: Binance REST server-side gap-fills them (volume == 0, OHLC == prior close), and the library delivers them (filtering is consumer policy). The live WS path omits them entirely — an asymmetry consumers should expect.

§Arguments
  • symbol - Market symbol, e.g. "BTCUSDT" (uppercased for Binance).
  • interval - Candle resolution. Both Binance surfaces support the full CandleInterval set, including Sec1.
  • start / end - Inclusive close_time range bounds.
§Errors

Each yielded item is a Result. On HTTP 429/418 the stream yields BinanceDataError::RateLimited and ends (resume by re-calling with start = last received close_time + 1ms, the next candle’s open — resuming exactly at the last close_time re-yields that candle, as the range is close_time-inclusive). Other failures surface as BinanceDataError::Api / Http / Deserialize / InvalidInput.

Source

pub async fn collect_candles( &self, symbol: &str, interval: CandleInterval, start: DateTime<Utc>, end: DateTime<Utc>, ) -> Result<Vec<Candle>, BinanceDataError>

Convenience wrapper over fetch_candles that collects the full range into a Vec (oldest first).

Heavy for large ranges — a 90d 1s backfill is millions of Candles (hundreds of MB). Prefer the streaming API for long ranges.

Trait Implementations§

Source§

impl Clone for BinanceHistoricalClient

Source§

fn clone(&self) -> BinanceHistoricalClient

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for BinanceHistoricalClient

Source§

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

Formats the value using the given formatter. 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, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
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