igosuki / binance-rs-async Goto Github PK
View Code? Open in Web Editor NEWAsync client for the Binance APIs
Home Page: https://crates.io/crates/binance-rs-async
License: Other
Async client for the Binance APIs
Home Page: https://crates.io/crates/binance-rs-async
License: Other
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 requirementbinance-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
Resloved.
some areas cannot access binance directly, so they need a proxy, does this project support it?
Here is the link: https://crates.io/crates/binance-rs-async
It would be nice if it could be added to the right side description. Thanks!
Btw, this will likely be implemented in https://github.com/termcrypt/termcrypt for binance support. If there are any missing features, I will try to contribute them :)
master branch
and found that some apis are not finished yet, and some have simple bugs.https://binance-docs.github.io/apidocs/delivery/en/#change-log
The base endpoint is: https://dapi.binance.com
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"
I see the endpoint is available in the code but it is not used anywhere, spot endpoint is used by default in connect
and connect_multiple
.
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?
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.
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.
Going to use futures in production so this part of the client has to be battle tested.
Add a a lib function and binary that can be used to diff the binance changelog :
{ is_changed: bool, changes: [ ]string }
binance-rs-async/src/client.rs
Lines 104 to 112 in 555577f
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?;
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.
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
And the ContractType structs does not account for this particular response.
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.
See implementation in https://github.com/wisespace-io/binance-rs/tree/master/src/futures
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
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.
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.
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
tokio-tungstenite 0.21
tokio 1.37
csv 1.3
env_logger 0.11
tracing 0.1
tokio 1.37
tokio-test 0.4
.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
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))
Hello, @Igosuki
I need my own custom event loop, however I would like to use the latest version of tokio-tungstenite. Can You update it?
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:
Name | Type | Mandatory | Description |
---|---|---|---|
symbol | STRING | NO | |
recvWindow | LONG | NO | |
timestamp | LONG | YES |
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>`
error-chain is unmaintained and has several caveats, replace with thiserror and anyhow.
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:
Thanks,
Ádám
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
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.
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?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.