binance API client

Related tags

Cryptography bian-rs
Overview

bian-rs

币安API Rust async SDK

完成情况

接口 现货 U本位合约 币本位合约 欧式期权
http 🚧 开发中 🆗 🚧 开发中 未开始
websocket 🚧 开发中 🆗 🚧 开发中 未开始

使用

Cargo.toml 中添加依赖

[dependencies]
tokio = { version = "1", features = ["full"] }
bian-rs = { git = "https://github.com/PrivateRookie/bian-rs.git", branch = "main" }

在国内使用需要设置代理,bian-rs 通过 HTTP_PROXYHTTPS_PROXY 环境变量自动 设置代理。

http 接口

use bian_rs::client::UFuturesHttpClient;
use std::env;

#[tokio::main]
async fn main() {
    let api_key = "your api key";
    let secret_key = "your secret key";
    // 默认 endpoint
    let client = UFuturesHttpClient::default_endpoint(api_key.to_string(), secret_key.to_string());
    // 测试是否连通
    client.ping().await.unwrap();
}

websocket 接口

fn init_client() -> UFuturesWSClient {
    dotenv::dotenv().unwrap();
    let proxy = env::var("WS_PROXY").expect("cant not find WS_PROXY env variable");
    let proxy = Some(proxy.to_socket_addrs().unwrap().next().unwrap());
    UFuturesWSClient::default_endpoint(proxy, base_url)
}

#[test]
fn test_ws_kline() {
    let client = init_client();
    let mut stream = client
        .kline("btcusdt".to_string(), enums::Interval::Min1)
        .unwrap();
    for _ in 0..5 {
        dbg!(stream.read_stream_single().unwrap());
    }
}

贡献代码

因为币安 API 接口众多,若是 bian-rs 还没有实现, 可能需要自己实现。 不过好在bian-rs 使用过程宏 bian-proc::api 辅助生成 API 请求函数,你只需要定义API 请求类型,返回数据类型,接着共通过 #[api( url)] 即可。

如获取账户余额

首先在 src/params.rs 定义请求参数类型

use serde::Serialize;

#[derive(Debug, Serialize)]
pub struct AccountBalanceV2 {
    pub recv_window: Option<i64>,
    pub timestamp: i64,
}

接着在 src/response.rs 定义返回数据类型

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountBalance {
    pub account_alias: String,
    pub asset: String,
    #[serde(deserialize_with = "string_as_f64")]
    pub balance: f64,
    #[serde(deserialize_with = "string_as_f64")]
    pub cross_wallet_balance: f64,
    #[serde(deserialize_with = "string_as_f64")]
    pub cross_un_pnl: f64,
    #[serde(deserialize_with = "string_as_f64")]
    pub available_balance: f64,
    #[serde(deserialize_with = "string_as_f64")]
    pub max_withdraw_amount: f64,
}

币安返回的数据字段名为 camelCase, 需要通过 serde(rename_all) 将其重命名为符合 Rust lint 的 snake_case。 另外币安的某些数据是以字符的保存的浮点数或整数,可以通过 #[serde(deserialize_with = "string_as_f64")]#[serde(deserialize_with = "string_as_usize")] 将其直接转换为 f64 或 usize。

接着在 impl UFuturesHttpClient 块中使用 api! 来实现函数。

api! 接受两个参数,http 方法和 url. http 方法除了 GET, POST, PUT, DELETE 外,对于需要签名的请求,可以在前面加上 S,如 SGET

BianResult> { } ">
/// 账户余额V2
#[api(SGET "fapi/v2/balance")]
pub async fn account_balance_v2(
    &self,
    param: params::AccountBalanceV2,
) -> BianResult<Vec> {
}

接着编写测试用例,确保 url, 请求参数和返回值类型都已定义正确。

#[tokio::test]
async fn test_balance() {
    let (api_key, secret_key) = init_test();
    let client = UFuturesHttpClient::new(&api_key, &secret_key, BASE_URL);
    let now = chrono::Utc::now();
    let params = params::AccountBalanceV2 {
        timestamp: now.timestamp_millis(),
        recv_window: None,
    };
    client.account_balance_v2(params).await.unwrap();
}

TO DO

  • websocket 客户端
  • API 限速处理
  • 更多API...
You might also like...
Rust client to Opensea's APIs and Ethereum smart contracts

opensea.rs Rust bindings & CLI to the Opensea API and Contracts CLI Usage Run cargo r -- --help to get the top level help menu: opensea-cli 0.1.0 Choo

Simple template for building smart contract(Rust) and RPC Client(web3.js) on Solana (WIP) ⛏👷🚧⚠️
Simple template for building smart contract(Rust) and RPC Client(web3.js) on Solana (WIP) ⛏👷🚧⚠️

