diff --git a/Cargo.toml b/Cargo.toml index f09394f9..d99d68de 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,8 +31,11 @@ tungstenite = { version = "0.21.0", features = ["native-tls"] } url = "2.5.0" clap = "4.5.2" uuid = { version = "1.18.0", features = ["v4"] } +crypto-orderbook = { version = "0.5.2", default-features = false, optional = true } +rust_decimal = { version = "1", optional = true } [features] +orderbook = ["dep:crypto-orderbook", "dep:rust_decimal"] vendored-tls = [ "reqwest/native-tls-vendored", "tungstenite/native-tls-vendored", diff --git a/src/lib.rs b/src/lib.rs index 0c2d9a95..82163056 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,3 +32,6 @@ pub mod userstream; pub mod websockets; pub mod futures; + +#[cfg(feature = "orderbook")] +pub mod orderbook; diff --git a/src/orderbook.rs b/src/orderbook.rs new file mode 100644 index 00000000..5a584088 --- /dev/null +++ b/src/orderbook.rs @@ -0,0 +1,77 @@ +//! Local order book sync for the depth stream, behind the `orderbook` feature. +//! +//! `DepthOrderBookEvent` and `OrderBook` are plain diffs and snapshots. Keeping a +//! correct local book from them means Binance's buffer / snapshot / `U`-`u`-`pu` +//! handshake, which this module delegates to [`crypto_orderbook::BookSync`]: +//! feed it events and snapshots, it applies them or tells you to resync. +//! +//! ``` +//! use binance::orderbook::{BookSync, Market, OrderBook, Outcome}; +//! # let event: binance::model::DepthOrderBookEvent = serde_json::from_str( +//! # r#"{"e":"depthUpdate","E":1,"s":"BTCUSDT","U":101,"u":102,"b":[["64250.10","0.5"]],"a":[]}"#).unwrap(); +//! # let snapshot: binance::model::OrderBook = serde_json::from_str( +//! # r#"{"lastUpdateId":100,"bids":[["64250.00","1.2"]],"asks":[["64251.00","0.8"]]}"#).unwrap(); +//! let mut book = OrderBook::new(); +//! let mut sync = BookSync::new(Market::Spot); +//! assert_eq!(sync.on_event(&mut book, (&event).into()), Outcome::Buffered); +//! sync.on_snapshot(&mut book, (&snapshot).into()); +//! assert!(sync.is_live()); +//! ``` + +use std::str::FromStr; + +pub use crypto_orderbook::{ + BookSync, DepthSnapshot, DepthUpdate, Market, OrderBook, Outcome, PriceLevel, ResyncReason, +}; +use rust_decimal::Decimal; + +use crate::model::{Asks, Bids, DepthOrderBookEvent}; + +// f64 `Display` is the shortest string that round-trips, i.e. the decimal Binance sent. +fn level(price: f64, qty: f64) -> PriceLevel { + let dec = |v: f64| Decimal::from_str(&v.to_string()).unwrap_or_default(); + PriceLevel { + price: dec(price), + quantity: dec(qty), + } +} + +fn bids(levels: &[Bids]) -> Vec { + levels.iter().map(|l| level(l.price, l.qty)).collect() +} + +fn asks(levels: &[Asks]) -> Vec { + levels.iter().map(|l| level(l.price, l.qty)).collect() +} + +impl From<&DepthOrderBookEvent> for DepthUpdate { + fn from(e: &DepthOrderBookEvent) -> Self { + DepthUpdate { + first_update_id: e.first_update_id, + last_update_id: e.final_update_id, + prev_last_update_id: e.previous_final_update_id, + bids: bids(&e.bids), + asks: asks(&e.asks), + } + } +} + +impl From<&crate::model::OrderBook> for DepthSnapshot { + fn from(s: &crate::model::OrderBook) -> Self { + DepthSnapshot { + last_update_id: s.last_update_id, + bids: bids(&s.bids), + asks: asks(&s.asks), + } + } +} + +impl From<&crate::futures::model::OrderBook> for DepthSnapshot { + fn from(s: &crate::futures::model::OrderBook) -> Self { + DepthSnapshot { + last_update_id: s.last_update_id, + bids: bids(&s.bids), + asks: asks(&s.asks), + } + } +} diff --git a/tests/orderbook_tests.rs b/tests/orderbook_tests.rs new file mode 100644 index 00000000..634a763c --- /dev/null +++ b/tests/orderbook_tests.rs @@ -0,0 +1,65 @@ +#![cfg(feature = "orderbook")] + +use binance::model::{DepthOrderBookEvent, OrderBook as Snapshot}; +use binance::orderbook::{BookSync, Market, OrderBook, Outcome, ResyncReason}; + +fn event(json: &str) -> DepthOrderBookEvent { + serde_json::from_str(json).unwrap() +} + +#[test] +fn dropped_diff_forces_resync_instead_of_a_stale_bid() { + let mut book = OrderBook::new(); + let mut sync = BookSync::new(Market::Spot); + + let first = event( + r#"{"e":"depthUpdate","E":1,"s":"BTCUSDT","U":101,"u":102,"b":[["64250.10","0.5"]],"a":[]}"#, + ); + assert_eq!(sync.on_event(&mut book, (&first).into()), Outcome::Buffered); + + let snapshot: Snapshot = serde_json::from_str( + r#"{"lastUpdateId":100,"bids":[["64250.00","1.2"]],"asks":[["64251.00","0.8"]]}"#, + ) + .unwrap(); + sync.on_snapshot(&mut book, (&snapshot).into()); + assert!(sync.is_live()); + assert_eq!(book.best_bid().unwrap().price.to_string(), "64250.1"); + + // 103..=104 (which cancels the 64250.10 bid) never arrives. + let next = event( + r#"{"e":"depthUpdate","E":3,"s":"BTCUSDT","U":105,"u":105,"b":[],"a":[["64251.00","0.7"]]}"#, + ); + assert_eq!( + sync.on_event(&mut book, (&next).into()), + Outcome::Resync(ResyncReason::Gap { + expected: 103, + got: 105 + }) + ); + assert!(book.best_bid().is_none()); + assert!(sync.needs_snapshot()); +} + +#[test] +fn futures_events_are_sequenced_by_pu() { + let mut book = OrderBook::new(); + let mut sync = BookSync::new(Market::UsdM); + let snapshot: Snapshot = + serde_json::from_str(r#"{"lastUpdateId":100,"bids":[["1.5","2"]],"asks":[["1.6","3"]]}"#) + .unwrap(); + + let a = event( + r#"{"e":"depthUpdate","E":1,"s":"BTCUSDT","U":95,"u":105,"pu":90,"b":[["1.5","0"]],"a":[]}"#, + ); + sync.on_event(&mut book, (&a).into()); + sync.on_snapshot(&mut book, (&snapshot).into()); + assert!(sync.is_live()); + assert!(book.best_bid().is_none()); + + let b = + event(r#"{"e":"depthUpdate","E":2,"s":"BTCUSDT","U":110,"u":112,"pu":104,"b":[],"a":[]}"#); + assert!(matches!( + sync.on_event(&mut book, (&b).into()), + Outcome::Resync(_) + )); +}