Skip to main content

WebsocketApi

Struct WebsocketApi 

Source
pub struct WebsocketApi { /* private fields */ }

Implementations§

Source§

impl WebsocketApi

Source

pub fn subscribe_on_ws_events<F>(&self, callback: F) -> Subscription
where F: FnMut(WebsocketEvent) + Send + 'static,

Subscribes to WebSocket events with a provided callback function.

§Arguments
  • callback - A mutable function that will be called when a WebSocket event is received. The callback takes a WebsocketEvent as its parameter.
§Returns

A Subscription that can be used to manage the event subscription.

§Examples

let subscription = websocket_api.subscribe_on_ws_events(|event| { // Handle WebSocket event });

Source

pub fn unsubscribe_from_ws_events(&self, subscription: Subscription)

Unsubscribes from WebSocket events using the provided Subscription.

§Arguments
  • subscription - The Subscription to unsubscribe from WebSocket events.
§Examples

let subscription = websocket_api.subscribe_on_ws_events(|event| { // Handle WebSocket event }); websocket_api.unsubscribe_from_ws_events(subscription);

Source

pub async fn disconnect(&self) -> Result<()>

Disconnects the WebSocket connection.

§Returns

A Result indicating whether the disconnection was successful. Returns an error if the disconnection fails.

§Errors

Returns an anyhow::Error if the connection fails.

§Examples

let result = websocket_api.disconnect().await;

Source

pub async fn ping_server(&self)

Sends a ping message to the WebSocket server to check the connection status.

§Examples

websocket_api.ping_server().await;

This method sends a lightweight ping request to verify the WebSocket connection is still active.

Source

pub async fn is_connected(&self) -> bool

Checks if the WebSocket connection is currently active.

§Returns

A bool indicating whether the WebSocket connection is established and active.

§Examples

let is_active = websocket_api.is_connected().await; if is_active { // WebSocket connection is active }

This method provides a way to check the current status of the WebSocket connection.

Source

pub async fn send_message<R: DeserializeOwned + Send + Sync + 'static>( &self, method: &str, payload: BTreeMap<String, Value>, ) -> Result<WebsocketApiResponse<R>, WebsocketError>

Sends an unsigned WebSocket message with the specified method and payload.

§Type Parameters
  • R - The response type to deserialize the message into.
§Arguments
  • method - The WebSocket method to invoke.
  • payload - A map of key-value pairs representing the message payload.
§Returns

A Result containing the deserialized response or a WebsocketError.

§Errors

Returns a WebsocketError if the WebSocket connection fails or the response cannot be deserialized.

§Examples

let response = websocket_api.send_message::(“method_name”, payload).await;

Source

pub async fn send_signed_message<R: DeserializeOwned + Send + Sync + 'static>( &self, method: &str, payload: BTreeMap<String, Value>, ) -> Result<WebsocketApiResponse<R>, WebsocketError>

Sends a signed WebSocket message with the specified method and payload.

§Type Parameters
  • R - The response type to deserialize the message into.
§Arguments
  • method - The WebSocket method to invoke.
  • payload - A map of key-value pairs representing the message payload.
§Returns

A Result containing the deserialized response or a WebsocketError.

§Errors

Returns a WebsocketError if the WebSocket connection fails or the response cannot be deserialized.

§Examples

let response = websocket_api.send_signed_message::(“method_name”, payload).await;

Source

pub async fn account_commission( &self, params: AccountCommissionParams, ) -> Result<WebsocketApiResponse<Box<AccountCommissionResponseResult>>>

Account Commission Rates (USER_DATA)

Get current account commission rates.

Weight(IP): 20

Security Type: USER_DATA

Notes: Data Source: Database

§Arguments
§Returns

WebsocketApiResponse<Box<models::AccountCommissionResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn account_rate_limits_orders( &self, params: AccountRateLimitsOrdersParams, ) -> Result<WebsocketApiResponse<Vec<AccountRateLimitsOrdersResponseResultInner>>>

Unfilled Order Count (USER_DATA)

Query your current unfilled order count for all intervals.

Weight(IP): 40

Security Type: USER_DATA

Notes: Data Source: Memory

§Arguments
§Returns

WebsocketApiResponse<Vec<models::AccountRateLimitsOrdersResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn account_status( &self, params: AccountStatusParams, ) -> Result<WebsocketApiResponse<Box<AccountStatusResponseResult>>>

Account information (USER_DATA)

Query information about your account.

Weight(IP): 20

Security Type: USER_DATA

Notes: Data Source: Memory => Database

§Arguments
§Returns

WebsocketApiResponse<Box<models::AccountStatusResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn all_order_lists( &self, params: AllOrderListsParams, ) -> Result<WebsocketApiResponse<Vec<AllOrderListsResponseResultInner>>>

Account order list history (USER_DATA)

Query information about all your order lists, filtered by time range.

Weight(IP): 20

Security Type: USER_DATA

Notes: Data Source: Database

Notes:

  • If startTime and/or endTime are specified, fromId is ignored. Order lists are filtered by transactionTime of the last order list execution status update.
  • If fromId is specified, return order lists with order list ID >= fromId.
  • If no condition is specified, the most recent order lists are returned.
  • The time between startTime and endTime can’t be longer than 24 hours.
§Arguments
§Returns

WebsocketApiResponse<Vec<models::AllOrderListsResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn all_orders( &self, params: AllOrdersParams, ) -> Result<WebsocketApiResponse<Vec<AllOrdersResponseResultInner>>>

Account order history (USER_DATA)

Query information about all your orders – active, canceled, filled – filtered by time range.

Weight(IP): 20

Security Type: USER_DATA

Notes: Data Source: Database

Notes:

  • If startTime and/or endTime are specified, orderId is ignored.

Orders are filtered by time of the last execution status update.

  • If orderId is specified, return orders with order ID >= orderId.

  • If no condition is specified, the most recent orders are returned.

  • For some historical orders the cummulativeQuoteQty response field may be negative, meaning the data is not available at this time.

  • The time between startTime and endTime can’t be longer than 24 hours.

§Arguments
§Returns

WebsocketApiResponse<Vec<models::AllOrdersResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn my_allocations( &self, params: MyAllocationsParams, ) -> Result<WebsocketApiResponse<Vec<MyAllocationsResponseResultInner>>>

Account allocations (USER_DATA)

Retrieves allocations resulting from SOR order placement.

Weight(IP): 20

Security Type: USER_DATA

Notes: Data Source: Database

Supported parameter combinations:

ParametersResponse
symbolallocations from oldest to newest
symbol + startTimeoldest allocations since startTime
symbol + endTimenewest allocations until endTime
symbol + startTime + endTimeallocations within the time range
symbol + fromAllocationIdallocations by allocation ID
symbol + orderIdallocations related to an order starting with oldest
symbol + orderId + fromAllocationIdallocations related to an order by allocation ID

Note: The time between startTime and endTime can’t be longer than 24 hours.

§Arguments
§Returns

WebsocketApiResponse<Vec<models::MyAllocationsResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn my_filters( &self, params: MyFiltersParams, ) -> Result<WebsocketApiResponse<MyFiltersResponse>>

Query Relevant Filters (USER_DATA)

Retrieves the list of filters relevant to an account on a given symbol. This is the only method that shows if an account has MAX_ASSET filters applied to it.

Weight(IP): 40

Security Type: USER_DATA

Notes: Data Source: Memory

§Arguments
§Returns

WebsocketApiResponse<models::MyFiltersResponse> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn my_prevented_matches( &self, params: MyPreventedMatchesParams, ) -> Result<WebsocketApiResponse<Vec<MyPreventedMatchesResponseResultInner>>>

Account prevented matches (USER_DATA)

Displays the list of orders that were expired due to STP.

These are the combinations supported:

  • symbol + preventedMatchId
  • symbol + orderId
  • symbol + orderId + fromPreventedMatchId (limit will default to 500)
  • symbol + orderId + fromPreventedMatchId + limit
Weight: CaseWeight
If symbol is invalid2
Querying by preventedMatchId2
Querying by orderId20

Security Type: USER_DATA

Notes: Data Source: Database

§Arguments
§Returns

WebsocketApiResponse<Vec<models::MyPreventedMatchesResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn my_trades( &self, params: MyTradesParams, ) -> Result<WebsocketApiResponse<Vec<MyTradesResponseResultInner>>>

Account trade history (USER_DATA)

Query information about all your trades, filtered by time range.

Weight: ConditionWeight
Without orderId20
With orderId5

Security Type: USER_DATA

Notes: Data Source: Memory => Database

Notes:

  • If fromId is specified, return trades with trade ID >= fromId.
  • If startTime and/or endTime are specified, trades are filtered by execution time (time).
  • fromId cannot be used together with startTime and endTime.
  • If orderId is specified, only trades related to that order are returned.
  • startTime and endTime cannot be used together with orderId.
  • If no condition is specified, the most recent trades are returned.
  • The time between startTime and endTime can’t be longer than 24 hours.
§Arguments
§Returns

WebsocketApiResponse<Vec<models::MyTradesResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn open_order_lists_status( &self, params: OpenOrderListsStatusParams, ) -> Result<WebsocketApiResponse<Vec<OpenOrderListsStatusResponseResultInner>>>

Current open Order lists (USER_DATA)

Query execution status of all open order lists.

If you need to continuously monitor order status updates, please consider using WebSocket Streams:

  • userDataStream.subscribe if on an authenticated session
  • userDataStream.subscribe.signature if subscribing through signature subscription

Weight(IP): 6

Security Type: USER_DATA

Notes: Data Source: Memory -> Database

§Arguments
§Returns

WebsocketApiResponse<Vec<models::OpenOrderListsStatusResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn open_orders_status( &self, params: OpenOrdersStatusParams, ) -> Result<WebsocketApiResponse<Vec<OpenOrdersStatusResponseResultInner>>>

Current open orders (USER_DATA)

Query execution status of all open orders.

If you need to continuously monitor order status updates, please consider using WebSocket Streams:

  • userDataStream.subscribe if on an authenticated session
  • userDataStream.subscribe.signature if subscribing through signature subscription

Weight: | Parameter | Weight | | ——— | —— | | symbol | 6 | | none | 80 |

Security Type: USER_DATA

Notes: Data Source: Memory => Database

§Arguments
§Returns

WebsocketApiResponse<Vec<models::OpenOrdersStatusResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn order_amendments( &self, params: OrderAmendmentsParams, ) -> Result<WebsocketApiResponse<Vec<OrderAmendmentsResponseResultInner>>>

Query Order Amendments (USER_DATA)

Queries all amendments of a single order.

Weight(IP): 4

Security Type: USER_DATA

Notes: Data Source: Database

§Arguments
§Returns

WebsocketApiResponse<Vec<models::OrderAmendmentsResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn order_list_status( &self, params: OrderListStatusParams, ) -> Result<WebsocketApiResponse<Box<OrderListStatusResponseResult>>>

Query Order list (USER_DATA)

Check execution status of an Order list.

For execution status of individual orders, use order.status.

Weight(IP): 4

Security Type: USER_DATA

Notes: Data Source: Database

Notes:

  • origClientOrderId refers to listClientOrderId of the order list itself.

  • If both origClientOrderId and orderListId parameters are specified, only origClientOrderId is used and orderListId is ignored.

§Arguments
§Returns

WebsocketApiResponse<Box<models::OrderListStatusResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn order_status( &self, params: OrderStatusParams, ) -> Result<WebsocketApiResponse<Box<OrderStatusResponseResult>>>

Query order (USER_DATA)

Check execution status of an order.

Weight(IP): 4

Security Type: USER_DATA

Notes: Data Source: Memory => Database

Notes:

  • If both orderId and origClientOrderId are provided, the orderId is searched first, then the origClientOrderId from that result is checked against that order. If both conditions are not met the request will be rejected.

  • For some historical orders the cummulativeQuoteQty response field may be negative, meaning the data is not available at this time.

§Arguments
§Returns

WebsocketApiResponse<Box<models::OrderStatusResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn session_logon( &self, params: SessionLogonParams, ) -> Result<Vec<WebsocketApiResponse<Box<SessionLogonResponseResult>>>>

Log in with API key (USER_DATA)

Authenticate WebSocket connection using the provided API key.

After calling session.logon, you can omit apiKey and signature parameters for future requests that require them.

Note that only one API key can be authenticated.

Calling session.logon multiple times changes the current authenticated API key.

Note: Only Ed25519 keys are supported for this feature.

Weight(IP): 2

Security Type: USER_DATA

Notes: Data Source: Memory

§Arguments
§Returns

WebsocketApiResponse<Box<models::SessionLogonResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn session_logout( &self, params: SessionLogoutParams, ) -> Result<Vec<WebsocketApiResponse<Box<SessionLogoutResponseResult>>>>

Log out of the session

Forget the API key previously authenticated. If the connection is not authenticated, this request does nothing.

Note that the WebSocket connection stays open after session.logout request. You can continue using the connection, but now you will have to explicitly provide the apiKey and signature parameters where needed.

Weight(IP): 2

Security Type: NONE

Notes: Data Source: Memory

§Arguments
§Returns

WebsocketApiResponse<Box<models::SessionLogoutResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn session_status( &self, params: SessionStatusParams, ) -> Result<WebsocketApiResponse<Box<SessionStatusResponseResult>>>

Query session status

Query the status of the WebSocket connection, inspecting which API key (if any) is used to authorize requests.

Weight(IP): 2

Security Type: NONE

Notes: Data Source: Memory

§Arguments
§Returns

WebsocketApiResponse<Box<models::SessionStatusResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn exchange_info( &self, params: ExchangeInfoParams, ) -> Result<WebsocketApiResponse<ExchangeInfoResponse>>

Exchange information

Query current exchange trading rules, rate limits, and symbol information.

Weight(IP): 20

Security Type: NONE

Notes: Data Source: Memory

Notes:

  • If the value provided to symbol or symbols do not exist, the endpoint will throw an error saying the symbol is invalid.
  • All parameters are optional.
  • Only one of symbol, symbols, permissions parameters can be specified.
  • Without parameters, exchangeInfo displays all symbols with ["SPOT", "MARGIN", "LEVERAGED"] permissions.
  • In order to list all active symbols on the exchange, you need to explicitly request all permissions.
  • permissions accepts either a list of permissions, or a single permission name. E.g. "SPOT".

Examples of Symbol Permissions Interpretation from the Response:

  • [["A","B"]] means you may place an order if your account has either permission “A” or permission “B”.
  • [["A"],["B"]] means you can place an order if your account has permission “A” and permission “B”.
  • [["A"],["B","C"]] means you can place an order if your account has permission “A” and permission “B” or permission “C”. (Inclusive or is applied here, not exclusive or, so your account may have both permission “B” and permission “C”.)
§Arguments
§Returns

WebsocketApiResponse<models::ExchangeInfoResponse> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn execution_rules( &self, params: ExecutionRulesParams, ) -> Result<WebsocketApiResponse<Box<ExecutionRulesResponseResult>>>

Query Execution Rules

Query execution rules for symbols.

Weight: ParameterWeight
symbol2
symbols2 for each symbol, capped at a max of 40
symbolStatus40
None40

Security Type: NONE

Notes: Data Source: Memory

Note: No combination of multiple parameters is allowed.

§Arguments
§Returns

WebsocketApiResponse<Box<models::ExecutionRulesResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn ping( &self, params: PingParams, ) -> Result<WebsocketApiResponse<Value>>

Test connectivity

Test connectivity to the WebSocket API.

Note: You can use regular WebSocket ping frames to test connectivity as well, WebSocket API will respond with pong frames as soon as possible. ping request along with time is a safe way to test request-response handling in your application.

Weight(IP): 1

Security Type: NONE

Notes: Data Source: Memory

§Arguments
  • params: PingParams The parameters for this operation.
§Returns

WebsocketApiResponse<serde_json::Value> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn time( &self, params: TimeParams, ) -> Result<WebsocketApiResponse<Box<TimeResponseResult>>>

Check server time

Test connectivity to the WebSocket API and get the current server time.

Weight(IP): 1

Security Type: NONE

Notes: Data Source: Memory

§Arguments
  • params: TimeParams The parameters for this operation.
§Returns

WebsocketApiResponse<Box<models::TimeResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn avg_price( &self, params: AvgPriceParams, ) -> Result<WebsocketApiResponse<Box<AvgPriceResponseResult>>>

Current average price

Get current average price for a symbol.

Weight(IP): 2

Security Type: NONE

Notes: Data Source: Memory

§Arguments
§Returns

WebsocketApiResponse<Box<models::AvgPriceResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn block_trades_historical( &self, params: BlockTradesHistoricalParams, ) -> Result<WebsocketApiResponse<Vec<BlockTradesHistoricalResponseResultInner>>>

Historical Block Trades

Get block trades.

Weight(IP): 25

Security Type: NONE

Notes:

  • Data Source: Database
§Arguments
§Returns

WebsocketApiResponse<Vec<models::BlockTradesHistoricalResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn depth( &self, params: DepthParams, ) -> Result<WebsocketApiResponse<Box<DepthResponseResult>>>

Order book

Get current order book.

Note that this request returns limited market depth.

If you need to continuously monitor order book updates, please consider using WebSocket Streams:

  • <symbol>@depth<levels>
  • <symbol>@depth

You can use depth request together with <symbol>@depth streams to maintain a local order book.

Weight: Adjusted based on the limit:

LimitRequest Weight
1-1005
101-50025
501-100050
1001-5000250

Security Type: NONE

Notes: Data Source: Memory

§Arguments
  • params: DepthParams The parameters for this operation.
§Returns

WebsocketApiResponse<Box<models::DepthResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn klines( &self, params: KlinesParams, ) -> Result<WebsocketApiResponse<Vec<Vec<KlinesResponseResultInnerInner>>>>

Klines

Get klines (candlestick bars).

Klines are uniquely identified by their open & close time.

If you need access to real-time kline updates, please consider using WebSocket Streams:

  • <symbol>@kline_<interval>

If you need historical kline data, please consider using data.binance.vision.

Weight(IP): 2

Security Type: NONE

Notes: Data Source: Database

Supported kline intervals (case-sensitive):

Intervalinterval value
seconds1s
minutes1m, 3m, 5m, 15m, 30m
hours1h, 2h, 4h, 6h, 8h, 12h
days1d, 3d
weeks1w
months1M

Notes:

  • If startTime and endTime are not sent, the most recent klines are returned.
  • Supported values for timeZone:
  • Hours and minutes (e.g. -1:00, 05:45)
  • Only hours (e.g. 0, 8, 4)
  • Accepted range is strictly [-12:00 to +14:00] inclusive
  • If timeZone provided, kline intervals are interpreted in that timezone instead of UTC.
  • Note that startTime and endTime are always interpreted in UTC, regardless of timeZone.
§Arguments
§Returns

WebsocketApiResponse<Vec<Vec<models::KlinesResponseResultInnerInner>>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn reference_price( &self, params: ReferencePriceParams, ) -> Result<WebsocketApiResponse<Box<ReferencePriceResponseResult>>>

Query Reference Price

Query Reference Price

Weight(IP): 2

Security Type: NONE

Notes: Data Source: Memory

§Arguments
§Returns

WebsocketApiResponse<Box<models::ReferencePriceResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn reference_price_calculation( &self, params: ReferencePriceCalculationParams, ) -> Result<WebsocketApiResponse<Box<ReferencePriceCalculationResponseResult>>>

Query Reference Price Calculation

Query Reference Price Calculation

Weight(IP): 2

Security Type: NONE

Notes: Data Source: Memory

§Arguments
§Returns

WebsocketApiResponse<Box<models::ReferencePriceCalculationResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn ticker( &self, params: TickerParams, ) -> Result<WebsocketApiResponse<TickerResponse>>

Rolling window price change statistics

Get rolling window price change statistics with a custom window.

This request is similar to ticker.24hr but statistics are computed on demand using the arbitrary window you specify.

Note: Window size precision is limited to 1 minute. While the closeTime is the current time of the request, openTime always start on a minute boundary. As such, the effective window might be up to 59999 ms wider than the requested windowSize.

Window computation example

For example, a request for "windowSize": "7d" might result in the following window:

{
"openTime": 1659580020000,
"closeTime": 1660184865291
}

Time of the request – closeTime – is 1660184865291 (August 11, 2022 02:27:45.291). Requested window size should put the openTime 7 days before that – August 4, 02:27:45.291 – but due to limited precision it ends up a bit earlier: 1659580020000 (August 4, 2022 02:27:00), exactly at the start of a minute.

If you need to continuously monitor trading statistics, please consider using WebSocket Streams:

  • <symbol>@ticker_<window_size> or !ticker_<window-size>@arr

Weight: Adjusted based on the number of requested symbols:

SymbolsWeight
1–504 per symbol
51–100200

Security Type: NONE

Notes: Data Source: Database

Supported window sizes:

UnitwindowSize value
minutes1m, 2m59m
hours1h, 2h23h
days1d, 2d7d

Notes:

  • Either symbol or symbols must be specified.

  • Maximum number of symbols in one request: 200.

  • Window size units cannot be combined. E.g., 1d 2h is not supported.

§Arguments
§Returns

WebsocketApiResponse<models::TickerResponse> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn ticker24hr( &self, params: Ticker24hrParams, ) -> Result<WebsocketApiResponse<Ticker24hrResponse>>

24hr ticker price change statistics

Get 24-hour rolling window price change statistics.

If you need to continuously monitor trading statistics, please consider using WebSocket Streams:

  • <symbol>@ticker or !ticker@arr

  • <symbol>@miniTicker or !miniTicker@arr

If you need different window sizes,

use the ticker request.

Weight: Adjusted based on the number of requested symbols:

ParameterSymbols ProvidedWeight
symbol12
omitted80
symbols1-202
21-10040
101+80
omitted80

Security Type: NONE

Notes: Data Source: Memory

Notes:

  • symbol and symbols cannot be used together.

  • If no symbol is specified, returns information about all symbols currently trading on the exchange.

§Arguments
§Returns

WebsocketApiResponse<models::Ticker24hrResponse> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn ticker_book( &self, params: TickerBookParams, ) -> Result<WebsocketApiResponse<TickerBookResponse>>

Symbol order book ticker

Get the current best price and quantity on the order book.

If you need access to real-time order book ticker updates, please consider using WebSocket Streams:

  • <symbol>@bookTicker

Weight: Adjusted based on the number of requested symbols:

ParameterSymbols ProvidedWeight
symbol12
omitted4
symbolsAny4

Security Type: NONE

Notes: Data Source: Memory

Notes:

  • symbol and symbols cannot be used together.

  • If no symbol is specified, returns information about all symbols currently trading on the exchange.

§Arguments
§Returns

WebsocketApiResponse<models::TickerBookResponse> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn ticker_price( &self, params: TickerPriceParams, ) -> Result<WebsocketApiResponse<TickerPriceResponse>>

Symbol price ticker

Get the latest market price for a symbol.

If you need access to real-time price updates, please consider using WebSocket Streams:

  • <symbol>@aggTrade

  • <symbol>@trade

Weight: Adjusted based on the number of requested symbols:

ParameterSymbols ProvidedWeight
symbol12
omitted4
symbolsAny4

Security Type: NONE

Notes: Data Source: Memory

Notes:

  • symbol and symbols cannot be used together.

  • If no symbol is specified, returns information about all symbols currently trading on the exchange.

§Arguments
§Returns

WebsocketApiResponse<models::TickerPriceResponse> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn ticker_trading_day( &self, params: TickerTradingDayParams, ) -> Result<WebsocketApiResponse<Vec<TickerTradingDayResponseResultInner>>>

Trading Day Ticker

Price change statistics for a trading day.

Weight: 4 for each requested symbol regardless of windowSize. The weight for this request will cap at 200 once the number of symbols in the request is more than 50.

Security Type: NONE

Notes: Data Source: Database

Notes:

  • Supported values for timeZone:
  • Hours and minutes (e.g. -1:00, 05:45)
  • Only hours (e.g. 0, 8, 4)
§Arguments
§Returns

WebsocketApiResponse<Vec<models::TickerTradingDayResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn trades_aggregate( &self, params: TradesAggregateParams, ) -> Result<WebsocketApiResponse<Vec<TradesAggregateResponseResultInner>>>

Aggregate trades

Get aggregate trades.

An aggregate trade (aggtrade) represents one or more individual trades.

Trades that fill at the same time, from the same taker order, with the same price –

those trades are collected into an aggregate trade with total quantity of the individual trades.

If you need access to real-time trading activity, please consider using WebSocket Streams:

  • <symbol>@aggTrade

If you need historical aggregate trade data, please consider using data.binance.vision.

Weight(IP): 4

Security Type: NONE

Notes: Data Source: Database

  • If fromId is specified, return aggtrades with aggregate trade ID >= fromId. Use fromId and limit to page through all aggtrades.
  • If startTime and/or endTime are specified, aggtrades are filtered by execution time (T). fromId cannot be used together with startTime and endTime.
  • If no condition is specified, the most recent aggregate trades are returned.
§Arguments
§Returns

WebsocketApiResponse<Vec<models::TradesAggregateResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn trades_historical( &self, params: TradesHistoricalParams, ) -> Result<WebsocketApiResponse<Vec<TradesHistoricalResponseResultInner>>>

Historical trades

Get historical trades.

Weight(IP): 25

Security Type: NONE

Notes: Data Source: Database

Notes:

  • If fromId is not specified, the most recent trades are returned.
§Arguments
§Returns

WebsocketApiResponse<Vec<models::TradesHistoricalResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn trades_recent( &self, params: TradesRecentParams, ) -> Result<WebsocketApiResponse<Vec<TradesRecentResponseResultInner>>>

Recent trades

Get recent trades.

If you need access to real-time trading activity, please consider using WebSocket Streams:

  • <symbol>@trade

Weight(IP): 25

Security Type: NONE

Notes: Data Source: Memory

§Arguments
§Returns

WebsocketApiResponse<Vec<models::TradesRecentResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn ui_klines( &self, params: UiKlinesParams, ) -> Result<WebsocketApiResponse<Vec<Vec<KlinesResponseResultInnerInner>>>>

UI Klines

Get klines (candlestick bars) optimized for presentation.

This request is similar to klines, having the same parameters and response. uiKlines return modified kline data, optimized for presentation of candlestick charts.

Weight(IP): 2

Security Type: NONE

Notes: Data Source: Database

  • If startTime and endTime are not sent, the most recent klines are returned.
  • Supported values for timeZone:
  • Hours and minutes (e.g. -1:00, 05:45)
  • Only hours (e.g. 0, 8, 4)
  • Accepted range is strictly [-12:00 to +14:00] inclusive
  • If timeZone provided, kline intervals are interpreted in that timezone instead of UTC.
  • Note that startTime and endTime are always interpreted in UTC, regardless of timeZone.
§Arguments
§Returns

WebsocketApiResponse<Vec<Vec<models::KlinesResponseResultInnerInner>>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn open_orders_cancel_all( &self, params: OpenOrdersCancelAllParams, ) -> Result<WebsocketApiResponse<Vec<OpenOrdersCancelAllResponseResultInner>>>

Cancel open orders (TRADE)

Cancel all open orders on a symbol. This includes orders that are part of an order list.

Weight(IP): 1

Security Type: TRADE

Notes: Data Source: Matching Engine

§Arguments
§Returns

WebsocketApiResponse<Vec<models::OpenOrdersCancelAllResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn order_amend_keep_priority( &self, params: OrderAmendKeepPriorityParams, ) -> Result<WebsocketApiResponse<Box<OrderAmendKeepPriorityResponseResult>>>

Order Amend Keep Priority (TRADE)

Reduce the quantity of an existing open order.

This adds 0 orders to the EXCHANGE_MAX_ORDERS filter and the MAX_NUM_ORDERS filter.

Read Order Amend Keep Priority FAQ to learn more.

Weight(IP): 4

Unfilled Order Count: 0

Security Type: TRADE

Notes: Data Source: Matching Engine

§Arguments
§Returns

WebsocketApiResponse<Box<models::OrderAmendKeepPriorityResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn order_cancel( &self, params: OrderCancelParams, ) -> Result<WebsocketApiResponse<Box<OrderCancelResponseResult>>>

Cancel order (TRADE)

Cancel an active order.

Weight(IP): 1

Security Type: TRADE

Notes: Data Source: Matching Engine

Notes:

  • If both orderId and origClientOrderId parameters are provided, the orderId is searched first, then the origClientOrderId from that result is checked against that order. If both conditions are not met the request will be rejected.

  • newClientOrderId will replace clientOrderId of the canceled order, freeing it up for new orders.

  • If you cancel an order that is a part of an order list, the entire order list is canceled.

  • The performance for canceling an order (single cancel or as part of a cancel-replace) is always better when only orderId is sent. Sending origClientOrderId or both orderId + origClientOrderId will be slower.

§Arguments
§Returns

WebsocketApiResponse<Box<models::OrderCancelResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn order_cancel_replace( &self, params: OrderCancelReplaceParams, ) -> Result<WebsocketApiResponse<Box<OrderCancelReplaceResponseResult>>>

Cancel and replace order (TRADE)

  • Cancel an existing order and immediately place a new order instead of the canceled one.
  • A new order that was not attempted (i.e. when newOrderResult: NOT_ATTEMPTED), will still increase the unfilled order count by 1.
  • You can only cancel an individual order from an orderList using this method, but the result is the same as canceling the entire orderList.not attempted (i.e. when newOrderResult: NOT_ATTEMPTED), will still increase the unfilled order count by 1.

Weight(IP): 1

Unfilled Order Count: 1

Security Type: TRADE

Notes: Data Source: Matching Engine

Similar to the order.place request, additional mandatory parameters (*) are determined by the new order type.

Available cancelReplaceMode options:

  • STOP_ON_FAILURE – if cancellation request fails, new order placement will not be attempted.
  • ALLOW_FAILURE – new order placement will be attempted even if the cancel request fails.
Request Response
cancelReplaceMode orderRateLimitExceededMode Unfilled Order Count cancelResult newOrderResult status
STOP_ON_FAILURE DO_NOTHING Within Limits SUCCESS SUCCESS 200
FAILURE NOT_ATTEMPTED 400
SUCCESS FAILURE 409
Exceeds Limits SUCCESS SUCCESS N/A
FAILURE NOT_ATTEMPTED N/A
SUCCESS FAILURE N/A
CANCEL_ONLY Within Limits SUCCESS SUCCESS 200
FAILURE NOT_ATTEMPTED 400
SUCCESS FAILURE 409
Exceeds Limits FAILURE NOT_ATTEMPTED 429
SUCCESS FAILURE 429
ALLOW_FAILURE DO_NOTHING Within Limits SUCCESS SUCCESS 200
FAILURE FAILURE 400
FAILURE SUCCESS 409
SUCCESS FAILURE 409
Exceeds Limits SUCCESS SUCCESS N/A
FAILURE FAILURE N/A
FAILURE SUCCESS N/A
SUCCESS FAILURE N/A
CANCEL_ONLY Within Limits SUCCESS SUCCESS 200
FAILURE FAILURE 400
FAILURE SUCCESS 409
SUCCESS FAILURE 409
Exceeds Limits SUCCESS SUCCESS 200
FAILURE FAILURE 400
FAILURE SUCCESS N/A
SUCCESS FAILURE 409

Notes:

  • If both cancelOrderId and cancelOrigClientOrderId parameters are provided, the cancelOrderId is searched first, then the cancelOrigClientOrderId from that result is checked against that order. If both conditions are not met the request will be rejected.

  • cancelNewClientOrderId will replace clientOrderId of the canceled order, freeing it up for new orders.

  • newClientOrderId specifies clientOrderId value for the placed order.

A new order with the same clientOrderId is accepted only when the previous one is filled or expired.

The new order can reuse old clientOrderId of the canceled order.

  • This cancel-replace operation is not transactional.

If one operation succeeds but the other one fails, the successful operation is still executed.

For example, in STOP_ON_FAILURE mode, if the new order placement fails, the old order is still canceled.

  • Filters and order count limits are evaluated before cancellation and order placement occurs.

  • If new order placement is not attempted, your order count is still incremented.

  • Like order.cancel, if you cancel an individual order from an order list, the entire order list is canceled.

  • The performance for canceling an order (single cancel or as part of a cancel-replace) is always better when only orderId is sent. Sending origClientOrderId or both orderId + origClientOrderId will be slower.

§Arguments
§Returns

WebsocketApiResponse<Box<models::OrderCancelReplaceResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn order_list_cancel( &self, params: OrderListCancelParams, ) -> Result<WebsocketApiResponse<Box<OrderListCancelResponseResult>>>

Cancel Order list (TRADE)

Cancel an active order list.

Weight(IP): 1

Security Type: TRADE

Notes: Data Source: Matching Engine

Notes:

  • If both orderListId and listClientOrderId parameters are provided, the orderListId is searched first, then the listClientOrderId from that result is checked against that order. If both conditions are not met the request will be rejected.

  • Canceling an individual order with order.cancel will cancel the entire order list as well.

§Arguments
§Returns

WebsocketApiResponse<Box<models::OrderListCancelResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn order_list_place( &self, params: OrderListPlaceParams, ) -> Result<WebsocketApiResponse<Box<OrderListPlaceResponseResult>>>

👎Deprecated

Place new OCO - Deprecated (TRADE)

Send in a new one-cancels-the-other (OCO) pair: LIMIT_MAKER + STOP_LOSS/STOP_LOSS_LIMIT orders (called legs), where activation of one order immediately cancels the other.

This adds 1 order to EXCHANGE_MAX_ORDERS filter and the MAX_NUM_ORDERS filter

Weight(IP): 1

Unfilled Order Count: 1

Security Type: TRADE

Notes: Data Source: Matching Engine

Notes:

  • listClientOrderId parameter specifies listClientOrderId for the OCO pair.

A new OCO with the same listClientOrderId is accepted only when the previous one is filled or completely expired.

listClientOrderId is distinct from clientOrderId of individual orders.

  • limitClientOrderId and stopClientOrderId specify clientOrderId values for both legs of the OCO.

A new order with the same clientOrderId is accepted only when the previous one is filled or expired.

  • Price restrictions on the legs:
sidePrice relation
BUYprice < market price < stopPrice
SELLprice > market price > stopPrice
  • Both legs have the same quantity.

However, you can set different iceberg quantity for individual legs.

If stopIcebergQty is used, stopLimitTimeInForce must be GTC.

  • trailingDelta applies only to the STOP_LOSS/STOP_LOSS_LIMIT leg of the OCO.
§Arguments
§Returns

WebsocketApiResponse<Box<models::OrderListPlaceResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

§Deprecation

Deprecated: This method may be removed in a future version.

Source

pub async fn order_list_place_oco( &self, params: OrderListPlaceOcoParams, ) -> Result<WebsocketApiResponse<Box<OrderListPlaceOcoResponseResult>>>

Place new Order list - OCO (TRADE)

Send in an one-cancels-the-other (OCO) pair, where activation of one order immediately cancels the other.

  • An OCO has 2 orders called the above order and below order.

  • One of the orders must be a LIMIT_MAKER/TAKE_PROFIT/TAKE_PROFIT_LIMIT order and the other must be STOP_LOSS or STOP_LOSS_LIMIT order.

  • Price restrictions:

  • If the OCO is on the SELL side:

  • LIMIT_MAKER/TAKE_PROFIT_LIMIT price > Last Traded Price > STOP_LOSS/STOP_LOSS_LIMIT stopPrice

  • TAKE_PROFIT stopPrice > Last Traded Price > STOP_LOSS/STOP_LOSS_LIMIT stopPrice

  • If the OCO is on the BUY side:

  • LIMIT_MAKER price < Last Traded Price < STOP_LOSS/STOP_LOSS_LIMIT stopPrice

  • TAKE_PROFIT stopPrice > Last Traded Price > STOP_LOSS/STOP_LOSS_LIMIT stopPrice

  • OCOs add 2 orders to the EXCHANGE_MAX_ORDERS filter and MAX_NUM_ORDERS filter.

Weight(IP): 1

Unfilled Order Count: 2

Security Type: TRADE

Notes: Data Source: Matching Engine

§Arguments
§Returns

WebsocketApiResponse<Box<models::OrderListPlaceOcoResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn order_list_place_opo( &self, params: OrderListPlaceOpoParams, ) -> Result<WebsocketApiResponse<Box<OrderListPlaceOpoResponseResult>>>

OPO (TRADE)

Place an OPO.

  • OPOs add 2 orders to the EXCHANGE_MAX_NUM_ORDERS filter and MAX_NUM_ORDERS filter.

Weight(IP): 1

Unfilled Order Count: 2

Security Type: TRADE

Notes: Data Source: Matching Engine

§Arguments
§Returns

WebsocketApiResponse<Box<models::OrderListPlaceOpoResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn order_list_place_opoco( &self, params: OrderListPlaceOpocoParams, ) -> Result<WebsocketApiResponse<Box<OrderListPlaceOpocoResponseResult>>>

OPOCO (TRADE)

Place an OPOCO.

Weight(IP): 1

Unfilled Order Count: 3

Security Type: TRADE

Notes: Data Source: Matching Engine

§Arguments
§Returns

WebsocketApiResponse<Box<models::OrderListPlaceOpocoResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn order_list_place_oto( &self, params: OrderListPlaceOtoParams, ) -> Result<WebsocketApiResponse<Box<OrderListPlaceOtoResponseResult>>>

Place new Order list - OTO (TRADE)

Places an OTO.

  • An OTO (One-Triggers-the-Other) is an order list comprised of 2 orders.

  • The first order is called the working order and must be LIMIT or LIMIT_MAKER. Initially, only the working order goes on the order book.

  • The second order is called the pending order. It can be any order type except for MARKET orders using parameter quoteOrderQty. The pending order is only placed on the order book when the working order gets fully filled.

  • If either the working order or the pending order is cancelled individually, the other order in the order list will also be canceled or expired.

  • When the order list is placed, if the working order gets immediately fully filled, the placement response will show the working order as FILLED but the pending order will still appear as PENDING_NEW. You need to query the status of the pending order again to see its updated status.

  • OTOs add 2 orders to the EXCHANGE_MAX_NUM_ORDERS filter and MAX_NUM_ORDERS filter.

Weight(IP): 1

Unfilled Order Count: 2

Security Type: TRADE

Notes: Data Source: Matching Engine

Mandatory parameters based on pendingType or workingType

Depending on the pendingType or workingType, some optional parameters will become mandatory.

TypeAdditional mandatory parametersAdditional information
workingType = LIMITworkingTimeInForce
pendingType = LIMITpendingPrice, pendingTimeInForce
pendingType = STOP_LOSS or TAKE_PROFITpendingStopPrice and/or pendingTrailingDelta
pendingType =STOP_LOSS_LIMIT or TAKE_PROFIT_LIMITpendingPrice, pendingStopPrice and/or pendingTrailingDelta, pendingTimeInForce
§Arguments
§Returns

WebsocketApiResponse<Box<models::OrderListPlaceOtoResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn order_list_place_otoco( &self, params: OrderListPlaceOtocoParams, ) -> Result<WebsocketApiResponse<Box<OrderListPlaceOtocoResponseResult>>>

Place new Order list - OTOCO (TRADE)

Place an OTOCO.

  • An OTOCO (One-Triggers-One-Cancels-the-Other) is an order list comprised of 3 orders.
  • The first order is called the working order and must be LIMIT or LIMIT_MAKER. Initially, only the working order goes on the order book.
  • The behavior of the working order is the same as the OTO.
  • OTOCO has 2 pending orders (pending above and pending below), forming an OCO pair. The pending orders are only placed on the order book when the working order gets fully filled.
  • The rules of the pending above and pending below follow the same rules as the Order list OCO.
  • OTOCOs add 3 orders to the EXCHANGE_MAX_NUM_ORDERS filter and MAX_NUM_ORDERS filter.

Weight(IP): 1

Unfilled Order Count: 3

Security Type: TRADE

Notes: Data Source: Matching Engine

Mandatory parameters based on pendingAboveType, pendingBelowType or workingType

Depending on the pendingAboveType/pendingBelowType or workingType, some optional parameters will become mandatory.

TypeAdditional mandatory parametersAdditional information
workingType = LIMITworkingTimeInForce
pendingAboveType= LIMIT_MAKERpendingAbovePrice
pendingAboveType = STOP_LOSS/TAKE_PROFITpendingAboveStopPrice and/or pendingAboveTrailingDelta
pendingAboveType=STOP_LOSS_LIMIT/TAKE_PROFIT_LIMITpendingAbovePrice, pendingAboveStopPrice and/or pendingAboveTrailingDelta, pendingAboveTimeInForce
pendingBelowType= LIMIT_MAKERpendingBelowPrice
pendingBelowType= STOP_LOSS/TAKE_PROFITpendingBelowStopPrice and/or pendingBelowTrailingDelta
pendingBelowType=STOP_LOSS_LIMIT/TAKE_PROFIT_LIMITpendingBelowPrice, pendingBelowStopPrice and/or pendingBelowTrailingDelta, pendingBelowTimeInForce
§Arguments
§Returns

WebsocketApiResponse<Box<models::OrderListPlaceOtocoResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn order_place( &self, params: OrderPlaceParams, ) -> Result<WebsocketApiResponse<Box<OrderPlaceResponseResult>>>

Place new order (TRADE)

Send in a new order.

This adds 1 order to the EXCHANGE_MAX_ORDERS filter and the MAX_NUM_ORDERS filter.

Weight(IP): 1

Unfilled Order Count: 1

Security Type: TRADE

Notes: Data Source: Matching Engine

Certain parameters (*) become mandatory based on the order type:

Order type Mandatory parameters
LIMIT
  • timeInForce
  • price
  • quantity
LIMIT_MAKER
  • price
  • quantity
MARKET
  • quantity or quoteOrderQty
STOP_LOSS
  • quantity
  • stopPrice or trailingDelta
STOP_LOSS_LIMIT
  • timeInForce
  • price
  • quantity
  • stopPrice or trailingDelta
TAKE_PROFIT
  • quantity
  • stopPrice or trailingDelta
TAKE_PROFIT_LIMIT
  • timeInForce
  • price
  • quantity
  • stopPrice or trailingDelta

Supported order types:

Order type Description
LIMIT

Buy or sell quantity at the specified price or better.

LIMIT_MAKER

LIMIT order that will be rejected if it immediately matches and trades as a taker.

This order type is also known as a POST-ONLY order.

MARKET

Buy or sell at the best available market price.

  • MARKET order with quantity parameter specifies the amount of the base asset you want to buy or sell. Actually executed quantity of the quote asset will be determined by available market liquidity.

    E.g., a MARKET BUY order on BTCUSDT for "quantity": "0.1000" specifies that you want to buy 0.1 BTC at the best available price. If there is not enough BTC at the best price, keep buying at the next best price, until either your order is filled, or you run out of USDT, or market runs out of BTC.

  • MARKET order with quoteOrderQty parameter specifies the amount of the quote asset you want to spend (when buying) or receive (when selling). Actually executed quantity of the base asset will be determined by available market liquidity.

    E.g., a MARKET BUY on BTCUSDT for "quoteOrderQty": "100.00" specifies that you want to buy as much BTC as you can for 100 USDT at the best available price. Similarly, a SELL order will sell as much available BTC as needed for you to receive 100 USDT (before commission).

STOP_LOSS

Execute a MARKET order for given quantity when specified conditions are met.

I.e., when stopPrice is reached, or when trailingDelta is activated.

STOP_LOSS_LIMIT

Place a LIMIT order with given parameters when specified conditions are met.

TAKE_PROFIT

Like STOP_LOSS but activates when market price moves in the favorable direction.

TAKE_PROFIT_LIMIT

Like STOP_LOSS_LIMIT but activates when market price moves in the favorable direction.

Notes on using parameters for Pegged Orders:

  • These parameters are allowed for LIMIT, LIMIT_MAKER, STOP_LOSS_LIMIT, TAKE_PROFIT_LIMIT orders.
  • If pegPriceType is specified, price becomes optional. Otherwise, it is still mandatory.
  • pegPriceType=PRIMARY_PEG means the primary peg, that is the best price on the same side of the order book as your order.
  • pegPriceType=MARKET_PEG means the market peg, that is the best price on the opposite side of the order book from your order.
  • Use pegOffsetType and pegOffsetValue to request a price level other than the best one. These parameters must be specified together.

Available timeInForce options, setting how long the order should be active before expiration:

TIFDescription
GTCGood ’til Canceled – the order will remain on the book until you cancel it, or the order is completely filled.
IOCImmediate or Cancel – the order will be filled for as much as possible, the unfilled quantity immediately expires.
FOKFill or Kill – the order will expire unless it cannot be immediately filled for the entire quantity.

Notes:

  • newClientOrderId specifies clientOrderId value for the order.

A new order with the same clientOrderId is accepted only when the previous one is filled or expired.

  • Any LIMIT or LIMIT_MAKER order can be made into an iceberg order by specifying the icebergQty.

An order with an icebergQty must have timeInForce set to GTC.

  • Trigger order price rules for STOP_LOSS/TAKE_PROFIT orders:

  • stopPrice must be above market price: STOP_LOSS BUY, TAKE_PROFIT SELL

  • stopPrice must be below market price: STOP_LOSS SELL, TAKE_PROFIT BUY

  • MARKET orders using quoteOrderQty follow LOT_SIZE filter rules.

The order will execute a quantity that has notional value as close as possible to requested quoteOrderQty.

§Arguments
§Returns

WebsocketApiResponse<Box<models::OrderPlaceResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn order_test( &self, params: OrderTestParams, ) -> Result<WebsocketApiResponse<Box<OrderTestResponseResult>>>

Test new order (TRADE)

Test order placement.

Validates new order parameters and verifies your signature but does not send the order into the matching engine.

Weight: | Condition | Request Weight | | — | — | | Without computeCommissionRates | 1 | | With computeCommissionRates | 20 |

Security Type: TRADE

Notes: Data Source: Memory

§Arguments
§Returns

WebsocketApiResponse<Box<models::OrderTestResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn sor_order_place( &self, params: SorOrderPlaceParams, ) -> Result<WebsocketApiResponse<Vec<SorOrderPlaceResponseResultInner>>>

Place new order using SOR (TRADE)

Places an order using smart order routing (SOR).

This adds 1 order to the EXCHANGE_MAX_ORDERS filter and the MAX_NUM_ORDERS filter.

Read SOR FAQ to learn more.

Weight(IP): 1

Unfilled Order Count: 1

Security Type: TRADE

Notes: Data Source: Matching Engine

Note: sor.order.place only supports LIMIT and MARKET orders. quoteOrderQty is not supported.

§Arguments
§Returns

WebsocketApiResponse<Vec<models::SorOrderPlaceResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn sor_order_test( &self, params: SorOrderTestParams, ) -> Result<WebsocketApiResponse<Box<SorOrderTestResponseResult>>>

Test new order using SOR (TRADE)

Test new order creation and signature/recvWindow using smart order routing (SOR). Creates and validates a new order but does not send it into the matching engine.

Weight: | Condition | Request Weight | | — | — | | Without computeCommissionRates | 1 | | With computeCommissionRates | 20 |

Security Type: TRADE

Notes: Data Source: Memory

§Arguments
§Returns

WebsocketApiResponse<Box<models::SorOrderTestResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn session_subscriptions( &self, params: SessionSubscriptionsParams, ) -> Result<WebsocketApiResponse<Vec<SessionSubscriptionsResponseResultInner>>>

Listing all subscriptions

Note:

  • Users should track the corresponding subscription status of related accounts as needed.

Weight(IP): 2

Security Type: NONE

Notes: Data Source: Memory

§Arguments
§Returns

WebsocketApiResponse<Vec<models::SessionSubscriptionsResponseResultInner>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn user_data_stream_subscribe( &self, params: UserDataStreamSubscribeParams, ) -> Result<(WebsocketApiResponse<Box<UserDataStreamSubscribeResponseResult>>, Arc<WebsocketStream<UserDataStreamEventsResponse>>)>

Subscribe to User Data Stream

Subscribe to the User Data Stream in the current WebSocket connection.

Notes:

  • This method requires an authenticated WebSocket connection using Ed25519 keys. Please refer to session.logon.
  • To check the subscription status, use session.status, see the userDataStream flag indicating you have have an active subscription.
  • User Data Stream events are available in both JSON and SBE sessions.
  • Please refer to User Data Streams for the event format details.
  • For SBE, only SBE schema 2:1 or later is supported.

Weight(IP): 2

Security Type: NONE

§Arguments
§Returns

WebsocketApiResponse<Box<models::UserDataStreamSubscribeResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn user_data_stream_subscribe_signature( &self, params: UserDataStreamSubscribeSignatureParams, ) -> Result<(WebsocketApiResponse<Box<UserDataStreamSubscribeResponseResult>>, Arc<WebsocketStream<UserDataStreamEventsResponse>>)>

Subscribe to User Data Stream through signature subscription (USER_STREAM)

Weight(IP): 2

Security Type: USER_STREAM

Notes: Data Source: Memory

§Arguments
§Returns

WebsocketApiResponse<Box<models::UserDataStreamSubscribeResponseResult>> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Source

pub async fn user_data_stream_unsubscribe( &self, params: UserDataStreamUnsubscribeParams, ) -> Result<WebsocketApiResponse<Value>>

WebSocket Unsubscribe from User Data Stream

Stop listening to the User Data Stream in the current WebSocket connection.

Note that session.logout will only close the subscription created with userDataStream.subscribe but not subscriptions opened with userDataStream.subscribe.signature.

Weight(IP): 2

§Arguments
§Returns

WebsocketApiResponse<serde_json::Value> on success.

§Errors

Returns an anyhow::Error if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.

For full API details, see the Binance API Documentation.

Trait Implementations§

Source§

impl Clone for WebsocketApi

Source§

fn clone(&self) -> WebsocketApi

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

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

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

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

Source§

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

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

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

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

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

fn in_current_span(self) -> Instrumented<Self>

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

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

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

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

Source§

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

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

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

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

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

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

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

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

Source§

type Error = Infallible

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

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

Performs the conversion.
Source§

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

Source§

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

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

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

Performs the conversion.
Source§

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

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

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

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

fn with_current_subscriber(self) -> WithDispatch<Self>

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