Skip to main content

Binance

Struct Binance 

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

Main entry point for the Binance API client.

The Binance struct provides access to all API modules and handles configuration and authentication.

Implementations§

Source§

impl Binance

Source

pub fn new( api_key: impl Into<String>, secret_key: impl Into<String>, ) -> Result<Self>

Create a new authenticated Binance client with default production configuration.

§Arguments
  • api_key - Your Binance API key
  • secret_key - Your Binance secret key
§Example
use binance_api_client::Binance;

let client = Binance::new("api_key", "secret_key")?;
Source

pub fn new_unauthenticated() -> Result<Self>

Create a new unauthenticated Binance client for public endpoints only.

This client can only access public market data endpoints. For account and trading endpoints, use Binance::new() with credentials.

§Example
use binance_api_client::Binance;

let client = Binance::new_unauthenticated()?;
Source

pub fn with_config<S: Into<String>>( config: Config, credentials: Option<(S, S)>, ) -> Result<Self>

Create a new Binance client with custom configuration.

§Arguments
  • config - Custom configuration (testnet, Binance.US, etc.)
  • credentials - Optional credentials tuple (api_key, secret_key)
§Example
use binance_api_client::{Binance, Config};

// Testnet with credentials
let config = Config::testnet();
let client = Binance::with_config(config, Some(("api_key", "secret_key")))?;

// Production without credentials
let config = Config::default();
let client = Binance::with_config(config, None::<(&str, &str)>)?;
Source

pub fn from_env() -> Result<Self>

Create a new Binance client from environment variables.

Expects BINANCE_API_KEY and BINANCE_SECRET_KEY environment variables.

§Example
use binance_api_client::Binance;

let client = Binance::from_env()?;
Source

pub fn testnet( api_key: impl Into<String>, secret_key: impl Into<String>, ) -> Result<Self>

Create a new testnet Binance client with credentials.

§Example
use binance_api_client::Binance;

let client = Binance::testnet("api_key", "secret_key")?;
Source

pub fn testnet_unauthenticated() -> Result<Self>

Create a new testnet Binance client without credentials.

§Example
use binance_api_client::Binance;

let client = Binance::testnet_unauthenticated()?;
Source

pub fn binance_us( api_key: impl Into<String>, secret_key: impl Into<String>, ) -> Result<Self>

Create a new Binance.US client with credentials.

§Example
use binance_api_client::Binance;

let client = Binance::binance_us("api_key", "secret_key")?;
Source

pub fn client(&self) -> &Client

Get the underlying HTTP client.

This is useful for advanced use cases where you need direct access to the client.

Source

pub fn config(&self) -> &Config

Get the current configuration.

Source

pub fn has_credentials(&self) -> bool

Check if this client has credentials for authenticated endpoints.

Source

pub fn market(&self) -> Market

Access market data API endpoints.

Market data endpoints are public and don’t require authentication.

§Example
let client = Binance::new_unauthenticated()?;

// Get current BTC price
let price = client.market().price("BTCUSDT").await?;
println!("BTC/USDT: {}", price.price);

// Get order book
let depth = client.market().depth("BTCUSDT", Some(10)).await?;
Source

pub fn user_stream(&self) -> UserStream

Access user data stream API endpoints.

User data streams provide real-time updates for account balance changes, order updates, and other account events via WebSocket.

Requires authentication.

§Example
let client = Binance::new("api_key", "secret_key")?;

// Start a user data stream
let listen_key = client.user_stream().start().await?;

// Keep it alive (call every 30 minutes)
client.user_stream().keepalive(&listen_key).await?;

// Close when done
client.user_stream().close(&listen_key).await?;
Source

pub fn account(&self) -> Account

Access account and trading API endpoints.

Account and trading endpoints require authentication. Use these to manage orders, query account balances, and view trade history.

Requires authentication.

§Example
let client = Binance::new("api_key", "secret_key")?;

// Get account info
let account = client.account().get_account().await?;

// Place a limit buy order
let order = client.account().limit_buy("BTCUSDT", "0.001", "50000.00").await?;

// Or use the order builder for more control
use binance_api_client::{OrderBuilder, OrderSide, OrderType, TimeInForce};

let order = OrderBuilder::new("BTCUSDT", OrderSide::Buy, OrderType::Limit)
    .quantity("0.001")
    .price("50000.00")
    .time_in_force(TimeInForce::GTC)
    .build();

let response = client.account().create_order(&order).await?;
Source

pub fn wallet(&self) -> Wallet

Access wallet SAPI endpoints.

Wallet endpoints provide access to deposit/withdrawal operations, asset management, universal transfers, and account status.

Requires authentication.

§Example
let client = Binance::new("api_key", "secret_key")?;

// Check system status
let status = client.wallet().system_status().await?;
if status.is_normal() {
    println!("System is operational");
}

// Get all coin information
let coins = client.wallet().all_coins().await?;

// Get deposit address
let address = client.wallet().deposit_address("BTC", None).await?;
println!("Deposit BTC to: {}", address.address);

// Get trade fees
let fees = client.wallet().trade_fee(Some("BTCUSDT")).await?;
Source

pub fn margin(&self) -> Margin

Access margin trading SAPI endpoints.

Margin endpoints provide access to cross-margin and isolated margin trading, loans, transfers, and account management.

Requires authentication.

§Example
let client = Binance::new("api_key", "secret_key")?;

// Get cross-margin account details
let account = client.margin().account().await?;
println!("Margin level: {}", account.margin_level);

// Check max borrowable
let max = client.margin().max_borrowable("BTC", None).await?;
println!("Max borrowable BTC: {}", max.amount);

// Transfer to margin account
use binance_api_client::MarginTransferType;
let result = client.margin()
    .transfer("USDT", "100.0", MarginTransferType::MainToMargin)
    .await?;

// Borrow
let loan = client.margin().loan("USDT", "50.0", false, None).await?;
Source

pub fn websocket(&self) -> WebSocketClient

Access WebSocket streaming API.

The WebSocket client provides real-time market data streams including trades, klines, tickers, and order book updates. It also supports user data streams for account updates when connected with a listen key.

§Example
use binance_api_client::Binance;

let client = Binance::new_unauthenticated()?;
let ws = client.websocket();

// Connect to aggregate trade stream
let stream_name = ws.agg_trade_stream("btcusdt");
let mut conn = ws.connect(&stream_name).await?;

// Receive events
while let Some(event) = conn.next().await {
    println!("{:?}", event?);
}

Trait Implementations§

Source§

impl Clone for Binance

Source§

fn clone(&self) -> Binance

Returns a duplicate 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 Debug for Binance

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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: 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: 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