Solana BPF Boilerplate Simple template for building smart contract(Rust) and RPC Client(web3.js) on Solana This boilerplate provides the following. Si

An encrypted multi client messaging system written in pure Rust

🚩 Preamble This is a pure Rust multi-client encrypted messaging system, also known as Edode's Secured Messaging System. It is an end-to-end(s) commun

Easily and securely share files from the command line. A fully featured Firefox Send client.

Notice: the default Send host is provided by @timvisee (info). Please consider to donate and help keep it running. ffsend Easily and securely share fi

Rust implementation of the i2p client/server/router protocols

ri2p Rust implementation of the i2p client/server/router protocols Status Common Commands cargo build: Builds the ri2p binary cargo run: Runs the ri2p

The fast, light, and robust client for Ethereum-like networks.

The Fastest and most Advanced Ethereum Client. » Download the latest release « Table of Contents Description Technical Overview Building 3.1 Building

Reference client for NEAR Protocol

Reference implementation of NEAR Protocol About NEAR NEAR's purpose is to enable community-driven innovation to benefit people around the world. To ac

In addition to encryption library, pure RUST implementation of SSH-2.0 client protocol

In addition to encryption library, pure RUST implementation of SSH-2.0 client protocol

The Fastest and most Advanced Ethereum Client

The Fastest and most Advanced Ethereum Client. » Download the latest release « Table of Contents Description Technical Overview Building 3.1 Building

Comments
  • cargo添加依赖后无法fetch head,导致无法正确下载为依赖

    cargo添加依赖后无法fetch head,导致无法正确下载为依赖

    RT

    Caused by:
      process didn't exit successfully: `git fetch --force --update-head-ok https://github.com/PrivateRookie/bian-rs.git refs/heads/master:refs/remotes/origin/master HEAD:refs/remotes/origin/HEAD` (exit code: 128)
      --- stderr
      fatal: couldn't find remote ref refs/heads/master
    
    opened by veink-y 4
  • 一个结构体需要更新

    一个结构体需要更新

    ``SpotExchangeInfo>SpotSymbolFilter>MAX_POSITION

    thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: DecodeError("missing field `max_position` at line 1 column 942330")'

    可能是需要添加一个

     #[serde(rename = "maxPosition")]
    
    opened by veink-y 0
Owner
多少事,从来急。天地转,光阴迫。
null
Gnosis Safe Tx Service API client & associated tooling

Safe Transaction Service API Client Using the SDK Instantiate an API client use safe_sdk::SafeClient; /// From a chain id, by looking up hardcoded en

Nomad 3 Dec 15, 2022
A smart-contract api and client for revm

revmup A smart contract and client API for revm. Features: Auto-generate contracts that interact directly with revm without needing ethers provider Co

Dave Bryson 17 Aug 6, 2023
Coinbase pro client for Rust

Coinbase pro client for Rust Supports SYNC/ASYNC/Websocket-feed data support Features private and public API sync and async support websocket-feed sup

null 126 Dec 30, 2022
Rust Ethereum 2.0 Client

Lighthouse: Ethereum 2.0 An open-source Ethereum 2.0 client, written in Rust and maintained by Sigma Prime. Documentation Overview Lighthouse is: Read

Sigma Prime 2.1k Jan 6, 2023
Reference client for NEAR Protocol

Reference implementation of NEAR Protocol About NEAR NEAR's purpose is to enable community-driven innovation to benefit people around the world. To ac

NEAR 2k Jan 3, 2023
The Parity Bitcoin client

The Parity Bitcoin client. Gitter Installing from source Installing the snap Running tests Going online Importing bitcoind database Command line inter

Parity Technologies 714 Dec 21, 2022
The fast, light, and robust client for the Ethereum mainnet.

OpenEthereum Fast and feature-rich multi-network Ethereum client. » Download the latest release « Table of Contents Description Technical Overview Bui

OpenEthereum 1.6k Dec 28, 2022
rust client libraries to deal with the current cardano mainnet (byron / cardano-sl)

Rust implementation of Cardano primitives, helpers, and related applications Cardano Rust is a modular toolbox of Cardano’s cryptographic primitives,

Input Output 275 Oct 9, 2022
A CLI Twitter client using kuon

petit A TUI Twitter client using kuon Install Use cargo $ cargo install petit How to use # Login for twitter $ petit login # Tweet $ petit tweet "Thi

uzimaru0000 11 Jan 12, 2022
The Mullvad VPN client app for desktop and mobile

Mullvad VPN desktop and mobile app Welcome to the Mullvad VPN client app. This repository contains all the source code for the desktop and mobile vers

Mullvad VPN 3k Jan 2, 2023