From e90ea4212091fdf07d5db31590ce40f8bb8470cf Mon Sep 17 00:00:00 2001 From: carlosmiei <43336371+carlosmiei@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:39:56 +0400 Subject: [PATCH 1/3] feat: update binance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Catch up with the Binance Spot and USDⓈ-M Futures API changes (2024 to Oct 2026): - Route futures conditional orders through the Algo service (/fapi/v1/algoOrder) with triggerPrice/activatePrice/clientAlgoId and the AlgoOrder response type; add algo query/cancel, batch place/cancel, modify order, amendments, force orders, countdown cancel-all, V3 account/balance/positionRisk, symbol and account config, commission rate, leverage brackets and the other missing account endpoints. - Replace the retired spot listenKey user stream with a WebSocket API signature subscription (WebSockets::connect_user_data_stream); route futures streams through /public, /market and /private. - Percent-encode signed payloads; add spot order lists (OCO/OTO/OTOCO), cancel-replace, amend-keep-priority, commission, myFilters, rate limits, trades, uiKlines, trading-day and rolling-window tickers. - Add unknown-filter fallback and the 2024-2026 response fields to the spot and futures models; fix markPriceUpdate, activatePrice and trade stream parsing; add ALGO_UPDATE, TRADE_LITE, MARGIN_CALL and ACCOUNT_CONFIG_UPDATE events. - Cover everything with mockito fixtures from the official docs. Co-Authored-By: Claude Fable 5.1 --- README.md | 89 +- examples/binance_futures_endpoints.rs | 16 +- examples/binance_websockets.rs | 103 +- src/account.rs | 683 +++++++++- src/api.rs | 111 ++ src/client.rs | 62 +- src/config.rs | 28 + src/futures/account.rs | 1127 +++++++++++++---- src/futures/market.rs | 470 ++++++- src/futures/model.rs | 1034 ++++++++++++++- src/futures/userstream.rs | 5 + src/futures/websockets.rs | 158 ++- src/general.rs | 35 + src/market.rs | 186 ++- src/model.rs | 635 +++++++++- src/userstream.rs | 16 +- src/util.rs | 57 +- src/websockets.rs | 145 ++- tests/account_tests.rs | 390 ++++++ tests/futures_account_tests.rs | 690 +++++++++- tests/futures_market_test.rs | 250 +++- tests/general_tests.rs | 90 +- tests/market_tests.rs | 115 ++ tests/mocks/account/account_commission.json | 7 + tests/mocks/account/all_orders.json | 24 + tests/mocks/account/amend_keep_priority.json | 23 + tests/mocks/account/cancel_order_list.json | 52 + tests/mocks/account/cancel_replace.json | 41 + .../cancel_replace_partial_failure.json | 26 + tests/mocks/account/get_account_full.json | 25 + tests/mocks/account/my_filters.json | 6 + tests/mocks/account/order_full.json | 33 + tests/mocks/account/order_list.json | 13 + tests/mocks/account/order_list_oco.json | 53 + tests/mocks/account/rate_limit_order.json | 4 + .../mocks/futures/account/account_config.json | 10 + .../account/account_information_v3.json | 44 + tests/mocks/futures/account/adl_quantile.json | 4 + .../futures/account/api_trading_status.json | 9 + tests/mocks/futures/account/balance_v3.json | 13 + tests/mocks/futures/account/batch_orders.json | 32 + .../futures/account/cancel_algo_order.json | 6 + .../account/cancel_all_algo_open_orders.json | 4 + .../futures/account/cancel_batch_orders.json | 33 + tests/mocks/futures/account/code_msg.json | 1 + .../futures/account/commission_rate.json | 6 + .../futures/account/countdown_cancel_all.json | 1 + tests/mocks/futures/account/fee_burn.json | 1 + tests/mocks/futures/account/force_orders.json | 26 + .../futures/account/leverage_bracket.json | 24 + tests/mocks/futures/account/limit_order.json | 28 + tests/mocks/futures/account/modify_order.json | 27 + .../futures/account/multi_assets_margin.json | 1 + .../mocks/futures/account/new_algo_order.json | 27 + .../futures/account/open_algo_orders.json | 34 + .../futures/account/order_amendment.json | 16 + .../account/position_margin_history.json | 4 + .../mocks/futures/account/position_mode.json | 1 + .../futures/account/position_risk_v3.json | 24 + .../futures/account/query_algo_order.json | 30 + tests/mocks/futures/account/query_order.json | 28 + .../futures/account/rate_limit_order.json | 4 + .../mocks/futures/account/symbol_config.json | 9 + tests/mocks/futures/market/basis.json | 3 + .../futures/market/continuous_klines.json | 4 + tests/mocks/futures/market/exchange_info.json | 52 + tests/mocks/futures/market/funding_info.json | 3 + tests/mocks/futures/market/funding_rate.json | 4 + .../futures/market/historical_trades.json | 3 + .../futures/market/index_constituents.json | 8 + .../futures/market/insurance_balance.json | 3 + .../futures/market/long_short_ratio.json | 4 + tests/mocks/futures/market/mark_price.json | 10 + .../mocks/futures/market/symbol_adl_risk.json | 1 + .../market/taker_long_short_ratio.json | 4 + tests/mocks/general/exchange_info_2026.json | 47 + .../market/rolling_window_tickers_mini.json | 30 + tests/mocks/market/trades.json | 3 + tests/mocks/market/trading_day_ticker.json | 17 + tests/util_tests.rs | 40 + tests/websocket_tests.rs | 279 ++++ 81 files changed, 7218 insertions(+), 546 deletions(-) create mode 100644 tests/mocks/account/account_commission.json create mode 100644 tests/mocks/account/all_orders.json create mode 100644 tests/mocks/account/amend_keep_priority.json create mode 100644 tests/mocks/account/cancel_order_list.json create mode 100644 tests/mocks/account/cancel_replace.json create mode 100644 tests/mocks/account/cancel_replace_partial_failure.json create mode 100644 tests/mocks/account/get_account_full.json create mode 100644 tests/mocks/account/my_filters.json create mode 100644 tests/mocks/account/order_full.json create mode 100644 tests/mocks/account/order_list.json create mode 100644 tests/mocks/account/order_list_oco.json create mode 100644 tests/mocks/account/rate_limit_order.json create mode 100644 tests/mocks/futures/account/account_config.json create mode 100644 tests/mocks/futures/account/account_information_v3.json create mode 100644 tests/mocks/futures/account/adl_quantile.json create mode 100644 tests/mocks/futures/account/api_trading_status.json create mode 100644 tests/mocks/futures/account/balance_v3.json create mode 100644 tests/mocks/futures/account/batch_orders.json create mode 100644 tests/mocks/futures/account/cancel_algo_order.json create mode 100644 tests/mocks/futures/account/cancel_all_algo_open_orders.json create mode 100644 tests/mocks/futures/account/cancel_batch_orders.json create mode 100644 tests/mocks/futures/account/code_msg.json create mode 100644 tests/mocks/futures/account/commission_rate.json create mode 100644 tests/mocks/futures/account/countdown_cancel_all.json create mode 100644 tests/mocks/futures/account/fee_burn.json create mode 100644 tests/mocks/futures/account/force_orders.json create mode 100644 tests/mocks/futures/account/leverage_bracket.json create mode 100644 tests/mocks/futures/account/limit_order.json create mode 100644 tests/mocks/futures/account/modify_order.json create mode 100644 tests/mocks/futures/account/multi_assets_margin.json create mode 100644 tests/mocks/futures/account/new_algo_order.json create mode 100644 tests/mocks/futures/account/open_algo_orders.json create mode 100644 tests/mocks/futures/account/order_amendment.json create mode 100644 tests/mocks/futures/account/position_margin_history.json create mode 100644 tests/mocks/futures/account/position_mode.json create mode 100644 tests/mocks/futures/account/position_risk_v3.json create mode 100644 tests/mocks/futures/account/query_algo_order.json create mode 100644 tests/mocks/futures/account/query_order.json create mode 100644 tests/mocks/futures/account/rate_limit_order.json create mode 100644 tests/mocks/futures/account/symbol_config.json create mode 100644 tests/mocks/futures/market/basis.json create mode 100644 tests/mocks/futures/market/continuous_klines.json create mode 100644 tests/mocks/futures/market/exchange_info.json create mode 100644 tests/mocks/futures/market/funding_info.json create mode 100644 tests/mocks/futures/market/funding_rate.json create mode 100644 tests/mocks/futures/market/historical_trades.json create mode 100644 tests/mocks/futures/market/index_constituents.json create mode 100644 tests/mocks/futures/market/insurance_balance.json create mode 100644 tests/mocks/futures/market/long_short_ratio.json create mode 100644 tests/mocks/futures/market/mark_price.json create mode 100644 tests/mocks/futures/market/symbol_adl_risk.json create mode 100644 tests/mocks/futures/market/taker_long_short_ratio.json create mode 100644 tests/mocks/general/exchange_info_2026.json create mode 100644 tests/mocks/market/rolling_window_tickers_mini.json create mode 100644 tests/mocks/market/trades.json create mode 100644 tests/mocks/market/trading_day_ticker.json create mode 100644 tests/websocket_tests.rs diff --git a/README.md b/README.md index 24cfebe7..594810a2 100644 --- a/README.md +++ b/README.md @@ -248,75 +248,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); +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. - 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)"); - } -} -``` +USDⓈ-M futures still use a `listenKey` (`FuturesUserStream::start`), connected through the +routed `/private` endpoint (`wss://fstream.binance.com/private/ws/`), 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); + } } ``` diff --git a/examples/binance_futures_endpoints.rs b/examples/binance_futures_endpoints.rs index 7cb1969f..4b0d2ea3 100644 --- a/examples/binance_futures_endpoints.rs +++ b/examples/binance_futures_endpoints.rs @@ -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), } diff --git a/examples/binance_websockets.rs b/examples/binance_websockets.rs index af870113..84a3de7f 100644 --- a/examples/binance_websockets.rs +++ b/examples/binance_websockets.rs @@ -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(); @@ -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() { diff --git a/src/account.rs b/src/account.rs index a56c263d..74cb045a 100644 --- a/src/account.rs +++ b/src/account.rs @@ -2,7 +2,9 @@ use error_chain::bail; use crate::util::{build_signed_request, is_start_time_valid, uuid_spot}; use crate::model::{ - AccountInformation, Balance, Empty, Order, OrderCanceled, TradeHistory, Transaction, + AccountCommission, AccountInformation, Allocation, AmendKeepPriorityResponse, Balance, + CancelReplaceResponse, Empty, MyFilters, Order, OrderCanceled, OrderList, OrderRateLimit, + PreventedMatch, SpotOrderAmendment, TradeHistory, Transaction, }; use crate::client::Client; use crate::errors::Result; @@ -38,10 +40,15 @@ struct OrderQuoteQuantityRequest { pub new_client_order_id: Option, } +#[derive(Debug, Clone, PartialEq, Eq)] pub enum OrderType { Limit, Market, StopLossLimit, + StopLoss, + TakeProfit, + TakeProfitLimit, + LimitMaker, } impl OrderType { @@ -50,6 +57,10 @@ impl OrderType { 1 => Some(OrderType::Limit), 2 => Some(OrderType::Market), 3 => Some(OrderType::StopLossLimit), + 4 => Some(OrderType::StopLoss), + 5 => Some(OrderType::TakeProfit), + 6 => Some(OrderType::TakeProfitLimit), + 7 => Some(OrderType::LimitMaker), _ => None, } } @@ -61,10 +72,191 @@ impl Display for OrderType { Self::Limit => write!(f, "LIMIT"), Self::Market => write!(f, "MARKET"), Self::StopLossLimit => write!(f, "STOP_LOSS_LIMIT"), + Self::StopLoss => write!(f, "STOP_LOSS"), + Self::TakeProfit => write!(f, "TAKE_PROFIT"), + Self::TakeProfitLimit => write!(f, "TAKE_PROFIT_LIMIT"), + Self::LimitMaker => write!(f, "LIMIT_MAKER"), } } } +/// Self-trade prevention modes. The allowed set depends on the symbol +/// (see `allowed_self_trade_prevention_modes` in exchange info). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SelfTradePreventionMode { + None, + ExpireTaker, + ExpireMaker, + ExpireBoth, + Decrement, + Transfer, +} + +impl Display for SelfTradePreventionMode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::None => write!(f, "NONE"), + Self::ExpireTaker => write!(f, "EXPIRE_TAKER"), + Self::ExpireMaker => write!(f, "EXPIRE_MAKER"), + Self::ExpireBoth => write!(f, "EXPIRE_BOTH"), + Self::Decrement => write!(f, "DECREMENT"), + Self::Transfer => write!(f, "TRANSFER"), + } + } +} + +/// How `POST /api/v3/order/cancelReplace` behaves when the cancel fails. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CancelReplaceMode { + /// If the cancel request fails, the new order placement will not be attempted. + StopOnFailure, + /// The new order placement will be attempted even if the cancel request fails. + AllowFailure, +} + +impl Display for CancelReplaceMode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::StopOnFailure => write!(f, "STOP_ON_FAILURE"), + Self::AllowFailure => write!(f, "ALLOW_FAILURE"), + } + } +} + +/// Parameters of one leg of an order list (OCO above/below, OTO working/pending, ...). +/// +/// Only the fields relevant to the leg's `order_type` are sent; everything is optional +/// except `order_type`. +#[derive(Debug, Clone, Default)] +pub struct OrderListLeg { + pub order_type: Option, + pub side: Option, + pub quantity: Option, + pub price: Option, + pub stop_price: Option, + pub trailing_delta: Option, + pub time_in_force: Option, + pub client_order_id: Option, + pub iceberg_qty: Option, + pub strategy_id: Option, + pub strategy_type: Option, +} + +impl OrderListLeg { + /// Insert this leg's parameters with the given prefix (`above`, `below`, `working`, + /// `pending`, `pendingAbove`, `pendingBelow`) into `params`. + fn insert_into(&self, prefix: &str, params: &mut BTreeMap) { + if let Some(t) = &self.order_type { + params.insert(format!("{}Type", prefix), t.to_string()); + } + if let Some(side) = &self.side { + params.insert(format!("{}Side", prefix), side.to_string()); + } + if let Some(q) = self.quantity { + params.insert(format!("{}Quantity", prefix), q.to_string()); + } + if let Some(p) = self.price { + params.insert(format!("{}Price", prefix), p.to_string()); + } + if let Some(sp) = self.stop_price { + params.insert(format!("{}StopPrice", prefix), sp.to_string()); + } + if let Some(td) = self.trailing_delta { + params.insert(format!("{}TrailingDelta", prefix), td.to_string()); + } + if let Some(tif) = &self.time_in_force { + params.insert(format!("{}TimeInForce", prefix), tif.to_string()); + } + if let Some(id) = &self.client_order_id { + params.insert(format!("{}ClientOrderId", prefix), id.clone()); + } + if let Some(iq) = self.iceberg_qty { + params.insert(format!("{}IcebergQty", prefix), iq.to_string()); + } + if let Some(sid) = self.strategy_id { + params.insert(format!("{}StrategyId", prefix), sid.to_string()); + } + if let Some(st) = self.strategy_type { + params.insert(format!("{}StrategyType", prefix), st.to_string()); + } + } +} + +/// `POST /api/v3/orderList/oco` request. +/// +/// One leg must be `LIMIT_MAKER`/`TAKE_PROFIT`/`TAKE_PROFIT_LIMIT` and the other +/// `STOP_LOSS`/`STOP_LOSS_LIMIT`. `quantity` applies to both legs. +#[derive(Debug, Clone)] +pub struct OcoOrderListRequest { + pub symbol: String, + pub side: OrderSide, + pub quantity: f64, + pub above: OrderListLeg, + pub below: OrderListLeg, + pub list_client_order_id: Option, + pub new_order_resp_type: Option, + pub self_trade_prevention_mode: Option, +} + +/// `POST /api/v3/orderList/oto` request: the `pending` order is placed once the +/// `working` order (`LIMIT` or `LIMIT_MAKER`) is fully filled. +#[derive(Debug, Clone)] +pub struct OtoOrderListRequest { + pub symbol: String, + pub working: OrderListLeg, + pub pending: OrderListLeg, + pub list_client_order_id: Option, + pub new_order_resp_type: Option, + pub self_trade_prevention_mode: Option, +} + +/// `POST /api/v3/orderList/otoco` request: once the `working` order fills, an OCO made of +/// `pending_above` and `pending_below` is placed. `pending_side` and `pending_quantity` +/// apply to both pending legs. +#[derive(Debug, Clone)] +pub struct OtocoOrderListRequest { + pub symbol: String, + pub working: OrderListLeg, + pub pending_side: OrderSide, + pub pending_quantity: f64, + pub pending_above: OrderListLeg, + pub pending_below: OrderListLeg, + pub list_client_order_id: Option, + pub new_order_resp_type: Option, + pub self_trade_prevention_mode: Option, +} + +/// `POST /api/v3/order/cancelReplace` request. +/// +/// Either `cancel_order_id` or `cancel_orig_client_order_id` must be set. The new order +/// is described by the remaining fields, which mirror `POST /api/v3/order`. +#[derive(Debug, Clone)] +pub struct CancelReplaceRequest { + pub symbol: String, + pub side: OrderSide, + pub order_type: OrderType, + pub cancel_replace_mode: CancelReplaceMode, + pub cancel_order_id: Option, + pub cancel_orig_client_order_id: Option, + pub cancel_new_client_order_id: Option, + pub time_in_force: Option, + pub quantity: Option, + pub quote_order_qty: Option, + pub price: Option, + pub new_client_order_id: Option, + pub stop_price: Option, + pub trailing_delta: Option, + pub iceberg_qty: Option, + pub strategy_id: Option, + pub strategy_type: Option, + pub new_order_resp_type: Option, + pub self_trade_prevention_mode: Option, + /// `ONLY_NEW` or `ONLY_PARTIALLY_FILLED` + pub cancel_restrictions: Option, + /// `DO_NOTHING` (default) or `CANCEL_ONLY` + pub order_rate_limit_exceeded_mode: Option, +} + #[derive(Debug, Clone)] pub enum OrderSide { Buy, @@ -91,6 +283,7 @@ impl Display for OrderSide { } #[allow(clippy::all)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum TimeInForce { GTC, IOC, @@ -126,6 +319,151 @@ impl Account { .get_signed(API::Spot(Spot::Account), Some(request)) } + /// Account information, optionally omitting zero balances (`omitZeroBalances=true`). + pub fn get_account_with_params(&self, omit_zero_balances: bool) -> Result { + let mut parameters: BTreeMap = BTreeMap::new(); + if omit_zero_balances { + parameters.insert("omitZeroBalances".into(), "true".into()); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Spot(Spot::Account), Some(request)) + } + + /// Current commission rates for a symbol (`GET /api/v3/account/commission`). + pub fn get_account_commission(&self, symbol: S) -> Result + where + S: Into, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Spot(Spot::AccountCommission), Some(request)) + } + + /// Filters relevant to this account on a symbol (`GET /api/v3/myFilters`). + /// + /// This is the only endpoint that shows account-level `MAX_ASSET` filters. + pub fn get_my_filters(&self, symbol: S) -> Result + where + S: Into, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Spot(Spot::MyFilters), Some(request)) + } + + /// Unfilled order count for all intervals (`GET /api/v3/rateLimit/order`). + pub fn get_order_rate_limits(&self) -> Result> { + let request = build_signed_request(BTreeMap::new(), self.recv_window)?; + self.client + .get_signed(API::Spot(Spot::RateLimitOrder), Some(request)) + } + + /// Orders that expired because of self-trade prevention (`GET /api/v3/myPreventedMatches`). + /// + /// Supported combinations: `symbol` + `prevented_match_id`, `symbol` + `order_id`, + /// `symbol` + `order_id` + `from_prevented_match_id`. + pub fn get_prevented_matches( + &self, symbol: S, prevented_match_id: P, order_id: O, from_prevented_match_id: F, limit: L, + ) -> Result> + where + S: Into, + P: Into>, + O: Into>, + F: Into>, + L: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + if let Some(id) = prevented_match_id.into() { + parameters.insert("preventedMatchId".into(), id.to_string()); + } + if let Some(id) = order_id.into() { + parameters.insert("orderId".into(), id.to_string()); + } + if let Some(id) = from_prevented_match_id.into() { + parameters.insert("fromPreventedMatchId".into(), id.to_string()); + } + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Spot(Spot::MyPreventedMatches), Some(request)) + } + + /// Allocations resulting from SOR order placement (`GET /api/v3/myAllocations`). + #[allow(clippy::too_many_arguments)] + pub fn get_allocations( + &self, symbol: S, start_time: T1, end_time: T2, from_allocation_id: F, limit: L, + order_id: O, + ) -> Result> + where + S: Into, + T1: Into>, + T2: Into>, + F: Into>, + L: Into>, + O: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + if let Some(st) = start_time.into() { + parameters.insert("startTime".into(), st.to_string()); + } + if let Some(et) = end_time.into() { + parameters.insert("endTime".into(), et.to_string()); + } + if let Some(id) = from_allocation_id.into() { + parameters.insert("fromAllocationId".into(), id.to_string()); + } + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + if let Some(id) = order_id.into() { + parameters.insert("orderId".into(), id.to_string()); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Spot(Spot::MyAllocations), Some(request)) + } + + /// All orders (active, canceled, filled) for a symbol (`GET /api/v3/allOrders`). + /// + /// If `order_id` is set, orders >= that id are returned; otherwise the most recent ones. + pub fn get_all_orders( + &self, symbol: S, order_id: O, start_time: T1, end_time: T2, limit: L, + ) -> Result> + where + S: Into, + O: Into>, + T1: Into>, + T2: Into>, + L: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + if let Some(id) = order_id.into() { + parameters.insert("orderId".into(), id.to_string()); + } + if let Some(st) = start_time.into() { + parameters.insert("startTime".into(), st.to_string()); + } + if let Some(et) = end_time.into() { + parameters.insert("endTime".into(), et.to_string()); + } + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Spot(Spot::AllOrders), Some(request)) + } + // Balance for a single Asset pub fn get_balance(&self, asset: S) -> Result where @@ -193,6 +531,22 @@ impl Account { .get_signed(API::Spot(Spot::Order), Some(request)) } + /// Check an order's status by its client order id. + pub fn order_status_with_client_id( + &self, symbol: S, orig_client_order_id: String, + ) -> Result + where + S: Into, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + parameters.insert("origClientOrderId".into(), orig_client_order_id); + + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Spot(Spot::Order), Some(request)) + } + /// Place a test status order /// /// This order is sandboxed: it is validated, but not sent to the matching engine. @@ -766,6 +1120,333 @@ impl Account { .map(|_| ()) } + /// Cancel an existing order and immediately place a new one + /// (`POST /api/v3/order/cancelReplace`). + /// + /// Note that Binance answers with HTTP 400 when the cancel fails in + /// `STOP_ON_FAILURE` mode, which surfaces here as a `BinanceError`. + pub fn cancel_replace_order(&self, req: CancelReplaceRequest) -> Result { + self.cancel_replace_order_with_params(req, BTreeMap::new()) + } + + /// Same as [`Account::cancel_replace_order`] with extra raw request parameters. + pub fn cancel_replace_order_with_params( + &self, req: CancelReplaceRequest, request_params: BTreeMap, + ) -> Result { + let mut p: BTreeMap = BTreeMap::new(); + p.insert("symbol".into(), req.symbol); + p.insert("side".into(), req.side.to_string()); + p.insert("type".into(), req.order_type.to_string()); + p.insert( + "cancelReplaceMode".into(), + req.cancel_replace_mode.to_string(), + ); + if let Some(id) = req.cancel_order_id { + p.insert("cancelOrderId".into(), id.to_string()); + } + if let Some(id) = req.cancel_orig_client_order_id { + p.insert("cancelOrigClientOrderId".into(), id); + } + if let Some(id) = req.cancel_new_client_order_id { + p.insert("cancelNewClientOrderId".into(), id); + } + if let Some(tif) = req.time_in_force { + p.insert("timeInForce".into(), tif.to_string()); + } + if let Some(q) = req.quantity { + p.insert("quantity".into(), q.to_string()); + } + if let Some(q) = req.quote_order_qty { + p.insert("quoteOrderQty".into(), q.to_string()); + } + if let Some(price) = req.price { + p.insert("price".into(), price.to_string()); + } + p.insert( + "newClientOrderId".into(), + req.new_client_order_id.unwrap_or_else(uuid_spot), + ); + if let Some(sp) = req.stop_price { + p.insert("stopPrice".into(), sp.to_string()); + } + if let Some(td) = req.trailing_delta { + p.insert("trailingDelta".into(), td.to_string()); + } + if let Some(iq) = req.iceberg_qty { + p.insert("icebergQty".into(), iq.to_string()); + } + if let Some(sid) = req.strategy_id { + p.insert("strategyId".into(), sid.to_string()); + } + if let Some(st) = req.strategy_type { + p.insert("strategyType".into(), st.to_string()); + } + if let Some(rt) = req.new_order_resp_type { + p.insert("newOrderRespType".into(), rt); + } + if let Some(stp) = req.self_trade_prevention_mode { + p.insert("selfTradePreventionMode".into(), stp.to_string()); + } + if let Some(cr) = req.cancel_restrictions { + p.insert("cancelRestrictions".into(), cr); + } + if let Some(m) = req.order_rate_limit_exceeded_mode { + p.insert("orderRateLimitExceededMode".into(), m); + } + for (key, value) in request_params { + p.insert(key, value); + } + let request = build_signed_request(p, self.recv_window)?; + self.client + .post_signed(API::Spot(Spot::OrderCancelReplace), request) + } + + /// Reduce the quantity of an open order while keeping its queue priority + /// (`PUT /api/v3/order/amend/keepPriority`). + /// + /// Exactly one of `order_id` / `orig_client_order_id` must be provided; `new_qty` + /// must be greater than 0 and lower than the order's current quantity. + pub fn amend_order_keep_priority( + &self, symbol: S, order_id: O, orig_client_order_id: C, new_qty: f64, + new_client_order_id: N, + ) -> Result + where + S: Into, + O: Into>, + C: Into>, + N: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + parameters.insert("newQty".into(), new_qty.to_string()); + if let Some(id) = order_id.into() { + parameters.insert("orderId".into(), id.to_string()); + } + if let Some(id) = orig_client_order_id.into() { + parameters.insert("origClientOrderId".into(), id); + } + if let Some(id) = new_client_order_id.into() { + parameters.insert("newClientOrderId".into(), id); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .put_signed(API::Spot(Spot::OrderAmendKeepPriority), request) + } + + /// Amendments made to an order (`GET /api/v3/order/amendments`). + pub fn get_order_amendments( + &self, symbol: S, order_id: u64, from_execution_id: F, limit: L, + ) -> Result> + where + S: Into, + F: Into>, + L: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + parameters.insert("orderId".into(), order_id.to_string()); + if let Some(id) = from_execution_id.into() { + parameters.insert("fromExecutionId".into(), id.to_string()); + } + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Spot(Spot::OrderAmendments), Some(request)) + } + + /// Place an OCO order list (`POST /api/v3/orderList/oco`). + /// + /// This replaces the deprecated `POST /api/v3/order/oco` endpoint. + pub fn new_oco_order_list(&self, req: OcoOrderListRequest) -> Result { + let mut p: BTreeMap = BTreeMap::new(); + p.insert("symbol".into(), req.symbol); + p.insert("side".into(), req.side.to_string()); + p.insert("quantity".into(), req.quantity.to_string()); + req.above.insert_into("above", &mut p); + req.below.insert_into("below", &mut p); + Self::insert_list_common( + &mut p, + req.list_client_order_id, + req.new_order_resp_type, + req.self_trade_prevention_mode, + ); + let request = build_signed_request(p, self.recv_window)?; + self.client + .post_signed(API::Spot(Spot::OrderListOco), request) + } + + /// Place an OTO (one-triggers-the-other) order list (`POST /api/v3/orderList/oto`). + pub fn new_oto_order_list(&self, req: OtoOrderListRequest) -> Result { + let mut p: BTreeMap = BTreeMap::new(); + p.insert("symbol".into(), req.symbol); + req.working.insert_into("working", &mut p); + req.pending.insert_into("pending", &mut p); + Self::insert_list_common( + &mut p, + req.list_client_order_id, + req.new_order_resp_type, + req.self_trade_prevention_mode, + ); + let request = build_signed_request(p, self.recv_window)?; + self.client + .post_signed(API::Spot(Spot::OrderListOto), request) + } + + /// Place an OTOCO (one-triggers-one-cancels-the-other) order list + /// (`POST /api/v3/orderList/otoco`). + pub fn new_otoco_order_list(&self, req: OtocoOrderListRequest) -> Result { + let mut p: BTreeMap = BTreeMap::new(); + p.insert("symbol".into(), req.symbol); + req.working.insert_into("working", &mut p); + p.insert("pendingSide".into(), req.pending_side.to_string()); + p.insert("pendingQuantity".into(), req.pending_quantity.to_string()); + req.pending_above.insert_into("pendingAbove", &mut p); + req.pending_below.insert_into("pendingBelow", &mut p); + Self::insert_list_common( + &mut p, + req.list_client_order_id, + req.new_order_resp_type, + req.self_trade_prevention_mode, + ); + let request = build_signed_request(p, self.recv_window)?; + self.client + .post_signed(API::Spot(Spot::OrderListOtoco), request) + } + + fn insert_list_common( + p: &mut BTreeMap, list_client_order_id: Option, + new_order_resp_type: Option, stp: Option, + ) { + if let Some(id) = list_client_order_id { + p.insert("listClientOrderId".into(), id); + } + if let Some(rt) = new_order_resp_type { + p.insert("newOrderRespType".into(), rt); + } + if let Some(stp) = stp { + p.insert("selfTradePreventionMode".into(), stp.to_string()); + } + } + + /// Query an order list by `orderListId` (`GET /api/v3/orderList`). + pub fn get_order_list(&self, order_list_id: u64) -> Result { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("orderListId".into(), order_list_id.to_string()); + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Spot(Spot::OrderList), Some(request)) + } + + /// Query an order list by its `listClientOrderId` (`GET /api/v3/orderList`). + pub fn get_order_list_with_client_id(&self, list_client_order_id: S) -> Result + where + S: Into, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("origClientOrderId".into(), list_client_order_id.into()); + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Spot(Spot::OrderList), Some(request)) + } + + /// All order lists (`GET /api/v3/allOrderList`). + pub fn get_all_order_lists( + &self, from_id: F, start_time: T1, end_time: T2, limit: L, + ) -> Result> + where + F: Into>, + T1: Into>, + T2: Into>, + L: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + if let Some(id) = from_id.into() { + parameters.insert("fromId".into(), id.to_string()); + } + if let Some(st) = start_time.into() { + parameters.insert("startTime".into(), st.to_string()); + } + if let Some(et) = end_time.into() { + parameters.insert("endTime".into(), et.to_string()); + } + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Spot(Spot::AllOrderList), Some(request)) + } + + /// Currently open order lists (`GET /api/v3/openOrderList`). + pub fn get_open_order_lists(&self) -> Result> { + let request = build_signed_request(BTreeMap::new(), self.recv_window)?; + self.client + .get_signed(API::Spot(Spot::OpenOrderList), Some(request)) + } + + /// Cancel an entire order list (`DELETE /api/v3/orderList`). + /// + /// Either `order_list_id` or `list_client_order_id` must be provided. + pub fn cancel_order_list( + &self, symbol: S, order_list_id: O, list_client_order_id: C, + ) -> Result + where + S: Into, + O: Into>, + C: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + if let Some(id) = order_list_id.into() { + parameters.insert("orderListId".into(), id.to_string()); + } + if let Some(id) = list_client_order_id.into() { + parameters.insert("listClientOrderId".into(), id); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .delete_signed(API::Spot(Spot::OrderList), Some(request)) + } + + /// Account trade list with all supported filters (`GET /api/v3/myTrades`). + /// + /// `order_id` can only be combined with `symbol`; `from_id` cannot be combined with + /// `start_time`/`end_time`. + pub fn trade_history_with_params( + &self, symbol: S, order_id: O, start_time: T1, end_time: T2, from_id: F, limit: L, + ) -> Result> + where + S: Into, + O: Into>, + T1: Into>, + T2: Into>, + F: Into>, + L: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + if let Some(id) = order_id.into() { + parameters.insert("orderId".into(), id.to_string()); + } + if let Some(st) = start_time.into() { + parameters.insert("startTime".into(), st.to_string()); + } + if let Some(et) = end_time.into() { + parameters.insert("endTime".into(), et.to_string()); + } + if let Some(id) = from_id.into() { + parameters.insert("fromId".into(), id.to_string()); + } + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Spot(Spot::MyTrades), Some(request)) + } + // Trade history pub fn trade_history(&self, symbol: S) -> Result> where diff --git a/src/api.rs b/src/api.rs index 3357c926..8b7884ae 100644 --- a/src/api.rs +++ b/src/api.rs @@ -32,20 +32,41 @@ pub enum Spot { HistoricalTrades, AggTrades, Klines, + UiKlines, AvgPrice, Ticker24hr, + TickerTradingDay, + /// Rolling window price change statistics (`GET /api/v3/ticker`) + Ticker, Price, BookTicker, Order, OrderTest, + OrderCancelReplace, + OrderAmendKeepPriority, OpenOrders, AllOrders, + /// Deprecated by Binance in favour of [`Spot::OrderListOco`] Oco, OrderList, + OrderListOco, + OrderListOto, + OrderListOtoco, + OrderListOpo, + OrderListOpoco, AllOrderList, OpenOrderList, + SorOrder, + SorOrderTest, Account, + AccountCommission, MyTrades, + RateLimitOrder, + MyPreventedMatches, + MyAllocations, + OrderAmendments, + MyFilters, + /// Retired by Binance on 2026-02-20; use the WebSocket API user data stream instead. UserDataStream, } @@ -61,6 +82,7 @@ pub enum Futures { Time, ExchangeInfo, Depth, + RpiDepth, Trades, HistoricalTrades, AggTrades, @@ -68,35 +90,72 @@ pub enum Futures { ContinuousKlines, IndexPriceKlines, MarkPriceKlines, + PremiumIndexKlines, PremiumIndex, FundingRate, + FundingInfo, Ticker24hr, TickerPrice, + TickerPriceV2, BookTicker, + /// Removed by Binance; `/fapi/v1/allForceOrders` no longer exists. Use [`Futures::ForceOrders`]. AllForceOrders, + ForceOrders, AllOpenOrders, AllOrders, UserTrades, Order, + OpenOrder, + BatchOrders, + CountdownCancelAll, + OrderAmendment, AlgoOrder, + AlgoOpenOrders, + OpenAlgoOrders, + AllAlgoOrders, + /// Deprecated by Binance in favour of [`Futures::PositionRiskV3`] PositionRisk, + PositionRiskV3, + /// Deprecated by Binance in favour of [`Futures::BalanceV3`] Balance, + BalanceV3, PositionSide, + MultiAssetsMargin, OpenInterest, OpenInterestHist, TopLongShortAccountRatio, TopLongShortPositionRatio, GlobalLongShortAccountRatio, TakerlongshortRatio, + Basis, LvtKlines, IndexInfo, + AssetIndex, + Constituents, + InsuranceBalance, + SymbolAdlRisk, + DeliveryPrice, + TradingSchedule, ChangeInitialLeverage, MarginType, PositionMargin, + PositionMarginHistory, + /// Deprecated by Binance in favour of [`Futures::AccountV3`] Account, + AccountV3, + AccountConfig, + SymbolConfig, + CommissionRate, + LeverageBracket, + AdlQuantile, + ApiTradingStatus, + FeeBurn, + RateLimitOrder, OpenOrders, UserDataStream, Income, + IncomeAsyn, + IncomeAsynId, } impl From for String { @@ -111,20 +170,38 @@ impl From for String { Spot::HistoricalTrades => "/api/v3/historicalTrades", Spot::AggTrades => "/api/v3/aggTrades", Spot::Klines => "/api/v3/klines", + Spot::UiKlines => "/api/v3/uiKlines", Spot::AvgPrice => "/api/v3/avgPrice", Spot::Ticker24hr => "/api/v3/ticker/24hr", + Spot::TickerTradingDay => "/api/v3/ticker/tradingDay", + Spot::Ticker => "/api/v3/ticker", Spot::Price => "/api/v3/ticker/price", Spot::BookTicker => "/api/v3/ticker/bookTicker", Spot::Order => "/api/v3/order", Spot::OrderTest => "/api/v3/order/test", + Spot::OrderCancelReplace => "/api/v3/order/cancelReplace", + Spot::OrderAmendKeepPriority => "/api/v3/order/amend/keepPriority", Spot::OpenOrders => "/api/v3/openOrders", Spot::AllOrders => "/api/v3/allOrders", Spot::Oco => "/api/v3/order/oco", Spot::OrderList => "/api/v3/orderList", + Spot::OrderListOco => "/api/v3/orderList/oco", + Spot::OrderListOto => "/api/v3/orderList/oto", + Spot::OrderListOtoco => "/api/v3/orderList/otoco", + Spot::OrderListOpo => "/api/v3/orderList/opo", + Spot::OrderListOpoco => "/api/v3/orderList/opoco", Spot::AllOrderList => "/api/v3/allOrderList", Spot::OpenOrderList => "/api/v3/openOrderList", + Spot::SorOrder => "/api/v3/sor/order", + Spot::SorOrderTest => "/api/v3/sor/order/test", Spot::Account => "/api/v3/account", + Spot::AccountCommission => "/api/v3/account/commission", Spot::MyTrades => "/api/v3/myTrades", + Spot::RateLimitOrder => "/api/v3/rateLimit/order", + Spot::MyPreventedMatches => "/api/v3/myPreventedMatches", + Spot::MyAllocations => "/api/v3/myAllocations", + Spot::OrderAmendments => "/api/v3/order/amendments", + Spot::MyFilters => "/api/v3/myFilters", Spot::UserDataStream => "/api/v3/userDataStream", }, API::Savings(route) => match route { @@ -138,6 +215,7 @@ impl From for String { Futures::Time => "/fapi/v1/time", Futures::ExchangeInfo => "/fapi/v1/exchangeInfo", Futures::Depth => "/fapi/v1/depth", + Futures::RpiDepth => "/fapi/v1/rpiDepth", Futures::Trades => "/fapi/v1/trades", Futures::HistoricalTrades => "/fapi/v1/historicalTrades", Futures::AggTrades => "/fapi/v1/aggTrades", @@ -145,35 +223,68 @@ impl From for String { Futures::ContinuousKlines => "/fapi/v1/continuousKlines", Futures::IndexPriceKlines => "/fapi/v1/indexPriceKlines", Futures::MarkPriceKlines => "/fapi/v1/markPriceKlines", + Futures::PremiumIndexKlines => "/fapi/v1/premiumIndexKlines", Futures::PremiumIndex => "/fapi/v1/premiumIndex", Futures::FundingRate => "/fapi/v1/fundingRate", + Futures::FundingInfo => "/fapi/v1/fundingInfo", Futures::Ticker24hr => "/fapi/v1/ticker/24hr", Futures::TickerPrice => "/fapi/v1/ticker/price", + Futures::TickerPriceV2 => "/fapi/v2/ticker/price", Futures::BookTicker => "/fapi/v1/ticker/bookTicker", Futures::AllForceOrders => "/fapi/v1/allForceOrders", + Futures::ForceOrders => "/fapi/v1/forceOrders", Futures::AllOpenOrders => "/fapi/v1/allOpenOrders", Futures::AllOrders => "/fapi/v1/allOrders", Futures::UserTrades => "/fapi/v1/userTrades", Futures::PositionSide => "/fapi/v1/positionSide/dual", + Futures::MultiAssetsMargin => "/fapi/v1/multiAssetsMargin", Futures::Order => "/fapi/v1/order", + Futures::OpenOrder => "/fapi/v1/openOrder", + Futures::BatchOrders => "/fapi/v1/batchOrders", + Futures::CountdownCancelAll => "/fapi/v1/countdownCancelAll", + Futures::OrderAmendment => "/fapi/v1/orderAmendment", Futures::AlgoOrder => "/fapi/v1/algoOrder", + Futures::AlgoOpenOrders => "/fapi/v1/algoOpenOrders", + Futures::OpenAlgoOrders => "/fapi/v1/openAlgoOrders", + Futures::AllAlgoOrders => "/fapi/v1/allAlgoOrders", Futures::PositionRisk => "/fapi/v2/positionRisk", + Futures::PositionRiskV3 => "/fapi/v3/positionRisk", Futures::Balance => "/fapi/v2/balance", + Futures::BalanceV3 => "/fapi/v3/balance", Futures::OpenInterest => "/fapi/v1/openInterest", Futures::OpenInterestHist => "/futures/data/openInterestHist", Futures::TopLongShortAccountRatio => "/futures/data/topLongShortAccountRatio", Futures::TopLongShortPositionRatio => "/futures/data/topLongShortPositionRatio", Futures::GlobalLongShortAccountRatio => "/futures/data/globalLongShortAccountRatio", Futures::TakerlongshortRatio => "/futures/data/takerlongshortRatio", + Futures::Basis => "/futures/data/basis", Futures::LvtKlines => "/fapi/v1/lvtKlines", Futures::IndexInfo => "/fapi/v1/indexInfo", + Futures::AssetIndex => "/fapi/v1/assetIndex", + Futures::Constituents => "/fapi/v1/constituents", + Futures::InsuranceBalance => "/fapi/v1/insuranceBalance", + Futures::SymbolAdlRisk => "/fapi/v1/symbolAdlRisk", + Futures::DeliveryPrice => "/futures/data/delivery-price", + Futures::TradingSchedule => "/fapi/v1/tradingSchedule", Futures::ChangeInitialLeverage => "/fapi/v1/leverage", Futures::MarginType => "/fapi/v1/marginType", Futures::PositionMargin => "/fapi/v1/positionMargin", + Futures::PositionMarginHistory => "/fapi/v1/positionMargin/history", Futures::Account => "/fapi/v2/account", + Futures::AccountV3 => "/fapi/v3/account", + Futures::AccountConfig => "/fapi/v1/accountConfig", + Futures::SymbolConfig => "/fapi/v1/symbolConfig", + Futures::CommissionRate => "/fapi/v1/commissionRate", + Futures::LeverageBracket => "/fapi/v1/leverageBracket", + Futures::AdlQuantile => "/fapi/v1/adlQuantile", + Futures::ApiTradingStatus => "/fapi/v1/apiTradingStatus", + Futures::FeeBurn => "/fapi/v1/feeBurn", + Futures::RateLimitOrder => "/fapi/v1/rateLimit/order", Futures::OpenOrders => "/fapi/v1/openOrders", Futures::UserDataStream => "/fapi/v1/listenKey", Futures::Income => "/fapi/v1/income", + Futures::IncomeAsyn => "/fapi/v1/income/asyn", + Futures::IncomeAsynId => "/fapi/v1/income/asyn/id", }, }) } diff --git a/src/client.rs b/src/client.rs index 2c708e99..853063bc 100644 --- a/src/client.rs +++ b/src/client.rs @@ -1,11 +1,9 @@ use error_chain::bail; -use hex::encode as hex_encode; -use hmac::{Hmac, Mac}; use crate::errors::{BinanceContentError, ErrorKind, Result}; +use crate::util::sign_hmac; use reqwest::StatusCode; use reqwest::blocking::Response; use reqwest::header::{HeaderMap, HeaderName, HeaderValue, USER_AGENT, CONTENT_TYPE}; -use sha2::Sha256; use serde::de::DeserializeOwned; use crate::api::API; @@ -69,6 +67,20 @@ impl Client { self.handler(response) } + pub fn put_signed(&self, endpoint: API, request: String) -> Result { + let url = self.sign_request(endpoint, Some(request)); + let client = &self.inner_client; + + let headers = self.build_headers(true)?; + if self.verbose { + println!("Request URL: {}", url); + println!("Request Headers: {:?}", headers); + } + let response = client.put(url.as_str()).headers(headers).send()?; + + self.handler(response) + } + pub fn delete_signed( &self, endpoint: API, request: Option, ) -> Result { @@ -101,6 +113,31 @@ impl Client { self.handler(response) } + /// Unsigned GET that still sends the `X-MBX-APIKEY` header. + /// + /// Used for `MARKET_DATA` endpoints such as `historicalTrades`, which require an + /// API key but no signature. + pub fn get_with_api_key( + &self, endpoint: API, request: Option, + ) -> Result { + let mut url: String = format!("{}{}", self.host, String::from(endpoint)); + if let Some(request) = request { + if !request.is_empty() { + url.push_str(format!("?{}", request).as_str()); + } + } + + let headers = self.build_headers(false)?; + if self.verbose { + println!("Request URL: {}", url); + println!("Request Headers: {:?}", headers); + } + let client = &self.inner_client; + let response = client.get(url.as_str()).headers(headers).send()?; + + self.handler(response) + } + pub fn post(&self, endpoint: API) -> Result { let url: String = format!("{}{}", self.host, String::from(endpoint)); @@ -150,19 +187,14 @@ impl Client { // Request must be signed fn sign_request(&self, endpoint: API, request: Option) -> String { - if let Some(request) = request { - let mut signed_key = - Hmac::::new_from_slice(self.secret_key.as_bytes()).unwrap(); - signed_key.update(request.as_bytes()); - let signature = hex_encode(signed_key.finalize().into_bytes()); - let request_body: String = format!("{}&signature={}", request, signature); - format!("{}{}?{}", self.host, String::from(endpoint), request_body) + let request = request.unwrap_or_default(); + let signature = sign_hmac(&self.secret_key, &request); + let request_body: String = if request.is_empty() { + format!("&signature={}", signature) } else { - let signed_key = Hmac::::new_from_slice(self.secret_key.as_bytes()).unwrap(); - let signature = hex_encode(signed_key.finalize().into_bytes()); - let request_body: String = format!("&signature={}", signature); - format!("{}{}?{}", self.host, String::from(endpoint), request_body) - } + format!("{}&signature={}", request, signature) + }; + format!("{}{}?{}", self.host, String::from(endpoint), request_body) } fn build_headers(&self, content_type: bool) -> Result { diff --git a/src/config.rs b/src/config.rs index 490f26c5..411c41b7 100755 --- a/src/config.rs +++ b/src/config.rs @@ -2,6 +2,11 @@ pub struct Config { pub rest_api_endpoint: String, pub ws_endpoint: String, + /// Spot WebSocket API endpoint (`wss://ws-api.binance.com:443/ws-api/v3`). + /// + /// Used for user data stream subscriptions, which replaced the retired + /// `listenKey` based `/api/v3/userDataStream` endpoints. + pub ws_api_endpoint: String, pub futures_rest_api_endpoint: String, pub futures_ws_endpoint: String, @@ -15,17 +20,34 @@ pub const SPOT_TESTNET: &str = "https://testnet.binance.vision"; pub const SPOT_WS_MAINNET: &str = "wss://stream.binance.com/ws"; pub const SPOT_WS_TESTNET: &str = "wss://testnet.binance.vision/ws"; +pub const SPOT_WS_API_MAINNET: &str = "wss://ws-api.binance.com:443/ws-api/v3"; +pub const SPOT_WS_API_TESTNET: &str = "wss://ws-api.testnet.binance.vision/ws-api/v3"; + pub const FUTURES_MAINNET: &str = "https://fapi.binance.com"; pub const FUTURES_TESTNET: &str = "https://testnet.binancefuture.com"; pub const FUTURES_WS_MAINNET: &str = "wss://fstream.binance.com/ws"; pub const FUTURES_WS_TESTNET: &str = "wss://fstream.binancefuture.com/ws"; +/// Routed USDⓈ-M futures WebSocket base URLs. +/// +/// Since 2026 Binance routes futures streams through dedicated paths: `/public` for +/// high-frequency public data (book ticker, depth), `/market` for regular market data +/// (aggTrade, markPrice, klines, tickers, liquidations) and `/private` for user data +/// streams. Un-routed connections only receive `/public` streams. +pub const FUTURES_WS_PUBLIC_MAINNET: &str = "wss://fstream.binance.com/public"; +pub const FUTURES_WS_MARKET_MAINNET: &str = "wss://fstream.binance.com/market"; +pub const FUTURES_WS_PRIVATE_MAINNET: &str = "wss://fstream.binance.com/private"; +pub const FUTURES_WS_PUBLIC_TESTNET: &str = "wss://fstream.binancefuture.com/public"; +pub const FUTURES_WS_MARKET_TESTNET: &str = "wss://fstream.binancefuture.com/market"; +pub const FUTURES_WS_PRIVATE_TESTNET: &str = "wss://fstream.binancefuture.com/private"; + impl Default for Config { fn default() -> Self { Self { rest_api_endpoint: SPOT_MAINNET.into(), ws_endpoint: SPOT_WS_MAINNET.into(), + ws_api_endpoint: SPOT_WS_API_MAINNET.into(), futures_rest_api_endpoint: FUTURES_MAINNET.into(), futures_ws_endpoint: FUTURES_WS_MAINNET.into(), @@ -40,6 +62,7 @@ impl Config { Self::default() .set_rest_api_endpoint(SPOT_TESTNET) .set_ws_endpoint(SPOT_WS_TESTNET) + .set_ws_api_endpoint(SPOT_WS_API_TESTNET) .set_futures_rest_api_endpoint(FUTURES_TESTNET) .set_futures_ws_endpoint(FUTURES_WS_TESTNET) } @@ -53,6 +76,11 @@ impl Config { self.ws_endpoint = ws_endpoint.into(); self } + pub fn set_ws_api_endpoint>(mut self, ws_api_endpoint: T) -> Self { + self.ws_api_endpoint = ws_api_endpoint.into(); + self + } + pub fn set_futures_rest_api_endpoint>( mut self, futures_rest_api_endpoint: T, ) -> Self { diff --git a/src/futures/account.rs b/src/futures/account.rs index a91c488e..7fa64960 100644 --- a/src/futures/account.rs +++ b/src/futures/account.rs @@ -1,8 +1,9 @@ use std::collections::BTreeMap; use std::fmt::Display; +use error_chain::bail; -use crate::util::{build_signed_request, uuid_futures}; +use crate::util::{build_signed_request, json_string_array, uuid_futures}; use crate::errors::Result; use crate::client::Client; use crate::api::{API, Futures}; @@ -11,8 +12,11 @@ use crate::account::OrderSide; use crate::futures::model::{Order, TradeHistory}; use super::model::{ - ChangeLeverageResponse, Transaction, CanceledOrder, PositionRisk, AccountBalance, - AccountInformation, + AccountBalance, AccountConfig, AccountInformation, AccountInformationV3, AdlQuantile, + AlgoOrder, ApiTradingStatus, BatchCancelResponse, BatchOrderResponse, CanceledAlgoOrder, + CanceledOrder, ChangeLeverageResponse, CodeMsg, CommissionRate, CountdownCancelAll, FeeBurn, + ForceOrder, LeverageBracket, ModifiedOrder, MultiAssetsMargin, OrderAmendment, OrderRateLimit, + PositionMarginChange, PositionMode, PositionRisk, PositionRiskV3, SymbolConfig, Transaction, }; #[derive(Clone)] @@ -27,6 +31,8 @@ pub enum ContractType { NextMonth, CurrentQuarter, NextQuarter, + /// Traditional finance perpetual (stocks, FX, commodities) + TradfiPerpetual, } impl From for String { @@ -37,22 +43,33 @@ impl From for String { ContractType::NextMonth => String::from("NEXT_MONTH"), ContractType::CurrentQuarter => String::from("CURRENT_QUARTER"), ContractType::NextQuarter => String::from("NEXT_QUARTER"), + ContractType::TradfiPerpetual => String::from("TRADIFI_PERPETUAL"), } } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum PositionSide { Both, Long, Short, } -#[derive(Debug, Clone)] +/// Algo order type. Conditional orders are the only algo type currently exposed by the +/// USDⓈ-M futures Algo service. +#[derive(Debug, Clone, PartialEq, Eq)] pub enum AlgoType { Conditional, } +impl Display for AlgoType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Conditional => write!(f, "CONDITIONAL"), + } + } +} + impl Display for PositionSide { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { @@ -63,7 +80,7 @@ impl Display for PositionSide { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum OrderType { Limit, Market, @@ -74,6 +91,21 @@ pub enum OrderType { TrailingStopMarket, } +impl OrderType { + /// Conditional order types are handled by the Algo service (`/fapi/v1/algoOrder`) + /// since 2025-12-09; `POST /fapi/v1/order` rejects them with error `-4120`. + pub fn is_conditional(&self) -> bool { + matches!( + self, + Self::Stop + | Self::StopMarket + | Self::TakeProfit + | Self::TakeProfitMarket + | Self::TrailingStopMarket + ) + } +} + impl Display for OrderType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { @@ -88,6 +120,7 @@ impl Display for OrderType { } } +#[derive(Debug, Clone, PartialEq, Eq)] pub enum WorkingType { MarkPrice, ContractPrice, @@ -103,6 +136,7 @@ impl Display for WorkingType { } #[allow(clippy::all)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum TimeInForce { /// Good Till Cancel GTC, @@ -110,10 +144,12 @@ pub enum TimeInForce { IOC, /// Fill or Kill FOK, - /// Good Till Crossing + /// Good Till Crossing (post only) GTX, /// Good Till Date GTD, + /// Retail Price Improvement: post-only order that only matches against retail flow + RPI, } impl Display for TimeInForce { @@ -124,36 +160,65 @@ impl Display for TimeInForce { Self::FOK => write!(f, "FOK"), Self::GTX => write!(f, "GTX"), Self::GTD => write!(f, "GTD"), + Self::RPI => write!(f, "RPI"), } } } -struct OrderRequest { - pub symbol: String, - pub side: OrderSide, - pub position_side: Option, - pub order_type: OrderType, - pub time_in_force: Option, - pub qty: Option, - pub reduce_only: Option, - pub price: Option, - pub stop_price: Option, - pub close_position: Option, - pub activation_price: Option, - pub callback_rate: Option, - pub working_type: Option, - pub price_protect: Option, - pub new_client_order_id: Option, - pub good_till_date: Option, - pub algo_type: Option, - pub client_algo_id: Option, +/// Price match mode: let the engine pick the price relative to the best opposite +/// (`OPPONENT*`) or same-side (`QUEUE*`) order. Cannot be combined with `price`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PriceMatch { + Opponent, + Opponent5, + Opponent10, + Opponent20, + Queue, + Queue5, + Queue10, + Queue20, +} + +impl Display for PriceMatch { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Opponent => write!(f, "OPPONENT"), + Self::Opponent5 => write!(f, "OPPONENT_5"), + Self::Opponent10 => write!(f, "OPPONENT_10"), + Self::Opponent20 => write!(f, "OPPONENT_20"), + Self::Queue => write!(f, "QUEUE"), + Self::Queue5 => write!(f, "QUEUE_5"), + Self::Queue10 => write!(f, "QUEUE_10"), + Self::Queue20 => write!(f, "QUEUE_20"), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SelfTradePreventionMode { + None, + ExpireTaker, + ExpireMaker, + ExpireBoth, +} + +impl Display for SelfTradePreventionMode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::None => write!(f, "NONE"), + Self::ExpireTaker => write!(f, "EXPIRE_TAKER"), + Self::ExpireMaker => write!(f, "EXPIRE_MAKER"), + Self::ExpireBoth => write!(f, "EXPIRE_BOTH"), + } + } } +/// Full order description used by [`FuturesAccount::custom_order`], +/// [`FuturesAccount::custom_algo_order`] and [`FuturesAccount::custom_batch_orders`]. +/// +/// Use [`CustomOrderRequest::new`] and set the optional fields you need. +#[derive(Debug, Clone)] pub struct CustomOrderRequest { - // algoOrder params - pub algo_type: AlgoType, - pub client_algo_id: Option, - // pub symbol: String, pub side: OrderSide, /// Default `BOTH` for One-way Mode ; `LONG` or `SHORT` for Hedge Mode. \ @@ -165,26 +230,80 @@ pub struct CustomOrderRequest { pub qty: Option, pub reduce_only: Option, pub price: Option, - /// Used with `STOP`/`STOP_MARKET` or `TAKE_PROFIT`/`TAKE_PROFIT_MARKET` orders. + /// Trigger price, used with `STOP`/`STOP_MARKET` or `TAKE_PROFIT`/`TAKE_PROFIT_MARKET` + /// orders (sent as `triggerPrice` to the Algo service). pub stop_price: Option, /// Close-All,used with `STOP_MARKET` or `TAKE_PROFIT_MARKET`. pub close_position: Option, /// Used with `TRAILING_STOP_MARKET` orders, default as the latest price(supporting different `workingType`) pub activation_price: Option, - /// Used with `TRAILING_STOP_MARKET` orders, min `0.1`, max `10` where `1` for `1%` + /// Used with `TRAILING_STOP_MARKET` orders, min `0.1`, max `20` where `1` for `1%` pub callback_rate: Option, /// `stopPrice` triggered by: `MARK_PRICE`, `CONTRACT_PRICE`. Default `CONTRACT_PRICE` pub working_type: Option, - pub price_protect: Option, + /// Price protection for conditional orders + pub price_protect: Option, /// A unique id among open orders. \ /// Automatically generated if not sent. \ - /// Can only be string following the rule: `^[\.A-Z\:/a-z0-9_-]{1,32}$` + /// Can only be string following the rule: `^[\.A-Z\:/a-z0-9_-]{1,36}$` pub new_client_order_id: Option, + /// Client id of a conditional order. Falls back to `new_client_order_id` (or an auto + /// generated id) when sent to the Algo service. + pub client_algo_id: Option, /// order cancel time for timeInForce **GTD**, mandatory when [TimeInForce] set to **GTD** \ /// order the timestamp only retains second-level precision, **ms part will be ignored** \ /// The goodTillDate timestamp must be greater than the current time **plus 600 seconds** and smaller than **253402300799000**. /// the timestamp should be in `UTC` timezone pub good_till_date: Option, + /// Only for `LIMIT`/`STOP`/`TAKE_PROFIT` orders; cannot be combined with `price` + pub price_match: Option, + pub self_trade_prevention_mode: Option, + /// `ACK` (default) or `RESULT` + pub new_order_resp_type: Option, +} + +impl CustomOrderRequest { + pub fn new>(symbol: S, side: OrderSide, order_type: OrderType) -> Self { + CustomOrderRequest { + symbol: symbol.into(), + side, + position_side: None, + order_type, + time_in_force: None, + qty: None, + reduce_only: None, + price: None, + stop_price: None, + close_position: None, + activation_price: None, + callback_rate: None, + working_type: None, + price_protect: None, + new_client_order_id: None, + client_algo_id: None, + good_till_date: None, + price_match: None, + self_trade_prevention_mode: None, + new_order_resp_type: None, + } + } +} + +/// `PUT /fapi/v1/order` request. Either `order_id` or `orig_client_order_id` is required; +/// both `quantity` and `price` (or `price_match`) must be sent. +#[derive(Debug, Clone)] +pub struct ModifyOrderRequest { + pub symbol: String, + pub side: OrderSide, + pub order_id: Option, + pub orig_client_order_id: Option, + pub quantity: f64, + pub price: Option, + pub price_match: Option, + /// User-defined id echoed back in the response and in `ORDER_TRADE_UPDATE` + pub modify_id: Option, + /// When `true` and the original order is reduce-only, the `MIN_NOTIONAL` check is skipped + pub reduce_only: Option, } pub struct IncomeRequest { @@ -201,6 +320,8 @@ pub enum IncomeType { WELCOME_BONUS, REALIZED_PNL, FUNDING_FEE, + /// TradFi dividend funding fee + SPECIAL_FUNDING_FEE, COMMISSION, INSURANCE_CLEAR, REFERRAL_KICKBACK, @@ -216,6 +337,9 @@ pub enum IncomeType { COIN_SWAP_DEPOSIT, COIN_SWAP_WITHDRAW, POSITION_LIMIT_INCREASE_FEE, + STRATEGY_UMFUTURES_TRANSFER, + FEE_RETURN, + BFUSD_REWARD, } impl Display for IncomeType { @@ -225,6 +349,7 @@ impl Display for IncomeType { Self::WELCOME_BONUS => write!(f, "WELCOME_BONUS"), Self::REALIZED_PNL => write!(f, "REALIZED_PNL"), Self::FUNDING_FEE => write!(f, "FUNDING_FEE"), + Self::SPECIAL_FUNDING_FEE => write!(f, "SPECIAL_FUNDING_FEE"), Self::COMMISSION => write!(f, "COMMISSION"), Self::INSURANCE_CLEAR => write!(f, "INSURANCE_CLEAR"), Self::REFERRAL_KICKBACK => write!(f, "REFERRAL_KICKBACK"), @@ -240,6 +365,9 @@ impl Display for IncomeType { Self::COIN_SWAP_DEPOSIT => write!(f, "COIN_SWAP_DEPOSIT"), Self::COIN_SWAP_WITHDRAW => write!(f, "COIN_SWAP_WITHDRAW"), Self::POSITION_LIMIT_INCREASE_FEE => write!(f, "POSITION_LIMIT_INCREASE_FEE"), + Self::STRATEGY_UMFUTURES_TRANSFER => write!(f, "STRATEGY_UMFUTURES_TRANSFER"), + Self::FEE_RETURN => write!(f, "FEE_RETURN"), + Self::BFUSD_REWARD => write!(f, "BFUSD_REWARD"), } } } @@ -249,60 +377,22 @@ impl FuturesAccount { &self, symbol: impl Into, qty: impl Into, price: f64, time_in_force: TimeInForce, ) -> Result { - let buy = OrderRequest { - symbol: symbol.into(), - side: OrderSide::Buy, - position_side: None, - order_type: OrderType::Limit, - time_in_force: Some(time_in_force), - qty: Some(qty.into()), - reduce_only: None, - price: Some(price), - stop_price: None, - close_position: None, - activation_price: None, - callback_rate: None, - working_type: None, - price_protect: None, - new_client_order_id: None, - good_till_date: None, - algo_type: None, - client_algo_id: None, - }; - let order = self.build_order(buy, None, None); - let request = build_signed_request(order, self.recv_window)?; - self.client - .post_signed(API::Futures(Futures::Order), request) + let mut buy = CustomOrderRequest::new(symbol, OrderSide::Buy, OrderType::Limit); + buy.time_in_force = Some(time_in_force); + buy.qty = Some(qty.into()); + buy.price = Some(price); + self.custom_order(buy) } pub fn limit_sell( &self, symbol: impl Into, qty: impl Into, price: f64, time_in_force: TimeInForce, ) -> Result { - let sell = OrderRequest { - symbol: symbol.into(), - side: OrderSide::Sell, - position_side: None, - order_type: OrderType::Limit, - time_in_force: Some(time_in_force), - qty: Some(qty.into()), - reduce_only: None, - price: Some(price), - stop_price: None, - close_position: None, - activation_price: None, - callback_rate: None, - working_type: None, - price_protect: None, - new_client_order_id: None, - good_till_date: None, - algo_type: None, - client_algo_id: None, - }; - let order = self.build_order(sell, None, None); - let request = build_signed_request(order, self.recv_window)?; - self.client - .post_signed(API::Futures(Futures::Order), request) + let mut sell = CustomOrderRequest::new(symbol, OrderSide::Sell, OrderType::Limit); + sell.time_in_force = Some(time_in_force); + sell.qty = Some(qty.into()); + sell.price = Some(price); + self.custom_order(sell) } // Place a MARKET order - BUY @@ -311,30 +401,9 @@ impl FuturesAccount { S: Into, F: Into, { - let buy = OrderRequest { - symbol: symbol.into(), - side: OrderSide::Buy, - position_side: None, - order_type: OrderType::Market, - time_in_force: None, - qty: Some(qty.into()), - reduce_only: None, - price: None, - stop_price: None, - close_position: None, - activation_price: None, - callback_rate: None, - working_type: None, - price_protect: None, - new_client_order_id: None, - good_till_date: None, - algo_type: None, - client_algo_id: None, - }; - let order = self.build_order(buy, None, None); - let request = build_signed_request(order, self.recv_window)?; - self.client - .post_signed(API::Futures(Futures::Order), request) + let mut buy = CustomOrderRequest::new(symbol, OrderSide::Buy, OrderType::Market); + buy.qty = Some(qty.into()); + self.custom_order(buy) } // Place a MARKET order - SELL @@ -343,30 +412,9 @@ impl FuturesAccount { S: Into, F: Into, { - let sell = OrderRequest { - symbol: symbol.into(), - side: OrderSide::Sell, - position_side: None, - order_type: OrderType::Market, - time_in_force: None, - qty: Some(qty.into()), - reduce_only: None, - price: None, - stop_price: None, - close_position: None, - activation_price: None, - callback_rate: None, - working_type: None, - price_protect: None, - new_client_order_id: None, - good_till_date: None, - algo_type: None, - client_algo_id: None, - }; - let order = self.build_order(sell, None, None); - let request = build_signed_request(order, self.recv_window)?; - self.client - .post_signed(API::Futures(Futures::Order), request) + let mut sell = CustomOrderRequest::new(symbol, OrderSide::Sell, OrderType::Market); + sell.qty = Some(qty.into()); + self.custom_order(sell) } pub fn cancel_order(&self, symbol: S, order_id: u64) -> Result @@ -397,153 +445,390 @@ impl FuturesAccount { .delete_signed(API::Futures(Futures::Order), Some(request)) } - // Place a STOP_MARKET close - BUY - pub fn stop_market_close_buy(&self, symbol: S, stop_price: F) -> Result + /// Cancel several orders at once (`DELETE /fapi/v1/batchOrders`), max 10 ids. + pub fn cancel_batch_orders( + &self, symbol: S, order_ids: &[u64], + ) -> Result> where S: Into, - F: Into, { - let sell = OrderRequest { - symbol: symbol.into(), - side: OrderSide::Buy, - position_side: None, - order_type: OrderType::StopMarket, - time_in_force: None, - qty: None, - reduce_only: None, - price: None, - stop_price: Some(stop_price.into()), - close_position: Some(true), - activation_price: None, - callback_rate: None, - working_type: None, - price_protect: None, - new_client_order_id: None, - good_till_date: None, - algo_type: Some(AlgoType::Conditional), - client_algo_id: None, - }; - let order = self.build_order(sell, None, None); - let request = build_signed_request(order, self.recv_window)?; + let mut parameters = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + parameters.insert( + "orderIdList".into(), + serde_json::Value::Array( + order_ids + .iter() + .map(|id| serde_json::Value::from(*id)) + .collect(), + ) + .to_string(), + ); + let request = build_signed_request(parameters, self.recv_window)?; self.client - .post_signed(API::Futures(Futures::AlgoOrder), request) + .delete_signed(API::Futures(Futures::BatchOrders), Some(request)) } - // Place a STOP_MARKET close - SELL - pub fn stop_market_close_sell(&self, symbol: S, stop_price: F) -> Result + /// Cancel several orders by client order id (`DELETE /fapi/v1/batchOrders`), max 10 ids. + pub fn cancel_batch_orders_with_client_ids( + &self, symbol: S, orig_client_order_ids: &[C], + ) -> Result> where S: Into, - F: Into, + C: AsRef, { - let sell = OrderRequest { - symbol: symbol.into(), - side: OrderSide::Sell, - position_side: None, - order_type: OrderType::StopMarket, - time_in_force: None, - qty: None, - reduce_only: None, - price: None, - stop_price: Some(stop_price.into()), - close_position: Some(true), - activation_price: None, - callback_rate: None, - working_type: None, - price_protect: None, - new_client_order_id: None, - good_till_date: None, - algo_type: Some(AlgoType::Conditional), - client_algo_id: None, - }; - let order = self.build_order(sell, None, Some(API::Futures(Futures::AlgoOrder))); - let request = build_signed_request(order, self.recv_window)?; + let mut parameters = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + parameters.insert( + "origClientOrderIdList".into(), + json_string_array(orig_client_order_ids), + ); + let request = build_signed_request(parameters, self.recv_window)?; self.client - .post_signed(API::Futures(Futures::AlgoOrder), request) + .delete_signed(API::Futures(Futures::BatchOrders), Some(request)) + } + + /// Cancel all open orders of a symbol after `countdown_time_ms` milliseconds unless the + /// countdown is refreshed (`POST /fapi/v1/countdownCancelAll`). `0` cancels the timer. + pub fn countdown_cancel_all( + &self, symbol: S, countdown_time_ms: u64, + ) -> Result + where + S: Into, + { + let mut parameters = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + parameters.insert("countdownTime".into(), countdown_time_ms.to_string()); + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .post_signed(API::Futures(Futures::CountdownCancelAll), request) } - // Custom order for for professional traders + /// Place a STOP_MARKET close-all order - BUY (closes a short position). + /// + /// Conditional orders are placed through the Algo service and identified by `algo_id`. + pub fn stop_market_close_buy(&self, symbol: S, stop_price: F) -> Result + where + S: Into, + F: Into, + { + let mut order = CustomOrderRequest::new(symbol, OrderSide::Buy, OrderType::StopMarket); + order.stop_price = Some(stop_price.into()); + order.close_position = Some(true); + self.custom_algo_order(order) + } + + /// Place a STOP_MARKET close-all order - SELL (closes a long position). + /// + /// Conditional orders are placed through the Algo service and identified by `algo_id`. + pub fn stop_market_close_sell(&self, symbol: S, stop_price: F) -> Result + where + S: Into, + F: Into, + { + let mut order = CustomOrderRequest::new(symbol, OrderSide::Sell, OrderType::StopMarket); + order.stop_price = Some(stop_price.into()); + order.close_position = Some(true); + self.custom_algo_order(order) + } + + /// Place a `LIMIT` or `MARKET` order (`POST /fapi/v1/order`). + /// + /// Conditional order types must go through [`FuturesAccount::custom_algo_order`]; + /// this method refuses them instead of letting Binance answer `-4120`. pub fn custom_order(&self, order_request: CustomOrderRequest) -> Result { self.custom_order_with_params(order_request, BTreeMap::new()) } - // Custom order for for professional traders + /// Same as [`FuturesAccount::custom_order`] with extra raw request parameters. pub fn custom_order_with_params( &self, order_request: CustomOrderRequest, request_params: BTreeMap, ) -> Result { - let order = OrderRequest { - symbol: order_request.symbol, - side: order_request.side, - position_side: order_request.position_side, - order_type: order_request.order_type, - time_in_force: order_request.time_in_force, - qty: order_request.qty, - reduce_only: order_request.reduce_only, - price: order_request.price, - stop_price: order_request.stop_price, - close_position: order_request.close_position, - activation_price: order_request.activation_price, - callback_rate: order_request.callback_rate, - working_type: order_request.working_type, - price_protect: order_request.price_protect, - new_client_order_id: order_request.new_client_order_id, - good_till_date: order_request.good_till_date, - algo_type: Some(order_request.algo_type), - client_algo_id: order_request.client_algo_id, - }; - let order = self.build_order( - order, - Some(request_params), - Some(API::Futures(Futures::AlgoOrder)), - ); + if order_request.order_type.is_conditional() { + bail!(format!( + "{} orders are conditional and must be placed with custom_algo_order", + order_request.order_type + )); + } + let order = Self::build_order(order_request, Some(request_params)); + let request = build_signed_request(order, self.recv_window)?; + self.client + .post_signed(API::Futures(Futures::Order), request) + } + + /// Place a conditional order (`STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET`, + /// `TRAILING_STOP_MARKET`) through the Algo service (`POST /fapi/v1/algoOrder`). + pub fn custom_algo_order(&self, order_request: CustomOrderRequest) -> Result { + self.custom_algo_order_with_params(order_request, BTreeMap::new()) + } + + /// Same as [`FuturesAccount::custom_algo_order`] with extra raw request parameters. + pub fn custom_algo_order_with_params( + &self, order_request: CustomOrderRequest, request_params: BTreeMap, + ) -> Result { + if !order_request.order_type.is_conditional() { + bail!(format!( + "{} orders are not conditional and must be placed with custom_order", + order_request.order_type + )); + } + let order = Self::build_algo_order(order_request, Some(request_params)); let request = build_signed_request(order, self.recv_window)?; self.client .post_signed(API::Futures(Futures::AlgoOrder), request) } - // Custom order for for professional traders + /// Place up to 5 `LIMIT`/`MARKET` orders in one request (`POST /fapi/v1/batchOrders`). + /// + /// Results come back in the same order as the requests; each entry is either the + /// placed order or the error for that order. + pub fn custom_batch_orders( + &self, order_requests: Vec, + ) -> Result> { + self.custom_batch_orders_with_params(order_requests, BTreeMap::new()) + } + + /// Same as [`FuturesAccount::custom_batch_orders`] with extra raw request parameters + /// applied to every order of the batch. pub fn custom_batch_orders_with_params( - &self, _order_count: u64, order_requests: Vec, - request_params: BTreeMap, - ) -> Result { - let request = String::from(""); + &self, order_requests: Vec, request_params: BTreeMap, + ) -> Result> { + if order_requests.is_empty() || order_requests.len() > 5 { + bail!("batchOrders accepts between 1 and 5 orders"); + } + let mut batch = Vec::with_capacity(order_requests.len()); for order_request in order_requests { - let order = OrderRequest { - symbol: order_request.symbol, - side: order_request.side, - position_side: order_request.position_side, - order_type: order_request.order_type, - time_in_force: order_request.time_in_force, - qty: order_request.qty, - reduce_only: order_request.reduce_only, - price: order_request.price, - stop_price: order_request.stop_price, - close_position: order_request.close_position, - activation_price: order_request.activation_price, - callback_rate: order_request.callback_rate, - working_type: order_request.working_type, - price_protect: order_request.price_protect, - new_client_order_id: order_request.new_client_order_id, - good_till_date: order_request.good_till_date, - algo_type: Some(order_request.algo_type), - client_algo_id: order_request.client_algo_id, - }; - let _order = self.build_order( - order, - Some(request_params.clone()), - Some(API::Futures(Futures::AlgoOrder)), - ); - // TODO : make a request string for batch orders api - // let request = build_signed_request(order, self.recv_window)?; + if order_request.order_type.is_conditional() { + bail!(format!( + "{} orders are conditional and cannot be placed in a batch", + order_request.order_type + )); + } + let order = Self::build_order(order_request, Some(request_params.clone())); + batch.push(serde_json::Value::Object( + order + .into_iter() + .map(|(k, v)| (k, serde_json::Value::String(v))) + .collect(), + )); } + let mut parameters = BTreeMap::new(); + parameters.insert( + "batchOrders".into(), + serde_json::Value::Array(batch).to_string(), + ); + let request = build_signed_request(parameters, self.recv_window)?; self.client - .post_signed(API::Futures(Futures::AlgoOrder), request) + .post_signed(API::Futures(Futures::BatchOrders), request) } - // Custom order for for professional traders - pub fn custom_batch_orders( - &self, _order_count: u64, order_requests: Vec, - ) -> Result { - self.custom_batch_orders_with_params(_order_count, order_requests, BTreeMap::new()) + /// Modify the price and/or quantity of an open `LIMIT` order (`PUT /fapi/v1/order`). + pub fn modify_order(&self, req: ModifyOrderRequest) -> Result { + let mut parameters = BTreeMap::new(); + parameters.insert("symbol".into(), req.symbol); + parameters.insert("side".into(), req.side.to_string()); + parameters.insert("quantity".into(), req.quantity.to_string()); + if let Some(id) = req.order_id { + parameters.insert("orderId".into(), id.to_string()); + } + if let Some(id) = req.orig_client_order_id { + parameters.insert("origClientOrderId".into(), id); + } + if let Some(price) = req.price { + parameters.insert("price".into(), price.to_string()); + } + if let Some(pm) = req.price_match { + parameters.insert("priceMatch".into(), pm.to_string()); + } + if let Some(id) = req.modify_id { + parameters.insert("modifyId".into(), id.to_string()); + } + if let Some(ro) = req.reduce_only { + parameters.insert("reduceOnly".into(), ro.to_string()); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .put_signed(API::Futures(Futures::Order), request) + } + + /// Modification history of an order (`GET /fapi/v1/orderAmendment`). + pub fn get_order_amendments( + &self, symbol: S, order_id: O, orig_client_order_id: C, start_time: T1, end_time: T2, + limit: L, + ) -> Result> + where + S: Into, + O: Into>, + C: Into>, + T1: Into>, + T2: Into>, + L: Into>, + { + let mut parameters = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + if let Some(id) = order_id.into() { + parameters.insert("orderId".into(), id.to_string()); + } + if let Some(id) = orig_client_order_id.into() { + parameters.insert("origClientOrderId".into(), id); + } + if let Some(st) = start_time.into() { + parameters.insert("startTime".into(), st.to_string()); + } + if let Some(et) = end_time.into() { + parameters.insert("endTime".into(), et.to_string()); + } + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::OrderAmendment), Some(request)) + } + + /// Query an order (`GET /fapi/v1/order`). + pub fn order_status(&self, symbol: S, order_id: u64) -> Result + where + S: Into, + { + let mut parameters = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + parameters.insert("orderId".into(), order_id.to_string()); + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::Order), Some(request)) + } + + /// Query an order by client order id (`GET /fapi/v1/order`). + pub fn order_status_with_client_id( + &self, symbol: S, orig_client_order_id: String, + ) -> Result + where + S: Into, + { + let mut parameters = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + parameters.insert("origClientOrderId".into(), orig_client_order_id); + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::Order), Some(request)) + } + + /// Query a currently open order (`GET /fapi/v1/openOrder`); returns an error if the + /// order is filled or canceled. + pub fn get_open_order(&self, symbol: S, order_id: u64) -> Result + where + S: Into, + { + let mut parameters = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + parameters.insert("orderId".into(), order_id.to_string()); + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::OpenOrder), Some(request)) + } + + /// Cancel a conditional order by `algoId` (`DELETE /fapi/v1/algoOrder`). + pub fn cancel_algo_order(&self, algo_id: u64) -> Result { + let mut parameters = BTreeMap::new(); + parameters.insert("algoId".into(), algo_id.to_string()); + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .delete_signed(API::Futures(Futures::AlgoOrder), Some(request)) + } + + /// Cancel a conditional order by `clientAlgoId` (`DELETE /fapi/v1/algoOrder`). + pub fn cancel_algo_order_with_client_id( + &self, client_algo_id: S, + ) -> Result + where + S: Into, + { + let mut parameters = BTreeMap::new(); + parameters.insert("clientAlgoId".into(), client_algo_id.into()); + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .delete_signed(API::Futures(Futures::AlgoOrder), Some(request)) + } + + /// Cancel all open conditional orders of a symbol (`DELETE /fapi/v1/algoOpenOrders`). + pub fn cancel_all_open_algo_orders(&self, symbol: S) -> Result + where + S: Into, + { + let mut parameters = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .delete_signed(API::Futures(Futures::AlgoOpenOrders), Some(request)) + } + + /// Query a conditional order by `algoId` (`GET /fapi/v1/algoOrder`). + pub fn get_algo_order(&self, algo_id: u64) -> Result { + let mut parameters = BTreeMap::new(); + parameters.insert("algoId".into(), algo_id.to_string()); + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::AlgoOrder), Some(request)) + } + + /// Query a conditional order by `clientAlgoId` (`GET /fapi/v1/algoOrder`). + pub fn get_algo_order_with_client_id(&self, client_algo_id: S) -> Result + where + S: Into, + { + let mut parameters = BTreeMap::new(); + parameters.insert("clientAlgoId".into(), client_algo_id.into()); + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::AlgoOrder), Some(request)) + } + + /// Open conditional orders (`GET /fapi/v1/openAlgoOrders`), all symbols when `None`. + pub fn get_open_algo_orders(&self, symbol: S) -> Result> + where + S: Into>, + { + let mut parameters = BTreeMap::new(); + parameters.insert("algoType".into(), AlgoType::Conditional.to_string()); + if let Some(symbol) = symbol.into() { + parameters.insert("symbol".into(), symbol); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::OpenAlgoOrders), Some(request)) + } + + /// All conditional orders of a symbol (`GET /fapi/v1/allAlgoOrders`). + /// + /// If `algo_id` is set, orders >= that id are returned; otherwise the most recent ones. + pub fn get_all_algo_orders( + &self, symbol: S, algo_id: A, start_time: T1, end_time: T2, limit: L, + ) -> Result> + where + S: Into, + A: Into>, + T1: Into>, + T2: Into>, + L: Into>, + { + let mut parameters = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + if let Some(id) = algo_id.into() { + parameters.insert("algoId".into(), id.to_string()); + } + if let Some(st) = start_time.into() { + parameters.insert("startTime".into(), st.to_string()); + } + if let Some(et) = end_time.into() { + parameters.insert("endTime".into(), et.to_string()); + } + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::AllAlgoOrders), Some(request)) } pub fn get_all_orders( @@ -601,28 +886,50 @@ impl FuturesAccount { self.client .get_signed(API::Futures(Futures::UserTrades), Some(request)) } + + /// The account's liquidation / ADL orders (`GET /fapi/v1/forceOrders`), last 90 days. + /// + /// `auto_close_type`: `LIQUIDATION` or `ADL`; both when `None`. + pub fn get_force_orders( + &self, symbol: S, auto_close_type: A, start_time: T1, end_time: T2, limit: L, + ) -> Result> + where + S: Into>, + A: Into>, + T1: Into>, + T2: Into>, + L: Into>, + { + let mut parameters = BTreeMap::new(); + if let Some(symbol) = symbol.into() { + parameters.insert("symbol".into(), symbol); + } + if let Some(t) = auto_close_type.into() { + parameters.insert("autoCloseType".into(), t); + } + if let Some(st) = start_time.into() { + parameters.insert("startTime".into(), st.to_string()); + } + if let Some(et) = end_time.into() { + parameters.insert("endTime".into(), et.to_string()); + } + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::ForceOrders), Some(request)) + } + + /// Parameters for `POST /fapi/v1/order` and `POST /fapi/v1/batchOrders`. fn build_order( - &self, order: OrderRequest, request_params: Option>, - api_type: Option, + order: CustomOrderRequest, request_params: Option>, ) -> BTreeMap { let mut parameters = BTreeMap::new(); parameters.insert("symbol".into(), order.symbol); parameters.insert("side".into(), order.side.to_string()); parameters.insert("type".into(), order.order_type.to_string()); - if let Some(API::Futures(Futures::AlgoOrder)) = api_type { - parameters.insert("algoType".into(), "Conditional".into()); - parameters.insert("clientAlgoId".into(), "Conditional".into()); - - if let Some(client_algo_id) = order.client_algo_id { - parameters.insert("clientAlgoId".into(), client_algo_id.to_string()); - } - - if let Some(stop_price) = order.stop_price { - parameters.insert("triggerPrice".into(), stop_price.to_string()); - } - } - if let Some(position_side) = order.position_side { parameters.insert("positionSide".into(), position_side.to_string()); } @@ -662,26 +969,112 @@ impl FuturesAccount { price_protect.to_string().to_uppercase(), ); } - if let Some(new_client_order_id) = order.new_client_order_id { - parameters.insert("newClientOrderId".into(), new_client_order_id); - } else { - let uuid = uuid_futures(); - parameters.insert("newClientOrderId".into(), uuid); + parameters.insert( + "newClientOrderId".into(), + order.new_client_order_id.unwrap_or_else(uuid_futures), + ); + if let Some(good_till_date) = order.good_till_date { + parameters.insert("goodTillDate".into(), good_till_date.to_string()); + } + if let Some(price_match) = order.price_match { + parameters.insert("priceMatch".into(), price_match.to_string()); + } + if let Some(stp) = order.self_trade_prevention_mode { + parameters.insert("selfTradePreventionMode".into(), stp.to_string()); + } + if let Some(rt) = order.new_order_resp_type { + parameters.insert("newOrderRespType".into(), rt); + } + + if let Some(params) = request_params { + for (key, value) in params { + parameters.insert(key, value); + } } + parameters + } + + /// Parameters for `POST /fapi/v1/algoOrder`: same as a regular order except that the + /// trigger price is `triggerPrice`, the activation price `activatePrice` and the client + /// id `clientAlgoId`. + fn build_algo_order( + order: CustomOrderRequest, request_params: Option>, + ) -> BTreeMap { + let mut parameters = BTreeMap::new(); + parameters.insert("algoType".into(), AlgoType::Conditional.to_string()); + parameters.insert("symbol".into(), order.symbol); + parameters.insert("side".into(), order.side.to_string()); + parameters.insert("type".into(), order.order_type.to_string()); + + if let Some(position_side) = order.position_side { + parameters.insert("positionSide".into(), position_side.to_string()); + } + if let Some(time_in_force) = order.time_in_force { + parameters.insert("timeInForce".into(), time_in_force.to_string()); + } + if let Some(qty) = order.qty { + parameters.insert("quantity".into(), qty.to_string()); + } + if let Some(reduce_only) = order.reduce_only { + parameters.insert("reduceOnly".into(), reduce_only.to_string().to_uppercase()); + } + if let Some(price) = order.price { + parameters.insert("price".into(), price.to_string()); + } + if let Some(stop_price) = order.stop_price { + parameters.insert("triggerPrice".into(), stop_price.to_string()); + } + if let Some(close_position) = order.close_position { + parameters.insert( + "closePosition".into(), + close_position.to_string().to_uppercase(), + ); + } + if let Some(activation_price) = order.activation_price { + parameters.insert("activatePrice".into(), activation_price.to_string()); + } + if let Some(callback_rate) = order.callback_rate { + parameters.insert("callbackRate".into(), callback_rate.to_string()); + } + if let Some(working_type) = order.working_type { + parameters.insert("workingType".into(), working_type.to_string()); + } + if let Some(price_protect) = order.price_protect { + parameters.insert( + "priceProtect".into(), + price_protect.to_string().to_uppercase(), + ); + } + let client_algo_id = order + .client_algo_id + .or(order.new_client_order_id) + .unwrap_or_else(uuid_futures); + parameters.insert("clientAlgoId".into(), client_algo_id); if let Some(good_till_date) = order.good_till_date { parameters.insert("goodTillDate".into(), good_till_date.to_string()); } + if let Some(price_match) = order.price_match { + parameters.insert("priceMatch".into(), price_match.to_string()); + } + if let Some(stp) = order.self_trade_prevention_mode { + parameters.insert("selfTradePreventionMode".into(), stp.to_string()); + } + if let Some(rt) = order.new_order_resp_type { + parameters.insert("newOrderRespType".into(), rt); + } if let Some(params) = request_params { for (key, value) in params { - parameters.insert(key, value.to_string()); + parameters.insert(key, value); } } parameters } + /// Position information (`GET /fapi/v2/positionRisk`). + #[deprecated(note = "deprecated by Binance, use position_information_v3")] pub fn position_information(&self, symbol: S) -> Result> where S: Into, @@ -694,6 +1087,25 @@ impl FuturesAccount { .get_signed(API::Futures(Futures::PositionRisk), Some(request)) } + /// Position information (`GET /fapi/v3/positionRisk`). + /// + /// Only symbols with an open position or open orders are returned; all symbols when + /// `symbol` is `None`. + pub fn position_information_v3(&self, symbol: S) -> Result> + where + S: Into>, + { + let mut parameters = BTreeMap::new(); + if let Some(symbol) = symbol.into() { + parameters.insert("symbol".into(), symbol); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::PositionRiskV3), Some(request)) + } + + /// Account information (`GET /fapi/v2/account`). + #[deprecated(note = "deprecated by Binance, use account_information_v3")] pub fn account_information(&self) -> Result { let parameters = BTreeMap::new(); @@ -702,6 +1114,19 @@ impl FuturesAccount { .get_signed(API::Futures(Futures::Account), Some(request)) } + /// Account information (`GET /fapi/v3/account`). + /// + /// Only symbols with an open position or open orders are listed in `positions`; the + /// account/symbol configuration fields of V2 moved to + /// [`FuturesAccount::get_account_config`] and [`FuturesAccount::get_symbol_config`]. + pub fn account_information_v3(&self) -> Result { + let request = build_signed_request(BTreeMap::new(), self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::AccountV3), Some(request)) + } + + /// Account balance (`GET /fapi/v2/balance`). + #[deprecated(note = "deprecated by Binance, use account_balance_v3")] pub fn account_balance(&self) -> Result> { let parameters = BTreeMap::new(); @@ -710,6 +1135,130 @@ impl FuturesAccount { .get_signed(API::Futures(Futures::Balance), Some(request)) } + /// Account balance (`GET /fapi/v3/balance`). + pub fn account_balance_v3(&self) -> Result> { + let request = build_signed_request(BTreeMap::new(), self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::BalanceV3), Some(request)) + } + + /// Account configuration (`GET /fapi/v1/accountConfig`): fee tier, position mode, + /// multi-assets mode, ... + pub fn get_account_config(&self) -> Result { + let request = build_signed_request(BTreeMap::new(), self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::AccountConfig), Some(request)) + } + + /// Symbol configuration (`GET /fapi/v1/symbolConfig`): margin type, leverage, max + /// notional. All symbols when `symbol` is `None`. + pub fn get_symbol_config(&self, symbol: S) -> Result> + where + S: Into>, + { + let mut parameters = BTreeMap::new(); + if let Some(symbol) = symbol.into() { + parameters.insert("symbol".into(), symbol); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::SymbolConfig), Some(request)) + } + + /// User commission rate for a symbol (`GET /fapi/v1/commissionRate`). + pub fn get_commission_rate(&self, symbol: S) -> Result + where + S: Into, + { + let mut parameters = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::CommissionRate), Some(request)) + } + + /// Notional and leverage brackets (`GET /fapi/v1/leverageBracket`). All symbols when + /// `symbol` is `None`. + pub fn get_leverage_brackets(&self, symbol: S) -> Result> + where + S: Into>, + { + let mut parameters = BTreeMap::new(); + if let Some(symbol) = symbol.into() { + parameters.insert("symbol".into(), symbol); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::LeverageBracket), Some(request)) + } + + /// Position ADL quantile estimation (`GET /fapi/v1/adlQuantile`). + pub fn get_adl_quantile(&self, symbol: S) -> Result> + where + S: Into>, + { + let mut parameters = BTreeMap::new(); + if let Some(symbol) = symbol.into() { + parameters.insert("symbol".into(), symbol); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::AdlQuantile), Some(request)) + } + + /// Futures trading quantitative rules indicators (`GET /fapi/v1/apiTradingStatus`). + pub fn get_api_trading_status(&self, symbol: S) -> Result + where + S: Into>, + { + let mut parameters = BTreeMap::new(); + if let Some(symbol) = symbol.into() { + parameters.insert("symbol".into(), symbol); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::ApiTradingStatus), Some(request)) + } + + /// Current order count usage (`GET /fapi/v1/rateLimit/order`). + pub fn get_order_rate_limits(&self) -> Result> { + let request = build_signed_request(BTreeMap::new(), self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::RateLimitOrder), Some(request)) + } + + /// Position margin change history (`GET /fapi/v1/positionMargin/history`), last 30 days. + /// + /// `change_type`: 1 for added margin, 2 for reduced margin. + pub fn get_position_margin_history( + &self, symbol: S, change_type: C, start_time: T1, end_time: T2, limit: L, + ) -> Result> + where + S: Into, + C: Into>, + T1: Into>, + T2: Into>, + L: Into>, + { + let mut parameters = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + if let Some(t) = change_type.into() { + parameters.insert("type".into(), t.to_string()); + } + if let Some(st) = start_time.into() { + parameters.insert("startTime".into(), st.to_string()); + } + if let Some(et) = end_time.into() { + parameters.insert("endTime".into(), et.to_string()); + } + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::PositionMarginHistory), Some(request)) + } + pub fn change_initial_leverage( &self, symbol: S, leverage: u8, ) -> Result @@ -758,6 +1307,7 @@ impl FuturesAccount { .map(|_| ()) } + /// Switch between One-way (`false`) and Hedge (`true`) position mode. pub fn change_position_mode(&self, dual_side_position: bool) -> Result<()> { let mut parameters: BTreeMap = BTreeMap::new(); let dual_side = if dual_side_position { "true" } else { "false" }; @@ -769,6 +1319,46 @@ impl FuturesAccount { .map(|_| ()) } + /// Current position mode (`GET /fapi/v1/positionSide/dual`). + pub fn get_position_mode(&self) -> Result { + let request = build_signed_request(BTreeMap::new(), self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::PositionSide), Some(request)) + } + + /// Switch between Single-Asset (`false`) and Multi-Assets (`true`) margin mode + /// (`POST /fapi/v1/multiAssetsMargin`). + pub fn change_multi_assets_margin(&self, multi_assets_margin: bool) -> Result { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("multiAssetsMargin".into(), multi_assets_margin.to_string()); + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .post_signed(API::Futures(Futures::MultiAssetsMargin), request) + } + + /// Current margin mode (`GET /fapi/v1/multiAssetsMargin`). + pub fn get_multi_assets_margin(&self) -> Result { + let request = build_signed_request(BTreeMap::new(), self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::MultiAssetsMargin), Some(request)) + } + + /// Toggle BNB fee burn on futures trades (`POST /fapi/v1/feeBurn`). + pub fn set_fee_burn(&self, fee_burn: bool) -> Result { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("feeBurn".into(), fee_burn.to_string()); + let request = build_signed_request(parameters, self.recv_window)?; + self.client + .post_signed(API::Futures(Futures::FeeBurn), request) + } + + /// BNB fee burn status (`GET /fapi/v1/feeBurn`). + pub fn get_fee_burn(&self) -> Result { + let request = build_signed_request(BTreeMap::new(), self.recv_window)?; + self.client + .get_signed(API::Futures(Futures::FeeBurn), Some(request)) + } + pub fn cancel_all_open_orders(&self, symbol: S) -> Result<()> where S: Into, @@ -813,7 +1403,6 @@ impl FuturesAccount { } let request = build_signed_request(parameters, self.recv_window)?; - println!("{}", request); self.client .get_signed(API::Futures(Futures::Income), Some(request)) } diff --git a/src/futures/market.rs b/src/futures/market.rs index 5a0193a1..aa0fd77f 100644 --- a/src/futures/market.rs +++ b/src/futures/market.rs @@ -1,29 +1,37 @@ /*! ## Implemented functionality -- [x] `Order Book` +- [x] `Order Book` / `RPI Order Book` - [x] `Recent Trades List` -- [ ] `Old Trades Lookup (MARKET_DATA)` +- [x] `Old Trades Lookup (MARKET_DATA)` - [x] `Compressed/Aggregate Trades List` -- [x] `Kline/Candlestick Data` +- [x] `Kline/Candlestick Data` (plus continuous, index price, mark price, premium index) - [x] `Mark Price` -- [ ] `Get Funding Rate History (MARKET_DATA)` +- [x] `Get Funding Rate History` / `Get Funding Rate Info` - [x] `24hr Ticker Price Change Statistics` - [x] `Symbol Price Ticker` - [x] `Symbol Order Book Ticker` -- [x] `Get all Liquidation Orders` -- [x] `Open Interest` -- [ ] `Notional and Leverage Brackets (MARKET_DATA)` -- [ ] `Open Interest Statistics (MARKET_DATA)` -- [ ] `Top Trader Long/Short Ratio (Accounts) (MARKET_DATA)` -- [ ] `Top Trader Long/Short Ratio (Positions) (MARKET_DATA)` -- [ ] `Long/Short Ratio (MARKET_DATA)` -- [ ] `Taker Buy/Sell Volume (MARKET_DATA)` +- [x] `Open Interest` / `Open Interest Statistics` +- [x] `Top Trader Long/Short Ratio (Accounts)` / `(Positions)` +- [x] `Long/Short Ratio` +- [x] `Taker Buy/Sell Volume` +- [x] `Basis` +- [x] `Composite Index Symbol Information` +- [x] `Multi-Assets Mode Asset Index` +- [x] `Query Index Price Constituents` +- [x] `Query Insurance Fund Balance Snapshot` +- [x] `ADL Risk` +- [x] `Quarterly Contract Settlement Price` + +`Notional and Leverage Brackets` and the user's liquidation orders are signed endpoints, +see [`crate::futures::account::FuturesAccount`]. */ -use crate::util::{build_request, build_signed_request}; +use crate::util::build_request; use crate::futures::model::{ - AggTrades, BookTickers, KlineSummaries, KlineSummary, LiquidationOrders, MarkPrices, - OpenInterest, OpenInterestHist, OrderBook, PriceStats, SymbolPrice, Tickers, Trades, + AdlRisk, AggTrades, AssetIndex, Basis, BookTickers, DeliveryPrice, FundingInfo, FundingRate, + IndexConstituents, IndexInfo, InsuranceBalance, KlineSummaries, KlineSummary, + LiquidationOrders, LongShortRatio, MarkPrice, MarkPrices, OpenInterest, OpenInterestHist, + OrderBook, PriceStats, SymbolPrice, TakerLongShortRatio, Tickers, Trades, }; use crate::client::Client; use crate::errors::Result; @@ -32,11 +40,6 @@ use serde_json::Value; use crate::api::API; use crate::api::Futures; -// TODO -// Make enums for Strings -// Add limit parameters to functions -// Implement all functions - #[derive(Clone)] pub struct FuturesMarket { pub client: Client, @@ -81,7 +84,8 @@ impl FuturesMarket { .get(API::Futures(Futures::Trades), Some(request)) } - // TODO This may be incomplete, as it hasn't been tested + /// Older trades (`GET /fapi/v1/historicalTrades`). Requires an API key; only the last + /// month of trades is available and `limit` is capped at 500 (default 100). pub fn get_historical_trades( &self, symbol: S1, from_id: S2, limit: S3, ) -> Result @@ -94,7 +98,6 @@ impl FuturesMarket { parameters.insert("symbol".into(), symbol.into()); - // Add three optional parameters if let Some(lt) = limit.into() { parameters.insert("limit".into(), format!("{}", lt)); } @@ -102,10 +105,10 @@ impl FuturesMarket { parameters.insert("fromId".into(), format!("{}", fi)); } - let request = build_signed_request(parameters, self.recv_window)?; + let request = build_request(parameters); self.client - .get_signed(API::Futures(Futures::HistoricalTrades), Some(request)) + .get_with_api_key(API::Futures(Futures::HistoricalTrades), Some(request)) } pub fn get_agg_trades( @@ -245,6 +248,56 @@ impl FuturesMarket { self.client.get(API::Futures(Futures::PremiumIndex), None) } + /// Mark price, index price and funding rate of one symbol (`GET /fapi/v1/premiumIndex`). + pub fn get_mark_price(&self, symbol: S) -> Result + where + S: Into, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + let request = build_request(parameters); + self.client + .get(API::Futures(Futures::PremiumIndex), Some(request)) + } + + /// Funding rate history (`GET /fapi/v1/fundingRate`), all symbols when `None`. + pub fn get_funding_rate_history( + &self, symbol: S, start_time: T1, end_time: T2, limit: L, + ) -> Result> + where + S: Into>, + T1: Into>, + T2: Into>, + L: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + if let Some(symbol) = symbol.into() { + parameters.insert("symbol".into(), symbol); + } + if let Some(st) = start_time.into() { + parameters.insert("startTime".into(), st.to_string()); + } + if let Some(et) = end_time.into() { + parameters.insert("endTime".into(), et.to_string()); + } + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + let request = build_request(parameters); + self.client + .get(API::Futures(Futures::FundingRate), Some(request)) + } + + /// Funding rate caps, floors and intervals for symbols with adjusted funding + /// (`GET /fapi/v1/fundingInfo`). + pub fn get_funding_info(&self) -> Result> { + self.client.get(API::Futures(Futures::FundingInfo), None) + } + + /// `GET /fapi/v1/allForceOrders` was removed by Binance; this call always fails. + /// Use [`crate::futures::account::FuturesAccount::get_force_orders`] for the account's + /// liquidation orders or the `@forceOrder` / `!forceOrder@arr` streams. + #[deprecated(note = "endpoint removed by Binance, use FuturesAccount::get_force_orders")] pub fn get_all_liquidation_orders(&self) -> Result { self.client.get(API::Futures(Futures::AllForceOrders), None) } @@ -288,4 +341,373 @@ impl FuturesMarket { self.client .get(API::Futures(Futures::OpenInterestHist), Some(request)) } + + #[allow(clippy::too_many_arguments)] + fn get_klines_from( + &self, endpoint: Futures, key: &str, symbol_or_pair: S1, extra: Option<(&str, String)>, + interval: S2, limit: S3, start_time: S4, end_time: S4, + ) -> Result + where + S1: Into, + S2: Into, + S3: Into>, + S4: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert(key.into(), symbol_or_pair.into()); + if let Some((k, v)) = extra { + parameters.insert(k.into(), v); + } + parameters.insert("interval".into(), interval.into()); + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + if let Some(st) = start_time.into() { + parameters.insert("startTime".into(), st.to_string()); + } + if let Some(et) = end_time.into() { + parameters.insert("endTime".into(), et.to_string()); + } + let request = build_request(parameters); + let data: Vec> = self.client.get(API::Futures(endpoint), Some(request))?; + Ok(KlineSummaries::AllKlineSummaries( + data.iter() + .map(|row| row.try_into()) + .collect::>>()?, + )) + } + + /// Klines of a contract type on a pair (`GET /fapi/v1/continuousKlines`), e.g. + /// `("BTCUSDT", ContractType::Perpetual, "1h", ...)`. + pub fn get_continuous_klines( + &self, pair: S1, contract_type: crate::futures::account::ContractType, interval: S2, + limit: S3, start_time: S4, end_time: S4, + ) -> Result + where + S1: Into, + S2: Into, + S3: Into>, + S4: Into>, + { + self.get_klines_from( + Futures::ContinuousKlines, + "pair", + pair, + Some(("contractType", String::from(contract_type))), + interval, + limit, + start_time, + end_time, + ) + } + + /// Index price klines of a pair (`GET /fapi/v1/indexPriceKlines`). Only the OHLC and + /// time fields are meaningful; volume fields are zero. + pub fn get_index_price_klines( + &self, pair: S1, interval: S2, limit: S3, start_time: S4, end_time: S4, + ) -> Result + where + S1: Into, + S2: Into, + S3: Into>, + S4: Into>, + { + self.get_klines_from( + Futures::IndexPriceKlines, + "pair", + pair, + None, + interval, + limit, + start_time, + end_time, + ) + } + + /// Mark price klines of a symbol (`GET /fapi/v1/markPriceKlines`). + pub fn get_mark_price_klines( + &self, symbol: S1, interval: S2, limit: S3, start_time: S4, end_time: S4, + ) -> Result + where + S1: Into, + S2: Into, + S3: Into>, + S4: Into>, + { + self.get_klines_from( + Futures::MarkPriceKlines, + "symbol", + symbol, + None, + interval, + limit, + start_time, + end_time, + ) + } + + /// Premium index klines of a symbol (`GET /fapi/v1/premiumIndexKlines`). + pub fn get_premium_index_klines( + &self, symbol: S1, interval: S2, limit: S3, start_time: S4, end_time: S4, + ) -> Result + where + S1: Into, + S2: Into, + S3: Into>, + S4: Into>, + { + self.get_klines_from( + Futures::PremiumIndexKlines, + "symbol", + symbol, + None, + interval, + limit, + start_time, + end_time, + ) + } + + #[allow(clippy::too_many_arguments)] + fn get_futures_data( + &self, endpoint: Futures, key: &str, symbol: S1, period: S2, limit: S3, start_time: S4, + end_time: S5, + ) -> Result + where + T: serde::de::DeserializeOwned, + S1: Into, + S2: Into, + S3: Into>, + S4: Into>, + S5: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert(key.into(), symbol.into()); + parameters.insert("period".into(), period.into()); + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + if let Some(st) = start_time.into() { + parameters.insert("startTime".into(), st.to_string()); + } + if let Some(et) = end_time.into() { + parameters.insert("endTime".into(), et.to_string()); + } + let request = build_request(parameters); + self.client.get(API::Futures(endpoint), Some(request)) + } + + /// Top trader long/short ratio by accounts (`GET /futures/data/topLongShortAccountRatio`). + /// `period`: `5m`, `15m`, `30m`, `1h`, `2h`, `4h`, `6h`, `12h`, `1d`; last 30 days only. + pub fn top_long_short_account_ratio( + &self, symbol: S1, period: S2, limit: S3, start_time: S4, end_time: S5, + ) -> Result> + where + S1: Into, + S2: Into, + S3: Into>, + S4: Into>, + S5: Into>, + { + self.get_futures_data( + Futures::TopLongShortAccountRatio, + "symbol", + symbol, + period, + limit, + start_time, + end_time, + ) + } + + /// Top trader long/short ratio by positions (`GET /futures/data/topLongShortPositionRatio`). + pub fn top_long_short_position_ratio( + &self, symbol: S1, period: S2, limit: S3, start_time: S4, end_time: S5, + ) -> Result> + where + S1: Into, + S2: Into, + S3: Into>, + S4: Into>, + S5: Into>, + { + self.get_futures_data( + Futures::TopLongShortPositionRatio, + "symbol", + symbol, + period, + limit, + start_time, + end_time, + ) + } + + /// Global long/short account ratio (`GET /futures/data/globalLongShortAccountRatio`). + pub fn global_long_short_account_ratio( + &self, symbol: S1, period: S2, limit: S3, start_time: S4, end_time: S5, + ) -> Result> + where + S1: Into, + S2: Into, + S3: Into>, + S4: Into>, + S5: Into>, + { + self.get_futures_data( + Futures::GlobalLongShortAccountRatio, + "symbol", + symbol, + period, + limit, + start_time, + end_time, + ) + } + + /// Taker buy/sell volume ratio (`GET /futures/data/takerlongshortRatio`). + pub fn taker_long_short_ratio( + &self, symbol: S1, period: S2, limit: S3, start_time: S4, end_time: S5, + ) -> Result> + where + S1: Into, + S2: Into, + S3: Into>, + S4: Into>, + S5: Into>, + { + self.get_futures_data( + Futures::TakerlongshortRatio, + "symbol", + symbol, + period, + limit, + start_time, + end_time, + ) + } + + /// Basis between a pair's futures contract and its index (`GET /futures/data/basis`). + pub fn basis( + &self, pair: S1, contract_type: crate::futures::account::ContractType, period: S2, + limit: S3, start_time: S4, end_time: S5, + ) -> Result> + where + S1: Into, + S2: Into, + S3: Into>, + S4: Into>, + S5: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("pair".into(), pair.into()); + parameters.insert("contractType".into(), String::from(contract_type)); + parameters.insert("period".into(), period.into()); + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + if let Some(st) = start_time.into() { + parameters.insert("startTime".into(), st.to_string()); + } + if let Some(et) = end_time.into() { + parameters.insert("endTime".into(), et.to_string()); + } + let request = build_request(parameters); + self.client.get(API::Futures(Futures::Basis), Some(request)) + } + + fn get_optional_symbol(&self, endpoint: Futures, symbol: Option) -> Result + where + T: serde::de::DeserializeOwned, + { + let mut parameters: BTreeMap = BTreeMap::new(); + if let Some(symbol) = symbol { + parameters.insert("symbol".into(), symbol); + } + let request = build_request(parameters); + self.client.get(API::Futures(endpoint), Some(request)) + } + + /// Insurance fund balance snapshot (`GET /fapi/v1/insuranceBalance`). + pub fn get_insurance_balance(&self, symbol: S) -> Result> + where + S: Into>, + { + match symbol.into() { + Some(symbol) => self + .get_optional_symbol::(Futures::InsuranceBalance, Some(symbol)) + .map(|b| vec![b]), + None => self.get_optional_symbol(Futures::InsuranceBalance, None), + } + } + + /// ADL risk rating of a symbol (`GET /fapi/v1/symbolAdlRisk`), updated every 30 minutes. + pub fn get_symbol_adl_risk(&self, symbol: S) -> Result> + where + S: Into>, + { + match symbol.into() { + Some(symbol) => self + .get_optional_symbol::(Futures::SymbolAdlRisk, Some(symbol)) + .map(|r| vec![r]), + None => self.get_optional_symbol(Futures::SymbolAdlRisk, None), + } + } + + /// Order book of Retail Price Improvement orders (`GET /fapi/v1/rpiDepth`). + pub fn get_rpi_depth(&self, symbol: S) -> Result + where + S: Into, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + let request = build_request(parameters); + self.client + .get(API::Futures(Futures::RpiDepth), Some(request)) + } + + /// Composite index information (`GET /fapi/v1/indexInfo`), all indexes when `None`. + pub fn get_index_info(&self, symbol: S) -> Result> + where + S: Into>, + { + match symbol.into() { + Some(symbol) => self + .get_optional_symbol::(Futures::IndexInfo, Some(symbol)) + .map(|i| vec![i]), + None => self.get_optional_symbol(Futures::IndexInfo, None), + } + } + + /// Multi-assets mode asset index (`GET /fapi/v1/assetIndex`), all assets when `None`. + pub fn get_asset_index(&self, symbol: S) -> Result> + where + S: Into>, + { + match symbol.into() { + Some(symbol) => self + .get_optional_symbol::(Futures::AssetIndex, Some(symbol)) + .map(|i| vec![i]), + None => self.get_optional_symbol(Futures::AssetIndex, None), + } + } + + /// Index price constituents (`GET /fapi/v1/constituents`). + pub fn get_index_constituents(&self, symbol: S) -> Result + where + S: Into, + { + self.get_optional_symbol(Futures::Constituents, Some(symbol.into())) + } + + /// Quarterly contract settlement prices of a pair (`GET /futures/data/delivery-price`). + pub fn get_delivery_price(&self, pair: S) -> Result> + where + S: Into, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("pair".into(), pair.into()); + let request = build_request(parameters); + self.client + .get(API::Futures(Futures::DeliveryPrice), Some(request)) + } } diff --git a/src/futures/model.rs b/src/futures/model.rs index e6debac4..d1ec0a73 100644 --- a/src/futures/model.rs +++ b/src/futures/model.rs @@ -1,5 +1,6 @@ use serde::{Deserialize, Serialize}; -use crate::model::{string_or_float, string_or_float_opt, string_or_bool}; +use std::collections::BTreeMap; +use crate::model::{string_or_float, string_or_float_opt, string_or_bool, string_or_i64}; pub use crate::model::{ Asks, Bids, BookTickers, Filters, KlineSummaries, KlineSummary, RateLimit, ServerTime, @@ -12,24 +13,53 @@ pub struct ExchangeInformation { pub timezone: String, pub server_time: u64, pub rate_limits: Vec, - pub exchange_filters: Vec, + #[serde(default)] + pub exchange_filters: Vec, + /// Margin assets available in Multi-Assets mode + #[serde(default)] + pub assets: Vec, pub symbols: Vec, } +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct ExchangeAsset { + pub asset: String, + pub margin_available: bool, + #[serde(default, with = "string_or_float_opt")] + pub auto_asset_exchange: Option, +} + #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct Symbol { pub symbol: String, + pub pair: Option, + /// `PERPETUAL`, `CURRENT_QUARTER`, `NEXT_QUARTER`, `TRADIFI_PERPETUAL`, ... + pub contract_type: Option, + pub delivery_date: Option, pub status: String, pub maint_margin_percent: String, pub required_margin_percent: String, pub base_asset: String, pub quote_asset: String, + pub margin_asset: Option, pub onboard_date: u128, pub price_precision: u16, pub quantity_precision: u16, pub base_asset_precision: u64, pub quote_precision: u64, + pub underlying_type: Option, + #[serde(default)] + pub underlying_sub_type: Vec, + pub settle_plan: Option, + #[serde(default, with = "string_or_float_opt")] + pub trigger_protect: Option, + #[serde(default, with = "string_or_float_opt")] + pub liquidation_fee: Option, + #[serde(default, with = "string_or_float_opt")] + pub market_take_bound: Option, + pub max_move_order_limit: Option, pub filters: Vec, pub order_types: Vec, pub time_in_force: Vec, @@ -119,6 +149,9 @@ pub struct Trade { #[serde(with = "string_or_float")] pub quote_qty: f64, pub time: u64, + /// Whether this is a Retail Price Improvement trade + #[serde(rename = "isRPITrade")] + pub is_rpi_trade: Option, } #[derive(Debug, Serialize, Deserialize, Clone)] @@ -158,12 +191,45 @@ pub struct MarkPrice { pub symbol: String, #[serde(with = "string_or_float")] pub mark_price: f64, + #[serde(default, with = "string_or_float_opt")] + pub index_price: Option, + #[serde(default, with = "string_or_float_opt")] + pub estimated_settle_price: Option, #[serde(with = "string_or_float")] pub last_funding_rate: f64, + #[serde(default, with = "string_or_float_opt")] + pub interest_rate: Option, pub next_funding_time: u64, pub time: u64, } +/// Element of `GET /fapi/v1/fundingRate` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct FundingRate { + pub symbol: String, + #[serde(with = "string_or_float")] + pub funding_rate: f64, + pub funding_time: u64, + #[serde(default, with = "string_or_float_opt")] + pub mark_price: Option, + /// `Regular` or `Special` (stock-dividend funding fee) + pub rate_type: Option, +} + +/// Element of `GET /fapi/v1/fundingInfo` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct FundingInfo { + pub symbol: String, + #[serde(with = "string_or_float")] + pub adjusted_funding_rate_cap: f64, + #[serde(with = "string_or_float")] + pub adjusted_funding_rate_floor: f64, + pub funding_interval_hours: u32, + pub disclaimer: Option, +} + #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(untagged)] pub enum LiquidationOrders { @@ -203,9 +269,161 @@ pub struct OpenInterestHist { pub symbol: String, pub sum_open_interest: String, pub sum_open_interest_value: String, + #[serde(rename = "CMCCirculatingSupply")] + pub cmc_circulating_supply: Option, + pub timestamp: u64, +} + +/// Element of the `topLongShortAccountRatio`, `topLongShortPositionRatio` and +/// `globalLongShortAccountRatio` endpoints +#[derive(Debug, Deserialize, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct LongShortRatio { + pub symbol: String, + #[serde(with = "string_or_float")] + pub long_short_ratio: f64, + #[serde(with = "string_or_float")] + pub long_account: f64, + #[serde(with = "string_or_float")] + pub short_account: f64, + pub timestamp: u64, +} + +/// Element of `GET /futures/data/takerlongshortRatio` +#[derive(Debug, Deserialize, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct TakerLongShortRatio { + #[serde(with = "string_or_float")] + pub buy_sell_ratio: f64, + #[serde(with = "string_or_float")] + pub buy_vol: f64, + #[serde(with = "string_or_float")] + pub sell_vol: f64, + pub timestamp: u64, +} + +/// Element of `GET /futures/data/basis` +#[derive(Debug, Deserialize, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Basis { + pub pair: String, + pub contract_type: String, + #[serde(with = "string_or_float")] + pub index_price: f64, + #[serde(with = "string_or_float")] + pub futures_price: f64, + #[serde(with = "string_or_float")] + pub basis: f64, + #[serde(with = "string_or_float")] + pub basis_rate: f64, + /// Empty for perpetual contracts + #[serde(default, with = "string_or_float_opt")] + pub annualized_basis_rate: Option, pub timestamp: u64, } +/// Element of `GET /fapi/v1/insuranceBalance` +#[derive(Debug, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct InsuranceBalance { + pub symbols: Vec, + pub assets: Vec, +} + +#[derive(Debug, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct InsuranceAsset { + pub asset: String, + #[serde(with = "string_or_float")] + pub margin_balance: f64, + pub update_time: u64, +} + +/// Element of `GET /fapi/v1/symbolAdlRisk` +#[derive(Debug, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct AdlRisk { + pub symbol: String, + /// `low`, `medium` or `high` + pub adl_risk: String, + pub update_time: u64, +} + +/// Element of `GET /fapi/v1/indexInfo` +#[derive(Debug, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct IndexInfo { + pub symbol: String, + pub time: u64, + pub component: String, + pub base_asset_list: Vec, +} + +#[derive(Debug, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct IndexBaseAsset { + pub base_asset: String, + pub quote_asset: String, + #[serde(with = "string_or_float")] + pub weight_in_quantity: f64, + #[serde(with = "string_or_float")] + pub weight_in_percentage: f64, +} + +/// Element of `GET /fapi/v1/assetIndex` +#[derive(Debug, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct AssetIndex { + pub symbol: String, + pub time: u64, + #[serde(with = "string_or_float")] + pub index: f64, + #[serde(with = "string_or_float")] + pub bid_buffer: f64, + #[serde(with = "string_or_float")] + pub ask_buffer: f64, + #[serde(with = "string_or_float")] + pub bid_rate: f64, + #[serde(with = "string_or_float")] + pub ask_rate: f64, + #[serde(with = "string_or_float")] + pub auto_exchange_bid_buffer: f64, + #[serde(with = "string_or_float")] + pub auto_exchange_ask_buffer: f64, + #[serde(with = "string_or_float")] + pub auto_exchange_bid_rate: f64, + #[serde(with = "string_or_float")] + pub auto_exchange_ask_rate: f64, +} + +/// Response of `GET /fapi/v1/constituents` +#[derive(Debug, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct IndexConstituents { + pub symbol: String, + pub time: u64, + pub constituents: Vec, +} + +#[derive(Debug, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct IndexConstituent { + pub exchange: String, + pub symbol: String, + #[serde(default, with = "string_or_float_opt")] + pub price: Option, + #[serde(default, with = "string_or_float_opt")] + pub weight: Option, +} + +/// Element of `GET /futures/data/delivery-price` +#[derive(Debug, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct DeliveryPrice { + pub delivery_time: u64, + pub delivery_price: f64, +} + #[derive(Debug, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct Order { @@ -231,17 +449,26 @@ pub struct Order { pub stop_price: f64, pub close_position: bool, pub symbol: String, + pub time: Option, pub time_in_force: String, #[serde(rename = "type")] pub order_type: String, pub orig_type: String, - #[serde(with = "string_or_float", default = "default_activation_price")] + /// Activation price of `TRAILING_STOP_MARKET` orders (`activatePrice` in the API) + #[serde( + rename = "activatePrice", + with = "string_or_float", + default = "default_activation_price" + )] pub activation_price: f64, #[serde(with = "string_or_float", default = "default_price_rate")] pub price_rate: f64, pub update_time: u64, pub working_type: String, pub price_protect: bool, + pub price_match: Option, + pub self_trade_prevention_mode: Option, + pub good_till_date: Option, } #[derive(Debug, Serialize, Deserialize, Clone)] @@ -250,20 +477,22 @@ pub struct Transaction { pub client_order_id: String, #[serde(with = "string_or_float")] pub cum_qty: f64, - #[serde(with = "string_or_float")] + #[serde(with = "string_or_float", default = "default_stop_price")] pub cum_quote: f64, #[serde(with = "string_or_float")] pub executed_qty: f64, pub order_id: u64, - #[serde(with = "string_or_float")] + #[serde(with = "string_or_float", default = "default_stop_price")] pub avg_price: f64, #[serde(with = "string_or_float")] pub orig_qty: f64, + #[serde(default, with = "string_or_float_opt")] + pub price: Option, pub reduce_only: bool, pub side: String, pub position_side: String, pub status: String, - #[serde(with = "string_or_float")] + #[serde(with = "string_or_float", default = "default_stop_price")] pub stop_price: f64, pub close_position: bool, pub symbol: String, @@ -279,16 +508,232 @@ pub struct Transaction { pub price_rate: Option, pub update_time: u64, pub working_type: String, - price_protect: bool, + pub price_protect: bool, + pub price_match: Option, + pub self_trade_prevention_mode: Option, + pub good_till_date: Option, +} + +/// Element of the `POST /fapi/v1/batchOrders` and `PUT /fapi/v1/batchOrders` responses. +/// +/// Each entry is either the placed/modified order or a Binance error for that order; +/// results are returned in the same order as the submitted list. +#[allow(clippy::large_enum_variant)] +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(untagged)] +pub enum BatchOrderResponse { + Error { code: i64, msg: String }, + Order(Transaction), +} + +/// Element of the `DELETE /fapi/v1/batchOrders` response. +#[allow(clippy::large_enum_variant)] +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(untagged)] +pub enum BatchCancelResponse { + Error { code: i64, msg: String }, + Order(CanceledOrder), } +/// Response of `PUT /fapi/v1/order` (modify order) #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] -pub struct CanceledOrder { +pub struct ModifiedOrder { + pub order_id: u64, + pub symbol: String, + pub pair: Option, + pub status: String, pub client_order_id: String, + /// Echo of the `modifyId` sent in the request, if any + pub modify_id: Option, + #[serde(with = "string_or_float")] + pub price: f64, + #[serde(with = "string_or_float")] + pub orig_qty: f64, + #[serde(with = "string_or_float")] + pub executed_qty: f64, #[serde(with = "string_or_float")] pub cum_qty: f64, + #[serde(with = "string_or_float", default = "default_stop_price")] + pub cum_base: f64, + pub time_in_force: String, + #[serde(rename = "type")] + pub type_name: String, + pub reduce_only: bool, + pub close_position: bool, + pub side: String, + pub position_side: String, + #[serde(with = "string_or_float", default = "default_stop_price")] + pub stop_price: f64, + pub working_type: String, + pub price_protect: bool, + pub orig_type: String, + pub price_match: Option, + pub self_trade_prevention_mode: Option, + pub good_till_date: Option, + pub update_time: u64, +} + +/// Element of `GET /fapi/v1/orderAmendment` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct OrderAmendment { + pub amendment_id: u64, + pub symbol: String, + pub pair: Option, + pub order_id: u64, + pub client_order_id: String, + pub time: u64, + pub amendment: Amendment, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct Amendment { + pub price: AmendedValue, + pub orig_qty: AmendedValue, + pub count: u64, + pub modify_id: Option, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct AmendedValue { + #[serde(with = "string_or_float")] + pub before: f64, + #[serde(with = "string_or_float")] + pub after: f64, +} + +/// Response of `POST /fapi/v1/countdownCancelAll` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct CountdownCancelAll { + pub symbol: String, + #[serde(with = "string_or_i64")] + pub countdown_time: i64, +} + +/// Element of `GET /fapi/v1/forceOrders` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct ForceOrder { + pub order_id: u64, + pub symbol: String, + pub pair: Option, + pub status: String, + pub client_order_id: String, + #[serde(with = "string_or_float")] + pub price: f64, + #[serde(with = "string_or_float")] + pub avg_price: f64, + #[serde(with = "string_or_float")] + pub orig_qty: f64, + #[serde(with = "string_or_float")] + pub executed_qty: f64, + #[serde(with = "string_or_float", default = "default_stop_price")] + pub cum_quote: f64, + #[serde(with = "string_or_float", default = "default_stop_price")] + pub cum_base: f64, + pub time_in_force: String, + #[serde(rename = "type")] + pub type_name: String, + pub reduce_only: bool, + pub close_position: bool, + pub side: String, + pub position_side: String, + #[serde(with = "string_or_float", default = "default_stop_price")] + pub stop_price: f64, + pub working_type: String, + pub orig_type: String, + pub time: u64, + pub update_time: u64, +} + +/// A conditional (algo) order as returned by the `/fapi/v1/algoOrder` family of endpoints. +/// +/// Since 2025-12-09 the conditional order types `STOP`, `STOP_MARKET`, `TAKE_PROFIT`, +/// `TAKE_PROFIT_MARKET` and `TRAILING_STOP_MARKET` are handled by the Algo service and +/// identified by `algo_id` rather than `order_id`. `actual_*` fields are only populated +/// once the order has been triggered and placed in the matching engine. +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct AlgoOrder { + pub algo_id: u64, + pub client_algo_id: String, + pub algo_type: String, + pub order_type: String, + pub symbol: String, + pub side: String, + pub position_side: String, + pub time_in_force: String, + #[serde(with = "string_or_float", default = "default_stop_price")] + pub quantity: f64, + /// `NEW`, `CANCELED`, `TRIGGERING`, `TRIGGERED`, `FINISHED`, `REJECTED`, `EXPIRED` + pub algo_status: String, + pub actual_order_id: Option, + #[serde(default, with = "string_or_float_opt")] + pub actual_price: Option, + pub actual_type: Option, + #[serde(default, with = "string_or_float_opt")] + pub actual_qty: Option, + #[serde(with = "string_or_float", default = "default_stop_price")] + pub trigger_price: f64, + #[serde(with = "string_or_float", default = "default_stop_price")] + pub price: f64, + #[serde(default, with = "string_or_float_opt")] + pub iceberg_quantity: Option, + #[serde(default, with = "string_or_float_opt")] + pub tp_trigger_price: Option, + #[serde(default, with = "string_or_float_opt")] + pub tp_price: Option, + #[serde(default, with = "string_or_float_opt")] + pub sl_trigger_price: Option, + #[serde(default, with = "string_or_float_opt")] + pub sl_price: Option, + pub tp_order_type: Option, + pub self_trade_prevention_mode: Option, + pub working_type: String, + pub price_match: Option, + pub close_position: bool, + pub price_protect: bool, + pub reduce_only: bool, + #[serde(default, with = "string_or_float_opt")] + pub activate_price: Option, + #[serde(default, with = "string_or_float_opt")] + pub callback_rate: Option, + pub create_time: u64, + pub update_time: u64, + pub trigger_time: Option, + pub good_till_date: Option, +} + +/// Response of `DELETE /fapi/v1/algoOrder` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct CanceledAlgoOrder { + pub algo_id: u64, + pub client_algo_id: String, + #[serde(with = "string_or_i64")] + pub code: i64, + pub msg: String, +} + +/// Generic `{"code": 200, "msg": "..."}` acknowledgement +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct CodeMsg { + #[serde(with = "string_or_i64")] + pub code: i64, + pub msg: String, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct CanceledOrder { + pub client_order_id: String, #[serde(with = "string_or_float")] + pub cum_qty: f64, + #[serde(with = "string_or_float", default = "default_stop_price")] pub cum_quote: f64, #[serde(with = "string_or_float")] pub executed_qty: f64, @@ -302,7 +747,7 @@ pub struct CanceledOrder { pub side: String, pub position_side: String, pub status: String, - #[serde(with = "string_or_float")] + #[serde(with = "string_or_float", default = "default_stop_price")] pub stop_price: f64, pub close_position: bool, pub symbol: String, @@ -317,7 +762,10 @@ pub struct CanceledOrder { pub price_rate: Option, pub update_time: u64, pub working_type: String, - price_protect: bool, + pub price_protect: bool, + pub price_match: Option, + pub self_trade_prevention_mode: Option, + pub good_till_date: Option, } #[derive(Debug, Serialize, Deserialize, Clone)] @@ -483,26 +931,304 @@ pub struct ChangeLeverageResponse { pub symbol: String, } -fn default_stop_price() -> f64 { - 0.0 -} -fn default_activation_price() -> f64 { - 0.0 -} -fn default_price_rate() -> f64 { - 0.0 -} - +/// Element of `GET /fapi/v3/positionRisk`. +/// +/// Unlike V2, only symbols with an open position or open orders are returned and the +/// symbol configuration fields (leverage, margin type, ...) are not included; use +/// `GET /fapi/v1/symbolConfig` for those. #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] -pub struct OrderUpdate { - #[serde(rename = "s")] +pub struct PositionRiskV3 { pub symbol: String, - - #[serde(rename = "c")] - pub new_client_order_id: String, - - #[serde(rename = "S")] + pub position_side: String, + #[serde(with = "string_or_float", rename = "positionAmt")] + pub position_amount: f64, + #[serde(with = "string_or_float")] + pub entry_price: f64, + #[serde(with = "string_or_float", default = "default_stop_price")] + pub break_even_price: f64, + #[serde(with = "string_or_float")] + pub mark_price: f64, + #[serde(with = "string_or_float", rename = "unRealizedProfit")] + pub unrealized_profit: f64, + #[serde(with = "string_or_float")] + pub liquidation_price: f64, + #[serde(with = "string_or_float")] + pub isolated_margin: f64, + #[serde(with = "string_or_float")] + pub notional: f64, + pub margin_asset: String, + #[serde(with = "string_or_float")] + pub isolated_wallet: f64, + #[serde(with = "string_or_float")] + pub initial_margin: f64, + #[serde(with = "string_or_float")] + pub maint_margin: f64, + #[serde(with = "string_or_float")] + pub position_initial_margin: f64, + #[serde(with = "string_or_float")] + pub open_order_initial_margin: f64, + /// ADL quantile (0-4) + pub adl: u8, + #[serde(with = "string_or_float")] + pub bid_notional: f64, + #[serde(with = "string_or_float")] + pub ask_notional: f64, + pub update_time: u64, +} + +/// Response of `GET /fapi/v3/account` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct AccountInformationV3 { + #[serde(with = "string_or_float")] + pub total_initial_margin: f64, + #[serde(with = "string_or_float")] + pub total_maint_margin: f64, + #[serde(with = "string_or_float")] + pub total_wallet_balance: f64, + #[serde(with = "string_or_float")] + pub total_unrealized_profit: f64, + #[serde(with = "string_or_float")] + pub total_margin_balance: f64, + #[serde(with = "string_or_float")] + pub total_position_initial_margin: f64, + #[serde(with = "string_or_float")] + pub total_open_order_initial_margin: f64, + #[serde(with = "string_or_float")] + pub total_cross_wallet_balance: f64, + #[serde(with = "string_or_float")] + pub total_cross_un_pnl: f64, + #[serde(with = "string_or_float")] + pub available_balance: f64, + #[serde(with = "string_or_float")] + pub max_withdraw_amount: f64, + pub assets: Vec, + pub positions: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct FuturesAssetV3 { + pub asset: String, + #[serde(with = "string_or_float")] + pub wallet_balance: f64, + #[serde(with = "string_or_float")] + pub unrealized_profit: f64, + #[serde(with = "string_or_float")] + pub margin_balance: f64, + #[serde(with = "string_or_float")] + pub maint_margin: f64, + #[serde(with = "string_or_float")] + pub initial_margin: f64, + #[serde(with = "string_or_float")] + pub position_initial_margin: f64, + #[serde(with = "string_or_float")] + pub open_order_initial_margin: f64, + #[serde(with = "string_or_float")] + pub cross_wallet_balance: f64, + #[serde(with = "string_or_float")] + pub cross_un_pnl: f64, + #[serde(with = "string_or_float")] + pub available_balance: f64, + #[serde(with = "string_or_float")] + pub max_withdraw_amount: f64, + pub margin_available: Option, + pub update_time: u64, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct FuturesPositionV3 { + pub symbol: String, + pub position_side: String, + #[serde(with = "string_or_float", rename = "positionAmt")] + pub position_amount: f64, + #[serde(with = "string_or_float")] + pub unrealized_profit: f64, + #[serde(with = "string_or_float")] + pub isolated_margin: f64, + #[serde(with = "string_or_float")] + pub notional: f64, + #[serde(with = "string_or_float")] + pub isolated_wallet: f64, + #[serde(with = "string_or_float")] + pub initial_margin: f64, + #[serde(with = "string_or_float")] + pub maint_margin: f64, + pub update_time: u64, +} + +/// Element of `GET /fapi/v1/symbolConfig` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct SymbolConfig { + pub symbol: String, + pub margin_type: String, + pub is_auto_add_margin: bool, + pub leverage: u16, + #[serde(with = "string_or_float")] + pub max_notional_value: f64, +} + +/// Response of `GET /fapi/v1/accountConfig` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct AccountConfig { + pub fee_tier: u16, + pub can_trade: bool, + pub can_deposit: bool, + pub can_withdraw: bool, + pub dual_side_position: bool, + pub update_time: u64, + pub multi_assets_margin: bool, + pub trade_group_id: i64, +} + +/// Response of `GET /fapi/v1/commissionRate` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct CommissionRate { + pub symbol: String, + #[serde(with = "string_or_float")] + pub maker_commission_rate: f64, + #[serde(with = "string_or_float")] + pub taker_commission_rate: f64, + #[serde(default, with = "string_or_float_opt")] + pub rpi_commission_rate: Option, +} + +/// Element of `GET /fapi/v1/leverageBracket` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct LeverageBracket { + pub symbol: String, + pub notional_coef: Option, + pub brackets: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct Bracket { + pub bracket: u16, + pub initial_leverage: u16, + pub notional_cap: f64, + pub notional_floor: f64, + pub maint_margin_ratio: f64, + pub cum: f64, +} + +/// Element of `GET /fapi/v1/positionMargin/history` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct PositionMarginChange { + pub symbol: String, + /// 1: add position margin, 2: reduce position margin + #[serde(rename = "type")] + pub change_type: u8, + pub delta_type: Option, + #[serde(with = "string_or_float")] + pub amount: f64, + pub asset: String, + pub time: u64, + pub position_side: String, +} + +/// Element of `GET /fapi/v1/adlQuantile` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct AdlQuantile { + pub symbol: String, + pub adl_quantile: AdlQuantileValues, +} + +/// ADL quantile per position side. In one-way mode only `both` is set; in hedge mode +/// `long`/`short` are set, and `hedge` replaces them when the position sizes are equal. +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct AdlQuantileValues { + #[serde(rename = "LONG")] + pub long: Option, + #[serde(rename = "SHORT")] + pub short: Option, + #[serde(rename = "HEDGE")] + pub hedge: Option, + #[serde(rename = "BOTH")] + pub both: Option, +} + +/// Response of `GET /fapi/v1/apiTradingStatus` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct ApiTradingStatus { + /// Keyed by symbol (or `ACCOUNT` for account level indicators) + pub indicators: BTreeMap>, + pub update_time: u64, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct TradingIndicator { + pub is_locked: bool, + pub planned_recover_time: u64, + /// `UFR`, `IFER`, `GCR`, `DR`, `TMV` + pub indicator: String, + pub value: f64, + pub trigger_value: f64, +} + +/// Response of `GET /fapi/v1/positionSide/dual` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct PositionMode { + /// `true` for Hedge mode, `false` for One-way mode + pub dual_side_position: bool, +} + +/// Response of `GET /fapi/v1/multiAssetsMargin` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct MultiAssetsMargin { + pub multi_assets_margin: bool, +} + +/// Response of `GET /fapi/v1/feeBurn` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct FeeBurn { + pub fee_burn: bool, +} + +/// Element of `GET /fapi/v1/rateLimit/order` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct OrderRateLimit { + pub rate_limit_type: String, + pub interval: String, + pub interval_num: u16, + pub limit: u64, +} + +fn default_stop_price() -> f64 { + 0.0 +} +fn default_activation_price() -> f64 { + 0.0 +} +fn default_price_rate() -> f64 { + 0.0 +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct OrderUpdate { + #[serde(rename = "s")] + pub symbol: String, + + #[serde(rename = "c")] + pub new_client_order_id: String, + + #[serde(rename = "S")] pub side: String, #[serde(rename = "o")] @@ -594,6 +1320,26 @@ pub struct OrderUpdate { #[serde(rename = "rp")] pub realized_profit: String, + + /// Self trade prevention mode + #[serde(rename = "V")] + pub self_trade_prevention_mode: Option, + + /// Price match mode + #[serde(rename = "pm")] + pub price_match: Option, + + /// Auto-cancel time for GTD orders + #[serde(rename = "gtd")] + pub good_till_date: Option, + + /// Expiry reason, only pushed for expired orders + #[serde(rename = "er")] + pub expiry_reason: Option, + + /// `modifyId` echoed on `AMENDMENT` executions when one was sent with the request + #[serde(rename = "M")] + pub modify_id: Option, } #[derive(Debug, Serialize, Deserialize, Clone)] @@ -625,3 +1371,237 @@ pub struct Income { pub tran_id: u64, pub trade_id: String, } + +/// `TRADE_LITE` user data event: a lightweight, lower-latency version of +/// `ORDER_TRADE_UPDATE` pushed only for `TRADE` executions. +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct TradeLiteEvent { + #[serde(rename = "e")] + pub event_type: String, + + #[serde(rename = "E")] + pub event_time: u64, + + #[serde(rename = "T")] + pub transaction_time: u64, + + #[serde(rename = "s")] + pub symbol: String, + + #[serde(rename = "q")] + pub original_qty: String, + + #[serde(rename = "p")] + pub original_price: String, + + #[serde(rename = "m")] + pub is_buyer_maker: bool, + + #[serde(rename = "c")] + pub client_order_id: String, + + #[serde(rename = "S")] + pub side: String, + + #[serde(rename = "L")] + pub last_filled_price: String, + + #[serde(rename = "l")] + pub last_filled_qty: String, + + #[serde(rename = "t")] + pub trade_id: u64, + + #[serde(rename = "i")] + pub order_id: u64, +} + +/// `ALGO_UPDATE` user data event: status change of a conditional (algo) order. +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct AlgoUpdateEvent { + #[serde(rename = "e")] + pub event_type: String, + + #[serde(rename = "E")] + pub event_time: u64, + + #[serde(rename = "T")] + pub transaction_time: u64, + + #[serde(rename = "o")] + pub algo_order: AlgoOrderUpdate, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct AlgoOrderUpdate { + #[serde(rename = "caid")] + pub client_algo_id: String, + + #[serde(rename = "aid")] + pub algo_id: u64, + + #[serde(rename = "at")] + pub algo_type: String, + + #[serde(rename = "o")] + pub order_type: String, + + #[serde(rename = "s")] + pub symbol: String, + + #[serde(rename = "S")] + pub side: String, + + #[serde(rename = "ps")] + pub position_side: String, + + #[serde(rename = "f")] + pub time_in_force: String, + + #[serde(rename = "q")] + pub quantity: String, + + /// `NEW`, `CANCELED`, `TRIGGERING`, `TRIGGERED`, `FINISHED`, `REJECTED`, `EXPIRED` + #[serde(rename = "X")] + pub algo_status: String, + + /// Order id in the matching engine, only once triggered + #[serde(rename = "ai")] + pub order_id: Option, + + /// Average fill price in the matching engine, only once triggered + #[serde(rename = "ap")] + pub avg_price: Option, + + /// Executed quantity in the matching engine, only once triggered + #[serde(rename = "aq")] + pub executed_qty: Option, + + /// Actual order type in the matching engine, only once triggered + #[serde(rename = "act")] + pub actual_type: Option, + + #[serde(rename = "tp")] + pub trigger_price: Option, + + #[serde(rename = "p")] + pub price: Option, + + #[serde(rename = "V")] + pub self_trade_prevention_mode: Option, + + #[serde(rename = "wt")] + pub working_type: Option, + + #[serde(rename = "pm")] + pub price_match: Option, + + #[serde(rename = "cp")] + pub close_position: Option, + + #[serde(rename = "pP")] + pub price_protect: Option, + + #[serde(rename = "R")] + pub reduce_only: Option, + + #[serde(rename = "tt")] + pub trigger_time: Option, + + #[serde(rename = "gtd")] + pub good_till_date: Option, + + /// Reason the algo order failed + #[serde(rename = "rm")] + pub reject_message: Option, + + /// Whether a trailing stop has been activated + #[serde(rename = "ia")] + pub is_activated: Option, +} + +/// `MARGIN_CALL` user data event +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct MarginCallEvent { + #[serde(rename = "e")] + pub event_type: String, + + #[serde(rename = "E")] + pub event_time: u64, + + /// Cross wallet balance, only pushed with crossed positions + #[serde(rename = "cw")] + pub cross_wallet_balance: Option, + + #[serde(rename = "p")] + pub positions: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct MarginCallPosition { + #[serde(rename = "s")] + pub symbol: String, + + #[serde(rename = "ps")] + pub position_side: String, + + #[serde(rename = "pa")] + pub position_amount: String, + + #[serde(rename = "mt")] + pub margin_type: String, + + /// Isolated wallet, only pushed for isolated positions + #[serde(rename = "iw")] + pub isolated_wallet: Option, + + #[serde(rename = "mp")] + pub mark_price: String, + + #[serde(rename = "up")] + pub unrealized_pnl: String, + + #[serde(rename = "mm")] + pub maintenance_margin_required: String, +} + +/// `ACCOUNT_CONFIG_UPDATE` user data event: leverage or multi-assets mode change +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct AccountConfigUpdateEvent { + #[serde(rename = "e")] + pub event_type: String, + + #[serde(rename = "E")] + pub event_time: u64, + + #[serde(rename = "T")] + pub transaction_time: u64, + + /// Leverage change of a symbol + #[serde(rename = "ac")] + pub leverage_config: Option, + + /// Multi-assets mode change + #[serde(rename = "ai")] + pub account_config: Option, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct LeverageConfigUpdate { + #[serde(rename = "s")] + pub symbol: String, + #[serde(rename = "l")] + pub leverage: u16, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct MultiAssetsConfigUpdate { + #[serde(rename = "j")] + pub multi_assets_mode: bool, +} diff --git a/src/futures/userstream.rs b/src/futures/userstream.rs index fdcad313..4398fc9e 100644 --- a/src/futures/userstream.rs +++ b/src/futures/userstream.rs @@ -10,6 +10,11 @@ pub struct FuturesUserStream { pub recv_window: u64, } +/// `listenKey` management for the USDⓈ-M futures user data stream. +/// +/// Connect the returned key with +/// [`crate::futures::websockets::FuturesWebSockets::connect`], which uses the `/private` +/// routed endpoint (`wss://fstream.binance.com/private/ws/`). impl FuturesUserStream { // User Stream pub fn start(&self) -> Result { diff --git a/src/futures/websockets.rs b/src/futures/websockets.rs index ce83fb64..65147c64 100755 --- a/src/futures/websockets.rs +++ b/src/futures/websockets.rs @@ -6,6 +6,9 @@ use crate::model::{ MarkPriceEvent, MiniTickerEvent, OrderBook, TradeEvent, UserDataStreamExpiredEvent, }; use crate::futures::model; +use crate::futures::model::{ + AccountConfigUpdateEvent, AlgoUpdateEvent, MarginCallEvent, TradeLiteEvent, +}; use error_chain::bail; use url::Url; use serde::{Deserialize, Serialize}; @@ -23,6 +26,43 @@ enum FuturesWebsocketAPI { Custom(String), } +/// Routed WebSocket entry point. Since 2026 Binance only pushes a stream on the path it +/// belongs to: `/public` for book ticker and depth streams, `/market` for aggTrade, mark +/// price, klines, tickers, liquidations and composite index, `/private` for user data. +/// Un-routed connections only receive `/public` streams. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FuturesStreamRoute { + /// Legacy un-routed base URL; only `/public` streams are delivered + Root, + Public, + Market, + Private, +} + +impl FuturesStreamRoute { + fn path(self) -> &'static str { + match self { + FuturesStreamRoute::Root => "", + FuturesStreamRoute::Public => "/public", + FuturesStreamRoute::Market => "/market", + FuturesStreamRoute::Private => "/private", + } + } + + /// Pick the route a stream name belongs to. + pub fn for_stream(stream: &str) -> FuturesStreamRoute { + let name = stream.split('@').nth(1).unwrap_or(""); + if stream == "!bookTicker" || name.starts_with("bookTicker") || name.starts_with("depth") { + FuturesStreamRoute::Public + } else if stream.contains('@') || stream.starts_with('!') { + FuturesStreamRoute::Market + } else { + // A bare listen key + FuturesStreamRoute::Private + } + } +} + pub enum FuturesMarket { USDM, COINM, @@ -33,7 +73,9 @@ pub enum FuturesMarket { } impl FuturesWebsocketAPI { - fn params(self, market: &FuturesMarket, subscription: &str) -> String { + fn params( + self, market: &FuturesMarket, route: FuturesStreamRoute, subscription: &str, + ) -> String { let baseurl = match market { FuturesMarket::USDM => "wss://fstream.binance.com", FuturesMarket::COINM => "wss://dstream.binance.com", @@ -45,21 +87,41 @@ impl FuturesWebsocketAPI { match self { FuturesWebsocketAPI::Default => { - format!("{}/ws/{}", baseurl, subscription) + format!("{}{}/ws/{}", baseurl, route.path(), subscription) } FuturesWebsocketAPI::MultiStream => { - format!("{}/stream?streams={}", baseurl, subscription) + format!( + "{}{}/stream?streams={}", + baseurl, + route.path(), + subscription + ) } FuturesWebsocketAPI::Custom(url) => url, } } } +/// Build the stream URL for a market, route and subscription. +pub fn futures_stream_url( + market: &FuturesMarket, route: FuturesStreamRoute, subscription: &str, +) -> String { + FuturesWebsocketAPI::Default.params(market, route, subscription) +} + #[allow(clippy::large_enum_variant)] #[derive(Debug, Serialize, Deserialize, Clone)] pub enum FuturesWebsocketEvent { AccountUpdate(AccountUpdateEvent), OrderTrade(model::OrderTradeEvent), + /// `TRADE_LITE`: lightweight trade execution event + TradeLite(TradeLiteEvent), + /// `ALGO_UPDATE`: conditional order status change + AlgoUpdate(AlgoUpdateEvent), + /// `MARGIN_CALL` + MarginCall(MarginCallEvent), + /// `ACCOUNT_CONFIG_UPDATE`: leverage or multi-assets mode change + AccountConfigUpdate(AccountConfigUpdateEvent), AggrTrades(AggrTradesEvent), Trade(TradeEvent), OrderBook(OrderBook), @@ -84,6 +146,7 @@ pub struct FuturesWebSockets<'a> { handler: Box Result<()> + 'a>, } +#[allow(clippy::large_enum_variant)] #[derive(Serialize, Deserialize, Debug)] #[serde(untagged)] enum FuturesEvents { @@ -119,22 +182,65 @@ impl<'a> FuturesWebSockets<'a> { } } + /// Connect to a single stream (or a listen key), picking the routed entry point + /// (`/public`, `/market` or `/private`) from the stream name. pub fn connect(&mut self, market: &FuturesMarket, subscription: &'a str) -> Result<()> { - self.connect_wss(&FuturesWebsocketAPI::Default.params(market, subscription)) + let route = Self::default_route(market, subscription); + self.connect_with_route(market, route, subscription) } + /// Routed paths only exist on USDⓈ-M futures; other markets keep the legacy base URL. + fn default_route(market: &FuturesMarket, subscription: &str) -> FuturesStreamRoute { + match market { + FuturesMarket::USDM | FuturesMarket::USDMTestnet => { + FuturesStreamRoute::for_stream(subscription) + } + _ => FuturesStreamRoute::Root, + } + } + + /// Connect to a single stream on an explicit route. + pub fn connect_with_route( + &mut self, market: &FuturesMarket, route: FuturesStreamRoute, subscription: &str, + ) -> Result<()> { + self.connect_wss(&FuturesWebsocketAPI::Default.params(market, route, subscription)) + } + + /// Connect to `config.futures_ws_endpoint`; the endpoint is used verbatim, so include the + /// route and `/ws/` part in it. pub fn connect_with_config( &mut self, market: &FuturesMarket, subscription: &'a str, config: &'a Config, ) -> Result<()> { self.connect_wss( - &FuturesWebsocketAPI::Custom(config.ws_endpoint.clone()).params(market, subscription), + &FuturesWebsocketAPI::Custom(config.futures_ws_endpoint.clone()).params( + market, + FuturesStreamRoute::Root, + subscription, + ), ) } + /// Connect to several streams at once. All streams must belong to the same route; the + /// route is picked from the first stream. pub fn connect_multiple_streams( &mut self, market: &FuturesMarket, endpoints: &[String], ) -> Result<()> { - self.connect_wss(&FuturesWebsocketAPI::MultiStream.params(market, &endpoints.join("/"))) + let route = endpoints + .first() + .map(|s| Self::default_route(market, s)) + .unwrap_or(FuturesStreamRoute::Root); + self.connect_multiple_streams_with_route(market, route, endpoints) + } + + /// Connect to several streams at once on an explicit route. + pub fn connect_multiple_streams_with_route( + &mut self, market: &FuturesMarket, route: FuturesStreamRoute, endpoints: &[String], + ) -> Result<()> { + self.connect_wss(&FuturesWebsocketAPI::MultiStream.params( + market, + route, + &endpoints.join("/"), + )) } fn connect_wss(&mut self, wss: &str) -> Result<()> { @@ -168,6 +274,46 @@ impl<'a> FuturesWebSockets<'a> { return Ok(()); } + // User data events sharing a shape are dispatched by name first. + if let Some(event_type) = value.get("e").and_then(|e| e.as_str()) { + let action = match event_type { + "ORDER_TRADE_UPDATE" => Some(FuturesWebsocketEvent::OrderTrade( + serde_json::from_value(value.clone())?, + )), + "ACCOUNT_UPDATE" => Some(FuturesWebsocketEvent::AccountUpdate( + serde_json::from_value(value.clone())?, + )), + "TRADE_LITE" => Some(FuturesWebsocketEvent::TradeLite(serde_json::from_value( + value.clone(), + )?)), + "ALGO_UPDATE" => Some(FuturesWebsocketEvent::AlgoUpdate(serde_json::from_value( + value.clone(), + )?)), + "MARGIN_CALL" => Some(FuturesWebsocketEvent::MarginCall(serde_json::from_value( + value.clone(), + )?)), + "ACCOUNT_CONFIG_UPDATE" => Some(FuturesWebsocketEvent::AccountConfigUpdate( + serde_json::from_value(value.clone())?, + )), + "listenKeyExpired" => Some(FuturesWebsocketEvent::UserDataStreamExpiredEvent( + serde_json::from_value(value.clone())?, + )), + // markPriceUpdate carries the index price too, so an untagged match would + // classify it as an IndexPriceEvent. + "markPriceUpdate" => Some(FuturesWebsocketEvent::MarkPrice( + serde_json::from_value(value.clone())?, + )), + "indexPriceUpdate" => Some(FuturesWebsocketEvent::IndexPrice( + serde_json::from_value(value.clone())?, + )), + _ => None, + }; + if let Some(action) = action { + (self.handler)(action)?; + return Ok(()); + } + } + if let Ok(events) = serde_json::from_value::(value) { let action = match events { FuturesEvents::Vec(v) => FuturesWebsocketEvent::DayTickerAll(v), diff --git a/src/general.rs b/src/general.rs index 357356b2..b386b095 100644 --- a/src/general.rs +++ b/src/general.rs @@ -5,6 +5,8 @@ use crate::client::Client; use crate::errors::Result; use crate::api::API; use crate::api::Spot; +use crate::util::{build_request, json_string_array}; +use std::collections::BTreeMap; #[derive(Clone)] pub struct General { @@ -29,6 +31,39 @@ impl General { self.client.get(API::Spot(Spot::ExchangeInfo), None) } + /// Exchange information filtered by symbol(s) and/or symbol status. + /// + /// - `symbols`: restrict the response to these symbols (an unknown symbol is an error) + /// - `symbol_status`: e.g. `TRADING`, `HALT`, `BREAK`, `CANCEL_ONLY`; cannot be combined + /// with `symbols` + /// - `show_permission_sets`: set to `false` to omit `permissionSets` (default `true`) + pub fn exchange_info_with_params( + &self, symbols: Option<&[S]>, symbol_status: T, show_permission_sets: P, + ) -> Result + where + S: AsRef, + T: Into>, + P: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + if let Some(symbols) = symbols { + if symbols.len() == 1 { + parameters.insert("symbol".into(), symbols[0].as_ref().to_string()); + } else { + parameters.insert("symbols".into(), json_string_array(symbols)); + } + } + if let Some(status) = symbol_status.into() { + parameters.insert("symbolStatus".into(), status); + } + if let Some(show) = show_permission_sets.into() { + parameters.insert("showPermissionSets".into(), show.to_string()); + } + let request = build_request(parameters); + self.client + .get(API::Spot(Spot::ExchangeInfo), Some(request)) + } + // Get Symbol information pub fn get_symbol_info(&self, symbol: S) -> Result where diff --git a/src/market.rs b/src/market.rs index 82b8b034..6220e387 100644 --- a/src/market.rs +++ b/src/market.rs @@ -1,7 +1,7 @@ -use crate::util::build_request; +use crate::util::{build_request, json_string_array}; use crate::model::{ AggTrade, AveragePrice, BookTickers, KlineSummaries, KlineSummary, OrderBook, PriceStats, - Prices, SymbolPrice, Tickers, + Prices, SymbolPrice, TickerStats, Tickers, Trade, }; use crate::client::Client; use crate::errors::Result; @@ -178,4 +178,186 @@ impl Market { Ok(klines) } + + /// Recent trades for a symbol (`GET /api/v3/trades`). `limit` defaults to 500, max 1000. + pub fn get_trades(&self, symbol: S, limit: L) -> Result> + where + S: Into, + L: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + let request = build_request(parameters); + self.client.get(API::Spot(Spot::Trades), Some(request)) + } + + /// Older trades (`GET /api/v3/historicalTrades`). Requires an API key. + /// + /// `from_id` is the trade id to fetch from; the most recent trades are returned when omitted. + pub fn get_historical_trades( + &self, symbol: S, from_id: F, limit: L, + ) -> Result> + where + S: Into, + F: Into>, + L: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + if let Some(fi) = from_id.into() { + parameters.insert("fromId".into(), fi.to_string()); + } + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + let request = build_request(parameters); + self.client + .get_with_api_key(API::Spot(Spot::HistoricalTrades), Some(request)) + } + + /// Klines optimised for presentation (`GET /api/v3/uiKlines`). + /// + /// Same parameters and response as [`Market::get_klines`]; `time_zone` (e.g. `"8"` or + /// `"-1:00"`) shifts the kline boundaries, default `0` (UTC). + pub fn get_ui_klines( + &self, symbol: S1, interval: S2, limit: S3, start_time: S4, end_time: S5, time_zone: S6, + ) -> Result + where + S1: Into, + S2: Into, + S3: Into>, + S4: Into>, + S5: Into>, + S6: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + parameters.insert("interval".into(), interval.into()); + if let Some(lt) = limit.into() { + parameters.insert("limit".into(), lt.to_string()); + } + if let Some(st) = start_time.into() { + parameters.insert("startTime".into(), st.to_string()); + } + if let Some(et) = end_time.into() { + parameters.insert("endTime".into(), et.to_string()); + } + if let Some(tz) = time_zone.into() { + parameters.insert("timeZone".into(), tz); + } + let request = build_request(parameters); + let data: Vec> = self.client.get(API::Spot(Spot::UiKlines), Some(request))?; + Ok(KlineSummaries::AllKlineSummaries( + data.iter() + .map(|row| row.try_into()) + .collect::>>()?, + )) + } + + /// Price change statistics for a trading day (`GET /api/v3/ticker/tradingDay`). + /// + /// `time_zone` defaults to `0` (UTC); `mini` selects the `MINI` response type. + pub fn get_trading_day_ticker( + &self, symbol: S, time_zone: T, mini: bool, + ) -> Result + where + S: Into, + T: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + if let Some(tz) = time_zone.into() { + parameters.insert("timeZone".into(), tz); + } + if mini { + parameters.insert("type".into(), "MINI".into()); + } + let request = build_request(parameters); + self.client + .get(API::Spot(Spot::TickerTradingDay), Some(request)) + } + + /// Trading day statistics for several symbols at once (max 100). + pub fn get_trading_day_tickers( + &self, symbols: &[S], time_zone: T, mini: bool, + ) -> Result> + where + S: AsRef, + T: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbols".into(), json_string_array(symbols)); + if let Some(tz) = time_zone.into() { + parameters.insert("timeZone".into(), tz); + } + if mini { + parameters.insert("type".into(), "MINI".into()); + } + let request = build_request(parameters); + self.client + .get(API::Spot(Spot::TickerTradingDay), Some(request)) + } + + /// Rolling window price change statistics (`GET /api/v3/ticker`). + /// + /// `window_size` examples: `1m`..`59m`, `1h`..`23h`, `1d`..`7d` (default `1d`). + pub fn get_rolling_window_ticker( + &self, symbol: S, window_size: W, mini: bool, + ) -> Result + where + S: Into, + W: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbol".into(), symbol.into()); + if let Some(ws) = window_size.into() { + parameters.insert("windowSize".into(), ws); + } + if mini { + parameters.insert("type".into(), "MINI".into()); + } + let request = build_request(parameters); + self.client.get(API::Spot(Spot::Ticker), Some(request)) + } + + /// Rolling window statistics for several symbols at once (max 100). + pub fn get_rolling_window_tickers( + &self, symbols: &[S], window_size: W, mini: bool, + ) -> Result> + where + S: AsRef, + W: Into>, + { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbols".into(), json_string_array(symbols)); + if let Some(ws) = window_size.into() { + parameters.insert("windowSize".into(), ws); + } + if mini { + parameters.insert("type".into(), "MINI".into()); + } + let request = build_request(parameters); + self.client.get(API::Spot(Spot::Ticker), Some(request)) + } + + /// Latest prices for a list of symbols. + pub fn get_prices_for_symbols>(&self, symbols: &[S]) -> Result> { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbols".into(), json_string_array(symbols)); + let request = build_request(parameters); + self.client.get(API::Spot(Spot::Price), Some(request)) + } + + /// 24hr statistics for a list of symbols. + pub fn get_24h_price_stats_for_symbols>( + &self, symbols: &[S], + ) -> Result> { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbols".into(), json_string_array(symbols)); + let request = build_request(parameters); + self.client.get(API::Spot(Spot::Ticker24hr), Some(request)) + } } diff --git a/src/model.rs b/src/model.rs index ed399c1c..93ef8500 100644 --- a/src/model.rs +++ b/src/model.rs @@ -17,7 +17,19 @@ pub struct ExchangeInformation { pub timezone: String, pub server_time: u64, pub rate_limits: Vec, + #[serde(default)] + pub exchange_filters: Vec, pub symbols: Vec, + /// Smart Order Routing groups, only present when SOR is available + #[serde(default)] + pub sors: Option>, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct Sor { + pub base_asset: String, + pub symbols: Vec, } #[derive(Debug, Serialize, Deserialize, Clone)] @@ -38,11 +50,30 @@ pub struct Symbol { pub base_asset_precision: u64, pub quote_asset: String, pub quote_precision: u64, + pub quote_asset_precision: Option, + pub base_commission_precision: Option, + pub quote_commission_precision: Option, pub order_types: Vec, pub iceberg_allowed: bool, + pub oco_allowed: Option, + pub oto_allowed: Option, + pub opo_allowed: Option, + pub quote_order_qty_market_allowed: Option, + pub allow_trailing_stop: Option, + pub cancel_replace_allowed: Option, + pub amend_allowed: Option, + pub peg_instructions_allowed: Option, pub is_spot_trading_allowed: bool, pub is_margin_trading_allowed: bool, pub filters: Vec, + /// Deprecated by Binance: always empty, use `permission_sets` + #[serde(default)] + pub permissions: Vec, + #[serde(default)] + pub permission_sets: Vec>, + pub default_self_trade_prevention_mode: Option, + #[serde(default)] + pub allowed_self_trade_prevention_modes: Vec, } #[derive(Debug, Serialize, Deserialize, Clone)] @@ -133,6 +164,31 @@ pub enum Filters { #[serde(rename = "MAX_NUM_ORDER_AMENDS")] #[serde(rename_all = "camelCase")] MaxNumOrderAmends { max_num_order_amends: Option }, + /// Account-level asset filter, only visible through `GET /api/v3/myFilters` + #[serde(rename = "MAX_ASSET")] + #[serde(rename_all = "camelCase")] + MaxAsset { + limit: Option, + asset: Option, + }, + #[serde(rename = "EXCHANGE_MAX_NUM_ORDERS")] + #[serde(rename_all = "camelCase")] + ExchangeMaxNumOrders { max_num_orders: Option }, + #[serde(rename = "EXCHANGE_MAX_NUM_ALGO_ORDERS")] + #[serde(rename_all = "camelCase")] + ExchangeMaxNumAlgoOrders { max_num_algo_orders: Option }, + #[serde(rename = "EXCHANGE_MAX_NUM_ICEBERG_ORDERS")] + #[serde(rename_all = "camelCase")] + ExchangeMaxNumIcebergOrders { max_num_iceberg_orders: Option }, + #[serde(rename = "EXCHANGE_MAX_NUM_ORDER_LISTS")] + #[serde(rename_all = "camelCase")] + ExchangeMaxNumOrderLists { max_num_order_lists: Option }, + /// Any filter type this library does not know about yet. + /// + /// Binance regularly adds new filters; this variant keeps `exchangeInfo` + /// deserialization working instead of failing on the first unknown `filterType`. + #[serde(other)] + Unknown, } #[derive(Debug, Serialize, Deserialize, Clone)] @@ -142,10 +198,123 @@ pub struct AccountInformation { pub taker_commission: f32, pub buyer_commission: f32, pub seller_commission: f32, + pub commission_rates: Option, pub can_trade: bool, pub can_withdraw: bool, pub can_deposit: bool, + pub brokered: Option, + pub require_self_trade_prevention: Option, + pub prevent_sor: Option, + pub update_time: Option, + pub account_type: Option, pub balances: Vec, + #[serde(default)] + pub permissions: Vec, + pub uid: Option, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct CommissionRates { + #[serde(with = "string_or_float")] + pub maker: f64, + #[serde(with = "string_or_float")] + pub taker: f64, + #[serde(with = "string_or_float")] + pub buyer: f64, + #[serde(with = "string_or_float")] + pub seller: f64, +} + +/// Response of `GET /api/v3/account/commission` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct AccountCommission { + pub symbol: String, + pub standard_commission: CommissionRates, + pub special_commission: Option, + pub tax_commission: CommissionRates, + pub discount: CommissionDiscount, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct CommissionDiscount { + pub enabled_for_account: bool, + pub enabled_for_symbol: bool, + pub discount_asset: Option, + #[serde(with = "string_or_float")] + pub discount: f64, +} + +/// Response of `GET /api/v3/myFilters` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct MyFilters { + #[serde(default)] + pub exchange_filters: Vec, + #[serde(default)] + pub symbol_filters: Vec, + #[serde(default)] + pub asset_filters: Vec, + #[serde(default)] + pub rate_limits: Vec, +} + +/// Rate limit including the current usage count, as returned by +/// `GET /api/v3/rateLimit/order` and `GET /api/v3/myFilters`. +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct OrderRateLimit { + pub rate_limit_type: String, + pub interval: String, + pub interval_num: u16, + pub limit: u64, + pub count: Option, +} + +/// Element of the `GET /api/v3/myPreventedMatches` response +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct PreventedMatch { + pub symbol: String, + pub prevented_match_id: u64, + pub taker_order_id: u64, + pub maker_symbol: Option, + pub maker_order_id: u64, + pub trade_group_id: u64, + pub self_trade_prevention_mode: String, + #[serde(with = "string_or_float")] + pub price: f64, + #[serde(default, with = "string_or_float_opt")] + pub maker_prevented_quantity: Option, + #[serde(default, with = "string_or_float_opt")] + pub taker_prevented_quantity: Option, + pub transact_time: u64, +} + +/// Element of the `GET /api/v3/myAllocations` response +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct Allocation { + pub symbol: String, + pub allocation_id: u64, + pub allocation_type: String, + pub order_id: u64, + pub order_list_id: i64, + #[serde(with = "string_or_float")] + pub price: f64, + #[serde(with = "string_or_float")] + pub qty: f64, + #[serde(with = "string_or_float")] + pub quote_qty: f64, + #[serde(with = "string_or_float")] + pub commission: f64, + pub commission_asset: String, + pub time: u64, + pub is_buyer: bool, + pub is_maker: bool, + pub is_allocator: bool, } #[derive(Debug, Serialize, Deserialize, Clone)] @@ -173,13 +342,36 @@ pub struct Order { #[serde(rename = "type")] pub type_name: String, pub side: String, - #[serde(with = "string_or_float")] + /// Only present for `STOP_LOSS`, `TAKE_PROFIT`, `STOP_LOSS_LIMIT` and `TAKE_PROFIT_LIMIT` + /// orders; `0.0` otherwise. + #[serde(with = "string_or_float", default = "default_stop_price")] pub stop_price: f64, + /// Only present if the order was placed with `icebergQty`; empty otherwise. + #[serde(default)] pub iceberg_qty: String, pub time: u64, pub update_time: u64, pub is_working: bool, + #[serde(default)] pub orig_quote_order_qty: String, + pub working_time: Option, + pub self_trade_prevention_mode: Option, + pub prevented_match_id: Option, + #[serde(default, with = "string_or_float_opt")] + pub prevented_quantity: Option, + pub strategy_id: Option, + pub strategy_type: Option, + pub trailing_delta: Option, + pub trailing_time: Option, + pub used_sor: Option, + pub working_floor: Option, + pub peg_price_type: Option, + pub peg_offset_type: Option, + pub peg_offset_value: Option, + #[serde(default, with = "string_or_float_opt")] + pub pegged_price: Option, + /// Cause of the order's expiration, only present for expired orders + pub expiry_reason: Option, } #[derive(Debug, Serialize, Deserialize, Clone)] @@ -188,7 +380,143 @@ pub struct OrderCanceled { pub symbol: String, pub orig_client_order_id: Option, pub order_id: Option, + pub order_list_id: Option, pub client_order_id: Option, + pub transact_time: Option, + #[serde(default, with = "string_or_float_opt")] + pub price: Option, + #[serde(default, with = "string_or_float_opt")] + pub orig_qty: Option, + #[serde(default, with = "string_or_float_opt")] + pub executed_qty: Option, + #[serde(default, with = "string_or_float_opt")] + pub orig_quote_order_qty: Option, + #[serde(default, with = "string_or_float_opt")] + pub cummulative_quote_qty: Option, + pub status: Option, + pub time_in_force: Option, + #[serde(rename = "type")] + pub type_name: Option, + pub side: Option, + #[serde(default, with = "string_or_float_opt")] + pub stop_price: Option, + #[serde(default, with = "string_or_float_opt")] + pub iceberg_qty: Option, + pub self_trade_prevention_mode: Option, + pub expiry_reason: Option, +} + +/// Result of `DELETE /api/v3/openOrders`, which cancels both plain orders and order lists. +#[allow(clippy::large_enum_variant)] +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(untagged)] +pub enum CanceledOrderOrList { + OrderList(OrderList), + Order(OrderCanceled), +} + +/// One of the orders making up an order list (OCO/OTO/OTOCO/OPO/OPOCO) +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct OrderListOrder { + pub symbol: String, + pub order_id: u64, + pub client_order_id: String, +} + +/// An order list as returned by the `orderList` family of endpoints. +/// +/// `order_reports` is only present on placement and cancellation responses. +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct OrderList { + pub order_list_id: i64, + pub contingency_type: String, + pub list_status_type: String, + pub list_order_status: String, + pub list_client_order_id: String, + pub transaction_time: u64, + pub symbol: String, + pub orders: Vec, + #[serde(default)] + pub order_reports: Option>, +} + +/// Response of `POST /api/v3/order/cancelReplace`. +/// +/// `cancel_response` and `new_order_response` either hold the order payload or, +/// when that step failed, a [`CancelReplaceOutcome::Error`] with the Binance error. +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct CancelReplaceResponse { + pub cancel_result: String, + pub new_order_result: String, + pub cancel_response: Option, + pub new_order_response: Option, +} + +#[allow(clippy::large_enum_variant)] +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(untagged)] +pub enum CancelReplaceOutcome { + Order(OrderCanceled), + Error { code: i64, msg: String }, +} + +/// Response of `PUT /api/v3/order/amend/keepPriority` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct AmendKeepPriorityResponse { + pub transact_time: u64, + pub execution_id: u64, + pub amended_order: AmendedOrder, + #[serde(default)] + pub list_status: Option, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct AmendedOrder { + pub symbol: String, + pub order_id: u64, + pub order_list_id: i64, + pub orig_client_order_id: String, + pub client_order_id: String, + #[serde(with = "string_or_float")] + pub price: f64, + #[serde(with = "string_or_float")] + pub qty: f64, + #[serde(with = "string_or_float")] + pub executed_qty: f64, + #[serde(default, with = "string_or_float_opt")] + pub prevented_qty: Option, + #[serde(default, with = "string_or_float_opt")] + pub quote_order_qty: Option, + #[serde(with = "string_or_float")] + pub cumulative_quote_qty: f64, + pub status: String, + pub time_in_force: String, + #[serde(rename = "type")] + pub type_name: String, + pub side: String, + pub working_time: Option, + pub self_trade_prevention_mode: Option, +} + +/// Element of the `GET /api/v3/order/amendments` response +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct SpotOrderAmendment { + pub symbol: String, + pub order_id: u64, + pub execution_id: u64, + pub orig_client_order_id: String, + pub new_client_order_id: String, + #[serde(with = "string_or_float")] + pub orig_qty: f64, + #[serde(with = "string_or_float")] + pub new_qty: f64, + pub time: u64, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] @@ -219,6 +547,8 @@ pub struct Transaction { pub orig_qty: f64, #[serde(with = "string_or_float")] pub executed_qty: f64, + #[serde(default, with = "string_or_float_opt")] + pub orig_quote_order_qty: Option, #[serde(with = "string_or_float")] pub cummulative_quote_qty: f64, #[serde(with = "string_or_float", default = "default_stop_price")] @@ -228,6 +558,9 @@ pub struct Transaction { #[serde(rename = "type")] pub type_name: String, pub side: String, + pub working_time: Option, + pub self_trade_prevention_mode: Option, + pub expiry_reason: Option, pub fills: Option>, } @@ -344,11 +677,16 @@ pub struct Tickers { #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct TradeHistory { + pub symbol: Option, pub id: u64, + pub order_id: Option, + pub order_list_id: Option, #[serde(with = "string_or_float")] pub price: f64, #[serde(with = "string_or_float")] pub qty: f64, + #[serde(default, with = "string_or_float_opt")] + pub quote_qty: Option, pub commission: String, pub commission_asset: String, pub time: u64, @@ -357,6 +695,53 @@ pub struct TradeHistory { pub is_best_match: bool, } +/// Element of `GET /api/v3/trades` and `GET /api/v3/historicalTrades` +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct Trade { + pub id: u64, + #[serde(with = "string_or_float")] + pub price: f64, + #[serde(with = "string_or_float")] + pub qty: f64, + #[serde(with = "string_or_float")] + pub quote_qty: f64, + pub time: u64, + pub is_buyer_maker: bool, + pub is_best_match: bool, +} + +/// Price change statistics returned by `GET /api/v3/ticker/tradingDay` and the +/// rolling-window `GET /api/v3/ticker` endpoint. +/// +/// The `MINI` response type omits `price_change`, `price_change_percent` and +/// `weighted_avg_price`. +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct TickerStats { + pub symbol: String, + pub price_change: Option, + pub price_change_percent: Option, + pub weighted_avg_price: Option, + #[serde(with = "string_or_float")] + pub open_price: f64, + #[serde(with = "string_or_float")] + pub high_price: f64, + #[serde(with = "string_or_float")] + pub low_price: f64, + #[serde(with = "string_or_float")] + pub last_price: f64, + #[serde(with = "string_or_float")] + pub volume: f64, + #[serde(with = "string_or_float")] + pub quote_volume: f64, + pub open_time: u64, + pub close_time: u64, + pub first_id: i64, + pub last_id: i64, + pub count: u64, +} + #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct PriceStats { @@ -441,6 +826,10 @@ pub struct AccountUpdateDataEvent { #[serde(rename = "P")] pub positions: Vec, + + /// Symbol, only pushed when the reason is `FUNDING_FEE` + #[serde(rename = "S")] + pub symbol: Option, } #[derive(Debug, Serialize, Deserialize, Clone)] @@ -465,6 +854,8 @@ pub struct EventPosition { pub position_amount: String, #[serde(rename = "ep")] pub entry_price: String, + #[serde(rename = "bep")] + pub breakeven_price: Option, #[serde(rename = "cr")] pub accumulated_realized: String, // (Pre-fee) Accumulated Realized #[serde(rename = "up")] @@ -579,6 +970,188 @@ pub struct OrderTradeEvent { #[serde(skip, rename = "M")] pub m_ignore: bool, + + /// Order creation time + #[serde(rename = "O")] + pub order_creation_time: Option, + + /// Cumulative quote asset transacted quantity + #[serde(rename = "Z")] + pub cumulative_quote_qty: Option, + + /// Last quote asset transacted quantity (lastPrice * lastQty) + #[serde(rename = "Y")] + pub last_quote_qty: Option, + + /// Quote order quantity + #[serde(rename = "Q")] + pub quote_order_qty: Option, + + /// Working time; only present once the order is on the book + #[serde(rename = "W")] + pub working_time: Option, + + /// Self trade prevention mode + #[serde(rename = "V")] + pub self_trade_prevention_mode: Option, + + /// Prevented match id, only present if the order expired due to STP + #[serde(rename = "v")] + pub prevented_match_id: Option, + + /// Prevented quantity, only present if the order expired due to STP + #[serde(rename = "A")] + pub prevented_quantity: Option, + + /// Trailing delta, only present for trailing stop orders + #[serde(rename = "d")] + pub trailing_delta: Option, + + /// Trailing time, only present for trailing stop orders + #[serde(rename = "D")] + pub trailing_time: Option, + + /// Working floor (`SOR` or `EXCHANGE`), only present for SOR orders + #[serde(rename = "k")] + pub working_floor: Option, + + /// Pegged price, only present for pegged orders + #[serde(rename = "gp")] + pub pegged_price: Option, + + /// Expiry reason, only present when the order has expired + #[serde(rename = "eR")] + pub expiry_reason: Option, +} + +/// Spot user data stream `outboundAccountPosition` event +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct OutboundAccountPositionEvent { + #[serde(rename = "e")] + pub event_type: String, + + #[serde(rename = "E")] + pub event_time: u64, + + /// Time of last account update + #[serde(rename = "u")] + pub last_account_update_time: u64, + + #[serde(rename = "B")] + pub balances: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct SpotEventBalance { + #[serde(rename = "a")] + pub asset: String, + #[serde(rename = "f")] + pub free: String, + #[serde(rename = "l")] + pub locked: String, +} + +/// Spot user data stream `balanceUpdate` event (deposit, withdrawal, transfer) +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct SpotBalanceUpdateEvent { + #[serde(rename = "e")] + pub event_type: String, + + #[serde(rename = "E")] + pub event_time: u64, + + #[serde(rename = "a")] + pub asset: String, + + /// Balance delta + #[serde(rename = "d")] + pub delta: String, + + /// Clear time + #[serde(rename = "T")] + pub clear_time: u64, +} + +/// Spot user data stream `listStatus` event (order list status change) +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct ListStatusEvent { + #[serde(rename = "e")] + pub event_type: String, + + #[serde(rename = "E")] + pub event_time: u64, + + #[serde(rename = "s")] + pub symbol: String, + + #[serde(rename = "g")] + pub order_list_id: i64, + + #[serde(rename = "c")] + pub contingency_type: String, + + #[serde(rename = "l")] + pub list_status_type: String, + + #[serde(rename = "L")] + pub list_order_status: String, + + #[serde(rename = "r")] + pub list_reject_reason: String, + + #[serde(rename = "C")] + pub list_client_order_id: String, + + #[serde(rename = "T")] + pub transaction_time: u64, + + #[serde(rename = "O")] + pub orders: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct ListStatusOrder { + #[serde(rename = "s")] + pub symbol: String, + #[serde(rename = "i")] + pub order_id: u64, + #[serde(rename = "c")] + pub client_order_id: String, +} + +/// Spot user data stream `externalLockUpdate` event +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct ExternalLockUpdateEvent { + #[serde(rename = "e")] + pub event_type: String, + + #[serde(rename = "E")] + pub event_time: u64, + + #[serde(rename = "a")] + pub asset: String, + + #[serde(rename = "d")] + pub delta: String, + + #[serde(rename = "T")] + pub transaction_time: u64, +} + +/// Generic event carrying only a type and a time: `eventStreamTerminated`, +/// `listenKeyExpired`, `serverShutdown`. +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GenericEvent { + #[serde(rename = "e")] + pub event_type: String, + + #[serde(rename = "E")] + pub event_time: u64, } /// The Aggregate Trade Streams push trade information that is aggregated for a single taker order. @@ -653,11 +1226,13 @@ pub struct TradeEvent { #[serde(rename = "q")] pub qty: String, + /// Buyer order id; removed from spot trade streams by Binance on 2024-06-18 #[serde(rename = "b")] - pub buyer_order_id: u64, + pub buyer_order_id: Option, + /// Seller order id; removed from spot trade streams by Binance on 2024-06-18 #[serde(rename = "a")] - pub seller_order_id: u64, + pub seller_order_id: Option, #[serde(rename = "T")] pub trade_order_time: u64, @@ -712,6 +1287,10 @@ pub struct MarkPriceEvent { #[serde(rename = "s")] pub symbol: String, + + /// Mark price moving average + #[serde(rename = "ap")] + pub mark_price_moving_average: Option, } // Object({"E": Number(1626118018407), "e": String("forceOrder"), "o": Object({"S": String("SELL"), "T": Number(1626118018404), "X": String("FILLED"), "ap": String("33028.07"), "f": String("IOC"), "l": String("0.010"), "o": String("LIMIT"), "p": String("32896.00"), "q": String("0.010"), "s": String("BTCUSDT"), "z": String("0.010")})}) @@ -1376,7 +1955,7 @@ pub(crate) mod string_or_float { pub(crate) mod string_or_float_opt { use std::fmt; - use serde::{Serializer, Deserialize, Deserializer}; + use serde::{de, Serializer, Deserialize, Deserializer}; pub fn serialize(value: &Option, serializer: S) -> Result where @@ -1400,9 +1979,49 @@ pub(crate) mod string_or_float_opt { Float(f64), } - Ok(Some(crate::model::string_or_float::deserialize( - deserializer, - )?)) + match Option::::deserialize(deserializer)? { + None => Ok(None), + Some(StringOrFloat::Float(f)) => Ok(Some(f)), + Some(StringOrFloat::String(s)) => { + if s.is_empty() || s == "null" { + Ok(None) + } else if s == "INF" { + Ok(Some(f64::INFINITY)) + } else { + s.parse().map(Some).map_err(de::Error::custom) + } + } + } + } +} + +/// Deserialize a value that Binance sends either as a JSON integer or as a numeric string +/// (e.g. the `code` field of algo order cancellations). +pub(crate) mod string_or_i64 { + use serde::{de, Serializer, Deserialize, Deserializer}; + + pub fn serialize(value: &i64, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_i64(*value) + } + + pub fn deserialize<'de, D>(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + #[derive(Deserialize)] + #[serde(untagged)] + enum StringOrInt { + String(String), + Int(i64), + } + + match StringOrInt::deserialize(deserializer)? { + StringOrInt::String(s) => s.parse().map_err(de::Error::custom), + StringOrInt::Int(i) => Ok(i), + } } } @@ -1496,7 +2115,7 @@ fn test_account_update_event() { } "#; - let res = r#"AccountUpdateEvent { event_type: "ACCOUNT_UPDATE", event_time: 1564745798939, data: AccountUpdateDataEvent { reason: "ORDER", balances: [EventBalance { asset: "USDT", wallet_balance: "122624.12345678", cross_wallet_balance: "100.12345678", balance_change: "50.12345678" }, EventBalance { asset: "BUSD", wallet_balance: "1.00000000", cross_wallet_balance: "0.00000000", balance_change: "-49.12345678" }], positions: [EventPosition { symbol: "BTCUSDT", position_amount: "0", entry_price: "0.00000", accumulated_realized: "200", unrealized_pnl: "0", margin_type: "isolated", isolated_wallet: "0.00000000", position_side: "BOTH" }, EventPosition { symbol: "BTCUSDT", position_amount: "20", entry_price: "6563.66500", accumulated_realized: "0", unrealized_pnl: "2850.21200", margin_type: "isolated", isolated_wallet: "13200.70726908", position_side: "LONG" }, EventPosition { symbol: "BTCUSDT", position_amount: "-10", entry_price: "6563.86000", accumulated_realized: "-45.04000000", unrealized_pnl: "-1423.15600", margin_type: "isolated", isolated_wallet: "6570.42511771", position_side: "SHORT" }] } }"#; + let res = r#"AccountUpdateEvent { event_type: "ACCOUNT_UPDATE", event_time: 1564745798939, data: AccountUpdateDataEvent { reason: "ORDER", balances: [EventBalance { asset: "USDT", wallet_balance: "122624.12345678", cross_wallet_balance: "100.12345678", balance_change: "50.12345678" }, EventBalance { asset: "BUSD", wallet_balance: "1.00000000", cross_wallet_balance: "0.00000000", balance_change: "-49.12345678" }], positions: [EventPosition { symbol: "BTCUSDT", position_amount: "0", entry_price: "0.00000", breakeven_price: None, accumulated_realized: "200", unrealized_pnl: "0", margin_type: "isolated", isolated_wallet: "0.00000000", position_side: "BOTH" }, EventPosition { symbol: "BTCUSDT", position_amount: "20", entry_price: "6563.66500", breakeven_price: None, accumulated_realized: "0", unrealized_pnl: "2850.21200", margin_type: "isolated", isolated_wallet: "13200.70726908", position_side: "LONG" }, EventPosition { symbol: "BTCUSDT", position_amount: "-10", entry_price: "6563.86000", breakeven_price: None, accumulated_realized: "-45.04000000", unrealized_pnl: "-1423.15600", margin_type: "isolated", isolated_wallet: "6570.42511771", position_side: "SHORT" }], symbol: None } }"#; let v: AccountUpdateEvent = serde_json::from_str(json).unwrap(); assert_eq!(format!("{:?}", v), res); //let event = from_value::(json).unwrap(); diff --git a/src/userstream.rs b/src/userstream.rs index 5c279162..7ca6f99f 100644 --- a/src/userstream.rs +++ b/src/userstream.rs @@ -10,17 +10,31 @@ pub struct UserStream { pub recv_window: u64, } +/// Legacy `listenKey` based user data stream management. +/// +/// Binance retired `POST`/`PUT`/`DELETE /api/v3/userDataStream` on 2026-02-20. Spot user +/// data must now be consumed through the WebSocket API; see +/// [`crate::websockets::WebSockets::connect_user_data_stream`]. These methods are kept +/// for API compatibility only and will fail against production. impl UserStream { // User Stream + #[deprecated( + note = "retired by Binance on 2026-02-20, use WebSockets::connect_user_data_stream" + )] pub fn start(&self) -> Result { self.client.post(API::Spot(Spot::UserDataStream)) } - // Current open orders on a symbol + #[deprecated( + note = "retired by Binance on 2026-02-20, use WebSockets::connect_user_data_stream" + )] pub fn keep_alive(&self, listen_key: &str) -> Result { self.client.put(API::Spot(Spot::UserDataStream), listen_key) } + #[deprecated( + note = "retired by Binance on 2026-02-20, use WebSockets::connect_user_data_stream" + )] pub fn close(&self, listen_key: &str) -> Result { self.client .delete(API::Spot(Spot::UserDataStream), listen_key) diff --git a/src/util.rs b/src/util.rs index 17859d6f..06793264 100644 --- a/src/util.rs +++ b/src/util.rs @@ -2,12 +2,38 @@ use crate::errors::Result; use std::collections::BTreeMap; use std::time::{SystemTime, UNIX_EPOCH}; use error_chain::bail; +use hex::encode as hex_encode; +use hmac::{Hmac, Mac}; use serde_json::Value; +use sha2::Sha256; +/// Percent-encode a query string value following RFC 3986. +/// +/// Only unreserved characters (`A-Z a-z 0-9 - _ . ~`) are kept as-is; everything else is +/// encoded as `%XX` (UTF-8 bytes). Binance requires that signed payloads are percent-encoded +/// before signing, and this is also what makes JSON array parameters (`symbols`, `batchOrders`, +/// `orderIdList`) and non-ASCII symbols round-trip correctly. +pub fn percent_encode(value: &str) -> String { + let mut out = String::with_capacity(value.len()); + for byte in value.bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + out.push(byte as char); + } + _ => out.push_str(&format!("%{:02X}", byte)), + } + } + out +} + +/// Build a `key=value&key=value` query string from the given parameters. +/// +/// Keys are emitted in alphabetical order (BTreeMap iteration order) which is the order +/// Binance uses for signature payloads; values are percent-encoded. pub fn build_request(parameters: BTreeMap) -> String { let mut request = String::new(); for (key, value) in parameters { - let param = format!("{}={}&", key, value); + let param = format!("{}={}&", key, percent_encode(&value)); request.push_str(param.as_ref()); } request.pop(); @@ -33,6 +59,24 @@ pub fn build_signed_request_custom( bail!("Failed to get timestamp") } +/// Compute the hex-encoded HMAC-SHA256 signature of `payload` using `secret_key`. +pub fn sign_hmac(secret_key: &str, payload: &str) -> String { + let mut mac = Hmac::::new_from_slice(secret_key.as_bytes()) + .expect("HMAC accepts keys of any length"); + mac.update(payload.as_bytes()); + hex_encode(mac.finalize().into_bytes()) +} + +/// Encode a list of strings as the JSON array format Binance expects for +/// parameters such as `symbols` or `origClientOrderIdList`: `["A","B"]`. +pub fn json_string_array>(items: &[S]) -> String { + let values: Vec = items + .iter() + .map(|s| Value::String(s.as_ref().to_string())) + .collect(); + Value::Array(values).to_string() +} + pub fn to_i64(v: &Value) -> i64 { v.as_i64().unwrap() } @@ -41,6 +85,11 @@ pub fn to_f64(v: &Value) -> f64 { v.as_str().unwrap().parse().unwrap() } +/// Current Unix time in milliseconds. +pub fn get_timestamp_now() -> Result { + get_timestamp(SystemTime::now()) +} + fn get_timestamp(start: SystemTime) -> Result { let since_epoch = start.duration_since(UNIX_EPOCH)?; Ok(since_epoch.as_secs() * 1000 + u64::from(since_epoch.subsec_nanos()) / 1_000_000) @@ -52,11 +101,7 @@ pub fn is_start_time_valid(start_time: &u64) -> bool { .unwrap() .as_secs(); - if start_time > ¤t_time { - false - } else { - true - } + start_time <= ¤t_time } pub fn generate_uuid22() -> String { diff --git a/src/websockets.rs b/src/websockets.rs index 15f2fdd2..89a0383f 100644 --- a/src/websockets.rs +++ b/src/websockets.rs @@ -2,11 +2,15 @@ use crate::errors::Result; use crate::config::Config; use crate::model::{ AccountUpdateEvent, AggrTradesEvent, BalanceUpdateEvent, BookTickerEvent, DayTickerEvent, - WindowTickerEvent, DepthOrderBookEvent, KlineEvent, OrderBook, OrderTradeEvent, TradeEvent, + WindowTickerEvent, DepthOrderBookEvent, ExternalLockUpdateEvent, GenericEvent, KlineEvent, + ListStatusEvent, OrderBook, OrderTradeEvent, OutboundAccountPositionEvent, + SpotBalanceUpdateEvent, TradeEvent, }; +use crate::util::{get_timestamp_now, sign_hmac}; use error_chain::bail; use url::Url; use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; use std::sync::atomic::{AtomicBool, Ordering}; use std::net::TcpStream; @@ -39,7 +43,22 @@ impl WebsocketAPI { pub enum WebsocketEvent { AccountUpdate(AccountUpdateEvent), BalanceUpdate(BalanceUpdateEvent), + /// `executionReport`: order placed, canceled, filled, expired, amended OrderTrade(OrderTradeEvent), + /// `outboundAccountPosition`: balances changed + OutboundAccountPosition(OutboundAccountPositionEvent), + /// `balanceUpdate`: deposit, withdrawal or transfer + SpotBalanceUpdate(SpotBalanceUpdateEvent), + /// `listStatus`: order list (OCO/OTO/...) status change + ListStatus(ListStatusEvent), + /// `externalLockUpdate`: part of the balance locked/unlocked by an external system + ExternalLockUpdate(ExternalLockUpdateEvent), + /// `eventStreamTerminated`: the user data stream subscription was closed + EventStreamTerminated(GenericEvent), + /// `listenKeyExpired`: legacy listen key based stream expired + ListenKeyExpired(GenericEvent), + /// `serverShutdown`: the server will close this connection in about 10 minutes + ServerShutdown(GenericEvent), AggrTrades(AggrTradesEvent), Trade(TradeEvent), OrderBook(OrderBook), @@ -52,11 +71,51 @@ pub enum WebsocketEvent { BookTicker(BookTickerEvent), } +/// Build the `userDataStream.subscribe.signature` request of the Spot WebSocket API. +/// +/// The signature payload is the alphabetically sorted `key=value&...` string of all +/// params (`apiKey`, optional `recvWindow`, `timestamp`), signed with HMAC-SHA256. +pub fn user_data_stream_subscribe_request( + api_key: &str, secret_key: &str, recv_window: u64, timestamp: u64, id: &str, +) -> String { + let mut params: BTreeMap = BTreeMap::new(); + params.insert("apiKey".into(), api_key.to_string()); + if recv_window > 0 { + params.insert("recvWindow".into(), recv_window.to_string()); + } + params.insert("timestamp".into(), timestamp.to_string()); + let payload = params + .iter() + .map(|(k, v)| format!("{}={}", k, v)) + .collect::>() + .join("&"); + let signature = sign_hmac(secret_key, &payload); + + let mut json_params = serde_json::Map::new(); + json_params.insert( + "apiKey".into(), + serde_json::Value::String(api_key.to_string()), + ); + if recv_window > 0 { + json_params.insert("recvWindow".into(), serde_json::Value::from(recv_window)); + } + json_params.insert("timestamp".into(), serde_json::Value::from(timestamp)); + json_params.insert("signature".into(), serde_json::Value::String(signature)); + + serde_json::json!({ + "id": id, + "method": "userDataStream.subscribe.signature", + "params": json_params, + }) + .to_string() +} + pub struct WebSockets<'a> { pub socket: Option<(WebSocket>, Response)>, handler: Box Result<()> + 'a>, } +#[allow(clippy::large_enum_variant)] #[derive(Serialize, Deserialize, Debug)] #[serde(untagged)] enum Events { @@ -98,6 +157,35 @@ impl<'a> WebSockets<'a> { self.connect_wss(&WebsocketAPI::MultiStream.params(&endpoints.join("/"))) } + /// Subscribe to the account's user data stream through the Spot WebSocket API + /// (`userDataStream.subscribe.signature`). + /// + /// This replaces the `listenKey` based `wss://stream.binance.com/ws/` flow, + /// which Binance retired on 2026-02-20. The connection goes to `config.ws_api_endpoint` + /// and works with HMAC API keys; no prior `session.logon` is required. + /// + /// Events arrive wrapped as `{"subscriptionId": n, "event": {...}}` and are unwrapped + /// by [`WebSockets::handle_msg`]. Run [`WebSockets::event_loop`] as usual afterwards. + pub fn connect_user_data_stream( + &mut self, api_key: &str, secret_key: &str, config: &Config, + ) -> Result<()> { + self.connect_wss(&config.ws_api_endpoint)?; + let timestamp = get_timestamp_now()?; + let id = uuid::Uuid::new_v4().to_string(); + let request = user_data_stream_subscribe_request( + api_key, + secret_key, + config.recv_window, + timestamp, + &id, + ); + if let Some(ref mut socket) = self.socket { + socket.0.write_message(Message::Text(request))?; + return Ok(()); + } + bail!("Not connected"); + } + fn connect_wss(&mut self, wss: &str) -> Result<()> { let url = Url::parse(wss)?; match connect(url) { @@ -124,11 +212,66 @@ impl<'a> WebSockets<'a> { pub fn handle_msg(&mut self, msg: &str) -> Result<()> { let value: serde_json::Value = serde_json::from_str(msg)?; + // Combined stream payload: {"stream": "...", "data": {...}} if let Some(data) = value.get("data") { self.handle_msg(&data.to_string())?; return Ok(()); } + // WebSocket API user data stream payload: {"subscriptionId": 0, "event": {...}} + if let Some(event) = value.get("event") { + self.handle_msg(&event.to_string())?; + return Ok(()); + } + + // WebSocket API response to one of our requests: {"id": ..., "status": 200, ...} + if let (Some(id), Some(status)) = (value.get("id"), value.get("status")) { + if status.as_u64() != Some(200) { + bail!(format!( + "WebSocket API request {} failed: {}", + id, + value.get("error").cloned().unwrap_or_default() + )); + } + return Ok(()); + } + + // User data stream events are dispatched by name: several of them share the same + // shape, which an untagged enum cannot tell apart. + if let Some(event_type) = value.get("e").and_then(|e| e.as_str()) { + let action = match event_type { + "executionReport" => Some(WebsocketEvent::OrderTrade(serde_json::from_value( + value.clone(), + )?)), + "outboundAccountPosition" => Some(WebsocketEvent::OutboundAccountPosition( + serde_json::from_value(value.clone())?, + )), + "balanceUpdate" => Some(WebsocketEvent::SpotBalanceUpdate(serde_json::from_value( + value.clone(), + )?)), + "listStatus" => Some(WebsocketEvent::ListStatus(serde_json::from_value( + value.clone(), + )?)), + "externalLockUpdate" => Some(WebsocketEvent::ExternalLockUpdate( + serde_json::from_value(value.clone())?, + )), + "eventStreamTerminated" => Some(WebsocketEvent::EventStreamTerminated( + serde_json::from_value(value.clone())?, + )), + "listenKeyExpired" => Some(WebsocketEvent::ListenKeyExpired( + serde_json::from_value(value.clone())?, + )), + "serverShutdown" => Some(WebsocketEvent::ServerShutdown(serde_json::from_value( + value.clone(), + )?)), + _ => None, + }; + if let Some(action) = action { + (self.handler)(action)?; + return Ok(()); + } + } + if let Ok(events) = serde_json::from_value::(value) { let action = match events { Events::DayTickerEventAll(v) => WebsocketEvent::DayTickerAll(v), diff --git a/tests/account_tests.rs b/tests/account_tests.rs index 190e3e26..3e88e3fe 100755 --- a/tests/account_tests.rs +++ b/tests/account_tests.rs @@ -909,4 +909,394 @@ mod tests { assert!(!history.is_maker); assert!(history.is_best_match); } + + #[test] + fn get_account_with_params_parses_new_fields() { + let mut server = Server::new(); + let mock = server + .mock("GET", "/api/v3/account") + .with_header("content-type", "application/json;charset=UTF-8") + .match_query(Matcher::Regex( + "omitZeroBalances=true&recvWindow=1234×tamp=\\d+&signature=.*".into(), + )) + .with_body_from_file("tests/mocks/account/get_account_full.json") + .create(); + + let config = Config::default() + .set_rest_api_endpoint(server.url()) + .set_recv_window(1234); + let account: Account = Binance::new_with_config(None, None, &config); + let info = account.get_account_with_params(true).unwrap(); + mock.assert(); + + let rates = info.commission_rates.unwrap(); + assert!(approx_eq!(f64, rates.maker, 0.0015, ulps = 2)); + assert_eq!(info.brokered, Some(false)); + assert_eq!(info.account_type.as_deref(), Some("SPOT")); + assert_eq!(info.permissions, vec!["SPOT"]); + assert_eq!(info.uid, Some(354937868)); + assert_eq!(info.balances.len(), 1); + } + + #[test] + fn account_commission_filters_and_rate_limits() { + let mut server = Server::new(); + let m1 = server + .mock("GET", "/api/v3/account/commission") + .match_query(Matcher::Regex( + "recvWindow=1234&symbol=BTCUSDT×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/account/account_commission.json") + .create(); + let m2 = server + .mock("GET", "/api/v3/myFilters") + .match_query(Matcher::Regex( + "recvWindow=1234&symbol=BTCUSDT×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/account/my_filters.json") + .create(); + let m3 = server + .mock("GET", "/api/v3/rateLimit/order") + .match_query(Matcher::Regex("recvWindow=1234×tamp=\\d+".into())) + .with_body_from_file("tests/mocks/account/rate_limit_order.json") + .create(); + + let config = Config::default() + .set_rest_api_endpoint(server.url()) + .set_recv_window(1234); + let account: Account = Binance::new_with_config(None, None, &config); + + let commission = account.get_account_commission("BTCUSDT").unwrap(); + assert_eq!(commission.symbol, "BTCUSDT"); + assert!(approx_eq!( + f64, + commission.standard_commission.taker, + 0.0000002, + ulps = 2 + )); + assert!(approx_eq!( + f64, + commission.special_commission.unwrap().maker, + 0.01, + ulps = 2 + )); + assert_eq!(commission.discount.discount_asset.as_deref(), Some("BNB")); + assert!(approx_eq!( + f64, + commission.discount.discount, + 0.75, + ulps = 2 + )); + + let filters = account.get_my_filters("BTCUSDT").unwrap(); + assert!(matches!( + filters.exchange_filters[0], + Filters::ExchangeMaxNumOrders { + max_num_orders: Some(1000) + } + )); + assert!(matches!( + filters.symbol_filters[0], + Filters::PriceFilter { .. } + )); + match &filters.asset_filters[0] { + Filters::MaxAsset { limit, asset } => { + assert_eq!(limit.as_deref(), Some("100.00000000")); + assert_eq!(asset.as_deref(), Some("BNB")); + } + other => panic!("unexpected {:?}", other), + } + assert_eq!(filters.rate_limits[0].count, Some(321)); + + let limits = account.get_order_rate_limits().unwrap(); + assert_eq!(limits.len(), 2); + assert_eq!(limits[1].interval, "DAY"); + assert_eq!(limits[1].limit, 160000); + + m1.assert(); + m2.assert(); + m3.assert(); + } + + #[test] + fn order_queries_with_new_fields() { + let mut server = Server::new(); + let m1 = server + .mock("GET", "/api/v3/order") + .match_query(Matcher::Regex( + "origClientOrderId=myOrder1&recvWindow=1234&symbol=LTCBTC×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/account/order_full.json") + .create(); + let m2 = server + .mock("GET", "/api/v3/allOrders") + .match_query(Matcher::Regex( + "limit=10&orderId=1&recvWindow=1234&symbol=LTCBTC×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/account/all_orders.json") + .create(); + + let config = Config::default() + .set_rest_api_endpoint(server.url()) + .set_recv_window(1234); + let account: Account = Binance::new_with_config(None, None, &config); + + let order = account + .order_status_with_client_id("LTCBTC", "myOrder1".into()) + .unwrap(); + assert_eq!(order.status, "EXPIRED"); + assert_eq!(order.working_time, Some(1499827319559)); + assert_eq!(order.self_trade_prevention_mode.as_deref(), Some("NONE")); + assert_eq!(order.prevented_quantity, Some(1.2)); + assert_eq!(order.used_sor, Some(true)); + assert_eq!(order.peg_price_type.as_deref(), Some("PRIMARY_PEG")); + assert_eq!(order.pegged_price, Some(87523.8371)); + assert_eq!( + order.expiry_reason.as_deref(), + Some("INSUFFICIENT_LIQUIDITY") + ); + // stopPrice / icebergQty are no longer always present + assert!(approx_eq!(f64, order.stop_price, 0.0, ulps = 2)); + assert_eq!(order.iceberg_qty, ""); + + let orders = account.get_all_orders("LTCBTC", 1, None, None, 10).unwrap(); + assert_eq!(orders.len(), 1); + assert_eq!(orders[0].client_order_id, "myOrder1"); + + m1.assert(); + m2.assert(); + } + + #[test] + fn order_lists() { + let mut server = Server::new(); + let m1 = server + .mock("POST", "/api/v3/orderList/oco") + .match_query(Matcher::AllOf(vec![ + Matcher::UrlEncoded("symbol".into(), "LTCBTC".into()), + Matcher::UrlEncoded("side".into(), "SELL".into()), + Matcher::UrlEncoded("quantity".into(), "5".into()), + Matcher::UrlEncoded("aboveType".into(), "LIMIT_MAKER".into()), + Matcher::UrlEncoded("abovePrice".into(), "3".into()), + Matcher::UrlEncoded("belowType".into(), "STOP_LOSS_LIMIT".into()), + Matcher::UrlEncoded("belowPrice".into(), "1".into()), + Matcher::UrlEncoded("belowStopPrice".into(), "1".into()), + Matcher::UrlEncoded("belowTimeInForce".into(), "GTC".into()), + Matcher::UrlEncoded("belowIcebergQty".into(), "1".into()), + Matcher::UrlEncoded("listClientOrderId".into(), "lH1YDkuQKWiXVXHPSKYEIp".into()), + Matcher::UrlEncoded("selfTradePreventionMode".into(), "EXPIRE_TAKER".into()), + Matcher::Regex(r"timestamp=\d+".into()), + ])) + .with_body_from_file("tests/mocks/account/order_list_oco.json") + .create(); + let m2 = server + .mock("GET", "/api/v3/orderList") + .match_query(Matcher::Regex( + "orderListId=27&recvWindow=1234×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/account/order_list.json") + .create(); + let m3 = server + .mock("GET", "/api/v3/allOrderList") + .match_query(Matcher::Regex( + "limit=3&recvWindow=1234×tamp=\\d+".into(), + )) + .with_body("[]") + .create(); + let m4 = server + .mock("GET", "/api/v3/openOrderList") + .match_query(Matcher::Regex("recvWindow=1234×tamp=\\d+".into())) + .with_body("[]") + .create(); + let m5 = server + .mock("DELETE", "/api/v3/orderList") + .match_query(Matcher::Regex( + "orderListId=0&recvWindow=1234&symbol=LTCBTC×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/account/cancel_order_list.json") + .create(); + + let config = Config::default() + .set_rest_api_endpoint(server.url()) + .set_recv_window(1234); + let account: Account = Binance::new_with_config(None, None, &config); + + let oco = account + .new_oco_order_list(OcoOrderListRequest { + symbol: "LTCBTC".into(), + side: OrderSide::Sell, + quantity: 5.0, + above: OrderListLeg { + order_type: Some(OrderType::LimitMaker), + price: Some(3.0), + ..Default::default() + }, + below: OrderListLeg { + order_type: Some(OrderType::StopLossLimit), + price: Some(1.0), + stop_price: Some(1.0), + time_in_force: Some(TimeInForce::GTC), + iceberg_qty: Some(1.0), + ..Default::default() + }, + list_client_order_id: Some("lH1YDkuQKWiXVXHPSKYEIp".into()), + new_order_resp_type: None, + self_trade_prevention_mode: Some(SelfTradePreventionMode::ExpireTaker), + }) + .unwrap(); + assert_eq!(oco.order_list_id, 1); + assert_eq!(oco.contingency_type, "OCO"); + assert_eq!(oco.orders.len(), 2); + let reports = oco.order_reports.unwrap(); + assert_eq!(reports[0].type_name.as_deref(), Some("STOP_LOSS_LIMIT")); + assert_eq!(reports[0].stop_price, Some(1.0)); + assert_eq!(reports[1].type_name.as_deref(), Some("LIMIT_MAKER")); + + let list = account.get_order_list(27).unwrap(); + assert_eq!(list.list_client_order_id, "h2USkA5YQpaXHPIrkd96xE"); + assert!(list.order_reports.is_none()); + + assert!( + account + .get_all_order_lists(None, None, None, 3) + .unwrap() + .is_empty() + ); + assert!(account.get_open_order_lists().unwrap().is_empty()); + + let canceled = account.cancel_order_list("LTCBTC", 0, None).unwrap(); + assert_eq!(canceled.list_status_type, "ALL_DONE"); + let reports = canceled.order_reports.unwrap(); + assert_eq!(reports[0].status.as_deref(), Some("CANCELED")); + assert_eq!( + reports[0].orig_client_order_id.as_deref(), + Some("pO9ufTiFGg3nw2fOdgeOXa") + ); + + for m in [m1, m2, m3, m4, m5] { + m.assert(); + } + } + + #[test] + fn cancel_replace_and_amend() { + let mut server = Server::new(); + let m1 = server + .mock("POST", "/api/v3/order/cancelReplace") + .match_query(Matcher::AllOf(vec![ + Matcher::UrlEncoded("symbol".into(), "BTCUSDT".into()), + Matcher::UrlEncoded("side".into(), "BUY".into()), + Matcher::UrlEncoded("type".into(), "LIMIT".into()), + Matcher::UrlEncoded("cancelReplaceMode".into(), "STOP_ON_FAILURE".into()), + Matcher::UrlEncoded("cancelOrderId".into(), "9".into()), + Matcher::UrlEncoded("timeInForce".into(), "GTC".into()), + Matcher::UrlEncoded("quantity".into(), "0.04".into()), + Matcher::UrlEncoded("price".into(), "0.02".into()), + Matcher::UrlEncoded("newClientOrderId".into(), "wOceeeOzNORyLiQfw7jd8S".into()), + Matcher::UrlEncoded("orderRateLimitExceededMode".into(), "CANCEL_ONLY".into()), + Matcher::Regex(r"timestamp=\d+".into()), + ])) + .with_body_from_file("tests/mocks/account/cancel_replace.json") + .create(); + let m2 = server + .mock("PUT", "/api/v3/order/amend/keepPriority") + .match_query(Matcher::Regex( + "newQty=5&orderId=60&recvWindow=1234&symbol=BTCUSDT×tamp=\\d+&signature=.*" + .into(), + )) + .with_body_from_file("tests/mocks/account/amend_keep_priority.json") + .create(); + + let config = Config::default() + .set_rest_api_endpoint(server.url()) + .set_recv_window(1234); + let account: Account = Binance::new_with_config(None, None, &config); + + let result = account + .cancel_replace_order(CancelReplaceRequest { + symbol: "BTCUSDT".into(), + side: OrderSide::Buy, + order_type: OrderType::Limit, + cancel_replace_mode: CancelReplaceMode::StopOnFailure, + cancel_order_id: Some(9), + cancel_orig_client_order_id: None, + cancel_new_client_order_id: None, + time_in_force: Some(TimeInForce::GTC), + quantity: Some(0.04), + quote_order_qty: None, + price: Some(0.02), + new_client_order_id: Some("wOceeeOzNORyLiQfw7jd8S".into()), + stop_price: None, + trailing_delta: None, + iceberg_qty: None, + strategy_id: None, + strategy_type: None, + new_order_resp_type: None, + self_trade_prevention_mode: None, + cancel_restrictions: None, + order_rate_limit_exceeded_mode: Some("CANCEL_ONLY".into()), + }) + .unwrap(); + assert_eq!(result.cancel_result, "SUCCESS"); + assert_eq!(result.new_order_result, "SUCCESS"); + match result.cancel_response.unwrap() { + CancelReplaceOutcome::Order(o) => assert_eq!(o.order_id, Some(9)), + other => panic!("unexpected {:?}", other), + } + match result.new_order_response.unwrap() { + CancelReplaceOutcome::Order(o) => { + assert_eq!(o.order_id, Some(10)); + assert_eq!(o.status.as_deref(), Some("NEW")); + } + other => panic!("unexpected {:?}", other), + } + + let amended = account + .amend_order_keep_priority("BTCUSDT", 60, None, 5.0, None) + .unwrap(); + assert_eq!(amended.execution_id, 75); + assert_eq!(amended.amended_order.order_id, 60); + assert!(approx_eq!(f64, amended.amended_order.qty, 5.0, ulps = 2)); + + m1.assert(); + m2.assert(); + } + + #[test] + fn cancel_replace_partial_failure_is_typed() { + let json = + std::fs::read_to_string("tests/mocks/account/cancel_replace_partial_failure.json") + .unwrap(); + let result: CancelReplaceResponse = serde_json::from_str(&json).unwrap(); + assert_eq!(result.new_order_result, "FAILURE"); + match result.new_order_response.unwrap() { + CancelReplaceOutcome::Error { code, msg } => { + assert_eq!(code, -2010); + assert!(msg.contains("immediately match")); + } + other => panic!("unexpected {:?}", other), + } + } + + #[test] + fn trade_history_with_params() { + let mut server = Server::new(); + let mock = server + .mock("GET", "/api/v3/myTrades") + .match_query(Matcher::Regex( + "endTime=20&limit=5&orderId=3&recvWindow=1234&startTime=10&symbol=BTCUSDT×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/account/trade_history.json") + .create(); + + let config = Config::default() + .set_rest_api_endpoint(server.url()) + .set_recv_window(1234); + let account: Account = Binance::new_with_config(None, None, &config); + let trades = account + .trade_history_with_params("BTCUSDT", 3, 10, 20, None, 5) + .unwrap(); + mock.assert(); + assert_eq!(trades.len(), 1); + } } diff --git a/tests/futures_account_tests.rs b/tests/futures_account_tests.rs index 3ff32f84..176cecb4 100644 --- a/tests/futures_account_tests.rs +++ b/tests/futures_account_tests.rs @@ -8,7 +8,7 @@ mod tests { use mockito::{Server, Matcher}; use float_cmp::*; use binance::account::OrderSide; - use binance::futures::model::Transaction; + use binance::futures::model::{AlgoOrder, BatchCancelResponse, BatchOrderResponse, Transaction}; #[test] fn change_initial_leverage() { @@ -136,21 +136,21 @@ mod tests { #[test] fn stop_market_close_buy() { let mut server = Server::new(); - let mock_stop_market_close_sell = server - .mock("POST", "/fapi/v1/order") + let mock = server + .mock("POST", "/fapi/v1/algoOrder") .with_header("content-type", "application/json;charset=UTF-8") - // .match_query(Matcher::Regex("closePosition=TRUE&recvWindow=1234&side=BUY&stopPrice=10.5&symbol=SRMUSDT×tamp=\\d+&type=STOP_MARKET&newClientOrderId=\\[A-Za-z0-9-]+".into())) .match_query(Matcher::AllOf(vec![ + Matcher::UrlEncoded("algoType".into(), "CONDITIONAL".into()), Matcher::UrlEncoded("symbol".into(), "SRMUSDT".into()), Matcher::UrlEncoded("side".into(), "BUY".into()), - Matcher::Regex(r"newClientOrderId=x-Cb7ytekJ[A-Za-z0-9]+".into()), + Matcher::Regex(r"clientAlgoId=x-Cb7ytekJ[A-Za-z0-9]+".into()), Matcher::UrlEncoded("type".into(), "STOP_MARKET".into()), Matcher::Regex(r"timestamp=\d+".into()), - Matcher::Regex(r"stopPrice=10.5".into()), - Matcher::Regex(r"closePosition=TRUE".into()), + Matcher::UrlEncoded("triggerPrice".into(), "10.5".into()), + Matcher::UrlEncoded("closePosition".into(), "TRUE".into()), Matcher::UrlEncoded("recvWindow".into(), "1234".into()), ])) - .with_body_from_file("tests/mocks/futures/account/stop_market_close_position_buy.json") + .with_body_from_file("tests/mocks/futures/account/new_algo_order.json") .create(); let config = Config::default() @@ -158,35 +158,38 @@ mod tests { .set_recv_window(1234); let account: FuturesAccount = Binance::new_with_config(None, None, &config); let _ = env_logger::try_init(); - let transaction: Transaction = account.stop_market_close_buy("SRMUSDT", 10.5).unwrap(); + let algo: AlgoOrder = account.stop_market_close_buy("SRMUSDT", 10.5).unwrap(); - mock_stop_market_close_sell.assert(); + mock.assert(); - assert_eq!(transaction.symbol, "SRMUSDT"); - assert_eq!(transaction.side, "BUY"); - assert_eq!(transaction.orig_type, "STOP_MARKET"); - assert!(transaction.close_position); - assert!(approx_eq!(f64, transaction.stop_price, 10.5, ulps = 2)); + assert_eq!(algo.algo_id, 2146760); + assert_eq!(algo.symbol, "SRMUSDT"); + assert_eq!(algo.order_type, "STOP_MARKET"); + assert_eq!(algo.algo_status, "NEW"); + assert!(algo.close_position); + assert!(approx_eq!(f64, algo.trigger_price, 7.4, ulps = 2)); + assert_eq!(algo.activate_price, None); + assert_eq!(algo.iceberg_quantity, None); } #[test] fn stop_market_close_sell() { let mut server = Server::new(); - let mock_stop_market_close_sell = server - .mock("POST", "/fapi/v1/order") + let mock = server + .mock("POST", "/fapi/v1/algoOrder") .with_header("content-type", "application/json;charset=UTF-8") - // .match_query(Matcher::Regex("closePosition=TRUE&recvWindow=1234&side=SELL&stopPrice=7.4&symbol=SRMUSDT×tamp=\\d+&type=STOP_MARKET".into())) .match_query(Matcher::AllOf(vec![ - Matcher::Regex(r"closePosition=TRUE".into()), + Matcher::UrlEncoded("algoType".into(), "CONDITIONAL".into()), + Matcher::UrlEncoded("closePosition".into(), "TRUE".into()), Matcher::UrlEncoded("recvWindow".into(), "1234".into()), Matcher::UrlEncoded("side".into(), "SELL".into()), - Matcher::Regex(r"stopPrice=7.4".into()), + Matcher::UrlEncoded("triggerPrice".into(), "7.4".into()), Matcher::UrlEncoded("symbol".into(), "SRMUSDT".into()), Matcher::Regex(r"timestamp=\d+".into()), Matcher::UrlEncoded("type".into(), "STOP_MARKET".into()), - Matcher::Regex(r"newClientOrderId=x-Cb7ytekJ[A-Za-z0-9]+".into()), + Matcher::Regex(r"clientAlgoId=x-Cb7ytekJ[A-Za-z0-9]+".into()), ])) - .with_body_from_file("tests/mocks/futures/account/stop_market_close_position_sell.json") + .with_body_from_file("tests/mocks/futures/account/new_algo_order.json") .create(); let config = Config::default() @@ -194,35 +197,35 @@ mod tests { .set_recv_window(1234); let account: FuturesAccount = Binance::new_with_config(None, None, &config); let _ = env_logger::try_init(); - let transaction: Transaction = account.stop_market_close_sell("SRMUSDT", 7.4).unwrap(); + let algo: AlgoOrder = account.stop_market_close_sell("SRMUSDT", 7.4).unwrap(); - mock_stop_market_close_sell.assert(); + mock.assert(); - assert_eq!(transaction.symbol, "SRMUSDT"); - assert_eq!(transaction.side, "SELL"); - assert_eq!(transaction.orig_type, "STOP_MARKET"); - assert!(transaction.close_position); - assert!(approx_eq!(f64, transaction.stop_price, 7.4, ulps = 2)); + assert_eq!(algo.side, "SELL"); + assert_eq!(algo.client_algo_id, "6B2I9XVcJpCjqPAJ4YoFX7"); + assert!(algo.reduce_only); } #[test] - fn custom_order() { + fn custom_algo_order() { let mut server = Server::new(); - let mock_custom_order = server - .mock("POST", "/fapi/v1/order") + let mock = server + .mock("POST", "/fapi/v1/algoOrder") .with_header("content-type", "application/json;charset=UTF-8") - // .match_query(Matcher::Regex("newClientOrderId=myId&closePosition=TRUE&recvWindow=1234&side=SELL&stopPrice=7.4&symbol=SRMUSDT×tamp=\\d+&type=STOP_MARKET".into())) .match_query(Matcher::AllOf(vec![ - Matcher::UrlEncoded("newClientOrderId".into(), "myId".into()), + Matcher::UrlEncoded("algoType".into(), "CONDITIONAL".into()), + Matcher::UrlEncoded("clientAlgoId".into(), "myAlgoId".into()), Matcher::UrlEncoded("closePosition".into(), "TRUE".into()), Matcher::UrlEncoded("recvWindow".into(), "1234".into()), Matcher::UrlEncoded("side".into(), "SELL".into()), - Matcher::UrlEncoded("stopPrice".into(), "7.4".into()), + Matcher::UrlEncoded("triggerPrice".into(), "7.4".into()), + Matcher::UrlEncoded("workingType".into(), "MARK_PRICE".into()), + Matcher::UrlEncoded("priceProtect".into(), "TRUE".into()), Matcher::UrlEncoded("symbol".into(), "SRMUSDT".into()), Matcher::Regex(r"timestamp=\d+".into()), Matcher::UrlEncoded("type".into(), "STOP_MARKET".into()), ])) - .with_body_from_file("tests/mocks/futures/account/stop_market_close_position_sell.json") + .with_body_from_file("tests/mocks/futures/account/new_algo_order.json") .create(); let config = Config::default() @@ -230,36 +233,595 @@ mod tests { .set_recv_window(1234); let account: FuturesAccount = Binance::new_with_config(None, None, &config); let _ = env_logger::try_init(); - let custom_order = CustomOrderRequest { - algo_type: AlgoType::Conditional, - client_algo_id: Some("myAlgoId".into()), - symbol: "SRMUSDT".into(), - side: OrderSide::Sell, - position_side: None, - order_type: OrderType::StopMarket, - time_in_force: None, - qty: None, - reduce_only: None, - price: None, - stop_price: Some(7.4), - close_position: Some(true), - activation_price: None, - callback_rate: None, - working_type: None, - price_protect: None, - new_client_order_id: Some("myId".into()), - good_till_date: None, - - }; - let transaction: Transaction = account.custom_order(custom_order).unwrap(); + let mut order = CustomOrderRequest::new("SRMUSDT", OrderSide::Sell, OrderType::StopMarket); + order.stop_price = Some(7.4); + order.close_position = Some(true); + order.working_type = Some(WorkingType::MarkPrice); + order.price_protect = Some(true); + order.client_algo_id = Some("myAlgoId".into()); + let algo: AlgoOrder = account.custom_algo_order(order).unwrap(); + + mock.assert(); + assert_eq!(algo.symbol, "SRMUSDT"); + assert_eq!(algo.algo_type, "CONDITIONAL"); + } + + #[test] + fn custom_order_rejects_conditional_types_locally() { + let config = Config::default().set_recv_window(1234); + let account: FuturesAccount = Binance::new_with_config(None, None, &config); + let mut order = CustomOrderRequest::new("BTCUSDT", OrderSide::Sell, OrderType::TakeProfit); + order.stop_price = Some(7.4); + let err = account.custom_order(order).unwrap_err(); + assert!(err.to_string().contains("custom_algo_order"), "{}", err); + + let limit = CustomOrderRequest::new("BTCUSDT", OrderSide::Sell, OrderType::Limit); + let err = account.custom_algo_order(limit).unwrap_err(); + assert!(err.to_string().contains("custom_order"), "{}", err); + } + + #[test] + fn custom_order_limit() { + let mut server = Server::new(); + let mock = server + .mock("POST", "/fapi/v1/order") + .with_header("content-type", "application/json;charset=UTF-8") + .match_query(Matcher::AllOf(vec![ + Matcher::UrlEncoded("symbol".into(), "BTCUSDT".into()), + Matcher::UrlEncoded("side".into(), "BUY".into()), + Matcher::UrlEncoded("type".into(), "LIMIT".into()), + Matcher::UrlEncoded("timeInForce".into(), "GTD".into()), + Matcher::UrlEncoded("goodTillDate".into(), "1693207680000".into()), + Matcher::UrlEncoded("quantity".into(), "10".into()), + Matcher::UrlEncoded("price".into(), "30000".into()), + Matcher::UrlEncoded("priceMatch".into(), "QUEUE_5".into()), + Matcher::UrlEncoded("selfTradePreventionMode".into(), "EXPIRE_BOTH".into()), + Matcher::UrlEncoded("newClientOrderId".into(), "testOrder".into()), + Matcher::Regex(r"timestamp=\d+".into()), + ])) + .with_body_from_file("tests/mocks/futures/account/limit_order.json") + .create(); + + let config = Config::default() + .set_futures_rest_api_endpoint(server.url()) + .set_recv_window(1234); + let account: FuturesAccount = Binance::new_with_config(None, None, &config); + let mut order = CustomOrderRequest::new("BTCUSDT", OrderSide::Buy, OrderType::Limit); + order.time_in_force = Some(TimeInForce::GTD); + order.good_till_date = Some(1693207680000); + order.qty = Some(10.0); + order.price = Some(30000.0); + order.price_match = Some(PriceMatch::Queue5); + order.self_trade_prevention_mode = Some(SelfTradePreventionMode::ExpireBoth); + order.new_client_order_id = Some("testOrder".into()); + let transaction: Transaction = account.custom_order(order).unwrap(); + + mock.assert(); + assert_eq!(transaction.order_id, 22542179); + assert_eq!(transaction.price, Some(30000.0)); + assert_eq!(transaction.price_match.as_deref(), Some("NONE")); + assert_eq!( + transaction.self_trade_prevention_mode.as_deref(), + Some("EXPIRE_MAKER") + ); + assert_eq!(transaction.good_till_date, Some(0)); + } + + #[test] + fn custom_batch_orders() { + let mut server = Server::new(); + let mock = server + .mock("POST", "/fapi/v1/batchOrders") + .with_header("content-type", "application/json;charset=UTF-8") + .match_query(Matcher::AllOf(vec![ + Matcher::UrlEncoded( + "batchOrders".into(), + r#"[{"newClientOrderId":"a","price":"30000","quantity":"1","side":"BUY","symbol":"BTCUSDT","timeInForce":"GTC","type":"LIMIT"},{"newClientOrderId":"b","quantity":"2","reduceOnly":"TRUE","side":"SELL","symbol":"ETHUSDT","type":"MARKET"}]"#.into(), + ), + Matcher::UrlEncoded("recvWindow".into(), "1234".into()), + Matcher::Regex(r"timestamp=\d+".into()), + ])) + .with_body_from_file("tests/mocks/futures/account/batch_orders.json") + .create(); + + let config = Config::default() + .set_futures_rest_api_endpoint(server.url()) + .set_recv_window(1234); + let account: FuturesAccount = Binance::new_with_config(None, None, &config); + let mut first = CustomOrderRequest::new("BTCUSDT", OrderSide::Buy, OrderType::Limit); + first.time_in_force = Some(TimeInForce::GTC); + first.qty = Some(1.0); + first.price = Some(30000.0); + first.new_client_order_id = Some("a".into()); + let mut second = CustomOrderRequest::new("ETHUSDT", OrderSide::Sell, OrderType::Market); + second.qty = Some(2.0); + second.reduce_only = Some(true); + second.new_client_order_id = Some("b".into()); + let responses = account.custom_batch_orders(vec![first, second]).unwrap(); + + mock.assert(); + assert_eq!(responses.len(), 2); + match &responses[0] { + BatchOrderResponse::Order(t) => assert_eq!(t.order_id, 22542179), + other => panic!("unexpected {:?}", other), + } + match &responses[1] { + BatchOrderResponse::Error { code, msg } => { + assert_eq!(*code, -2022); + assert_eq!(msg, "ReduceOnly Order is rejected."); + } + other => panic!("unexpected {:?}", other), + } + } + + #[test] + fn custom_batch_orders_validation() { + let config = Config::default(); + let account: FuturesAccount = Binance::new_with_config(None, None, &config); + assert!(account.custom_batch_orders(vec![]).is_err()); + let mut stop = CustomOrderRequest::new("BTCUSDT", OrderSide::Sell, OrderType::StopMarket); + stop.stop_price = Some(1.0); + assert!(account.custom_batch_orders(vec![stop]).is_err()); + } + + #[test] + fn cancel_batch_orders() { + let mut server = Server::new(); + let mock = server + .mock("DELETE", "/fapi/v1/batchOrders") + .with_header("content-type", "application/json;charset=UTF-8") + .match_query(Matcher::AllOf(vec![ + Matcher::UrlEncoded("symbol".into(), "BTCUSDT".into()), + Matcher::UrlEncoded("orderIdList".into(), "[283194212,1]".into()), + Matcher::Regex(r"timestamp=\d+".into()), + ])) + .with_body_from_file("tests/mocks/futures/account/cancel_batch_orders.json") + .create(); + + let config = Config::default() + .set_futures_rest_api_endpoint(server.url()) + .set_recv_window(1234); + let account: FuturesAccount = Binance::new_with_config(None, None, &config); + let responses = account + .cancel_batch_orders("BTCUSDT", &[283194212, 1]) + .unwrap(); + + mock.assert(); + assert_eq!(responses.len(), 2); + assert!(matches!(&responses[0], BatchCancelResponse::Order(o) if o.order_id == 283194212)); + assert!(matches!( + &responses[1], + BatchCancelResponse::Error { code: -2011, .. } + )); + } + + #[test] + fn modify_order() { + let mut server = Server::new(); + let mock = server + .mock("PUT", "/fapi/v1/order") + .with_header("content-type", "application/json;charset=UTF-8") + .match_query(Matcher::AllOf(vec![ + Matcher::UrlEncoded("symbol".into(), "BTCUSDT".into()), + Matcher::UrlEncoded("side".into(), "BUY".into()), + Matcher::UrlEncoded("orderId".into(), "20072994037".into()), + Matcher::UrlEncoded("quantity".into(), "1".into()), + Matcher::UrlEncoded("price".into(), "30005".into()), + Matcher::UrlEncoded("modifyId".into(), "1".into()), + Matcher::UrlEncoded("reduceOnly".into(), "false".into()), + Matcher::Regex(r"timestamp=\d+&signature=.*".into()), + ])) + .with_body_from_file("tests/mocks/futures/account/modify_order.json") + .create(); + + let config = Config::default() + .set_futures_rest_api_endpoint(server.url()) + .set_recv_window(1234); + let account: FuturesAccount = Binance::new_with_config(None, None, &config); + let modified = account + .modify_order(ModifyOrderRequest { + symbol: "BTCUSDT".into(), + side: OrderSide::Buy, + order_id: Some(20072994037), + orig_client_order_id: None, + quantity: 1.0, + price: Some(30005.0), + price_match: None, + modify_id: Some(1), + reduce_only: Some(false), + }) + .unwrap(); + + mock.assert(); + assert_eq!(modified.order_id, 20072994037); + assert_eq!(modified.modify_id, Some(1)); + assert!(approx_eq!(f64, modified.price, 30005.0, ulps = 2)); + assert_eq!(modified.position_side, "LONG"); + } - mock_custom_order.assert(); + #[test] + fn order_status() { + let mut server = Server::new(); + let mock = server + .mock("GET", "/fapi/v1/order") + .with_header("content-type", "application/json;charset=UTF-8") + .match_query(Matcher::Regex( + "orderId=1573346959&recvWindow=1234&symbol=BTCUSDT×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/futures/account/query_order.json") + .create(); + + let config = Config::default() + .set_futures_rest_api_endpoint(server.url()) + .set_recv_window(1234); + let account: FuturesAccount = Binance::new_with_config(None, None, &config); + let order = account.order_status("BTCUSDT", 1573346959).unwrap(); + + mock.assert(); + assert_eq!(order.order_id, 1573346959); + assert_eq!(order.time, Some(1579276756075)); + assert_eq!(order.price_match.as_deref(), Some("NONE")); + assert_eq!(order.good_till_date, Some(0)); + assert!(approx_eq!(f64, order.activation_price, 9020.0, ulps = 2)); + } + + #[test] + fn algo_order_queries() { + let mut server = Server::new(); + let mock_get = server + .mock("GET", "/fapi/v1/algoOrder") + .with_header("content-type", "application/json;charset=UTF-8") + .match_query(Matcher::Regex( + "algoId=2146760&recvWindow=1234×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/futures/account/query_algo_order.json") + .create(); + let mock_open = server + .mock("GET", "/fapi/v1/openAlgoOrders") + .with_header("content-type", "application/json;charset=UTF-8") + .match_query(Matcher::Regex( + "algoType=CONDITIONAL&recvWindow=1234&symbol=BTCUSDT×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/futures/account/open_algo_orders.json") + .create(); + let mock_all = server + .mock("GET", "/fapi/v1/allAlgoOrders") + .with_header("content-type", "application/json;charset=UTF-8") + .match_query(Matcher::Regex( + "limit=5&recvWindow=1234&symbol=BTCUSDT×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/futures/account/open_algo_orders.json") + .create(); + let mock_cancel = server + .mock("DELETE", "/fapi/v1/algoOrder") + .with_header("content-type", "application/json;charset=UTF-8") + .match_query(Matcher::Regex( + "clientAlgoId=myAlgo1&recvWindow=1234×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/futures/account/cancel_algo_order.json") + .create(); + let mock_cancel_all = server + .mock("DELETE", "/fapi/v1/algoOpenOrders") + .with_header("content-type", "application/json;charset=UTF-8") + .match_query(Matcher::Regex( + "recvWindow=1234&symbol=BTCUSDT×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/futures/account/cancel_all_algo_open_orders.json") + .create(); + + let config = Config::default() + .set_futures_rest_api_endpoint(server.url()) + .set_recv_window(1234); + let account: FuturesAccount = Binance::new_with_config(None, None, &config); + + let algo = account.get_algo_order(2146760).unwrap(); + assert_eq!(algo.algo_status, "CANCELED"); + assert_eq!(algo.actual_type.as_deref(), Some("LIMIT")); + assert_eq!(algo.actual_qty, Some(0.01)); + assert_eq!(algo.actual_order_id.as_deref(), Some("")); + + let open = account + .get_open_algo_orders(Some("BTCUSDT".to_string())) + .unwrap(); + assert_eq!(open.len(), 1); + assert_eq!(open[0].order_type, "TRAILING_STOP_MARKET"); + assert_eq!(open[0].working_type, "MARK_PRICE"); + assert_eq!(open[0].tp_trigger_price, None); + + let all = account + .get_all_algo_orders("BTCUSDT", None, None, None, 5) + .unwrap(); + assert_eq!(all.len(), 1); + + let canceled = account.cancel_algo_order_with_client_id("myAlgo1").unwrap(); + assert_eq!(canceled.algo_id, 2146760); + assert_eq!(canceled.code, 200); + + let canceled_all = account.cancel_all_open_algo_orders("BTCUSDT").unwrap(); + assert_eq!(canceled_all.code, 200); + + mock_get.assert(); + mock_open.assert(); + mock_all.assert(); + mock_cancel.assert(); + mock_cancel_all.assert(); + } + + #[test] + fn v3_account_endpoints() { + let mut server = Server::new(); + let mock_position = server + .mock("GET", "/fapi/v3/positionRisk") + .with_header("content-type", "application/json;charset=UTF-8") + .match_query(Matcher::Regex( + "recvWindow=1234&symbol=ADAUSDT×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/futures/account/position_risk_v3.json") + .create(); + let mock_account = server + .mock("GET", "/fapi/v3/account") + .with_header("content-type", "application/json;charset=UTF-8") + .match_query(Matcher::Regex("recvWindow=1234×tamp=\\d+".into())) + .with_body_from_file("tests/mocks/futures/account/account_information_v3.json") + .create(); + let mock_balance = server + .mock("GET", "/fapi/v3/balance") + .with_header("content-type", "application/json;charset=UTF-8") + .match_query(Matcher::Regex("recvWindow=1234×tamp=\\d+".into())) + .with_body_from_file("tests/mocks/futures/account/balance_v3.json") + .create(); + + let config = Config::default() + .set_futures_rest_api_endpoint(server.url()) + .set_recv_window(1234); + let account: FuturesAccount = Binance::new_with_config(None, None, &config); + + let positions = account + .position_information_v3(Some("ADAUSDT".to_string())) + .unwrap(); + assert_eq!(positions.len(), 1); + assert_eq!(positions[0].symbol, "ADAUSDT"); + assert!(approx_eq!( + f64, + positions[0].break_even_price, + 0.385077, + ulps = 2 + )); + assert_eq!(positions[0].adl, 2); + assert_eq!(positions[0].margin_asset, "USDT"); + + let info = account.account_information_v3().unwrap(); + assert!(approx_eq!( + f64, + info.total_wallet_balance, + 126.72469206, + ulps = 2 + )); + assert_eq!(info.assets[0].asset, "USDT"); + assert_eq!(info.positions[0].symbol, "BTCUSDT"); + assert!(approx_eq!( + f64, + info.positions[0].position_amount, + 1.0, + ulps = 2 + )); + + let balances = account.account_balance_v3().unwrap(); + assert_eq!(balances[0].asset, "USDT"); + assert!(balances[0].margin_available); + + mock_position.assert(); + mock_account.assert(); + mock_balance.assert(); + } + + #[test] + fn config_endpoints() { + let mut server = Server::new(); + let m1 = server + .mock("GET", "/fapi/v1/symbolConfig") + .match_query(Matcher::Regex( + "recvWindow=1234&symbol=BTCUSDT×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/futures/account/symbol_config.json") + .create(); + let m2 = server + .mock("GET", "/fapi/v1/accountConfig") + .match_query(Matcher::Any) + .with_body_from_file("tests/mocks/futures/account/account_config.json") + .create(); + let m3 = server + .mock("GET", "/fapi/v1/commissionRate") + .match_query(Matcher::Regex( + "recvWindow=1234&symbol=BTCUSDT×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/futures/account/commission_rate.json") + .create(); + let m4 = server + .mock("GET", "/fapi/v1/leverageBracket") + .match_query(Matcher::Regex( + "recvWindow=1234&symbol=ETHUSDT×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/futures/account/leverage_bracket.json") + .create(); + let m5 = server + .mock("GET", "/fapi/v1/positionSide/dual") + .match_query(Matcher::Any) + .with_body_from_file("tests/mocks/futures/account/position_mode.json") + .create(); + let m6 = server + .mock("GET", "/fapi/v1/multiAssetsMargin") + .match_query(Matcher::Any) + .with_body_from_file("tests/mocks/futures/account/multi_assets_margin.json") + .create(); + let m7 = server + .mock("POST", "/fapi/v1/multiAssetsMargin") + .match_query(Matcher::Regex( + "multiAssetsMargin=true&recvWindow=1234×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/futures/account/code_msg.json") + .create(); + let m8 = server + .mock("GET", "/fapi/v1/feeBurn") + .match_query(Matcher::Any) + .with_body_from_file("tests/mocks/futures/account/fee_burn.json") + .create(); + let m9 = server + .mock("POST", "/fapi/v1/feeBurn") + .match_query(Matcher::Regex( + "feeBurn=false&recvWindow=1234×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/futures/account/code_msg.json") + .create(); + let m10 = server + .mock("GET", "/fapi/v1/adlQuantile") + .match_query(Matcher::Any) + .with_body_from_file("tests/mocks/futures/account/adl_quantile.json") + .create(); + let m11 = server + .mock("GET", "/fapi/v1/apiTradingStatus") + .match_query(Matcher::Any) + .with_body_from_file("tests/mocks/futures/account/api_trading_status.json") + .create(); + let m12 = server + .mock("GET", "/fapi/v1/rateLimit/order") + .match_query(Matcher::Any) + .with_body_from_file("tests/mocks/futures/account/rate_limit_order.json") + .create(); + + let config = Config::default() + .set_futures_rest_api_endpoint(server.url()) + .set_recv_window(1234); + let account: FuturesAccount = Binance::new_with_config(None, None, &config); + + let symbol_config = account + .get_symbol_config(Some("BTCUSDT".to_string())) + .unwrap(); + assert_eq!(symbol_config[0].leverage, 21); + assert_eq!(symbol_config[0].margin_type, "CROSSED"); + + let account_config = account.get_account_config().unwrap(); + assert!(account_config.dual_side_position); + assert_eq!(account_config.trade_group_id, -1); + + let commission = account.get_commission_rate("BTCUSDT").unwrap(); + assert!(approx_eq!( + f64, + commission.taker_commission_rate, + 0.0004, + ulps = 2 + )); + assert_eq!(commission.rpi_commission_rate, Some(0.0001)); + + let brackets = account + .get_leverage_brackets(Some("ETHUSDT".to_string())) + .unwrap(); + assert_eq!(brackets[0].notional_coef, Some(1.5)); + assert_eq!(brackets[0].brackets.len(), 2); + assert_eq!(brackets[0].brackets[1].initial_leverage, 50); + + assert!(account.get_position_mode().unwrap().dual_side_position); + assert!( + !account + .get_multi_assets_margin() + .unwrap() + .multi_assets_margin + ); + assert_eq!(account.change_multi_assets_margin(true).unwrap().code, 200); + assert!(account.get_fee_burn().unwrap().fee_burn); + assert_eq!(account.set_fee_burn(false).unwrap().msg, "success"); + + let adl = account.get_adl_quantile(None).unwrap(); + assert_eq!(adl[0].adl_quantile.long, Some(3)); + assert_eq!(adl[0].adl_quantile.hedge, Some(0)); + assert_eq!(adl[1].adl_quantile.both, Some(0)); + + let status = account.get_api_trading_status(None).unwrap(); + assert_eq!(status.indicators["BTCUSDT"][0].indicator, "UFR"); + assert!(status.indicators["BTCUSDT"][0].is_locked); + + let limits = account.get_order_rate_limits().unwrap(); + assert_eq!(limits[1].interval, "MINUTE"); + + for m in [m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12] { + m.assert(); + } + } + + #[test] + fn force_orders_countdown_and_amendments() { + let mut server = Server::new(); + let m1 = server + .mock("GET", "/fapi/v1/forceOrders") + .match_query(Matcher::Regex( + "autoCloseType=LIQUIDATION&limit=10&recvWindow=1234&symbol=BTCUSDT×tamp=\\d+" + .into(), + )) + .with_body_from_file("tests/mocks/futures/account/force_orders.json") + .create(); + let m2 = server + .mock("POST", "/fapi/v1/countdownCancelAll") + .match_query(Matcher::Regex( + "countdownTime=100000&recvWindow=1234&symbol=BTCUSDT×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/futures/account/countdown_cancel_all.json") + .create(); + let m3 = server + .mock("GET", "/fapi/v1/orderAmendment") + .match_query(Matcher::Regex( + "orderId=20072994037&recvWindow=1234&symbol=BTCUSDT×tamp=\\d+".into(), + )) + .with_body_from_file("tests/mocks/futures/account/order_amendment.json") + .create(); + let m4 = server + .mock("GET", "/fapi/v1/positionMargin/history") + .match_query(Matcher::Regex( + "recvWindow=1234&symbol=BTCUSDT×tamp=\\d+&type=1".into(), + )) + .with_body_from_file("tests/mocks/futures/account/position_margin_history.json") + .create(); + + let config = Config::default() + .set_futures_rest_api_endpoint(server.url()) + .set_recv_window(1234); + let account: FuturesAccount = Binance::new_with_config(None, None, &config); + + let force = account + .get_force_orders( + Some("BTCUSDT".to_string()), + Some("LIQUIDATION".to_string()), + None, + None, + 10, + ) + .unwrap(); + assert_eq!(force[0].client_order_id, "autoclose-1596107620040000020"); + assert!(approx_eq!(f64, force[0].avg_price, 10913.21, ulps = 2)); + + let countdown = account.countdown_cancel_all("BTCUSDT", 100000).unwrap(); + assert_eq!(countdown.countdown_time, 100000); + + let amendments = account + .get_order_amendments("BTCUSDT", 20072994037, None, None, None, None) + .unwrap(); + assert_eq!(amendments[0].amendment.count, 3); + assert_eq!(amendments[0].amendment.modify_id, Some(7)); + assert!(approx_eq!( + f64, + amendments[0].amendment.price.after, + 30003.2, + ulps = 2 + )); + + let history = account + .get_position_margin_history("BTCUSDT", 1, None, None, None) + .unwrap(); + assert_eq!(history.len(), 2); + assert_eq!(history[1].position_side, "LONG"); - assert_eq!(transaction.symbol, "SRMUSDT"); - assert_eq!(transaction.side, "SELL"); - assert_eq!(transaction.orig_type, "STOP_MARKET"); - assert!(transaction.close_position); - assert!(approx_eq!(f64, transaction.stop_price, 7.4, ulps = 2)); + for m in [m1, m2, m3, m4] { + m.assert(); + } } #[test] diff --git a/tests/futures_market_test.rs b/tests/futures_market_test.rs index c9e80dc5..19fc44f2 100644 --- a/tests/futures_market_test.rs +++ b/tests/futures_market_test.rs @@ -1,7 +1,9 @@ use binance::api::*; use binance::config::*; use binance::futures::market::FuturesMarket; -use binance::futures::model::OpenInterestHist; +use binance::futures::general::FuturesGeneral; +use binance::futures::account::ContractType; +use binance::futures::model::{Filters, KlineSummaries, OpenInterestHist, Trades}; #[cfg(test)] mod tests { @@ -31,16 +33,262 @@ mod tests { symbol: "BTCUSDT".into(), sum_open_interest: "20403.63700000".into(), sum_open_interest_value: "150570784.07809979".into(), + cmc_circulating_supply: None, timestamp: 1583127900000, }, OpenInterestHist { symbol: "BTCUSDT".into(), sum_open_interest: "20401.36700000".into(), sum_open_interest_value: "149940752.14464448".into(), + cmc_circulating_supply: None, timestamp: 1583128200000, }, ]; assert_eq!(open_interest_hists, expectation); } + + #[test] + fn funding_rate_and_mark_price() { + let mut server = Server::new(); + let m1 = server + .mock("GET", "/fapi/v1/fundingRate") + .match_query(Matcher::Regex("limit=2&symbol=BTCUSDT".into())) + .with_body_from_file("tests/mocks/futures/market/funding_rate.json") + .create(); + let m2 = server + .mock("GET", "/fapi/v1/fundingInfo") + .with_body_from_file("tests/mocks/futures/market/funding_info.json") + .create(); + let m3 = server + .mock("GET", "/fapi/v1/premiumIndex") + .match_query(Matcher::Regex("symbol=BTCUSDT".into())) + .with_body_from_file("tests/mocks/futures/market/mark_price.json") + .create(); + + let config = Config::default().set_futures_rest_api_endpoint(server.url()); + let market: FuturesMarket = Binance::new_with_config(None, None, &config); + + let rates = market + .get_funding_rate_history(Some("BTCUSDT".to_string()), None, None, 2) + .unwrap(); + assert_eq!(rates.len(), 2); + assert_eq!(rates[0].rate_type.as_deref(), Some("Regular")); + assert_eq!(rates[0].funding_rate, 0.0001); + + let info = market.get_funding_info().unwrap(); + assert_eq!(info[0].funding_interval_hours, 8); + + let mark = market.get_mark_price("BTCUSDT").unwrap(); + assert_eq!(mark.index_price, Some(11781.80495970)); + assert_eq!(mark.interest_rate, Some(0.0001)); + + m1.assert(); + m2.assert(); + m3.assert(); + } + + #[test] + fn futures_data_endpoints() { + let mut server = Server::new(); + let m1 = server + .mock("GET", "/futures/data/topLongShortAccountRatio") + .match_query(Matcher::Regex("limit=2&period=5m&symbol=BTCUSDT".into())) + .with_body_from_file("tests/mocks/futures/market/long_short_ratio.json") + .create(); + let m2 = server + .mock("GET", "/futures/data/topLongShortPositionRatio") + .match_query(Matcher::Regex("period=5m&symbol=BTCUSDT".into())) + .with_body_from_file("tests/mocks/futures/market/long_short_ratio.json") + .create(); + let m3 = server + .mock("GET", "/futures/data/globalLongShortAccountRatio") + .match_query(Matcher::Regex("period=5m&symbol=BTCUSDT".into())) + .with_body_from_file("tests/mocks/futures/market/long_short_ratio.json") + .create(); + let m4 = server + .mock("GET", "/futures/data/takerlongshortRatio") + .match_query(Matcher::Regex("period=5m&symbol=BTCUSDT".into())) + .with_body_from_file("tests/mocks/futures/market/taker_long_short_ratio.json") + .create(); + let m5 = server + .mock("GET", "/futures/data/basis") + .match_query(Matcher::Regex( + "contractType=PERPETUAL&pair=BTCUSDT&period=5m".into(), + )) + .with_body_from_file("tests/mocks/futures/market/basis.json") + .create(); + + let config = Config::default().set_futures_rest_api_endpoint(server.url()); + let market: FuturesMarket = Binance::new_with_config(None, None, &config); + + let top_accounts = market + .top_long_short_account_ratio("BTCUSDT", "5m", 2, None, None) + .unwrap(); + assert_eq!(top_accounts.len(), 2); + assert_eq!(top_accounts[0].long_short_ratio, 1.8105); + let top_positions = market + .top_long_short_position_ratio("BTCUSDT", "5m", None, None, None) + .unwrap(); + assert_eq!(top_positions[1].timestamp, 1583139900000); + let global = market + .global_long_short_account_ratio("BTCUSDT", "5m", None, None, None) + .unwrap(); + assert_eq!(global[0].short_account, 0.3558); + let taker = market + .taker_long_short_ratio("BTCUSDT", "5m", None, None, None) + .unwrap(); + assert_eq!(taker[0].buy_sell_ratio, 1.5586); + let basis = market + .basis("BTCUSDT", ContractType::Perpetual, "5m", None, None, None) + .unwrap(); + assert_eq!(basis[0].contract_type, "PERPETUAL"); + assert_eq!(basis[0].basis, 13.94054945); + + for m in [m1, m2, m3, m4, m5] { + m.assert(); + } + } + + #[test] + fn kline_variants() { + let mut server = Server::new(); + let m1 = server + .mock("GET", "/fapi/v1/continuousKlines") + .match_query(Matcher::Regex( + "contractType=PERPETUAL&interval=1m&limit=2&pair=BTCUSDT".into(), + )) + .with_body_from_file("tests/mocks/futures/market/continuous_klines.json") + .create(); + let m2 = server + .mock("GET", "/fapi/v1/indexPriceKlines") + .match_query(Matcher::Regex("interval=1m&pair=BTCUSDT".into())) + .with_body_from_file("tests/mocks/futures/market/continuous_klines.json") + .create(); + let m3 = server + .mock("GET", "/fapi/v1/markPriceKlines") + .match_query(Matcher::Regex("interval=1m&symbol=BTCUSDT".into())) + .with_body_from_file("tests/mocks/futures/market/continuous_klines.json") + .create(); + let m4 = server + .mock("GET", "/fapi/v1/premiumIndexKlines") + .match_query(Matcher::Regex("interval=1m&symbol=BTCUSDT".into())) + .with_body_from_file("tests/mocks/futures/market/continuous_klines.json") + .create(); + + let config = Config::default().set_futures_rest_api_endpoint(server.url()); + let market: FuturesMarket = Binance::new_with_config(None, None, &config); + + let KlineSummaries::AllKlineSummaries(klines) = market + .get_continuous_klines("BTCUSDT", ContractType::Perpetual, "1m", 2, None, None) + .unwrap(); + assert_eq!(klines.len(), 2); + assert_eq!(klines[0].open, "18879.99"); + market + .get_index_price_klines("BTCUSDT", "1m", None, None, None) + .unwrap(); + market + .get_mark_price_klines("BTCUSDT", "1m", None, None, None) + .unwrap(); + market + .get_premium_index_klines("BTCUSDT", "1m", None, None, None) + .unwrap(); + + for m in [m1, m2, m3, m4] { + m.assert(); + } + } + + #[test] + fn historical_trades_sends_api_key_without_signature() { + let mut server = Server::new(); + let mock = server + .mock("GET", "/fapi/v1/historicalTrades") + .match_header("x-mbx-apikey", "my-key") + .match_query(Matcher::AllOf(vec![ + Matcher::UrlEncoded("symbol".into(), "BTCUSDT".into()), + Matcher::UrlEncoded("fromId".into(), "28457".into()), + Matcher::UrlEncoded("limit".into(), "1".into()), + ])) + .with_body_from_file("tests/mocks/futures/market/historical_trades.json") + .create(); + + let config = Config::default().set_futures_rest_api_endpoint(server.url()); + let market: FuturesMarket = Binance::new_with_config(Some("my-key".into()), None, &config); + let Trades::AllTrades(trades) = market.get_historical_trades("BTCUSDT", 28457, 1).unwrap(); + assert_eq!(trades[0].id, 28457); + assert_eq!(trades[0].is_rpi_trade, Some(false)); + mock.assert(); + } + + #[test] + fn misc_market_endpoints() { + let mut server = Server::new(); + let m1 = server + .mock("GET", "/fapi/v1/insuranceBalance") + .with_body_from_file("tests/mocks/futures/market/insurance_balance.json") + .create(); + let m2 = server + .mock("GET", "/fapi/v1/constituents") + .match_query(Matcher::Regex("symbol=BTCUSDT".into())) + .with_body_from_file("tests/mocks/futures/market/index_constituents.json") + .create(); + let m3 = server + .mock("GET", "/fapi/v1/symbolAdlRisk") + .match_query(Matcher::Regex("symbol=BTCUSDT".into())) + .with_body_from_file("tests/mocks/futures/market/symbol_adl_risk.json") + .create(); + + let config = Config::default().set_futures_rest_api_endpoint(server.url()); + let market: FuturesMarket = Binance::new_with_config(None, None, &config); + + let insurance = market.get_insurance_balance(None).unwrap(); + assert_eq!(insurance[0].symbols[0], "BNBUSDT"); + assert_eq!(insurance[0].assets[1].asset, "USDT"); + + let constituents = market.get_index_constituents("BTCUSDT").unwrap(); + assert_eq!(constituents.constituents[1].exchange, "coinbase"); + assert_eq!(constituents.constituents[1].weight, Some(0.15384615)); + + let risk = market + .get_symbol_adl_risk(Some("BTCUSDT".to_string())) + .unwrap(); + assert_eq!(risk[0].adl_risk, "low"); + + for m in [m1, m2, m3] { + m.assert(); + } + } + + #[test] + fn exchange_info_tolerates_new_fields_and_filters() { + let mut server = Server::new(); + let mock = server + .mock("GET", "/fapi/v1/exchangeInfo") + .with_body_from_file("tests/mocks/futures/market/exchange_info.json") + .create(); + let config = Config::default().set_futures_rest_api_endpoint(server.url()); + let general: FuturesGeneral = Binance::new_with_config(None, None, &config); + let info = general.exchange_info().unwrap(); + mock.assert(); + + assert_eq!(info.assets.len(), 3); + assert_eq!(info.assets[2].auto_asset_exchange, None); + let symbol = &info.symbols[0]; + assert_eq!(symbol.pair.as_deref(), Some("BLZUSDT")); + assert_eq!(symbol.contract_type.as_deref(), Some("PERPETUAL")); + assert_eq!(symbol.margin_asset.as_deref(), Some("USDT")); + assert_eq!(symbol.trigger_protect, Some(0.15)); + assert_eq!(symbol.liquidation_fee, Some(0.01)); + assert_eq!(symbol.underlying_sub_type, vec!["STORAGE"]); + assert_eq!(symbol.filters.len(), 8); + assert!(matches!(symbol.filters[7], Filters::Unknown)); + assert!(matches!( + symbol.filters[3], + Filters::MaxNumOrders { + max_num_orders: None + } + )); + assert!(symbol.time_in_force.contains(&"RPI".to_string())); + } } diff --git a/tests/general_tests.rs b/tests/general_tests.rs index 1c8e7a9c..023e2a80 100755 --- a/tests/general_tests.rs +++ b/tests/general_tests.rs @@ -6,7 +6,7 @@ use binance::model::*; #[cfg(test)] mod tests { use super::*; - use mockito::Server; + use mockito::{Server, Matcher}; use float_cmp::*; #[test] @@ -162,4 +162,92 @@ mod tests { } } } + + #[test] + fn exchange_info_2026_fields_and_unknown_filters() { + let mut server = Server::new(); + let mock = server + .mock("GET", "/api/v3/exchangeInfo") + .match_query(Matcher::Regex( + "showPermissionSets=false&symbol=ETHBTC".into(), + )) + .with_body_from_file("tests/mocks/general/exchange_info_2026.json") + .create(); + + let config = Config::default().set_rest_api_endpoint(server.url()); + let general: General = Binance::new_with_config(None, None, &config); + let info = general + .exchange_info_with_params(Some(&["ETHBTC"]), None, false) + .unwrap(); + mock.assert(); + + assert_eq!(info.exchange_filters.len(), 2); + assert!(matches!( + info.exchange_filters[1], + Filters::ExchangeMaxNumOrderLists { + max_num_order_lists: Some(20) + } + )); + let sors = info.sors.unwrap(); + assert_eq!(sors[0].base_asset, "BTC"); + + let symbol = &info.symbols[0]; + assert_eq!(symbol.oto_allowed, Some(true)); + assert_eq!(symbol.opo_allowed, Some(true)); + assert_eq!(symbol.amend_allowed, Some(false)); + assert_eq!(symbol.peg_instructions_allowed, Some(true)); + assert_eq!(symbol.permission_sets, vec![vec!["SPOT", "MARGIN"]]); + assert_eq!( + symbol.default_self_trade_prevention_mode.as_deref(), + Some("NONE") + ); + assert!( + symbol + .allowed_self_trade_prevention_modes + .contains(&"TRANSFER".to_string()) + ); + assert_eq!(symbol.filters.len(), 4); + assert!(matches!( + symbol.filters[1], + Filters::MaxNumOrderLists { + max_num_order_lists: Some(20) + } + )); + assert!(matches!( + symbol.filters[2], + Filters::MaxNumOrderAmends { + max_num_order_amends: Some(10) + } + )); + assert!(matches!(symbol.filters[3], Filters::Unknown)); + } + + #[test] + fn exchange_info_with_symbols_and_status() { + let mut server = Server::new(); + let mock = server + .mock("GET", "/api/v3/exchangeInfo") + .match_query(Matcher::AllOf(vec![Matcher::UrlEncoded( + "symbols".into(), + r#"["ETHBTC","BNBBTC"]"#.into(), + )])) + .with_body_from_file("tests/mocks/general/exchange_info.json") + .create(); + let mock_status = server + .mock("GET", "/api/v3/exchangeInfo") + .match_query(Matcher::UrlEncoded("symbolStatus".into(), "TRADING".into())) + .with_body_from_file("tests/mocks/general/exchange_info.json") + .create(); + + let config = Config::default().set_rest_api_endpoint(server.url()); + let general: General = Binance::new_with_config(None, None, &config); + general + .exchange_info_with_params(Some(&["ETHBTC", "BNBBTC"]), None, None) + .unwrap(); + general + .exchange_info_with_params::<&str, _, _>(None, Some("TRADING".to_string()), None) + .unwrap(); + mock.assert(); + mock_status.assert(); + } } diff --git a/tests/market_tests.rs b/tests/market_tests.rs index fc7d3c3d..70cb196f 100644 --- a/tests/market_tests.rs +++ b/tests/market_tests.rs @@ -352,4 +352,119 @@ mod tests { } } } + + #[test] + fn get_trades_and_historical_trades() { + let mut server = Server::new(); + let m1 = server + .mock("GET", "/api/v3/trades") + .match_query(Matcher::Regex("limit=1&symbol=LTCBTC".into())) + .with_body_from_file("tests/mocks/market/trades.json") + .create(); + let m2 = server + .mock("GET", "/api/v3/historicalTrades") + .match_header("x-mbx-apikey", "api-key") + .match_query(Matcher::Regex("fromId=28457&limit=1&symbol=LTCBTC".into())) + .with_body_from_file("tests/mocks/market/trades.json") + .create(); + + let config = Config::default().set_rest_api_endpoint(server.url()); + let market: Market = Binance::new_with_config(Some("api-key".into()), None, &config); + + let trades = market.get_trades("LTCBTC", 1).unwrap(); + assert_eq!(trades[0].id, 28457); + assert!(approx_eq!(f64, trades[0].quote_qty, 48.000012, ulps = 2)); + assert!(trades[0].is_buyer_maker); + + let historical = market.get_historical_trades("LTCBTC", 28457, 1).unwrap(); + assert_eq!(historical.len(), 1); + + m1.assert(); + m2.assert(); + } + + #[test] + fn get_ui_klines() { + let mut server = Server::new(); + let mock = server + .mock("GET", "/api/v3/uiKlines") + .match_query(Matcher::AllOf(vec![ + Matcher::UrlEncoded("symbol".into(), "LTCBTC".into()), + Matcher::UrlEncoded("interval".into(), "5m".into()), + Matcher::UrlEncoded("limit".into(), "10".into()), + Matcher::UrlEncoded("timeZone".into(), "-1:00".into()), + ])) + .with_body_from_file("tests/mocks/market/get_klines.json") + .create(); + + let config = Config::default().set_rest_api_endpoint(server.url()); + let market: Market = Binance::new_with_config(None, None, &config); + let KlineSummaries::AllKlineSummaries(klines) = market + .get_ui_klines("LTCBTC", "5m", 10, None, None, Some("-1:00".to_string())) + .unwrap(); + mock.assert(); + assert!(!klines.is_empty()); + } + + #[test] + fn trading_day_and_rolling_window_tickers() { + let mut server = Server::new(); + let m1 = server + .mock("GET", "/api/v3/ticker/tradingDay") + .match_query(Matcher::Regex("symbol=BTCUSDT&timeZone=8".into())) + .with_body_from_file("tests/mocks/market/trading_day_ticker.json") + .create(); + let m2 = server + .mock("GET", "/api/v3/ticker") + .match_query(Matcher::AllOf(vec![ + Matcher::UrlEncoded("symbols".into(), r#"["BTCUSDT","BNBBTC"]"#.into()), + Matcher::UrlEncoded("windowSize".into(), "4h".into()), + Matcher::UrlEncoded("type".into(), "MINI".into()), + ])) + .with_body_from_file("tests/mocks/market/rolling_window_tickers_mini.json") + .create(); + + let config = Config::default().set_rest_api_endpoint(server.url()); + let market: Market = Binance::new_with_config(None, None, &config); + + let day = market + .get_trading_day_ticker("BTCUSDT", Some("8".to_string()), false) + .unwrap(); + assert_eq!(day.price_change.as_deref(), Some("-83.13000000")); + assert!(approx_eq!(f64, day.last_price, 26221.67, ulps = 2)); + assert_eq!(day.count, 697727); + + let tickers = market + .get_rolling_window_tickers(&["BTCUSDT", "BNBBTC"], Some("4h".to_string()), true) + .unwrap(); + assert_eq!(tickers.len(), 2); + assert_eq!(tickers[1].symbol, "BNBBTC"); + assert!(tickers[1].price_change.is_none()); + assert!(approx_eq!(f64, tickers[1].volume, 166.67, ulps = 2)); + + m1.assert(); + m2.assert(); + } + + #[test] + fn prices_for_symbols_encodes_json_array() { + let mut server = Server::new(); + let mock = server + .mock("GET", "/api/v3/ticker/price") + .match_query(Matcher::UrlEncoded( + "symbols".into(), + r#"["LTCBTC","ETHBTC"]"#.into(), + )) + .with_body(r#"[{"symbol":"LTCBTC","price":"4.00000200"},{"symbol":"ETHBTC","price":"0.07946600"}]"#) + .create(); + + let config = Config::default().set_rest_api_endpoint(server.url()); + let market: Market = Binance::new_with_config(None, None, &config); + let prices = market + .get_prices_for_symbols(&["LTCBTC", "ETHBTC"]) + .unwrap(); + mock.assert(); + assert_eq!(prices.len(), 2); + assert_eq!(prices[1].symbol, "ETHBTC"); + } } diff --git a/tests/mocks/account/account_commission.json b/tests/mocks/account/account_commission.json new file mode 100644 index 00000000..6771169c --- /dev/null +++ b/tests/mocks/account/account_commission.json @@ -0,0 +1,7 @@ +{ + "symbol": "BTCUSDT", + "standardCommission": { "maker": "0.00000010", "taker": "0.00000020", "buyer": "0.00000030", "seller": "0.00000040" }, + "specialCommission": { "maker": "0.01000000", "taker": "0.02000000", "buyer": "0.03000000", "seller": "0.04000000" }, + "taxCommission": { "maker": "0.00000112", "taker": "0.00000114", "buyer": "0.00000118", "seller": "0.00000116" }, + "discount": { "enabledForAccount": true, "enabledForSymbol": true, "discountAsset": "BNB", "discount": "0.75000000" } +} diff --git a/tests/mocks/account/all_orders.json b/tests/mocks/account/all_orders.json new file mode 100644 index 00000000..fa28012b --- /dev/null +++ b/tests/mocks/account/all_orders.json @@ -0,0 +1,24 @@ +[ + { + "symbol": "LTCBTC", + "orderId": 1, + "orderListId": -1, + "clientOrderId": "myOrder1", + "price": "0.1", + "origQty": "1.0", + "executedQty": "0.0", + "origQuoteOrderQty": "0.000000", + "cummulativeQuoteQty": "0.0", + "status": "NEW", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0.0", + "icebergQty": "0.0", + "time": 1499827319559, + "updateTime": 1499827319559, + "isWorking": true, + "workingTime": 1499827319559, + "selfTradePreventionMode": "NONE" + } +] diff --git a/tests/mocks/account/amend_keep_priority.json b/tests/mocks/account/amend_keep_priority.json new file mode 100644 index 00000000..5f4906b8 --- /dev/null +++ b/tests/mocks/account/amend_keep_priority.json @@ -0,0 +1,23 @@ +{ + "transactTime": 1741924229819, + "executionId": 75, + "amendedOrder": { + "symbol": "BTCUSDT", + "orderId": 60, + "orderListId": -1, + "origClientOrderId": "W2U8LCKNRVKPnoSZTNPfh7", + "clientOrderId": "jvDNRe8ia0Rt8v8rYlqdBT", + "price": "30000.00000000", + "qty": "5.00000000", + "executedQty": "0.00000000", + "preventedQty": "0.00000000", + "quoteOrderQty": "0.00000000", + "cumulativeQuoteQty": "0.00000000", + "status": "NEW", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "workingTime": 1741924229819, + "selfTradePreventionMode": "NONE" + } +} diff --git a/tests/mocks/account/cancel_order_list.json b/tests/mocks/account/cancel_order_list.json new file mode 100644 index 00000000..3f3930a5 --- /dev/null +++ b/tests/mocks/account/cancel_order_list.json @@ -0,0 +1,52 @@ +{ + "orderListId": 0, + "contingencyType": "OCO", + "listStatusType": "ALL_DONE", + "listOrderStatus": "ALL_DONE", + "listClientOrderId": "C3wyj4WVEktd7u9aVBRXcN", + "transactionTime": 1574040868128, + "symbol": "LTCBTC", + "orders": [ + { "symbol": "LTCBTC", "orderId": 2, "clientOrderId": "pO9ufTiFGg3nw2fOdgeOXa" }, + { "symbol": "LTCBTC", "orderId": 3, "clientOrderId": "TXOvglzXuaubXAaENpaRCB" } + ], + "orderReports": [ + { + "symbol": "LTCBTC", + "origClientOrderId": "pO9ufTiFGg3nw2fOdgeOXa", + "orderId": 2, + "orderListId": 0, + "clientOrderId": "unfWT8ig8i0uj6lPuYLez6", + "transactTime": 1688005070874, + "price": "1.00000000", + "origQty": "10.00000000", + "executedQty": "0.00000000", + "origQuoteOrderQty": "0.000000", + "cummulativeQuoteQty": "0.00000000", + "status": "CANCELED", + "timeInForce": "GTC", + "type": "STOP_LOSS_LIMIT", + "side": "SELL", + "stopPrice": "1.00000000", + "selfTradePreventionMode": "NONE" + }, + { + "symbol": "LTCBTC", + "origClientOrderId": "TXOvglzXuaubXAaENpaRCB", + "orderId": 3, + "orderListId": 0, + "clientOrderId": "unfWT8ig8i0uj6lPuYLez6", + "transactTime": 1688005070874, + "price": "3.00000000", + "origQty": "10.00000000", + "executedQty": "0.00000000", + "origQuoteOrderQty": "0.000000", + "cummulativeQuoteQty": "0.00000000", + "status": "CANCELED", + "timeInForce": "GTC", + "type": "LIMIT_MAKER", + "side": "SELL", + "selfTradePreventionMode": "NONE" + } + ] +} diff --git a/tests/mocks/account/cancel_replace.json b/tests/mocks/account/cancel_replace.json new file mode 100644 index 00000000..c589bf29 --- /dev/null +++ b/tests/mocks/account/cancel_replace.json @@ -0,0 +1,41 @@ +{ + "cancelResult": "SUCCESS", + "newOrderResult": "SUCCESS", + "cancelResponse": { + "symbol": "BTCUSDT", + "origClientOrderId": "DnLo3vTAQcjha43lAZhZ0y", + "orderId": 9, + "orderListId": -1, + "clientOrderId": "osxN3JXAtJvKvCqGeMWMVR", + "transactTime": 1684804350068, + "price": "0.01000000", + "origQty": "0.000100", + "executedQty": "0.00000000", + "origQuoteOrderQty": "0.000000", + "cummulativeQuoteQty": "0.00000000", + "status": "CANCELED", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "SELL", + "selfTradePreventionMode": "NONE" + }, + "newOrderResponse": { + "symbol": "BTCUSDT", + "orderId": 10, + "orderListId": -1, + "clientOrderId": "wOceeeOzNORyLiQfw7jd8S", + "transactTime": 1652928801803, + "price": "0.02000000", + "origQty": "0.040000", + "executedQty": "0.00000000", + "origQuoteOrderQty": "0.000000", + "cummulativeQuoteQty": "0.00000000", + "status": "NEW", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "workingTime": 1669277163011, + "fills": [], + "selfTradePreventionMode": "NONE" + } +} diff --git a/tests/mocks/account/cancel_replace_partial_failure.json b/tests/mocks/account/cancel_replace_partial_failure.json new file mode 100644 index 00000000..26ac1060 --- /dev/null +++ b/tests/mocks/account/cancel_replace_partial_failure.json @@ -0,0 +1,26 @@ +{ + "cancelResult": "SUCCESS", + "newOrderResult": "FAILURE", + "cancelResponse": { + "symbol": "BTCUSDT", + "origClientOrderId": "DnLo3vTAQcjha43lAZhZ0y", + "orderId": 9, + "orderListId": -1, + "clientOrderId": "osxN3JXAtJvKvCqGeMWMVR", + "transactTime": 1684804350068, + "price": "0.01000000", + "origQty": "0.000100", + "executedQty": "0.00000000", + "origQuoteOrderQty": "0.000000", + "cummulativeQuoteQty": "0.00000000", + "status": "CANCELED", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "SELL", + "selfTradePreventionMode": "NONE" + }, + "newOrderResponse": { + "code": -2010, + "msg": "Order would immediately match and take." + } +} diff --git a/tests/mocks/account/get_account_full.json b/tests/mocks/account/get_account_full.json new file mode 100644 index 00000000..39a36677 --- /dev/null +++ b/tests/mocks/account/get_account_full.json @@ -0,0 +1,25 @@ +{ + "makerCommission": 15, + "takerCommission": 15, + "buyerCommission": 0, + "sellerCommission": 0, + "commissionRates": { + "maker": "0.00150000", + "taker": "0.00150000", + "buyer": "0.00000000", + "seller": "0.00000000" + }, + "canTrade": true, + "canWithdraw": true, + "canDeposit": true, + "brokered": false, + "requireSelfTradePrevention": false, + "preventSor": false, + "updateTime": 123456789, + "accountType": "SPOT", + "balances": [ + { "asset": "BTC", "free": "4723846.89208129", "locked": "0.00000000" } + ], + "permissions": ["SPOT"], + "uid": 354937868 +} diff --git a/tests/mocks/account/my_filters.json b/tests/mocks/account/my_filters.json new file mode 100644 index 00000000..e2825515 --- /dev/null +++ b/tests/mocks/account/my_filters.json @@ -0,0 +1,6 @@ +{ + "exchangeFilters": [ { "filterType": "EXCHANGE_MAX_NUM_ORDERS", "maxNumOrders": 1000 } ], + "symbolFilters": [ { "filterType": "PRICE_FILTER", "minPrice": "0.00000100", "maxPrice": "100000.00000000", "tickSize": "0.00000100" } ], + "assetFilters": [ { "filterType": "MAX_ASSET", "limit": "100.00000000", "asset": "BNB" } ], + "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 6000, "count": 321 } ] +} diff --git a/tests/mocks/account/order_full.json b/tests/mocks/account/order_full.json new file mode 100644 index 00000000..ff15270d --- /dev/null +++ b/tests/mocks/account/order_full.json @@ -0,0 +1,33 @@ +{ + "symbol": "LTCBTC", + "orderId": 1, + "orderListId": -1, + "clientOrderId": "myOrder1", + "price": "0.1", + "origQty": "1.0", + "executedQty": "0.0", + "origQuoteOrderQty": "0.000000", + "cummulativeQuoteQty": "0.0", + "status": "EXPIRED", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "time": 1499827319559, + "updateTime": 1499827319559, + "isWorking": true, + "workingTime": 1499827319559, + "selfTradePreventionMode": "NONE", + "preventedMatchId": 0, + "preventedQuantity": "1.200000", + "strategyId": 1, + "strategyType": 1000000, + "trailingDelta": 10, + "trailingTime": -1, + "usedSor": true, + "workingFloor": "SOR", + "pegPriceType": "PRIMARY_PEG", + "pegOffsetType": "PRICE_LEVEL", + "pegOffsetValue": 5, + "peggedPrice": "87523.83710000", + "expiryReason": "INSUFFICIENT_LIQUIDITY" +} diff --git a/tests/mocks/account/order_list.json b/tests/mocks/account/order_list.json new file mode 100644 index 00000000..b7a67a93 --- /dev/null +++ b/tests/mocks/account/order_list.json @@ -0,0 +1,13 @@ +{ + "orderListId": 27, + "contingencyType": "OCO", + "listStatusType": "EXEC_STARTED", + "listOrderStatus": "EXECUTING", + "listClientOrderId": "h2USkA5YQpaXHPIrkd96xE", + "transactionTime": 1565245656253, + "symbol": "LTCBTC", + "orders": [ + { "symbol": "LTCBTC", "orderId": 4, "clientOrderId": "qD1gy3kc3Gx0rihm9Y3xwS" }, + { "symbol": "LTCBTC", "orderId": 5, "clientOrderId": "ARzZ9I00CPM8i3NhmU9Ega" } + ] +} diff --git a/tests/mocks/account/order_list_oco.json b/tests/mocks/account/order_list_oco.json new file mode 100644 index 00000000..08e18996 --- /dev/null +++ b/tests/mocks/account/order_list_oco.json @@ -0,0 +1,53 @@ +{ + "orderListId": 1, + "contingencyType": "OCO", + "listStatusType": "EXEC_STARTED", + "listOrderStatus": "EXECUTING", + "listClientOrderId": "lH1YDkuQKWiXVXHPSKYEIp", + "transactionTime": 1710485608839, + "symbol": "LTCBTC", + "orders": [ + { "symbol": "LTCBTC", "orderId": 10, "clientOrderId": "44nZvqpemY7sVYgPYbvPih" }, + { "symbol": "LTCBTC", "orderId": 11, "clientOrderId": "NuMp0nVYnciDiFmVqfpBqK" } + ], + "orderReports": [ + { + "symbol": "LTCBTC", + "orderId": 10, + "orderListId": 1, + "clientOrderId": "44nZvqpemY7sVYgPYbvPih", + "transactTime": 1710485608839, + "price": "1.00000000", + "origQty": "5.00000000", + "executedQty": "0.00000000", + "origQuoteOrderQty": "0.000000", + "cummulativeQuoteQty": "0.00000000", + "status": "NEW", + "timeInForce": "GTC", + "type": "STOP_LOSS_LIMIT", + "side": "SELL", + "stopPrice": "1.00000000", + "workingTime": -1, + "icebergQty": "1.00000000", + "selfTradePreventionMode": "NONE" + }, + { + "symbol": "LTCBTC", + "orderId": 11, + "orderListId": 1, + "clientOrderId": "NuMp0nVYnciDiFmVqfpBqK", + "transactTime": 1710485608839, + "price": "3.00000000", + "origQty": "5.00000000", + "executedQty": "0.00000000", + "origQuoteOrderQty": "0.000000", + "cummulativeQuoteQty": "0.00000000", + "status": "NEW", + "timeInForce": "GTC", + "type": "LIMIT_MAKER", + "side": "SELL", + "workingTime": 1710485608839, + "selfTradePreventionMode": "NONE" + } + ] +} diff --git a/tests/mocks/account/rate_limit_order.json b/tests/mocks/account/rate_limit_order.json new file mode 100644 index 00000000..cd242e5b --- /dev/null +++ b/tests/mocks/account/rate_limit_order.json @@ -0,0 +1,4 @@ +[ + { "rateLimitType": "ORDERS", "interval": "SECOND", "intervalNum": 10, "limit": 50, "count": 0 }, + { "rateLimitType": "ORDERS", "interval": "DAY", "intervalNum": 1, "limit": 160000, "count": 0 } +] diff --git a/tests/mocks/futures/account/account_config.json b/tests/mocks/futures/account/account_config.json new file mode 100644 index 00000000..1196514b --- /dev/null +++ b/tests/mocks/futures/account/account_config.json @@ -0,0 +1,10 @@ +{ + "feeTier": 0, + "canTrade": true, + "canDeposit": true, + "canWithdraw": true, + "dualSidePosition": true, + "updateTime": 0, + "multiAssetsMargin": false, + "tradeGroupId": -1 +} diff --git a/tests/mocks/futures/account/account_information_v3.json b/tests/mocks/futures/account/account_information_v3.json new file mode 100644 index 00000000..2a2086f3 --- /dev/null +++ b/tests/mocks/futures/account/account_information_v3.json @@ -0,0 +1,44 @@ +{ + "totalInitialMargin": "0.00000000", + "totalMaintMargin": "0.00000000", + "totalWalletBalance": "126.72469206", + "totalUnrealizedProfit": "0.00000000", + "totalMarginBalance": "126.72469206", + "totalPositionInitialMargin": "0.00000000", + "totalOpenOrderInitialMargin": "0.00000000", + "totalCrossWalletBalance": "126.72469206", + "totalCrossUnPnl": "0.00000000", + "availableBalance": "126.72469206", + "maxWithdrawAmount": "126.72469206", + "assets": [ + { + "asset": "USDT", + "walletBalance": "23.72469206", + "unrealizedProfit": "0.00000000", + "marginBalance": "23.72469206", + "maintMargin": "0.00000000", + "initialMargin": "0.00000000", + "positionInitialMargin": "0.00000000", + "openOrderInitialMargin": "0.00000000", + "crossWalletBalance": "23.72469206", + "crossUnPnl": "0.00000000", + "availableBalance": "23.72469206", + "maxWithdrawAmount": "23.72469206", + "updateTime": 1625474304765 + } + ], + "positions": [ + { + "symbol": "BTCUSDT", + "positionSide": "BOTH", + "positionAmt": "1.000", + "unrealizedProfit": "0.00000000", + "isolatedMargin": "0.00000000", + "notional": "0", + "isolatedWallet": "0", + "initialMargin": "0", + "maintMargin": "0", + "updateTime": 0 + } + ] +} diff --git a/tests/mocks/futures/account/adl_quantile.json b/tests/mocks/futures/account/adl_quantile.json new file mode 100644 index 00000000..0939186e --- /dev/null +++ b/tests/mocks/futures/account/adl_quantile.json @@ -0,0 +1,4 @@ +[ + { "symbol": "ETHUSDT", "adlQuantile": { "LONG": 3, "SHORT": 3, "HEDGE": 0 } }, + { "symbol": "BTCUSDT", "adlQuantile": { "LONG": 1, "SHORT": 2, "BOTH": 0 } } +] diff --git a/tests/mocks/futures/account/api_trading_status.json b/tests/mocks/futures/account/api_trading_status.json new file mode 100644 index 00000000..5d8cd5c5 --- /dev/null +++ b/tests/mocks/futures/account/api_trading_status.json @@ -0,0 +1,9 @@ +{ + "indicators": { + "BTCUSDT": [ + { "isLocked": true, "plannedRecoverTime": 1545741270000, "indicator": "UFR", "value": 0.05, "triggerValue": 0.995 }, + { "isLocked": true, "plannedRecoverTime": 1545741270000, "indicator": "IFER", "value": 0.99, "triggerValue": 0.99 } + ] + }, + "updateTime": 1545741270000 +} diff --git a/tests/mocks/futures/account/balance_v3.json b/tests/mocks/futures/account/balance_v3.json new file mode 100644 index 00000000..79403409 --- /dev/null +++ b/tests/mocks/futures/account/balance_v3.json @@ -0,0 +1,13 @@ +[ + { + "accountAlias": "SgsR", + "asset": "USDT", + "balance": "122607.35137903", + "crossWalletBalance": "23.72469206", + "crossUnPnl": "0.00000000", + "availableBalance": "23.72469206", + "maxWithdrawAmount": "23.72469206", + "marginAvailable": true, + "updateTime": 1617939110373 + } +] diff --git a/tests/mocks/futures/account/batch_orders.json b/tests/mocks/futures/account/batch_orders.json new file mode 100644 index 00000000..870d2d7c --- /dev/null +++ b/tests/mocks/futures/account/batch_orders.json @@ -0,0 +1,32 @@ +[ + { + "clientOrderId": "testOrder", + "cumQty": "0", + "cumQuote": "0", + "executedQty": "0", + "orderId": 22542179, + "avgPrice": "0.00000", + "origQty": "10", + "price": "30000", + "reduceOnly": false, + "side": "BUY", + "positionSide": "BOTH", + "status": "NEW", + "stopPrice": "0", + "closePosition": false, + "symbol": "BTCUSDT", + "timeInForce": "GTC", + "type": "LIMIT", + "origType": "LIMIT", + "updateTime": 1566818724722, + "workingType": "CONTRACT_PRICE", + "priceProtect": false, + "priceMatch": "NONE", + "selfTradePreventionMode": "EXPIRE_MAKER", + "goodTillDate": 0 + }, + { + "code": -2022, + "msg": "ReduceOnly Order is rejected." + } +] diff --git a/tests/mocks/futures/account/cancel_algo_order.json b/tests/mocks/futures/account/cancel_algo_order.json new file mode 100644 index 00000000..d17b7ac2 --- /dev/null +++ b/tests/mocks/futures/account/cancel_algo_order.json @@ -0,0 +1,6 @@ +{ + "algoId": 2146760, + "clientAlgoId": "6B2I9XVcJpCjqPAJ4YoFX7", + "code": "200", + "msg": "success" +} diff --git a/tests/mocks/futures/account/cancel_all_algo_open_orders.json b/tests/mocks/futures/account/cancel_all_algo_open_orders.json new file mode 100644 index 00000000..769b3ae7 --- /dev/null +++ b/tests/mocks/futures/account/cancel_all_algo_open_orders.json @@ -0,0 +1,4 @@ +{ + "code": 200, + "msg": "The operation of cancel all open order is done." +} diff --git a/tests/mocks/futures/account/cancel_batch_orders.json b/tests/mocks/futures/account/cancel_batch_orders.json new file mode 100644 index 00000000..5dba2989 --- /dev/null +++ b/tests/mocks/futures/account/cancel_batch_orders.json @@ -0,0 +1,33 @@ +[ + { + "clientOrderId": "myOrder1", + "cumQty": "0", + "cumQuote": "0", + "executedQty": "0", + "orderId": 283194212, + "origQty": "11", + "origType": "TRAILING_STOP_MARKET", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "CANCELED", + "stopPrice": "9300", + "closePosition": false, + "symbol": "BTCUSDT", + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "activatePrice": "9020", + "priceRate": "0.3", + "updateTime": 1571110484038, + "workingType": "CONTRACT_PRICE", + "priceProtect": false, + "priceMatch": "NONE", + "selfTradePreventionMode": "NONE", + "goodTillDate": 0 + }, + { + "code": -2011, + "msg": "Unknown order sent." + } +] diff --git a/tests/mocks/futures/account/code_msg.json b/tests/mocks/futures/account/code_msg.json new file mode 100644 index 00000000..a309ebe1 --- /dev/null +++ b/tests/mocks/futures/account/code_msg.json @@ -0,0 +1 @@ +{ "code": 200, "msg": "success" } diff --git a/tests/mocks/futures/account/commission_rate.json b/tests/mocks/futures/account/commission_rate.json new file mode 100644 index 00000000..42c07f8e --- /dev/null +++ b/tests/mocks/futures/account/commission_rate.json @@ -0,0 +1,6 @@ +{ + "symbol": "BTCUSDT", + "makerCommissionRate": "0.0002", + "takerCommissionRate": "0.0004", + "rpiCommissionRate": "0.0001" +} diff --git a/tests/mocks/futures/account/countdown_cancel_all.json b/tests/mocks/futures/account/countdown_cancel_all.json new file mode 100644 index 00000000..ebbaf49b --- /dev/null +++ b/tests/mocks/futures/account/countdown_cancel_all.json @@ -0,0 +1 @@ +{ "symbol": "BTCUSDT", "countdownTime": "100000" } diff --git a/tests/mocks/futures/account/fee_burn.json b/tests/mocks/futures/account/fee_burn.json new file mode 100644 index 00000000..6302b482 --- /dev/null +++ b/tests/mocks/futures/account/fee_burn.json @@ -0,0 +1 @@ +{ "feeBurn": true } diff --git a/tests/mocks/futures/account/force_orders.json b/tests/mocks/futures/account/force_orders.json new file mode 100644 index 00000000..2f83636f --- /dev/null +++ b/tests/mocks/futures/account/force_orders.json @@ -0,0 +1,26 @@ +[ + { + "orderId": 6071832819, + "symbol": "BTCUSDT", + "pair": "BTCUSDT", + "status": "FILLED", + "clientOrderId": "autoclose-1596107620040000020", + "price": "10871.09", + "avgPrice": "10913.21000", + "origQty": "0.001", + "executedQty": "0.001", + "cumQuote": "10.91321", + "cumBase": "0", + "timeInForce": "IOC", + "type": "LIMIT", + "reduceOnly": false, + "closePosition": false, + "side": "SELL", + "positionSide": "BOTH", + "stopPrice": "0", + "workingType": "CONTRACT_PRICE", + "origType": "LIMIT", + "time": 1596107620044, + "updateTime": 1596107620087 + } +] diff --git a/tests/mocks/futures/account/leverage_bracket.json b/tests/mocks/futures/account/leverage_bracket.json new file mode 100644 index 00000000..387364fe --- /dev/null +++ b/tests/mocks/futures/account/leverage_bracket.json @@ -0,0 +1,24 @@ +[ + { + "symbol": "ETHUSDT", + "notionalCoef": 1.5, + "brackets": [ + { + "bracket": 1, + "initialLeverage": 75, + "notionalCap": 10000, + "notionalFloor": 0, + "maintMarginRatio": 0.0065, + "cum": 0 + }, + { + "bracket": 2, + "initialLeverage": 50, + "notionalCap": 50000, + "notionalFloor": 10000, + "maintMarginRatio": 0.01, + "cum": 35.0 + } + ] + } +] diff --git a/tests/mocks/futures/account/limit_order.json b/tests/mocks/futures/account/limit_order.json new file mode 100644 index 00000000..15b4e8fd --- /dev/null +++ b/tests/mocks/futures/account/limit_order.json @@ -0,0 +1,28 @@ +{ + "clientOrderId": "testOrder", + "cumQty": "0", + "cumQuote": "0", + "executedQty": "0", + "orderId": 22542179, + "avgPrice": "0.00000", + "origQty": "10", + "price": "30000", + "reduceOnly": false, + "side": "BUY", + "positionSide": "BOTH", + "status": "NEW", + "stopPrice": "0", + "closePosition": false, + "symbol": "BTCUSDT", + "timeInForce": "GTC", + "type": "LIMIT", + "origType": "LIMIT", + "activatePrice": "9020", + "priceRate": "0.3", + "updateTime": 1566818724722, + "workingType": "CONTRACT_PRICE", + "priceProtect": false, + "priceMatch": "NONE", + "selfTradePreventionMode": "EXPIRE_MAKER", + "goodTillDate": 0 +} diff --git a/tests/mocks/futures/account/modify_order.json b/tests/mocks/futures/account/modify_order.json new file mode 100644 index 00000000..9751f8c1 --- /dev/null +++ b/tests/mocks/futures/account/modify_order.json @@ -0,0 +1,27 @@ +{ + "orderId": 20072994037, + "symbol": "BTCUSDT", + "pair": "BTCUSDT", + "status": "NEW", + "clientOrderId": "LJ9R4QZDihCaS8UAOOLpgW", + "modifyId": 1, + "price": "30005", + "origQty": "1", + "executedQty": "0", + "cumQty": "0", + "cumBase": "0", + "timeInForce": "GTC", + "type": "LIMIT", + "reduceOnly": false, + "closePosition": false, + "side": "BUY", + "positionSide": "LONG", + "stopPrice": "0", + "workingType": "CONTRACT_PRICE", + "priceProtect": false, + "origType": "LIMIT", + "priceMatch": "NONE", + "selfTradePreventionMode": "EXPIRE_MAKER", + "goodTillDate": 0, + "updateTime": 1629182711600 +} diff --git a/tests/mocks/futures/account/multi_assets_margin.json b/tests/mocks/futures/account/multi_assets_margin.json new file mode 100644 index 00000000..e7c9c36a --- /dev/null +++ b/tests/mocks/futures/account/multi_assets_margin.json @@ -0,0 +1 @@ +{ "multiAssetsMargin": false } diff --git a/tests/mocks/futures/account/new_algo_order.json b/tests/mocks/futures/account/new_algo_order.json new file mode 100644 index 00000000..bed1968a --- /dev/null +++ b/tests/mocks/futures/account/new_algo_order.json @@ -0,0 +1,27 @@ +{ + "algoId": 2146760, + "clientAlgoId": "6B2I9XVcJpCjqPAJ4YoFX7", + "algoType": "CONDITIONAL", + "orderType": "STOP_MARKET", + "symbol": "SRMUSDT", + "side": "SELL", + "positionSide": "BOTH", + "timeInForce": "GTC", + "quantity": "0", + "algoStatus": "NEW", + "triggerPrice": "7.4", + "price": "0", + "icebergQuantity": "null", + "selfTradePreventionMode": "EXPIRE_MAKER", + "workingType": "CONTRACT_PRICE", + "priceMatch": "NONE", + "closePosition": true, + "priceProtect": false, + "reduceOnly": true, + "activatePrice": "", + "callbackRate": "", + "createTime": 1750485492076, + "updateTime": 1750485492076, + "triggerTime": 0, + "goodTillDate": 0 +} diff --git a/tests/mocks/futures/account/open_algo_orders.json b/tests/mocks/futures/account/open_algo_orders.json new file mode 100644 index 00000000..41595510 --- /dev/null +++ b/tests/mocks/futures/account/open_algo_orders.json @@ -0,0 +1,34 @@ +[ + { + "algoId": 2146761, + "clientAlgoId": "myAlgo1", + "algoType": "CONDITIONAL", + "orderType": "TRAILING_STOP_MARKET", + "symbol": "BTCUSDT", + "side": "SELL", + "positionSide": "BOTH", + "timeInForce": "GTC", + "quantity": "0.5", + "algoStatus": "NEW", + "actualOrderId": "", + "actualPrice": "0", + "triggerPrice": "0", + "price": "0", + "icebergQuantity": "null", + "tpTriggerPrice": "", + "tpPrice": "", + "slTriggerPrice": "", + "slPrice": "", + "tpOrderType": "", + "selfTradePreventionMode": "NONE", + "workingType": "MARK_PRICE", + "priceMatch": "NONE", + "closePosition": false, + "priceProtect": true, + "reduceOnly": true, + "createTime": 1750485492076, + "updateTime": 1750485492076, + "triggerTime": 0, + "goodTillDate": 0 + } +] diff --git a/tests/mocks/futures/account/order_amendment.json b/tests/mocks/futures/account/order_amendment.json new file mode 100644 index 00000000..53e9a5f3 --- /dev/null +++ b/tests/mocks/futures/account/order_amendment.json @@ -0,0 +1,16 @@ +[ + { + "amendmentId": 5363, + "symbol": "BTCUSDT", + "pair": "BTCUSDT", + "orderId": 20072994037, + "clientOrderId": "LJ9R4QZDihCaS8UAOOLpgW", + "time": 1629184560899, + "amendment": { + "price": { "before": "30004", "after": "30003.2" }, + "origQty": { "before": "1", "after": "1" }, + "count": 3, + "modifyId": 7 + } + } +] diff --git a/tests/mocks/futures/account/position_margin_history.json b/tests/mocks/futures/account/position_margin_history.json new file mode 100644 index 00000000..35a3a14c --- /dev/null +++ b/tests/mocks/futures/account/position_margin_history.json @@ -0,0 +1,4 @@ +[ + { "symbol": "BTCUSDT", "type": 1, "deltaType": "USER_ADJUST", "amount": "23.36332311", "asset": "USDT", "time": 1578047897183, "positionSide": "BOTH" }, + { "symbol": "BTCUSDT", "type": 1, "deltaType": "USER_ADJUST", "amount": "100", "asset": "USDT", "time": 1578047900425, "positionSide": "LONG" } +] diff --git a/tests/mocks/futures/account/position_mode.json b/tests/mocks/futures/account/position_mode.json new file mode 100644 index 00000000..fc54b9df --- /dev/null +++ b/tests/mocks/futures/account/position_mode.json @@ -0,0 +1 @@ +{ "dualSidePosition": true } diff --git a/tests/mocks/futures/account/position_risk_v3.json b/tests/mocks/futures/account/position_risk_v3.json new file mode 100644 index 00000000..3ed501d8 --- /dev/null +++ b/tests/mocks/futures/account/position_risk_v3.json @@ -0,0 +1,24 @@ +[ + { + "symbol": "ADAUSDT", + "positionSide": "BOTH", + "positionAmt": "30", + "entryPrice": "0.385", + "breakEvenPrice": "0.385077", + "markPrice": "0.41047590", + "unRealizedProfit": "0.76427700", + "liquidationPrice": "0", + "isolatedMargin": "0", + "notional": "12.31427700", + "marginAsset": "USDT", + "isolatedWallet": "0", + "initialMargin": "0.61571385", + "maintMargin": "0.08004280", + "positionInitialMargin": "0.61571385", + "openOrderInitialMargin": "0", + "adl": 2, + "bidNotional": "0", + "askNotional": "0", + "updateTime": 1720736417660 + } +] diff --git a/tests/mocks/futures/account/query_algo_order.json b/tests/mocks/futures/account/query_algo_order.json new file mode 100644 index 00000000..ff6a77a9 --- /dev/null +++ b/tests/mocks/futures/account/query_algo_order.json @@ -0,0 +1,30 @@ +{ + "algoId": 2146760, + "clientAlgoId": "6B2I9XVcJpCjqPAJ4YoFX7", + "algoType": "CONDITIONAL", + "orderType": "TAKE_PROFIT", + "symbol": "BNBUSDT", + "side": "SELL", + "positionSide": "BOTH", + "timeInForce": "GTC", + "quantity": "0.01", + "algoStatus": "CANCELED", + "actualOrderId": "", + "actualPrice": "0.00000", + "actualType": "LIMIT", + "actualQty": "0.01", + "triggerPrice": "750.000", + "price": "750.000", + "icebergQuantity": "null", + "tpOrderType": "", + "selfTradePreventionMode": "EXPIRE_MAKER", + "workingType": "CONTRACT_PRICE", + "priceMatch": "NONE", + "closePosition": false, + "priceProtect": false, + "reduceOnly": false, + "createTime": 1750485492076, + "updateTime": 1750514545091, + "triggerTime": 0, + "goodTillDate": 0 +} diff --git a/tests/mocks/futures/account/query_order.json b/tests/mocks/futures/account/query_order.json new file mode 100644 index 00000000..04fc4c68 --- /dev/null +++ b/tests/mocks/futures/account/query_order.json @@ -0,0 +1,28 @@ +{ + "avgPrice": "0.00000", + "clientOrderId": "abc", + "cumQuote": "0", + "executedQty": "0", + "orderId": 1573346959, + "origQty": "0.40", + "origType": "TRAILING_STOP_MARKET", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "NEW", + "stopPrice": "9300", + "closePosition": false, + "symbol": "BTCUSDT", + "time": 1579276756075, + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "activatePrice": "9020", + "priceRate": "0.3", + "updateTime": 1579276756075, + "workingType": "CONTRACT_PRICE", + "priceProtect": false, + "priceMatch": "NONE", + "selfTradePreventionMode": "EXPIRE_MAKER", + "goodTillDate": 0 +} diff --git a/tests/mocks/futures/account/rate_limit_order.json b/tests/mocks/futures/account/rate_limit_order.json new file mode 100644 index 00000000..dd6d671a --- /dev/null +++ b/tests/mocks/futures/account/rate_limit_order.json @@ -0,0 +1,4 @@ +[ + { "rateLimitType": "ORDERS", "interval": "SECOND", "intervalNum": 10, "limit": 10000 }, + { "rateLimitType": "ORDERS", "interval": "MINUTE", "intervalNum": 1, "limit": 20000 } +] diff --git a/tests/mocks/futures/account/symbol_config.json b/tests/mocks/futures/account/symbol_config.json new file mode 100644 index 00000000..2770de94 --- /dev/null +++ b/tests/mocks/futures/account/symbol_config.json @@ -0,0 +1,9 @@ +[ + { + "symbol": "BTCUSDT", + "marginType": "CROSSED", + "isAutoAddMargin": false, + "leverage": 21, + "maxNotionalValue": "1000000" + } +] diff --git a/tests/mocks/futures/market/basis.json b/tests/mocks/futures/market/basis.json new file mode 100644 index 00000000..6019a2ec --- /dev/null +++ b/tests/mocks/futures/market/basis.json @@ -0,0 +1,3 @@ +[ + { "indexPrice": "34400.15945055", "contractType": "PERPETUAL", "basisRate": "0.0004", "futuresPrice": "34414.10", "annualizedBasisRate": "", "basis": "13.94054945", "pair": "BTCUSDT", "timestamp": 1698742800000 } +] diff --git a/tests/mocks/futures/market/continuous_klines.json b/tests/mocks/futures/market/continuous_klines.json new file mode 100644 index 00000000..606b2871 --- /dev/null +++ b/tests/mocks/futures/market/continuous_klines.json @@ -0,0 +1,4 @@ +[ + [1607444700000, "18879.99", "18900.00", "18878.98", "18896.13", "492.363", 1607444759999, "9302145.66978", 1874, "385.983", "7292402.33370", "0"], + [1607444760000, "18896.13", "18910.00", "18890.00", "18905.00", "300.000", 1607444819999, "5670000.00000", 1500, "150.000", "2835000.00000", "0"] +] diff --git a/tests/mocks/futures/market/exchange_info.json b/tests/mocks/futures/market/exchange_info.json new file mode 100644 index 00000000..7e9a849f --- /dev/null +++ b/tests/mocks/futures/market/exchange_info.json @@ -0,0 +1,52 @@ +{ + "exchangeFilters": [], + "rateLimits": [ + { "interval": "MINUTE", "intervalNum": 1, "limit": 2400, "rateLimitType": "REQUEST_WEIGHT" }, + { "interval": "MINUTE", "intervalNum": 1, "limit": 1200, "rateLimitType": "ORDERS" } + ], + "serverTime": 1565613908500, + "assets": [ + { "asset": "BUSD", "marginAvailable": true, "autoAssetExchange": "0" }, + { "asset": "USDT", "marginAvailable": true, "autoAssetExchange": "0" }, + { "asset": "BNB", "marginAvailable": false, "autoAssetExchange": null } + ], + "symbols": [ + { + "symbol": "BLZUSDT", + "pair": "BLZUSDT", + "contractType": "PERPETUAL", + "deliveryDate": 4133404800000, + "onboardDate": 1598252400000, + "status": "TRADING", + "maintMarginPercent": "2.5000", + "requiredMarginPercent": "5.0000", + "baseAsset": "BLZ", + "quoteAsset": "USDT", + "marginAsset": "USDT", + "pricePrecision": 5, + "quantityPrecision": 0, + "baseAssetPrecision": 8, + "quotePrecision": 8, + "underlyingType": "COIN", + "underlyingSubType": ["STORAGE"], + "settlePlan": 0, + "triggerProtect": "0.15", + "filters": [ + { "filterType": "PRICE_FILTER", "maxPrice": "300", "minPrice": "0.0001", "tickSize": "0.0001" }, + { "filterType": "LOT_SIZE", "maxQty": "10000000", "minQty": "1", "stepSize": "1" }, + { "filterType": "MARKET_LOT_SIZE", "maxQty": "590119", "minQty": "1", "stepSize": "1" }, + { "filterType": "MAX_NUM_ORDERS", "limit": 200 }, + { "filterType": "MIN_NOTIONAL", "notional": "5.0" }, + { "filterType": "PERCENT_PRICE", "multiplierUp": "1.1500", "multiplierDown": "0.8500", "multiplierDecimal": "4" }, + { "filterType": "POSITION_RISK_CONTROL", "positionControlSide": "NONE" }, + { "filterType": "SOME_FUTURE_FILTER", "foo": "bar" } + ], + "OrderType": ["LIMIT", "MARKET", "STOP", "STOP_MARKET", "TAKE_PROFIT", "TAKE_PROFIT_MARKET", "TRAILING_STOP_MARKET"], + "orderTypes": ["LIMIT", "MARKET", "STOP", "STOP_MARKET", "TAKE_PROFIT", "TAKE_PROFIT_MARKET", "TRAILING_STOP_MARKET"], + "timeInForce": ["GTC", "IOC", "FOK", "GTX", "GTD", "RPI"], + "liquidationFee": "0.010000", + "marketTakeBound": "0.30" + } + ], + "timezone": "UTC" +} diff --git a/tests/mocks/futures/market/funding_info.json b/tests/mocks/futures/market/funding_info.json new file mode 100644 index 00000000..e444ac5a --- /dev/null +++ b/tests/mocks/futures/market/funding_info.json @@ -0,0 +1,3 @@ +[ + { "symbol": "BLZUSDT", "adjustedFundingRateCap": "0.02500000", "adjustedFundingRateFloor": "-0.02500000", "fundingIntervalHours": 8, "disclaimer": false } +] diff --git a/tests/mocks/futures/market/funding_rate.json b/tests/mocks/futures/market/funding_rate.json new file mode 100644 index 00000000..558a048f --- /dev/null +++ b/tests/mocks/futures/market/funding_rate.json @@ -0,0 +1,4 @@ +[ + { "symbol": "BTCUSDT", "fundingTime": 1698768000000, "fundingRate": "0.00010000", "markPrice": "34287.54619963", "rateType": "Regular" }, + { "symbol": "BTCUSDT", "fundingTime": 1698796800000, "fundingRate": "0.00010000", "markPrice": "34393.00000000", "rateType": "Regular" } +] diff --git a/tests/mocks/futures/market/historical_trades.json b/tests/mocks/futures/market/historical_trades.json new file mode 100644 index 00000000..b8e3f230 --- /dev/null +++ b/tests/mocks/futures/market/historical_trades.json @@ -0,0 +1,3 @@ +[ + { "id": 28457, "price": "4.00000100", "qty": "12.00000000", "quoteQty": "8000.00", "time": 1499865549590, "isBuyerMaker": true, "isRPITrade": false } +] diff --git a/tests/mocks/futures/market/index_constituents.json b/tests/mocks/futures/market/index_constituents.json new file mode 100644 index 00000000..e732298c --- /dev/null +++ b/tests/mocks/futures/market/index_constituents.json @@ -0,0 +1,8 @@ +{ + "symbol": "BTCUSDT", + "time": 1745401553408, + "constituents": [ + { "exchange": "binance", "symbol": "BTCUSDT", "price": "94057.03000000", "weight": "0.51282051" }, + { "exchange": "coinbase", "symbol": "BTC-USDT", "price": "94085.14000000", "weight": "0.15384615" } + ] +} diff --git a/tests/mocks/futures/market/insurance_balance.json b/tests/mocks/futures/market/insurance_balance.json new file mode 100644 index 00000000..675a4f6d --- /dev/null +++ b/tests/mocks/futures/market/insurance_balance.json @@ -0,0 +1,3 @@ +[ + { "symbols": ["BNBUSDT", "BTCUSDT"], "assets": [ { "asset": "USDC", "marginBalance": "299999998.6497832", "updateTime": 1745366402000 }, { "asset": "USDT", "marginBalance": "793930579.315848", "updateTime": 1745366402000 } ] } +] diff --git a/tests/mocks/futures/market/long_short_ratio.json b/tests/mocks/futures/market/long_short_ratio.json new file mode 100644 index 00000000..457b5bb4 --- /dev/null +++ b/tests/mocks/futures/market/long_short_ratio.json @@ -0,0 +1,4 @@ +[ + { "symbol": "BTCUSDT", "longShortRatio": "1.8105", "longAccount": "0.6442", "shortAccount": "0.3558", "timestamp": 1583139600000 }, + { "symbol": "BTCUSDT", "longShortRatio": "0.5576", "longAccount": "0.3580", "shortAccount": "0.6420", "timestamp": 1583139900000 } +] diff --git a/tests/mocks/futures/market/mark_price.json b/tests/mocks/futures/market/mark_price.json new file mode 100644 index 00000000..36878f8a --- /dev/null +++ b/tests/mocks/futures/market/mark_price.json @@ -0,0 +1,10 @@ +{ + "symbol": "BTCUSDT", + "markPrice": "11793.63104562", + "indexPrice": "11781.80495970", + "estimatedSettlePrice": "11781.16138815", + "lastFundingRate": "0.00038246", + "interestRate": "0.00010000", + "nextFundingTime": 1597392000000, + "time": 1597370495002 +} diff --git a/tests/mocks/futures/market/symbol_adl_risk.json b/tests/mocks/futures/market/symbol_adl_risk.json new file mode 100644 index 00000000..7d3036fa --- /dev/null +++ b/tests/mocks/futures/market/symbol_adl_risk.json @@ -0,0 +1 @@ +{ "symbol": "BTCUSDT", "adlRisk": "low", "updateTime": 1597370495002 } diff --git a/tests/mocks/futures/market/taker_long_short_ratio.json b/tests/mocks/futures/market/taker_long_short_ratio.json new file mode 100644 index 00000000..e09b0ab3 --- /dev/null +++ b/tests/mocks/futures/market/taker_long_short_ratio.json @@ -0,0 +1,4 @@ +[ + { "buySellRatio": "1.5586", "buyVol": "387.3300", "sellVol": "248.5030", "timestamp": 1585614900000 }, + { "buySellRatio": "1.3104", "buyVol": "343.9290", "sellVol": "248.5030", "timestamp": 1583139900000 } +] diff --git a/tests/mocks/general/exchange_info_2026.json b/tests/mocks/general/exchange_info_2026.json new file mode 100644 index 00000000..36e4daa9 --- /dev/null +++ b/tests/mocks/general/exchange_info_2026.json @@ -0,0 +1,47 @@ +{ + "timezone": "UTC", + "serverTime": 1565246363776, + "rateLimits": [ + { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 6000 } + ], + "exchangeFilters": [ + { "filterType": "EXCHANGE_MAX_NUM_ORDERS", "maxNumOrders": 1000 }, + { "filterType": "EXCHANGE_MAX_NUM_ORDER_LISTS", "maxNumOrderLists": 20 } + ], + "symbols": [ + { + "symbol": "ETHBTC", + "status": "TRADING", + "baseAsset": "ETH", + "baseAssetPrecision": 8, + "quoteAsset": "BTC", + "quotePrecision": 8, + "quoteAssetPrecision": 8, + "baseCommissionPrecision": 8, + "quoteCommissionPrecision": 8, + "orderTypes": ["LIMIT", "LIMIT_MAKER", "MARKET", "STOP_LOSS", "STOP_LOSS_LIMIT", "TAKE_PROFIT", "TAKE_PROFIT_LIMIT"], + "icebergAllowed": true, + "ocoAllowed": true, + "otoAllowed": true, + "opoAllowed": true, + "quoteOrderQtyMarketAllowed": true, + "allowTrailingStop": false, + "cancelReplaceAllowed": false, + "amendAllowed": false, + "pegInstructionsAllowed": true, + "isSpotTradingAllowed": true, + "isMarginTradingAllowed": true, + "filters": [ + { "filterType": "PRICE_FILTER", "minPrice": "0.00000100", "maxPrice": "100000.00000000", "tickSize": "0.00000100" }, + { "filterType": "MAX_NUM_ORDER_LISTS", "maxNumOrderLists": 20 }, + { "filterType": "MAX_NUM_ORDER_AMENDS", "maxNumOrderAmends": 10 }, + { "filterType": "BRAND_NEW_FILTER", "whatever": 1 } + ], + "permissions": [], + "permissionSets": [["SPOT", "MARGIN"]], + "defaultSelfTradePreventionMode": "NONE", + "allowedSelfTradePreventionModes": ["NONE", "EXPIRE_TAKER", "EXPIRE_MAKER", "EXPIRE_BOTH", "DECREMENT", "TRANSFER"] + } + ], + "sors": [ { "baseAsset": "BTC", "symbols": ["BTCUSDT", "BTCUSDC"] } ] +} diff --git a/tests/mocks/market/rolling_window_tickers_mini.json b/tests/mocks/market/rolling_window_tickers_mini.json new file mode 100644 index 00000000..937eff4a --- /dev/null +++ b/tests/mocks/market/rolling_window_tickers_mini.json @@ -0,0 +1,30 @@ +[ + { + "symbol": "BTCUSDT", + "openPrice": "20825.27000000", + "highPrice": "20972.46000000", + "lowPrice": "20327.92000000", + "lastPrice": "20671.14000000", + "volume": "72.65112300", + "quoteVolume": "1502240.91155513", + "openTime": 1655432400000, + "closeTime": 1655446835460, + "firstId": 11147809, + "lastId": 11149775, + "count": 1967 + }, + { + "symbol": "BNBBTC", + "openPrice": "0.01036170", + "highPrice": "0.01049850", + "lowPrice": "0.01033870", + "lastPrice": "0.01044700", + "volume": "166.67000000", + "quoteVolume": "1.73858301", + "openTime": 1655432400000, + "closeTime": 1655446835460, + "firstId": 2351674, + "lastId": 2352034, + "count": 361 + } +] diff --git a/tests/mocks/market/trades.json b/tests/mocks/market/trades.json new file mode 100644 index 00000000..5075e71d --- /dev/null +++ b/tests/mocks/market/trades.json @@ -0,0 +1,3 @@ +[ + { "id": 28457, "price": "4.00000100", "qty": "12.00000000", "quoteQty": "48.000012", "time": 1499865549590, "isBuyerMaker": true, "isBestMatch": true } +] diff --git a/tests/mocks/market/trading_day_ticker.json b/tests/mocks/market/trading_day_ticker.json new file mode 100644 index 00000000..70d43869 --- /dev/null +++ b/tests/mocks/market/trading_day_ticker.json @@ -0,0 +1,17 @@ +{ + "symbol": "BTCUSDT", + "priceChange": "-83.13000000", + "priceChangePercent": "-0.317", + "weightedAvgPrice": "26234.58803036", + "openPrice": "26304.80000000", + "highPrice": "26397.46000000", + "lowPrice": "26088.34000000", + "lastPrice": "26221.67000000", + "volume": "18495.35066000", + "quoteVolume": "485217905.04210480", + "openTime": 1695686400000, + "closeTime": 1695772799999, + "firstId": 3220151555, + "lastId": 3220849281, + "count": 697727 +} diff --git a/tests/util_tests.rs b/tests/util_tests.rs index cc51fc18..bbc6c0f5 100644 --- a/tests/util_tests.rs +++ b/tests/util_tests.rs @@ -59,4 +59,44 @@ mod tests { ulps = 2 )); } + + #[test] + fn percent_encode_keeps_unreserved_and_encodes_the_rest() { + assert_eq!(percent_encode("BTCUSDT"), "BTCUSDT"); + assert_eq!(percent_encode("x-HNA2TXFJabc_1.2~"), "x-HNA2TXFJabc_1.2~"); + assert_eq!( + percent_encode(r#"["BTCUSDT","BNBUSDT"]"#), + "%5B%22BTCUSDT%22%2C%22BNBUSDT%22%5D" + ); + assert_eq!(percent_encode("a b&c=d"), "a%20b%26c%3Dd"); + assert_eq!(percent_encode("12"), "%EF%BC%91%EF%BC%92"); + } + + #[test] + fn build_request_encodes_values_in_alphabetical_order() { + let mut parameters: BTreeMap = BTreeMap::new(); + parameters.insert("symbols".into(), json_string_array(&["BTCUSDT", "BNBUSDT"])); + parameters.insert("limit".into(), "5".into()); + assert_eq!( + build_request(parameters), + "limit=5&symbols=%5B%22BTCUSDT%22%2C%22BNBUSDT%22%5D" + ); + } + + #[test] + fn sign_hmac_matches_binance_documentation_example() { + // Example from the Binance Spot REST API docs, "SIGNED Endpoint Examples for POST /api/v3/order" + let secret = "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j"; + let payload = "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000×tamp=1499827319559"; + assert_eq!( + sign_hmac(secret, payload), + "c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71" + ); + } + + #[test] + fn json_string_array_format() { + assert_eq!(json_string_array(&["A"]), r#"["A"]"#); + assert_eq!(json_string_array::<&str>(&[]), "[]"); + } } diff --git a/tests/websocket_tests.rs b/tests/websocket_tests.rs new file mode 100644 index 00000000..66b9506c --- /dev/null +++ b/tests/websocket_tests.rs @@ -0,0 +1,279 @@ +use binance::config::Config; +use binance::futures::websockets::{ + futures_stream_url, FuturesMarket, FuturesStreamRoute, FuturesWebSockets, FuturesWebsocketEvent, +}; +use binance::util::sign_hmac; +use binance::websockets::{user_data_stream_subscribe_request, WebSockets, WebsocketEvent}; +use std::cell::RefCell; +use std::rc::Rc; + +fn spot_events(messages: &[&str]) -> Vec { + let events = Rc::new(RefCell::new(Vec::new())); + let sink = events.clone(); + let mut ws = WebSockets::new(move |event| { + sink.borrow_mut().push(event); + Ok(()) + }); + for msg in messages { + ws.test_handle_msg(msg).unwrap(); + } + let out = events.borrow().clone(); + out +} + +fn futures_events(messages: &[&str]) -> Vec { + let events = Rc::new(RefCell::new(Vec::new())); + let sink = events.clone(); + let mut ws = FuturesWebSockets::new(move |event| { + sink.borrow_mut().push(event); + Ok(()) + }); + for msg in messages { + ws.test_handle_msg(msg).unwrap(); + } + let out = events.borrow().clone(); + out +} + +#[test] +fn spot_execution_report_through_ws_api_wrapper() { + let msg = r#"{"subscriptionId":0,"event":{"e":"executionReport","E":1499405658658,"s":"ETHBTC","c":"mUvoqJxFIILMdfAW5iGSOW","S":"BUY","o":"LIMIT","f":"GTC","q":"1.00000000","p":"0.10264410","P":"0.00000000","F":"0.00000000","g":-1,"C":"","x":"NEW","X":"NEW","r":"NONE","i":4293153,"l":"0.00000000","z":"0.00000000","L":"0.00000000","n":"0","N":null,"T":1499405658657,"t":-1,"v":3,"I":8641984,"w":true,"m":false,"M":false,"O":1499405658657,"Z":"0.00000000","Y":"0.00000000","Q":"0.00000000","W":1499405658657,"V":"NONE","eR":"INSUFFICIENT_LIQUIDITY"}}"#; + let events = spot_events(&[msg]); + assert_eq!(events.len(), 1); + match &events[0] { + WebsocketEvent::OrderTrade(e) => { + assert_eq!(e.symbol, "ETHBTC"); + assert_eq!(e.order_id, 4293153); + assert_eq!(e.working_time, Some(1499405658657)); + assert_eq!(e.self_trade_prevention_mode.as_deref(), Some("NONE")); + assert_eq!(e.prevented_match_id, Some(3)); + assert_eq!(e.expiry_reason.as_deref(), Some("INSUFFICIENT_LIQUIDITY")); + } + other => panic!("unexpected {:?}", other), + } +} + +#[test] +fn spot_account_events_are_dispatched_by_name() { + let position = r#"{"e":"outboundAccountPosition","E":1564034571105,"u":1564034571073,"B":[{"a":"ETH","f":"10000.000000","l":"0.000000"}]}"#; + let balance = + r#"{"e":"balanceUpdate","E":1573200697110,"a":"BTC","d":"100.00000000","T":1573200697068}"#; + let list = r#"{"e":"listStatus","E":1564035303637,"s":"ETHBTC","g":2,"c":"OCO","l":"EXEC_STARTED","L":"EXECUTING","r":"NONE","C":"F4QN4G8DlFATFlIUQ0cjdD","T":1564035303625,"O":[{"s":"ETHBTC","i":17,"c":"AJYsMjErWJesZvqlJCTUgL"},{"s":"ETHBTC","i":18,"c":"bfYPSQdLoqAJeNrOr9adzq"}]}"#; + let lock = r#"{"e":"externalLockUpdate","E":1581557507324,"a":"NEO","d":"10.00000000","T":1581557507268}"#; + let terminated = + r#"{"subscriptionId":0,"event":{"e":"eventStreamTerminated","E":1728973001334}}"#; + let shutdown = r#"{"e":"serverShutdown","E":1728973001334}"#; + let events = spot_events(&[position, balance, list, lock, terminated, shutdown]); + assert_eq!(events.len(), 6); + assert!( + matches!(&events[0], WebsocketEvent::OutboundAccountPosition(e) if e.balances[0].asset == "ETH") + ); + assert!( + matches!(&events[1], WebsocketEvent::SpotBalanceUpdate(e) if e.delta == "100.00000000") + ); + assert!( + matches!(&events[2], WebsocketEvent::ListStatus(e) if e.orders.len() == 2 && e.order_list_id == 2) + ); + assert!(matches!(&events[3], WebsocketEvent::ExternalLockUpdate(e) if e.asset == "NEO")); + assert!(matches!( + &events[4], + WebsocketEvent::EventStreamTerminated(_) + )); + assert!(matches!(&events[5], WebsocketEvent::ServerShutdown(_))); +} + +#[test] +fn spot_ws_api_responses_are_checked() { + let ok = r#"{"id":"5494febb","status":200,"result":{"subscriptionId":0}}"#; + assert!(spot_events(&[ok]).is_empty()); + + let mut ws = WebSockets::new(|_| Ok(())); + let err = ws + .test_handle_msg(r#"{"id":"5494febb","status":400,"error":{"code":-1022,"msg":"Signature for this request is not valid."}}"#) + .unwrap_err(); + assert!(err.to_string().contains("-1022"), "{}", err); +} + +#[test] +fn spot_market_streams_still_parse() { + let trade = r#"{"e":"trade","E":1672515782136,"s":"BNBBTC","t":12345,"p":"0.001","q":"100","T":1672515782136,"m":true,"M":true}"#; + let events = spot_events(&[trade]); + assert!(matches!(&events[0], WebsocketEvent::Trade(e) if e.trade_id == 12345)); +} + +#[test] +fn user_data_stream_subscribe_request_is_signed_over_sorted_params() { + let request = + user_data_stream_subscribe_request("my-api-key", "my-secret", 5000, 1770736694138, "req-1"); + let value: serde_json::Value = serde_json::from_str(&request).unwrap(); + assert_eq!(value["id"], "req-1"); + assert_eq!(value["method"], "userDataStream.subscribe.signature"); + assert_eq!(value["params"]["apiKey"], "my-api-key"); + assert_eq!(value["params"]["timestamp"], 1770736694138u64); + assert_eq!(value["params"]["recvWindow"], 5000); + let expected = sign_hmac( + "my-secret", + "apiKey=my-api-key&recvWindow=5000×tamp=1770736694138", + ); + assert_eq!(value["params"]["signature"], expected); + + let no_window = user_data_stream_subscribe_request("k", "s", 0, 1, "id"); + let value: serde_json::Value = serde_json::from_str(&no_window).unwrap(); + assert!(value["params"].get("recvWindow").is_none()); + assert_eq!( + value["params"]["signature"], + sign_hmac("s", "apiKey=k×tamp=1") + ); +} + +#[test] +fn config_has_ws_api_endpoints() { + assert_eq!( + Config::default().ws_api_endpoint, + "wss://ws-api.binance.com:443/ws-api/v3" + ); + assert_eq!( + Config::testnet().ws_api_endpoint, + "wss://ws-api.testnet.binance.vision/ws-api/v3" + ); +} + +#[test] +fn futures_user_data_events() { + let algo = r#"{"e":"ALGO_UPDATE","T":1568879465650,"E":1568879465651,"o":{"caid":"myAlgo","aid":2146760,"at":"CONDITIONAL","o":"TRAILING_STOP_MARKET","s":"BTCUSDT","S":"SELL","ps":"BOTH","f":"GTC","q":"0.5","X":"TRIGGERED","ai":"8886774","ap":"0","aq":"0","act":"MARKET","tp":"0","p":"0","V":"NONE","wt":"MARK_PRICE","pm":"NONE","cp":false,"pP":true,"R":true,"tt":1568879465650,"gtd":0,"rm":"","ia":true}}"#; + let lite = r#"{"e":"TRADE_LITE","E":1721895408092,"T":1721895408214,"s":"BTCUSDT","q":"0.001","p":"0","m":false,"c":"z8hcUoOsqEdKMeprq6","S":"BUY","L":"64089.20","l":"0.040","t":109100866,"i":8886774}"#; + let order = r#"{"e":"ORDER_TRADE_UPDATE","E":1568879465651,"T":1568879465650,"o":{"s":"BTCUSDT","c":"TEST","S":"SELL","o":"LIMIT","f":"GTC","q":"0.001","p":"9910","ap":"0","sp":"0","x":"EXPIRED","X":"EXPIRED","i":8886774,"l":"0","z":"0","L":"0","N":"USDT","n":"0","T":1568879465650,"t":0,"b":"0","a":"9.91","m":false,"R":false,"wt":"CONTRACT_PRICE","ot":"LIMIT","ps":"LONG","cp":false,"pP":false,"si":0,"ss":0,"rp":"0","V":"EXPIRE_TAKER","pm":"OPPONENT","gtd":0,"er":"8","M":"7"}}"#; + let account = r#"{"e":"ACCOUNT_UPDATE","E":1564745798939,"T":1564745798938,"a":{"m":"FUNDING_FEE","B":[{"a":"USDT","wb":"122624.12345678","cw":"100.12345678","bc":"50.12345678"}],"P":[{"s":"BTCUSDT","pa":"20","ep":"6563.66500","bep":"6563.7","cr":"0","up":"2850.21200","mt":"isolated","iw":"13200.70726908","ps":"LONG"}],"S":"BTCUSDT"}}"#; + let margin_call = r#"{"e":"MARGIN_CALL","E":1587727187525,"cw":"3.16812045","p":[{"s":"ETHUSDT","ps":"LONG","pa":"1.327","mt":"CROSSED","iw":"0","mp":"187.17127","up":"-1.166074","mm":"1.614445"}]}"#; + let config_update = r#"{"e":"ACCOUNT_CONFIG_UPDATE","E":1611646737479,"T":1611646737476,"ac":{"s":"BTCUSDT","l":25}}"#; + let expired = r#"{"e":"listenKeyExpired","E":1576653824250,"listenKey":"abc"}"#; + let events = futures_events(&[ + algo, + lite, + order, + account, + margin_call, + config_update, + expired, + ]); + assert_eq!(events.len(), 7); + match &events[0] { + FuturesWebsocketEvent::AlgoUpdate(e) => { + assert_eq!(e.algo_order.algo_id, 2146760); + assert_eq!(e.algo_order.algo_status, "TRIGGERED"); + assert_eq!(e.algo_order.order_id.as_deref(), Some("8886774")); + assert_eq!(e.algo_order.is_activated, Some(true)); + } + other => panic!("unexpected {:?}", other), + } + assert!( + matches!(&events[1], FuturesWebsocketEvent::TradeLite(e) if e.order_id == 8886774 && e.last_filled_price == "64089.20") + ); + match &events[2] { + FuturesWebsocketEvent::OrderTrade(e) => { + assert_eq!(e.order.expiry_reason.as_deref(), Some("8")); + assert_eq!(e.order.price_match.as_deref(), Some("OPPONENT")); + assert_eq!( + e.order.self_trade_prevention_mode.as_deref(), + Some("EXPIRE_TAKER") + ); + assert_eq!(e.order.modify_id.as_deref(), Some("7")); + } + other => panic!("unexpected {:?}", other), + } + match &events[3] { + FuturesWebsocketEvent::AccountUpdate(e) => { + assert_eq!(e.data.symbol.as_deref(), Some("BTCUSDT")); + assert_eq!( + e.data.positions[0].breakeven_price.as_deref(), + Some("6563.7") + ); + } + other => panic!("unexpected {:?}", other), + } + assert!( + matches!(&events[4], FuturesWebsocketEvent::MarginCall(e) if e.positions[0].symbol == "ETHUSDT") + ); + assert!( + matches!(&events[5], FuturesWebsocketEvent::AccountConfigUpdate(e) if e.leverage_config.as_ref().unwrap().leverage == 25) + ); + assert!(matches!( + &events[6], + FuturesWebsocketEvent::UserDataStreamExpiredEvent(_) + )); +} + +#[test] +fn futures_mark_price_stream_with_moving_average() { + let msg = r#"{"e":"markPriceUpdate","E":1562305380000,"s":"BTCUSDT","p":"11794.15000000","i":"11784.62659091","P":"11784.25641265","r":"0.00038167","ap":"11790.1","T":1562306400000}"#; + let events = futures_events(&[msg]); + assert!( + matches!(&events[0], FuturesWebsocketEvent::MarkPrice(e) if e.mark_price_moving_average.as_deref() == Some("11790.1")) + ); +} + +#[test] +fn futures_stream_routes() { + assert_eq!( + FuturesStreamRoute::for_stream("btcusdt@depth"), + FuturesStreamRoute::Public + ); + assert_eq!( + FuturesStreamRoute::for_stream("btcusdt@depth20@100ms"), + FuturesStreamRoute::Public + ); + assert_eq!( + FuturesStreamRoute::for_stream("btcusdt@bookTicker"), + FuturesStreamRoute::Public + ); + assert_eq!( + FuturesStreamRoute::for_stream("!bookTicker"), + FuturesStreamRoute::Public + ); + assert_eq!( + FuturesStreamRoute::for_stream("btcusdt@aggTrade"), + FuturesStreamRoute::Market + ); + assert_eq!( + FuturesStreamRoute::for_stream("btcusdt@markPrice@1s"), + FuturesStreamRoute::Market + ); + assert_eq!( + FuturesStreamRoute::for_stream("!markPrice@arr"), + FuturesStreamRoute::Market + ); + assert_eq!( + FuturesStreamRoute::for_stream("btcusdt@kline_1m"), + FuturesStreamRoute::Market + ); + assert_eq!( + FuturesStreamRoute::for_stream( + "XaEAKTsQSRLZAGH9tuIu37plSRsdjmlAVBoNYPUITlTAko1WI22PgmBMpI1rS8Yh" + ), + FuturesStreamRoute::Private + ); + assert_eq!( + futures_stream_url( + &FuturesMarket::USDM, + FuturesStreamRoute::Market, + "btcusdt@aggTrade" + ), + "wss://fstream.binance.com/market/ws/btcusdt@aggTrade" + ); + assert_eq!( + futures_stream_url( + &FuturesMarket::USDMTestnet, + FuturesStreamRoute::Private, + "key" + ), + "wss://fstream.binancefuture.com/private/ws/key" + ); + assert_eq!( + futures_stream_url( + &FuturesMarket::COINM, + FuturesStreamRoute::Root, + "btcusd_perp@aggTrade" + ), + "wss://dstream.binance.com/ws/btcusd_perp@aggTrade" + ); +} From 572c89b2fcc3e897ae69eb46bb4f1b69388877fd Mon Sep 17 00:00:00 2001 From: carlosmiei <43336371+carlosmiei@users.noreply.github.com> Date: Fri, 30 Oct 2026 15:50:17 +0400 Subject: [PATCH 2/3] fix: make nightly clippy and rustfmt CI jobs pass - Format with nightly rustfmt (binop_separator = "Back" is only honored there). - Allow clippy::result_large_err: error_chain's Error is 152 bytes and boxing it would change the public Result type. - Drop `return bail!(...)` diverging sub-expressions, use `?` instead of a match, and remove a redundant to_string in the spot account module. Co-Authored-By: Claude Fable 5.1 --- src/account.rs | 13 +++++-------- src/futures/account.rs | 10 +++++----- src/lib.rs | 3 ++- tests/websocket_tests.rs | 2 ++ 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/account.rs b/src/account.rs index 74cb045a..927bf0a1 100644 --- a/src/account.rs +++ b/src/account.rs @@ -1466,7 +1466,7 @@ impl Account { S: Into, { if !is_start_time_valid(&start_time) { - return bail!("Start time should be less than the current time"); + bail!("Start time should be less than the current time"); } let mut parameters: BTreeMap = BTreeMap::new(); @@ -1485,10 +1485,10 @@ impl Account { S: Into, { if end_time <= start_time { - return bail!("End time should be greater than start time"); + bail!("End time should be greater than start time"); } if !is_start_time_valid(&start_time) { - return bail!("Start time should be less than the current time"); + bail!("Start time should be less than the current time"); } self.get_trades(symbol, start_time, end_time) } @@ -1497,10 +1497,7 @@ impl Account { where S: Into, { - let mut trades = match self.trade_history_from(symbol, start_time) { - Ok(trades) => trades, - Err(e) => return Err(e), - }; + let mut trades = self.trade_history_from(symbol, start_time)?; trades.retain(|trade| trade.time <= end_time); Ok(trades) } @@ -1533,7 +1530,7 @@ impl Account { if let Some(params) = request_params { for (key, value) in params { - order_parameters.insert(key, value.to_string()); + order_parameters.insert(key, value); } } diff --git a/src/futures/account.rs b/src/futures/account.rs index 7fa64960..b085bb13 100644 --- a/src/futures/account.rs +++ b/src/futures/account.rs @@ -97,11 +97,11 @@ impl OrderType { pub fn is_conditional(&self) -> bool { matches!( self, - Self::Stop - | Self::StopMarket - | Self::TakeProfit - | Self::TakeProfitMarket - | Self::TrailingStopMarket + Self::Stop | + Self::StopMarket | + Self::TakeProfit | + Self::TakeProfitMarket | + Self::TrailingStopMarket ) } } diff --git a/src/lib.rs b/src/lib.rs index 2b8e4396..0c2d9a95 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,7 +6,8 @@ unused_import_braces, clippy::all )] -#![allow(clippy::needless_doctest_main)] +// `error_chain`'s `Error` is 152 bytes; boxing it would change the public `Result` type. +#![allow(clippy::needless_doctest_main, clippy::result_large_err)] #![warn( clippy::wildcard_imports, clippy::manual_string_new, diff --git a/tests/websocket_tests.rs b/tests/websocket_tests.rs index 66b9506c..dd28e9bb 100644 --- a/tests/websocket_tests.rs +++ b/tests/websocket_tests.rs @@ -18,6 +18,7 @@ fn spot_events(messages: &[&str]) -> Vec { ws.test_handle_msg(msg).unwrap(); } let out = events.borrow().clone(); + drop(ws); out } @@ -32,6 +33,7 @@ fn futures_events(messages: &[&str]) -> Vec { ws.test_handle_msg(msg).unwrap(); } let out = events.borrow().clone(); + drop(ws); out } From 66547234a05bba283e71546e05edb4fc7379f791 Mon Sep 17 00:00:00 2001 From: carlosmiei <43336371+carlosmiei@users.noreply.github.com> Date: Fri, 30 Oct 2026 15:55:10 +0400 Subject: [PATCH 3/3] docs: note updated Spot and Futures API coverage in README Co-Authored-By: Claude Fable 5.1 --- README.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 594810a2..06933bdd 100644 --- a/README.md +++ b/README.md @@ -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) @@ -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