Giter VIP home page Giter VIP logo

binance-rs-async's Introduction

About me

CTO/Software engineer based in Paris, have mostly worked on scalable platforms for real time services using predictive AI.

Currently refactoring the world of offline data @DinMo

I commit on open source when I have time for others, or a useful project to contribute.

"Buy Me A Coffee"

Github Stats:

binance-rs-async's People

Contributors

agodnic avatar allada avatar chipshort avatar comeonletsgoo avatar daifukunem avatar dizda avatar doctoreenot avatar durango avatar emberfarkas avatar georgewhewell avatar ghostlee avatar gleize avatar guotie avatar hhstore avatar igosuki avatar joelchen avatar kennyyanxm avatar koenw avatar lucassimpson avatar mvines avatar nascent-chris avatar renovate[bot] avatar seongs1024 avatar tommysr avatar unv-annihilator avatar vchugreev avatar vikulikov avatar yongkangc avatar zannis avatar zhenpingfeng avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

binance-rs-async's Issues

WebSocketEvent not parsed properly

For some reason I get the error error on event loop: missing field "e" at line 1 column 186 with this code.
And column reported is always different error on event loop: missing field "e" at line 1 column 2337

async fn subscribe_to_streams<C>(
        &self,
        streams: Vec<String>,
        on_event: C,
        keep_running: &AtomicBool,
    ) where
        C: FnMut(WebsocketEvent) -> Result<(), binance::errors::Error>,
    {
        let mut websocket_connector: WebSockets<'_, WebsocketEvent> = WebSockets::new(on_event);
        websocket_connector.connect_multiple(streams).await.unwrap(); // TODO: handle result
        if let Err(e) = websocket_connector.event_loop(keep_running).await {
            error!(" {}: error on event loop: {}", self.cfg.name, e); // TODO: handle error
        }
        websocket_connector.disconnect().await.unwrap() // TODO: handle unwrap
    }

steams are just strings such as "btcusdt@depth@100ms"

Stop Loss Orders & Take Profit Orders for futures

I love the api design so far. However, it is missing Stop Loss Orders & Take Profit Orders for futures contract. I was wondering if the reason that this is not being added was to keep the api design minimal?

errors while using the wallet feature?

I get these errors when trying to use the wallet_api feature

error[E0599]: no method named `sub` found for enum `std::option::Option` in the current scope
   --> rust/.cargo/registry/src/github.com-1ecc6299db9ec823/binance-rs-async-1.1.10/src/wallet.rs:175:66
    |
175 |         let mut current_period_start: DateTime<Utc> = start_from.sub(interval_duration);
    |                                                                  ^^^ method not found in `std::option::Option<DateTime<Utc>>`
    |
note: the method `sub` exists on the type `DateTime<Utc>`
   --> rust/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/arith.rs:221:5
    |
221 |     fn sub(self, rhs: Rhs) -> Self::Output;
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: consider using `Option::expect` to unwrap the `DateTime<Utc>` value, panicking if the value is an `Option::None`
    |
175 |         let mut current_period_start: DateTime<Utc> = start_from.expect("REASON").sub(interval_duration);
    |                                                                 +++++++++++++++++

error[E0308]: mismatched types
   --> rust/.cargo/registry/src/github.com-1ecc6299db9ec823/binance-rs-async-1.1.10/src/wallet.rs:184:48
    |
184 |             let records = self.deposit_history(&query).await?;
    |                                --------------- ^^^^^^ expected struct `rest_model::DepositHistoryQuery`, found `&rest_model::DepositHistoryQuery`
    |                                |
    |                                arguments to this function are incorrect
    |
note: associated function defined here
   --> rust/.cargo/registry/src/github.com-1ecc6299db9ec823/binance-rs-async-1.1.10/src/wallet.rs:148:18
    |
