Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 39 additions & 59 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
# binance-rs

Unofficial Rust Library for the [Binance API](https://github.com/binance/binance-spot-api-docs) and [Binance Futures API (Under development with upcoming breaking changes)](https://binance-docs.github.io/apidocs/futures/en/#general-info)
Unofficial Rust Library for the [Binance Spot API](https://developers.binance.com/docs/binance-spot-api-docs) and the [Binance USDⓈ-M Futures API](https://developers.binance.com/docs/derivatives/usds-margined-futures/general-info).

Endpoints and models track the official changelogs as of October 2026, including:

- Spot: order lists (OCO/OTO/OTOCO), cancel-replace, amend-keep-priority, commission rates, `myFilters`, order rate limits, trading-day and rolling-window tickers, `uiKlines`, and the WebSocket API user data stream that replaced the retired `listenKey` endpoints.
- Futures: conditional orders through the Algo service (`/fapi/v1/algoOrder`), batch place/cancel, modify order, V3 account/balance/position endpoints, symbol and account config, leverage brackets, commission rate, funding rate history, long/short ratios, basis, insurance fund, routed `/public`, `/market` and `/private` websocket streams, and the `ALGO_UPDATE` / `TRADE_LITE` events.

[![Crates.io](https://img.shields.io/crates/v/binance.svg)](https://crates.io/crates/binance)
[![Build Status](https://travis-ci.org/wisespace-io/binance-rs.png?branch=master)](https://travis-ci.org/wisespace-io/binance-rs)
Expand All @@ -23,7 +28,7 @@ Add this to your Cargo.toml
binance = { git = "https://github.com/ccxt/binance-rs.git" }
```

## Rust >= 1.56.1
## Rust >= 1.89.0

```rust
rustup install stable
Expand Down Expand Up @@ -248,75 +253,50 @@ let general: General = if use_testnet {

### USER STREAM CONFIGURATION

```rust
use binance::api::*;
use binance::userstream::*;

fn main() {
let api_key_user = Some("YOUR_API_KEY".into());
let user_stream: UserStream = Binance::new(api_key_user.clone(), None);

if let Ok(answer) = user_stream.start() {
println!("Data Stream Started ...");
let listen_key = answer.listen_key;

match user_stream.keep_alive(&listen_key) {
Ok(msg) => println!("Keepalive user data stream: {:?}", msg),
Err(e) => println!("Error: {:?}", e),
}
Binance retired the `listenKey` based spot user data stream (`POST /api/v3/userDataStream`)
on 2026-02-20. Spot account events are now delivered through the WebSocket API
(`wss://ws-api.binance.com:443/ws-api/v3`) after a signed `userDataStream.subscribe.signature`
request, which `WebSockets::connect_user_data_stream` sends for you. HMAC API keys work; no
`session.logon` is needed. Events arrive wrapped in `{"subscriptionId": n, "event": {...}}`
and are unwrapped before reaching your handler.

match user_stream.close(&listen_key) {
Ok(msg) => println!("Close user data stream: {:?}", msg),
Err(e) => println!("Error: {:?}", e),
}
} else {
println!("Not able to start an User Stream (Check your API_KEY)");
}
}
```
USDⓈ-M futures still use a `listenKey` (`FuturesUserStream::start`), connected through the
routed `/private` endpoint (`wss://fstream.binance.com/private/ws/<listenKey>`), which
`FuturesWebSockets::connect` picks automatically.

#### USER STREAM

```rust
use binance::api::*;
use binance::userstream::*;
use binance::config::Config;
use binance::websockets::*;
use std::sync::atomic::{AtomicBool};

fn main() {
let api_key_user = Some("YOUR_KEY".into());
let keep_running = AtomicBool::new(true); // Used to control the event loop
let user_stream: UserStream = Binance::new(api_key_user, None);
let config = Config::default(); // Config::testnet() for the Spot testnet

if let Ok(answer) = user_stream.start() {
let listen_key = answer.listen_key;
let mut web_socket = WebSockets::new(|event: WebsocketEvent| {
match event {
WebsocketEvent::OutboundAccountPosition(position) => {
for balance in &position.balances {
println!("Asset: {}, free: {}, locked: {}", balance.asset, balance.free, balance.locked);
}
},
WebsocketEvent::OrderTrade(trade) => {
println!("Symbol: {}, Side: {}, Price: {}, Execution Type: {}", trade.symbol, trade.side, trade.price, trade.execution_type);
},
WebsocketEvent::EventStreamTerminated(_) => {
println!("Subscription closed, reconnect");
},
_ => (),
};
Ok(())
});

let mut web_socket = WebSockets::new(|event: WebsocketEvent| {
match event {
WebsocketEvent::AccountUpdate(account_update) => {
for balance in &account_update.balance {
println!("Asset: {}, free: {}, locked: {}", balance.asset, balance.free, balance.locked);
}
},
WebsocketEvent::OrderTrade(trade) => {
println!("Symbol: {}, Side: {}, Price: {}, Execution Type: {}", trade.symbol, trade.side, trade.price, trade.execution_type);
},
_ => (),
};
Ok(())
});

web_socket.connect(&listen_key).unwrap(); // check error
if let Err(e) = web_socket.event_loop(&keep_running) {
match e {
err => {
println!("Error: {:?}", err);
}
}
}
} else {
println!("Not able to start an User Stream (Check your API_KEY)");
}
web_socket.connect_user_data_stream("YOUR_KEY", "YOUR_SECRET", &config).unwrap(); // check error
if let Err(e) = web_socket.event_loop(&keep_running) {
println!("Error: {:?}", e);
}
}
```

Expand Down
16 changes: 12 additions & 4 deletions examples/binance_futures_endpoints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,18 @@ fn market_data() {
Err(e) => println!("Error: {}", e),
}

match market.get_all_liquidation_orders() {
Ok(LiquidationOrders::AllLiquidationOrders(answer)) => {
println!("First liquidation order: {:?}", answer[0]);
}
match market.get_funding_rate_history(Some("BTCUSDT".to_string()), None, None, 2) {
Ok(answer) => println!("Last funding rates: {:?}", answer),
Err(e) => println!("Error: {}", e),
}

match market.get_mark_price("BTCUSDT") {
Ok(answer) => println!("Mark price: {:?}", answer),
Err(e) => println!("Error: {}", e),
}

match market.top_long_short_account_ratio("BTCUSDT", "1h", 1, None, None) {
Ok(answer) => println!("Top trader long/short ratio: {:?}", answer),
Err(e) => println!("Error: {}", e),
}

Expand Down
103 changes: 44 additions & 59 deletions examples/binance_websockets.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
#![allow(dead_code)]

use binance::api::*;
use binance::userstream::*;
use binance::config::Config;
use binance::websockets::*;
use std::sync::atomic::{AtomicBool, Ordering};

fn main() {
//user_stream();
//user_stream_websocket();
//market_websocket();
//kline_websocket();
Expand All @@ -15,71 +13,58 @@ fn main() {
// multiple_streams();
}

fn user_stream() {
let api_key_user = Some("YOUR_API_KEY".into());
let user_stream: UserStream = Binance::new(api_key_user, None);

if let Ok(answer) = user_stream.start() {
println!("Data Stream Started ...");
let listen_key = answer.listen_key;

match user_stream.keep_alive(&listen_key) {
Ok(msg) => println!("Keepalive user data stream: {:?}", msg),
Err(e) => println!("Error: {}", e),
}

match user_stream.close(&listen_key) {
Ok(msg) => println!("Close user data stream: {:?}", msg),
Err(e) => println!("Error: {}", e),
}
} else {
println!("Not able to start an User Stream (Check your API_KEY)");
}
}
// The listenKey based user stream (`POST /api/v3/userDataStream`) was retired by Binance on
// 2026-02-20. Spot user data is now subscribed through the WebSocket API with an API key
// signature, see `user_stream_websocket` below.

fn user_stream_websocket() {
let keep_running = AtomicBool::new(true); // Used to control the event loop
let api_key_user = Some("YOUR_KEY".into());
let user_stream: UserStream = Binance::new(api_key_user, None);

if let Ok(answer) = user_stream.start() {
let listen_key = answer.listen_key;

let mut web_socket: WebSockets<'_> = WebSockets::new(|event: WebsocketEvent| {
match event {
WebsocketEvent::AccountUpdate(account_update) => {
for balance in &account_update.data.balances {
println!(
"Asset: {}, wallet_balance: {}, cross_wallet_balance: {}, balance: {}",
balance.asset,
balance.wallet_balance,
balance.cross_wallet_balance,
balance.balance_change
);
}
}
WebsocketEvent::OrderTrade(trade) => {
let api_key = "YOUR_KEY";
let secret_key = "YOUR_SECRET";
let config = Config::default();

let mut web_socket: WebSockets<'_> = WebSockets::new(|event: WebsocketEvent| {
match event {
WebsocketEvent::OutboundAccountPosition(position) => {
for balance in &position.balances {
println!(
"Symbol: {}, Side: {}, Price: {}, Execution Type: {}",
trade.symbol, trade.side, trade.price, trade.execution_type
"Asset: {}, free: {}, locked: {}",
balance.asset, balance.free, balance.locked
);
}
_ => (),
};
}
WebsocketEvent::SpotBalanceUpdate(update) => {
println!("Asset: {}, delta: {}", update.asset, update.delta);
}
WebsocketEvent::OrderTrade(trade) => {
println!(
"Symbol: {}, Side: {}, Price: {}, Execution Type: {}",
trade.symbol, trade.side, trade.price, trade.execution_type
);
}
WebsocketEvent::ListStatus(list) => {
println!(
"Order list {}: {}",
list.order_list_id, list.list_order_status
);
}
WebsocketEvent::EventStreamTerminated(_) => {
println!("User data stream terminated, reconnect");
}
_ => (),
};

Ok(())
});
Ok(())
});

web_socket.connect(&listen_key).unwrap(); // check error
if let Err(e) = web_socket.event_loop(&keep_running) {
println!("Error: {}", e);
}
user_stream.close(&listen_key).unwrap();
web_socket.disconnect().unwrap();
println!("Userstrem closed and disconnected");
} else {
println!("Not able to start an User Stream (Check your API_KEY)");
web_socket
.connect_user_data_stream(api_key, secret_key, &config)
.unwrap(); // check error
if let Err(e) = web_socket.event_loop(&keep_running) {
println!("Error: {}", e);
}
web_socket.disconnect().unwrap();
println!("Userstrem closed and disconnected");
}

fn market_websocket() {
Expand Down
Loading
Loading