Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

README.md

Binance Rust Alpha Connector

Crates.io docs.rs Build Status License: MIT

This is a client library for the Binance Alpha API, enabling developers to interact programmatically with Binance Alpha. The library provides tools to access curated early-stage token data, track Alpha project metrics and integrate discovery-focused market information into applications through the REST API:

Table of Contents

Supported Features

  • REST API Endpoints:
    • /bapi/defi/v1/*
  • WebSocket Endpoints: Real-time data streaming.
  • Inclusion of test cases and examples for quick onboarding.

Installation

Enable the alpha feature in your Cargo.toml under binance-sdk:

[dependencies]
binance-sdk = { version = "1.0.0", features = ["alpha"] }

In your code, import the alpha client:

use binance_sdk::alpha;

Documentation

REST APIs

All REST API endpoints are available through the rest_api module. Note that some endpoints require authentication using your Binance API credentials.

use binance_sdk::config::ConfigurationRestApi;
use binance_sdk::alpha;

let configuration = ConfigurationRestApi::builder()
  .api_key("YOUR_API_KEY")
  .api_secret("YOUR_SECRET_KEY")
  .build()?;

let client = alpha::AlphaRestApi::production(configuration);
let response = client.get_exchange_info(params).await?;

let data = response.data().await?;
println!("{:#?}", data);

Configuration Options

The alpha module can be configured with the following options via the ConfigurationRestApi builder pattern:

  • timeout (u64): Request timeout in milliseconds (default: 1000)
  • proxy (ProxyConfig): HTTP/HTTPS proxy settings
    • host (String): Proxy server hostname.
    • port (u16): Proxy server port.
    • protocol (String): Proxy protocol (http or https).
    • auth (ProxyAuth): Proxy authentication credentials:
      • username (String): Proxy username.
      • password (String): Proxy password.
  • keep_alive (bool): Enable HTTP keep-alive (default: true)
  • compression (bool): Enable response compression (default: true)
  • retries (u32): Number of retry attempts for failed requests (default: 3)
  • backoff (u64): Delay in milliseconds between retries (default: 1000)
  • agent (HttpAgent): Custom HTTP agent for advanced TLS configuration
  • private_key (PrivateKey): RSA or ED25519 private key for request signing (raw string or PEM file path)
  • private_key_passphrase (String): Passphrase for the private key, if encrypted

Refer to the configuration for more details.

Timeout

You can configure a timeout for requests in milliseconds. If the request exceeds the specified timeout, it will be aborted. See the Timeout example for detailed usage.

Proxy

The REST API supports HTTP/HTTPS proxy configurations. See the Proxy example for detailed usage.

Keep-Alive

Enable HTTP keep-alive for persistent connections. See the Keep-Alive example for detailed usage.

Compression

Enable or disable response compression. See the Compression example for detailed usage.

Retries

Configure the number of retry attempts and delay in milliseconds between retries for failed requests. See the Retries example for detailed usage.

HTTPS Agent

Customize the HTTPS agent for advanced TLS configurations. See the HTTPS Agent example for detailed usage.

Key Pair Based Authentication

The REST API supports key pair-based authentication for secure communication. You can use RSA or Ed25519 keys for signing requests. See the Key Pair Based Authentication example for detailed usage.

Certificate Pinning

To enhance security, you can use certificate pinning with the agent option in the configuration. This ensures the client only communicates with servers using specific certificates. See the Certificate Pinning example for detailed usage.

Error Handling

Errors are represented by the following types:

  • ConnectorClientError: General client error
  • UnauthorizedError: Invalid or missing authentication
  • ForbiddenError: Access to resource forbidden
  • TooManyRequestsError: Rate limit exceeded
  • RateLimitBanError: IP banned due to rate limits
  • ServerError: Internal server error
  • NetworkError: Network connectivity issues
  • NotFoundError: Resource not found
  • BadRequestError: Invalid request parameters

See the Error Handling example for detailed usage. Refer to the error module for more information.

Websocket Streams

The WebSocket Streams provide real-time data feeds for market trades, candlesticks, and more. Use the websocket_streams module to interact with these endpoints.

use binance_sdk::config::ConfigurationWebsocketStreams;
use binance_sdk::alpha;

let configuration = ConfigurationWebsocketStreams::builder().build()?;

let client = alpha::AlphaWsStreams::production(configuration);
let connection = client.connect().await?;
let params = alpha::websocket_streams::AllBookTickerStreamParams::default();
let stream = connection.all_book_ticker_stream(params).await?;

stream.on_message(|data| {
  println!("{:#?}", data);
});

Configuration Options

The alpha module can be configured with the following options via the ConfigurationWebsocketStreams builder pattern:

  • reconnect_delay (u64): Specify the delay between reconnection attempts in milliseconds (default: 5000)
  • mode (WebsocketMode): Choose between single and pool connection modes
    • Single: A single WebSocket connection
    • Pool: A pool of WebSocket connections
  • agent (AgentConnector): Customize the WebSocket agent for advanced configurations
  • handshake (WebsocketHandshakeFn): Provide a custom async TLS/WebSocket handshake (e.g. to tunnel through a SOCKS5 proxy)

Refer to the configuration for more details.

Reconnect Delay

Specify the delay in milliseconds between WebSocket reconnection attempts. See the Reconnect Delay example for detailed usage.

WebSocket Agent

Customize the agent for advanced configurations. See the WebSocket Agent example for detailed usage.

Custom Handshake

Supply a custom async TLS/WebSocket handshake to open your own transport (such as a SOCKS5 tunnel) before the handshake completes. See the Custom Handshake example for detailed usage.

Connection Mode

Choose between Single and Pool connection modes for WebSocket connections. The Single mode uses a single WebSocket connection, while the Pool mode uses a pool of WebSocket connections. See the Connection Mode example for detailed usage.

Certificate Pinning

To enhance security, you can use certificate pinning with the agent option in the configuration. This ensures the client only communicates with servers using specific certificates. See the Certificate Pinning example for detailed usage.

Unsubscribing from Streams

You can unsubscribe from specific WebSocket streams using the unsubscribe method. This is useful for managing active subscriptions without closing the connection.

use tokio::time::{Duration, sleep};

use binance_sdk::config::ConfigurationWebsocketStreams;
use binance_sdk::alpha;

let configuration = ConfigurationWebsocketStreams::builder().build()?;

let client = alpha::AlphaWsStreams::production(configuration);
let connection = client.connect().await?;
let params = alpha::websocket_streams::AllBookTickerStreamParams::default();
let stream = connection.all_book_ticker_stream(params).await?;

stream.on_message(|data| {
  println!("{:#?}", data);
});

sleep(Duration::from_secs(10)).await;

stream.unsubscribe().await;

Automatic Connection Renewal

The WebSocket connection is automatically renewed for WebSocket Streams connections, before the 24 hours expiration of the API key. This ensures continuous connectivity.

Logging

This crate ships with an optional default logger that you can enable with a single call:

use binance_sdk::logger;

fn main() {
    // Initialize the default logger once at the start of your application
    logger::init();

    // ... rest of your code
}

The logger integrates with the Rust tracing ecosystem and behaves as follows:

  • If another global subscriber is already set, logger::init() is a no-op and does not override your existing logging setup.
  • If no subscriber is set yet, it installs the crate’s default global subscriber (with sensible defaults) so you immediately get structured logs from the connector.

Testing

To run the tests for the Alpha module:

cargo test --features alpha

Tests cover:

  • REST API endpoint integration
  • Error scenarios and edge cases

Contributing

Contributions are welcome!

Since this repository contains auto-generated code, we encourage you to start by opening a GitHub issue to discuss your ideas or suggest improvements. This helps ensure that changes align with the project's goals and auto-generation processes.

To contribute:

  1. Open a GitHub issue describing your suggestion or the bug you've identified.
  2. If it's determined that changes are necessary, the maintainers will merge the changes into the main branch.

Please ensure that all tests pass with --features alpha if you're making a direct contribution. Submit a pull request only after discussing and confirming the change.

Thank you for your contributions!

Disclaimer

This SDK is provided by Binance on an "as is" and "as available" basis for use at your own risk. Binance makes no representations or warranties of any kind, whether express or implied, as to the operation of the SDK, its accuracy, reliability, completeness, or fitness for any particular purpose.

To the fullest extent permitted by law, Binance shall not be liable for any losses, damages, or expenses of any kind arising from or in connection with your use of, or inability to use, this SDK, including but not limited to any financial losses resulting from errors, bugs, interruptions, or inaccuracies in the SDK.

Your use of this SDK to access the Binance Platform is subject to the Binance API Key Terms and the Binance Terms of Use, which shall prevail in the event of any conflict with this disclaimer. You are solely responsible for any orders or transactions executed through the Binance Platform using this SDK.

This SDK is not intended to constitute investment advice or a recommendation to buy, sell, or hold any digital asset. You should independently evaluate and verify all information before acting.

License

This project is licensed under the MIT License. See the LICENSE file for details.