8 releases (4 breaking)

0.6.0 Dec 7, 2023
0.5.1 Mar 20, 2023
0.4.3 Feb 28, 2023
0.4.2 Jan 30, 2023
0.1.1 Dec 23, 2022

#739 in Magic Beans

Download history 9/week @ 2023-12-05 17/week @ 2024-02-06 1/week @ 2024-02-13 25/week @ 2024-02-20 33/week @ 2024-02-27 1/week @ 2024-03-05 7/week @ 2024-03-12

67 downloads per month

MIT license

135KB
2K SLoC

crypto-botters

日本語は下にあります

This is a Rust library for communicating with cryptocurrency exchange APIs.

This library:

  • is asynchronous
  • supports WebSocket
  • supports deserializing responses into user-defined types

Supported Exchanges

The following Exchanges are currently supported.

Exchange Official API document Example usages of this library
Binance API document Examples
bitFlyer API document Examples
Bybit API document Examples
Coincheck API document Examples

Usage

More than 20 examples can be found in the examples directory.

Cargo.toml:

[dependencies]
crypto-botters = { version = "0.6", features = ["binance", "bitflyer", "bybit", "coincheck"] }

Enable the features for the exchanges that you use.

Example

HTTP

use std::env;
use crypto_botters::{Client, binance::{BinanceAuth, BinanceHttpUrl, BinanceOption}};

#[tokio::main]
async fn main() {
  let key = env::var("BINANCE_API_KEY").expect("no API key found");
  let secret = env::var("BINANCE_API_SECRET").expect("no API secret found");
  let mut client = Client::new();
  client.update_default_option(BinanceOption::Key(key));
  client.update_default_option(BinanceOption::Secret(secret));
  
  let dusts: serde_json::Value = client.post_no_body(
    "https://api.binance.com/sapi/v1/asset/dust-btc",
    [BinanceOption::HttpAuth(BinanceAuth::Sign)],
  ).await.expect("failed get dusts");
  println!("My dust assets(BTC):\n{:?}", dusts["totalTransferBtc"]);
}

The above code queries assets that are convertable into BNB using the Binance API.

Options

When making a request, you pass some options to, for example, the post_no_body function. In the example, [BinanceOption::HttpAuth(BinanceAuth::Sign)] is the options. You would usually pass an array of options.

The options are for:

  • setting API key/secret
  • enabling authentication

etc.

The type of options passed is what determines the exchange used. In the above example, the library knows the request is for Binance because the type of the option passed is BinanceOption. When using Bybit, you would pass an array of BybitOptions.

Default Options

Some options are the same across requests. For example, you will probably use the same API key for each request. For those options, you can set default options for Client. Default options are applied to all requests.

In the above example, client.update_default_option(BinanceOption::Key(key)); sets the option for Binance API key as a default option. Because of this, passing an option for API key in post_no_body() is not required.

Response type

Responses are automatically deserialized into the specified type. In the above example, the response is of the type serde_json::Value because we specified the type of dusts. Any type that implements DeserializeOwned is supported.

WebSocket

use std::time::Duration;
use log::LevelFilter;
use crypto_botters::{binance::{BinanceOption, BinanceWebSocketUrl}, Client};

#[tokio::main]
async fn main() {
    let client = Client::new();

    let connection = client.websocket(
        "/ws/btcusdt@trade",
        |message| println!("{}", message),
        [BinanceOption::WebSocketUrl(BinanceWebSocketUrl::Spot443)],
    ).await.expect("failed to connect websocket");
    // receive messages
    tokio::time::sleep(Duration::from_secs(10)).await;
}

The above code opens a WebSocket connection and watches BTCUSDT trades happening on Binance.

The Client::websocket() method returns a WebSocketConnection. Using this, you can send messages, request a reconnection, or close the connection.

日本語

これは仮想通貨取引所のAPIと通信するためのRustライブラリです。

特徴:

  • 非同期
  • WebSocketに対応
  • レスポンスをユーザーの定義した型に変換

対応取引所

以下の取引所に対応しています。

取引所名 公式APIドキュメント 本ライブラリ使用例
Binance APIドキュメント 使用例
bitFlyer APIドキュメント 使用例
Bybit APIドキュメント 使用例
Coincheck APIドキュメント 使用例

使い方

examples ディレクトリ にサンプルが20以上あります。

Cargo.toml:

[dependencies]
crypto-botters = { version = "0.6", features = ["binance", "bitflyer", "bybit", "coincheck"] }

使いたい取引所のfeatureを有効化してください。

HTTP

use std::env;
use crypto_botters::{Client, binance::{BinanceAuth, BinanceHttpUrl, BinanceOption}};

#[tokio::main]
async fn main() {
  let key = env::var("BINANCE_API_KEY").expect("no API key found");
  let secret = env::var("BINANCE_API_SECRET").expect("no API secret found");
  let mut client = Client::new();
  client.update_default_option(BinanceOption::Key(key));
  client.update_default_option(BinanceOption::Secret(secret));
  
  let dusts: serde_json::Value = client.post_no_body(
    "https://api.binance.com/sapi/v1/asset/dust-btc",
    [BinanceOption::HttpAuth(BinanceAuth::Sign)],
  ).await.expect("failed get dusts");
  println!("My dust assets(BTC):\n{:?}", dusts["totalTransferBtc"]);
}

この例では、BinanceでBNBに変換できる資産を取得しています。

オプション

リクエストを送るときには、オプションを設定できます。この例では、[BinanceOption::HttpAuth(BinanceAuth::Sign)]がオプションです。 オプションのイテレータなら何でもいいです。この例では配列を使っています。

オプションは

  • APIキーやシークレットを指定する
  • 認証を有効にする

などのために設定します。

オプションの型がどの取引所を使うかを定めます。この例ではBinanceOption型を渡しているため、Binanceの認証アルゴリズムが用いられます。BybitOption型を渡せばBybitへのリクエストとして扱われます。

デフォルトオプション

複数のリクエスト間で変わらないオプションもあります。例えば、すべてのリクエストで同じAPIキーを使うことが多いと思います。 そのようなオプションはデフォルトオプションとしてClientに設定できます。デフォルトオプションは、そのClientを 使って送られるすべてのリクエストに適用されます。それぞれのリクエストで渡すオプションで上書きすることもできます。

この例では、client.update_default_option(BinanceOption::Key(key));でAPIキーのオプションをデフォルトオプションとして設定しています。 このため、post_no_body()にAPIキーのオプションを指定する必要がなくなっています。

レスポンスの型

レスポンスは指定した型に自動的に変換されます。この例では、dustsの型をserde_json::Valueと指定しているため、 レスポンスが自動でserde_json::Value型に変換されています。DeserializeOwnedを実装している型ならどんな型でも指定できます。

WebSocket

use std::time::Duration;
use log::LevelFilter;
use crypto_botters::{binance::{BinanceOption, BinanceWebSocketUrl}, Client};

#[tokio::main]
async fn main() {
    let client = Client::new();

    let connection = client.websocket(
        "/ws/btcusdt@trade",
        |message| println!("{}", message),
        [BinanceOption::WebSocketUrl(BinanceWebSocketUrl::Spot443)],
    ).await.expect("failed to connect websocket");
    // receive messages
    tokio::time::sleep(Duration::from_secs(10)).await;
}

この例では、BinanceのBTCUSDTの取引をリアルタイムで受信しています。

Client::websocket()メソッドはWebSocketConnection型を返します。これに対し、メッセージを送信する、再接続を要求する、接続を切断するなどの処理が行なえます。

その他

開発者:@negi_grass

Dependencies

~8–24MB
~371K SLoC