148 |     pub async fn deposit_history(&self, query: DepositHistoryQuery) -> Result<Vec<DepositRecord>> {
    |                  ^^^^^^^^^^^^^^^ -----  --------------------------
help: consider removing the borrow
    |
184 -             let records = self.deposit_history(&query).await?;
184 +             let records = self.deposit_history(query).await?;
    |

error[E0368]: binary assignment operation `-=` cannot be applied to type `DateTime<Utc>`
   --> rust/.cargo/registry/src/github.com-1ecc6299db9ec823/binance-rs-async-1.1.10/src/wallet.rs:195:13
    |
195 |             current_period_start -= interval_duration;
    |             --------------------^^^^^^^^^^^^^^^^^^^^^
    |             |
    |             cannot use `-=` on type `DateTime<Utc>`

error[E0368]: binary assignment operation `-=` cannot be applied to type `DateTime<Utc>`
   --> rust/.cargo/registry/src/github.com-1ecc6299db9ec823/binance-rs-async-1.1.10/src/wallet.rs:196:13
    |
196 |             current_period_end -= interval_duration;
    |             ------------------^^^^^^^^^^^^^^^^^^^^^
    |             |
    |             cannot use `-=` on type `DateTime<Utc>`

error[E0599]: no method named `sub` found for enum `std::option::Option` in the current scope
   --> rust/.cargo/registry/src/github.com-1ecc6299db9ec823/binance-rs-async-1.1.10/src/wallet.rs:241:66
    |
241 |         let mut current_period_start: DateTime<Utc> = start_from.sub(interval_duration);
    |                                                                  ^^^ method not found in `std::option::Option<DateTime<Utc>>`
    |
note: the method `sub` exists on the type `DateTime<Utc>`
   --> rust/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/arith.rs:221:5
    |
221 |     fn sub(self, rhs: Rhs) -> Self::Output;
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: consider using `Option::expect` to unwrap the `DateTime<Utc>` value, panicking if the value is an `Option::None`
    |
241 |         let mut current_period_start: DateTime<Utc> = start_from.expect("REASON").sub(interval_duration);
    |                                                                 +++++++++++++++++

error[E0308]: mismatched types
   --> rust/.cargo/registry/src/github.com-1ecc6299db9ec823/binance-rs-async-1.1.10/src/wallet.rs:250:49
    |
250 |             let records = self.withdraw_history(&query).await?;
    |                                ---------------- ^^^^^^ expected struct `rest_model::WithdrawalHistoryQuery`, found `&rest_model::WithdrawalHistoryQuery`
    |                                |
    |                                arguments to this function are incorrect
    |
note: associated function defined here
   --> rust/.cargo/registry/src/github.com-1ecc6299db9ec823/binance-rs-async-1.1.10/src/wallet.rs:212:18
    |
212 |     pub async fn withdraw_history(&self, query: WithdrawalHistoryQuery) -> Result<Vec<WithdrawalRecord>> {
    |                  ^^^^^^^^^^^^^^^^ -----  -----------------------------
help: consider removing the borrow
    |
250 -             let records = self.withdraw_history(&query).await?;
250 +             let records = self.withdraw_history(query).await?;
    |

error[E0368]: binary assignment operation `-=` cannot be applied to type `DateTime<Utc>`
   --> rust/.cargo/registry/src/github.com-1ecc6299db9ec823/binance-rs-async-1.1.10/src/wallet.rs:261:13
    |
261 |             current_period_start -= interval_duration;
    |             --------------------^^^^^^^^^^^^^^^^^^^^^
    |             |
    |             cannot use `-=` on type `DateTime<Utc>`

error[E0368]: binary assignment operation `-=` cannot be applied to type `DateTime<Utc>`
   --> rust/.cargo/registry/src/github.com-1ecc6299db9ec823/binance-rs-async-1.1.10/src/wallet.rs:262:13
    |
262 |             current_period_end -= interval_duration;
    |             ------------------^^^^^^^^^^^^^^^^^^^^^
    |             |
    |             cannot use `-=` on type `DateTime<Utc>`

Add changelog checker

Add a a lib function and binary that can be used to diff the binance changelog :

  • store a file locally with the timestamp of the latest change
  • binary returns 0 or 1 depending on whether or not there is a change
  • --json flag outputs { is_changed: bool, changes: [ ]string }
  • github issue is automatically posted with the changes

To support proxy connection to binance websocket

In some areas the network could not directly connect to binance web socket due to some reason which results to developing and debugging inconvenience.
I've tried to run the example web socket code behind a proxy and got failed with follwing message:
thread 'thread 'tokio-runtime-workertokio-runtime-worker' panicked at '' panicked at 'called `Result::unwrap()` on an `Err` value: Msg("Error during handshake IO error: Network is unreachable (os error 101)")called `Result::unwrap()` on an `Err` value: Msg("Error during handshake IO error: Network is unreachable (os error 101)")', ', examples/binance_websockets.rsexamples/binance_websockets.rs::185133::3842

then I modify /etc/hosts and add IP for stream.binance.com but got another error:

thread 'tokio-runtime-worker' panicked at 'called `Result::unwrap()` on an `Err` value: Msg("Error during handshake TLS error: native-tls error: Connection reset by peer (os error 104)")', examples/binance_websockets.rs:133:42

It would be great if it support connecting to binance websocket through a proxy.

Support Universal Transfer

Hello @Igosuki ,

I love this library of yours, and I'm considering adopting the previous transfer implementations for the "Universal Transfer", so more transfer scenarios can be covered.
https://binance-docs.github.io/apidocs/spot/en/#user-universal-transfer-user_data

I have multiple questions in this regard:

  • Is this library actively maintained?
  • Would you like to support the universal transfer endpoint?
  • Can you assist me to reach a valuable contribution?

Thanks,
Ádám

Version 1.3.2 didn't match with the available ones

The crate version in readme.md doesn't exist.
Run: cargo semver-checks check-release --package binance-rs-async --verbose
The output:

Error: cargo metadata exited with an error: Updating crates.io index
error: failed to select a version for the requirement binance-rs-async = "^1.3.2"
candidate versions found which didn't match: 1.3.1, 1.3.0, 1.2.2, ...
location searched: crates.io index

Proxy support?

some areas cannot access binance directly, so they need a proxy, does this project support it?

  1. REST API proxy
  2. websocket proxy

Async Callback design issue.

handler: Box<dyn FnMut(WE) -> Result<()> + 'a>

the callback block must implement FnMut(WE) -> Result<()> + 'a, but every async function returns an implementation of Future.
so basically this break the async consistency from the callback closure part, if we want to run async code in the callback we need
to write something like

use tokio::runtime::Runtime;
if let WebsocketEvent::OrderUpdate(trade) = event {
    let rt = Runtime::new().unwrap();
    rt.block_on(async { do_sth(event).await })
};

that is pretty ugly, we could change the callback to a channel to avoid this.

Configure timeout of the client.

Hi!
For now I am not at my home and I tried to develop my app.

Unfortunately, I had magic "timed out" error.

I found 2 seconds timeout in Client initialisation.

It would be very cool if there would be an option to configure this in Config or somewhere else.

To have backwards compatibility we can not add one more parameter to Client struct, but we can create new "new_with_timeout" method.

Best regards,
Vadims.

Futures API

Hi, I am a heavy futures API user. Can there be an implementation to transfer futures assets to spot wallet? For example move USDT in futures wallet to spot wallet.

The GET method internally creates a new `reqwest::Client` each time.

pub async fn get<T: DeserializeOwned>(&self, endpoint: &str, request: Option<&str>) -> Result<T> {
let url = request
.map(|r| format!("{}{}?{}", self.host, endpoint, r))
.unwrap_or_else(|| format!("{}{}", self.host, endpoint));
let response = reqwest::get(url).await?;
self.handler(response).await
}

Unlike other request methods, the get() method applys reqwest::get() shortcut method.
According to reqwest docs, this may lead to performace issues.
So it seems like a good idea to use the inner.get() method consistently.
Like below:

     let response = self.inner.get(&url).send().await?;

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

This repository currently has no open or pending branches.

Detected dependencies

cargo
Cargo.toml
  • chrono 0.4
  • futures 0.3
  • hex 0.4
  • reqwest 0.12
  • ring 0.17
  • serde 1.0
  • serde_json 1.0
  • serde_qs 0.13
  • serde_repr 0.1
  • thiserror 1.0
  • url 2.5
  • lazy_static 1.4
  • tokio-tungstenite 0.21
  • tokio 1.37
  • boolinator 2.4
  • csv 1.3
  • env_logger 0.11
  • tracing 0.1
  • tokio-test 0.4
github-actions
.github/workflows/clippy.yml
  • actions/checkout v4
  • swatinem/rust-cache v2
  • github/codeql-action v3
  • ubuntu 22.04
.github/workflows/onrelease.yml
  • cargo-bins/release-meta v1
  • actions/checkout v4
  • cargo-bins/release-rust v1
.github/workflows/release.yml
  • actions/checkout v4
  • taiki-e/install-action v2
  • cargo-bins/release-pr v2
.github/workflows/rust.yml
  • actions/checkout v4
  • swatinem/rust-cache v2
  • github/codeql-action v3
  • ubuntu 22.04

  • Check this box to trigger a request for Renovate to run again on this repository

Fix: wallet api bugs

Fix wallet api bugs:

PR(WIP) here:

  • #36
  • I have fixed some issues, others are still in progress.
  • Still under development, no need to merge for now.

Margin Account cancel_all_orders on open OCO order yields MarginOCOOrderResult instead of MarginOrderCancellationResult

Like the fix in OCOOrderReport (#42) where stopPrice is optional, calling cancel_all_orders when there is an open OCO order yields MarginOCOOrderResult instead of MarginOrderCancellationResult, and will cause an error returned by cancel_all_orders: missing field orderId at line 1 column 1124.
Binance API Documentation Reference: https://binance-docs.github.io/apidocs/spot/en/#margin-account-cancel-all-open-orders-on-a-symbol-trade

Signature for this request in not valid

let account: Account = Binance::new_with_env(&Config::testnet());
    let limit_buy = OrderRequest {
            symbol: "BTCUSDT".to_string(),
            quantity: Some(0.01),
            price: Some(40000.0),
            order_type: OrderType::Limit,
            side: OrderSide::Buy,
            time_in_force: Some(TimeInForce::FOK),
            ..OrderRequest::default()
        };
    match account.place_order(limit_buy).await {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {e}"),
    }

This is my code and output is

Error: code: -1022, msg: Signature for this request is not valid.

`Send` is not implemented for `dyn FnMut(binance::ws_model::WebsocketEvent) -> Result<(), binance::errors::Error>`

Tried to port a Rust project from binance-rs to binance-rs-async, but encountered the following error:

`dyn FnMut(binance::ws_model::WebsocketEvent) -> Result<(), binance::errors::Error>` cannot be sent between threads safely
the trait `Send` is not implemented for `dyn FnMut(binance::ws_model::WebsocketEvent) -> Result<(), binance::errors::Error>`

Ported project: https://github.com/joelchen/teleporter

futures position_information implementation

Hello. I tried using position_information that calls the endpoint /fapi/v2/positionRisk. The parameter to position_information is Symbol structure, which has like 20 fields on non Optional members. Is this function implemented correctly? I'd expect to only pass symbol: String to get the data about my positions

pointers:
https://github.com/Igosuki/binance-rs-async/blob/master/src/futures/account.rs#L203
https://github.com/Igosuki/binance-rs-async/blob/master/src/futures/rest_model.rs#L29
https://binance-docs.github.io/apidocs/futures/en/#position-information-v2-user_data

GET /fapi/v2/positionRisk (HMAC SHA256)

Get current position information.

Weight: 5

Parameters:


NameTypeMandatoryDescription
symbolSTRINGNO
recvWindowLONGNO
timestampLONGYES

NOT working - get_exchange_info

The types for get_exchange_info has stopped working with the following error:

Err(ReqError(reqwest::Error { kind: Decode, source: Error("unknown variant `CURRENT_QUARTER DELIVERING`, expected one of `PERPETUAL`, `CURRENT_MONTH`, `NEXT_MONTH`, `CURRENT_QUARTER`, `NEXT_QUARTER`, ``", line: 1, column: 246483) }))

This is due to the binance response mixing contractStatus and contractType

image

And the ContractType structs does not account for this particular response.

API Url: https://fapi.binance.com/fapi/v1/exchangeInfo

Some WebSocket payload doesn't have "e" tag.

Example: Spot bookTicker

use code:

async fn book_ticker() {
    let keep_running = AtomicBool::new(true);
    let agg_trade: String = "btcusdt@bookTicker".to_string();

    let mut web_socket: WebSockets<'_, WebsocketEvent> =
        WebSockets::new(|events: WebsocketEvent| {
            if let WebsocketEvent::BookTicker(tick_event) = events {
                println!("{:?}", tick_event)
            }
    
            Ok(())
        });

    web_socket.connect(&agg_trade).await.unwrap(); // check error
    if let Err(e) = web_socket.event_loop(&keep_running).await {
        println!("Error: {}", e);
    }
    web_socket.disconnect().await.unwrap();
    println!("disconnected");
}

to sub will get error: Error: missing field e at line 1 column 107 disconnected

The reason for this is that Websocket Variant uses the tag Marco to assume that each event has an event_type tag. We should disable the tag macro and implement every struct that matches the doc.

How to solve recvWindow error?

I've sync time with time.nist.gov in Windows system, but I still sometimes get the error like below:
BinanceContentError { code: -1021, msg: "Timestamp for this request is outside of the recvWindow.", extra: {} }

Is there any method to sync time with binance itself?

get exchange info: missing field `maxNumOrders`

use binance::api::*;
use binance::futures::general::*;
use futures::executor::block_on;
use tokio;

async fn get_all_symbols() {

    let general: FuturesGeneral = Binance::new(None, None);

    match general.exchange_info().await {
        Ok(answer) => println!("Exchange information: {:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }

}

#[tokio::main]
async fn async_main() {
    block_on(get_all_symbols());
}

fn main() {
    async_main();
}
Error: Json(Error("missing field `maxNumOrders`", line: 1, column: 1381))

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.