1use std::str::FromStr;
19
20use nautilus_core::nanos::UnixNanos;
21use nautilus_model::{
22 data::{
23 BarSpecification, BarType, BookOrder, FundingRateUpdate, IndexPriceUpdate, MarkPriceUpdate,
24 OrderBookDelta, OrderBookDeltas, QuoteTick, TradeTick,
25 },
26 enums::{
27 AggregationSource, AggressorSide, BarAggregation, BookAction, OrderSide, PriceType,
28 RecordFlag,
29 },
30 identifiers::TradeId,
31 instruments::{Instrument, InstrumentAny},
32 types::Price,
33};
34use rust_decimal::Decimal;
35use ustr::Ustr;
36
37use super::{
38 error::{BinanceWsError, BinanceWsResult},
39 messages::{
40 BinanceFuturesAggTradeMsg, BinanceFuturesBookTickerMsg, BinanceFuturesDepthUpdateMsg,
41 BinanceFuturesKlineMsg, BinanceFuturesMarkPriceMsg, BinanceFuturesTickerMsg,
42 BinanceFuturesTradeMsg,
43 },
44};
45use crate::{
46 common::{
47 bar::BinanceBar,
48 enums::{BinanceFuturesTradeType, BinanceKlineInterval, BinanceWsEventType},
49 parse::{
50 parse_millis, parse_millis_or_init, parse_required_price_at_precision,
51 parse_required_quantity_at_precision,
52 },
53 },
54 data_types::{BinanceFuturesMarkPriceUpdate, BinanceFuturesTicker},
55};
56
57pub fn parse_agg_trade(
63 msg: &BinanceFuturesAggTradeMsg,
64 instrument: &InstrumentAny,
65 ts_init: UnixNanos,
66) -> BinanceWsResult<TradeTick> {
67 let instrument_id = instrument.id();
68 let price_precision = instrument.price_precision();
69 let size_precision = instrument.size_precision();
70
71 let price = parse_required_price_at_precision(&msg.price, price_precision, "price")
72 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
73 let size = parse_required_quantity_at_precision(&msg.quantity, size_precision, "quantity")
74 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
75
76 let aggressor_side = if msg.is_buyer_maker {
77 AggressorSide::Sell
78 } else {
79 AggressorSide::Buy
80 };
81
82 let ts_event = parse_millis_or_init(msg.trade_time, "Futures aggregate trade time", ts_init);
83 let trade_id = TradeId::new(msg.agg_trade_id.to_string());
84
85 Ok(TradeTick::new(
86 instrument_id,
87 price,
88 size,
89 aggressor_side,
90 trade_id,
91 ts_event,
92 ts_init,
93 ))
94}
95
96pub fn parse_trade(
107 msg: &BinanceFuturesTradeMsg,
108 instrument: &InstrumentAny,
109 ts_init: UnixNanos,
110) -> BinanceWsResult<Option<TradeTick>> {
111 match msg.trade_type {
112 BinanceFuturesTradeType::Market | BinanceFuturesTradeType::Rpi => {}
113 BinanceFuturesTradeType::InsuranceFund
114 | BinanceFuturesTradeType::Adl
115 | BinanceFuturesTradeType::Na => return Ok(None),
116 BinanceFuturesTradeType::Unknown => {
117 return Err(BinanceWsError::ParseError(format!(
118 "unknown trade type for {} trade {}",
119 msg.symbol, msg.trade_id
120 )));
121 }
122 }
123
124 let instrument_id = instrument.id();
125 let price_precision = instrument.price_precision();
126 let size_precision = instrument.size_precision();
127
128 let price = parse_required_price_at_precision(&msg.price, price_precision, "price")
129 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
130 let size = parse_required_quantity_at_precision(&msg.quantity, size_precision, "quantity")
131 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
132
133 let aggressor_side = if msg.is_buyer_maker {
134 AggressorSide::Sell
135 } else {
136 AggressorSide::Buy
137 };
138
139 let ts_event = parse_millis_or_init(msg.trade_time, "Futures trade time", ts_init);
140 let trade_id = TradeId::new(msg.trade_id.to_string());
141
142 TradeTick::new_checked(
143 instrument_id,
144 price,
145 size,
146 aggressor_side,
147 trade_id,
148 ts_event,
149 ts_init,
150 )
151 .map(Some)
152 .map_err(|e| BinanceWsError::ParseError(e.to_string()))
153}
154
155pub fn parse_book_ticker(
161 msg: &BinanceFuturesBookTickerMsg,
162 instrument: &InstrumentAny,
163 ts_init: UnixNanos,
164) -> BinanceWsResult<QuoteTick> {
165 let instrument_id = instrument.id();
166 let price_precision = instrument.price_precision();
167 let size_precision = instrument.size_precision();
168
169 let bid_price =
170 parse_required_price_at_precision(&msg.best_bid_price, price_precision, "best_bid_price")
171 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
172 let bid_size =
173 parse_required_quantity_at_precision(&msg.best_bid_qty, size_precision, "best_bid_qty")
174 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
175 let ask_price =
176 parse_required_price_at_precision(&msg.best_ask_price, price_precision, "best_ask_price")
177 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
178 let ask_size =
179 parse_required_quantity_at_precision(&msg.best_ask_qty, size_precision, "best_ask_qty")
180 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
181
182 let ts_event = parse_millis_or_init(
183 msg.transaction_time,
184 "Futures book ticker transaction time",
185 ts_init,
186 );
187
188 Ok(QuoteTick::new(
189 instrument_id,
190 bid_price,
191 ask_price,
192 bid_size,
193 ask_size,
194 ts_event,
195 ts_init,
196 ))
197}
198
199pub fn parse_depth_update(
205 msg: &BinanceFuturesDepthUpdateMsg,
206 instrument: &InstrumentAny,
207 ts_init: UnixNanos,
208) -> BinanceWsResult<OrderBookDeltas> {
209 parse_book_depth(msg, instrument, ts_init, false)
210}
211
212pub(crate) fn parse_depth_snapshot(
213 msg: &BinanceFuturesDepthUpdateMsg,
214 instrument: &InstrumentAny,
215 ts_init: UnixNanos,
216) -> BinanceWsResult<OrderBookDeltas> {
217 parse_book_depth(msg, instrument, ts_init, true)
218}
219
220fn parse_book_depth(
221 msg: &BinanceFuturesDepthUpdateMsg,
222 instrument: &InstrumentAny,
223 ts_init: UnixNanos,
224 snapshot: bool,
225) -> BinanceWsResult<OrderBookDeltas> {
226 let instrument_id = instrument.id();
227 let price_precision = instrument.price_precision();
228 let size_precision = instrument.size_precision();
229
230 let ts_event = parse_millis_or_init(
231 msg.transaction_time,
232 "Futures depth update transaction time",
233 ts_init,
234 );
235
236 let mut deltas = Vec::with_capacity(msg.bids.len() + msg.asks.len() + usize::from(snapshot));
237 if snapshot {
238 deltas.push(OrderBookDelta::clear(
239 instrument_id,
240 msg.final_update_id,
241 ts_event,
242 ts_init,
243 ));
244 }
245
246 let flags = if snapshot {
247 RecordFlag::F_SNAPSHOT as u8
248 } else {
249 0
250 };
251
252 for bid in &msg.bids {
254 let price = parse_required_price_at_precision(&bid[0], price_precision, "bid_price")
255 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
256 let size = parse_required_quantity_at_precision(&bid[1], size_precision, "bid_quantity")
257 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
258
259 let action = if size.is_zero() {
260 BookAction::Delete
261 } else if snapshot {
262 BookAction::Add
263 } else {
264 BookAction::Update
265 };
266
267 let order = BookOrder::new(OrderSide::Buy, price, size, 0);
268
269 deltas.push(OrderBookDelta::new(
270 instrument_id,
271 action,
272 order,
273 flags,
274 msg.final_update_id,
275 ts_event,
276 ts_init,
277 ));
278 }
279
280 for ask in &msg.asks {
282 let price = parse_required_price_at_precision(&ask[0], price_precision, "ask_price")
283 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
284 let size = parse_required_quantity_at_precision(&ask[1], size_precision, "ask_quantity")
285 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
286
287 let action = if size.is_zero() {
288 BookAction::Delete
289 } else if snapshot {
290 BookAction::Add
291 } else {
292 BookAction::Update
293 };
294
295 let order = BookOrder::new(OrderSide::Sell, price, size, 0);
296
297 deltas.push(OrderBookDelta::new(
298 instrument_id,
299 action,
300 order,
301 flags,
302 msg.final_update_id,
303 ts_event,
304 ts_init,
305 ));
306 }
307
308 if let Some(last) = deltas.last_mut() {
309 last.flags |= RecordFlag::F_LAST as u8;
310 }
311
312 OrderBookDeltas::new_checked(instrument_id, deltas)
313 .map_err(|e| BinanceWsError::ParseError(e.to_string()))
314}
315
316pub fn parse_mark_price(
322 msg: &BinanceFuturesMarkPriceMsg,
323 instrument: &InstrumentAny,
324 ts_init: UnixNanos,
325) -> BinanceWsResult<(
326 MarkPriceUpdate,
327 IndexPriceUpdate,
328 FundingRateUpdate,
329 BinanceFuturesMarkPriceUpdate,
330)> {
331 let instrument_id = instrument.id();
332 let price_precision = instrument.price_precision();
333
334 let mark_price =
335 parse_required_price_at_precision(&msg.mark_price, price_precision, "mark_price")
336 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
337 let index_price =
338 parse_required_price_at_precision(&msg.index_price, price_precision, "index_price")
339 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
340 let estimated_settle_price = msg
341 .estimated_settle_price
342 .parse::<Decimal>()
343 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
344 let estimated_settle_price = Price::from_decimal_dp(estimated_settle_price, price_precision)
345 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
346 let funding_rate = msg
347 .funding_rate
348 .parse::<Decimal>()
349 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
350
351 let ts_event = parse_millis_or_init(msg.event_time, "Futures mark price event time", ts_init);
352 let next_funding_ns = if msg.next_funding_time > 0 {
353 match parse_millis(
354 msg.next_funding_time,
355 "Futures mark price next funding time",
356 ) {
357 Ok(timestamp) => Some(timestamp),
358 Err(e) => {
359 log::warn!("{e}; omitting next funding time");
360 None
361 }
362 }
363 } else {
364 None
365 };
366
367 let mark_update = MarkPriceUpdate::new(instrument_id, mark_price, ts_event, ts_init);
368
369 let index_update = IndexPriceUpdate::new(instrument_id, index_price, ts_event, ts_init);
370
371 let funding_update = FundingRateUpdate::new(
372 instrument_id,
373 funding_rate,
374 None, next_funding_ns,
376 ts_event,
377 ts_init,
378 );
379
380 let custom_update = BinanceFuturesMarkPriceUpdate {
381 instrument_id,
382 mark_price,
383 index_price,
384 estimated_settle_price,
385 funding_rate,
386 next_funding_time: next_funding_ns,
387 ts_event,
388 ts_init,
389 };
390
391 Ok((mark_update, index_update, funding_update, custom_update))
392}
393
394pub fn parse_ticker(
400 msg: &BinanceFuturesTickerMsg,
401 instrument: &InstrumentAny,
402 ts_init: UnixNanos,
403) -> BinanceWsResult<BinanceFuturesTicker> {
404 Ok(BinanceFuturesTicker::new(
405 instrument.id(),
406 parse_ticker_decimal("price_change", &msg.price_change)?,
407 parse_ticker_decimal("price_change_percent", &msg.price_change_percent)?,
408 parse_ticker_decimal("weighted_avg_price", &msg.weighted_avg_price)?,
409 parse_ticker_decimal("last_price", &msg.last_price)?,
410 parse_ticker_decimal("last_qty", &msg.last_qty)?,
411 parse_ticker_decimal("open_price", &msg.open_price)?,
412 parse_ticker_decimal("high_price", &msg.high_price)?,
413 parse_ticker_decimal("low_price", &msg.low_price)?,
414 parse_ticker_decimal("volume", &msg.volume)?,
415 parse_ticker_decimal("quote_volume", &msg.quote_volume)?,
416 parse_millis_or_init(msg.open_time, "Futures ticker open time", ts_init),
417 parse_millis_or_init(msg.close_time, "Futures ticker close time", ts_init),
418 msg.first_trade_id,
419 msg.last_trade_id,
420 msg.num_trades,
421 parse_millis_or_init(msg.event_time, "Futures ticker event time", ts_init),
422 ts_init,
423 ))
424}
425
426fn parse_ticker_decimal(field: &str, value: &str) -> BinanceWsResult<Decimal> {
427 Decimal::from_str(value).map_err(|e| {
428 BinanceWsError::ParseError(format!("invalid Binance ticker {field}='{value}': {e}"))
429 })
430}
431
432fn interval_to_bar_spec(interval: BinanceKlineInterval) -> BarSpecification {
434 match interval {
435 BinanceKlineInterval::Second1 => {
436 BarSpecification::new(1, BarAggregation::Second, PriceType::Last)
437 }
438 BinanceKlineInterval::Minute1 => {
439 BarSpecification::new(1, BarAggregation::Minute, PriceType::Last)
440 }
441 BinanceKlineInterval::Minute3 => {
442 BarSpecification::new(3, BarAggregation::Minute, PriceType::Last)
443 }
444 BinanceKlineInterval::Minute5 => {
445 BarSpecification::new(5, BarAggregation::Minute, PriceType::Last)
446 }
447 BinanceKlineInterval::Minute15 => {
448 BarSpecification::new(15, BarAggregation::Minute, PriceType::Last)
449 }
450 BinanceKlineInterval::Minute30 => {
451 BarSpecification::new(30, BarAggregation::Minute, PriceType::Last)
452 }
453 BinanceKlineInterval::Hour1 => {
454 BarSpecification::new(1, BarAggregation::Hour, PriceType::Last)
455 }
456 BinanceKlineInterval::Hour2 => {
457 BarSpecification::new(2, BarAggregation::Hour, PriceType::Last)
458 }
459 BinanceKlineInterval::Hour4 => {
460 BarSpecification::new(4, BarAggregation::Hour, PriceType::Last)
461 }
462 BinanceKlineInterval::Hour6 => {
463 BarSpecification::new(6, BarAggregation::Hour, PriceType::Last)
464 }
465 BinanceKlineInterval::Hour8 => {
466 BarSpecification::new(8, BarAggregation::Hour, PriceType::Last)
467 }
468 BinanceKlineInterval::Hour12 => {
469 BarSpecification::new(12, BarAggregation::Hour, PriceType::Last)
470 }
471 BinanceKlineInterval::Day1 => {
472 BarSpecification::new(1, BarAggregation::Day, PriceType::Last)
473 }
474 BinanceKlineInterval::Day3 => {
475 BarSpecification::new(3, BarAggregation::Day, PriceType::Last)
476 }
477 BinanceKlineInterval::Week1 => {
478 BarSpecification::new(1, BarAggregation::Week, PriceType::Last)
479 }
480 BinanceKlineInterval::Month1 => {
481 BarSpecification::new(1, BarAggregation::Month, PriceType::Last)
482 }
483 }
484}
485
486pub fn parse_kline(
494 msg: &BinanceFuturesKlineMsg,
495 instrument: &InstrumentAny,
496 ts_init: UnixNanos,
497) -> BinanceWsResult<Option<BinanceBar>> {
498 if !msg.kline.is_closed {
500 return Ok(None);
501 }
502
503 let instrument_id = instrument.id();
504 let price_precision = instrument.price_precision();
505 let size_precision = instrument.size_precision();
506
507 let spec = interval_to_bar_spec(msg.kline.interval);
508 let bar_type = BarType::new(instrument_id, spec, AggregationSource::External);
509
510 let price = |field: &str, value: &str| {
511 parse_required_price_at_precision(value, price_precision, field)
512 .map_err(|e| BinanceWsError::ParseError(e.to_string()))
513 };
514 let quantity = |field: &str, value: &str| {
515 parse_required_quantity_at_precision(value, size_precision, field)
516 .map_err(|e| BinanceWsError::ParseError(e.to_string()))
517 };
518 let decimal = |field: &str, value: &str| {
519 Decimal::from_str(value)
520 .map_err(|e| BinanceWsError::ParseError(format!("invalid {field} `{value}`: {e}")))
521 };
522 let count = u64::try_from(msg.kline.num_trades)
523 .map_err(|e| BinanceWsError::ParseError(e.to_string()))?;
524
525 let ts_event = parse_millis_or_init(msg.kline.close_time, "Futures kline close time", ts_init);
527
528 let bar = BinanceBar::new(
529 bar_type,
530 price("open", &msg.kline.open)?,
531 price("high", &msg.kline.high)?,
532 price("low", &msg.kline.low)?,
533 price("close", &msg.kline.close)?,
534 quantity("volume", &msg.kline.volume)?,
535 decimal("quote volume", &msg.kline.quote_volume)?,
536 count,
537 decimal("taker buy base volume", &msg.kline.taker_buy_volume)?,
538 decimal("taker buy quote volume", &msg.kline.taker_buy_quote_volume)?,
539 ts_event,
540 ts_init,
541 );
542
543 Ok(Some(bar))
544}
545
546pub fn extract_symbol(json: &serde_json::Value) -> Option<Ustr> {
548 json.get("s").and_then(|v| v.as_str()).map(Ustr::from)
549}
550
551pub fn extract_event_type(json: &serde_json::Value) -> Option<BinanceWsEventType> {
553 json.get("e")
554 .and_then(|v| serde_json::from_value(v.clone()).ok())
555}
556
557#[cfg(test)]
558mod tests {
559 use nautilus_model::{enums::BookType, orderbook::OrderBook, types::Quantity};
560 use rstest::rstest;
561 use rust_decimal_macros::dec;
562 use serde::de::DeserializeOwned;
563 use serde_json::json;
564
565 use super::*;
566 use crate::{
567 common::{
568 enums::{BinanceOrderStatus, BinanceSide, BinanceTradingStatus},
569 parse::parse_usdm_instrument,
570 testing::{load_fixture_string, load_json_fixture},
571 },
572 futures::{
573 http::models::BinanceFuturesUsdSymbol,
574 websocket::streams::messages::{BinanceFuturesLiquidationMsg, BinanceFuturesTickerMsg},
575 },
576 };
577
578 const PRICE_PRECISION: u8 = 8;
579 const SIZE_PRECISION: u8 = 3;
580
581 fn sample_futures_symbol() -> BinanceFuturesUsdSymbol {
582 BinanceFuturesUsdSymbol {
583 symbol: Ustr::from("BTCUSDT"),
584 pair: Ustr::from("BTCUSDT"),
585 contract_type: "PERPETUAL".to_string(),
586 delivery_date: 4_133_404_800_000,
587 onboard_date: 1_569_398_400_000,
588 status: BinanceTradingStatus::Trading,
589 maint_margin_percent: "2.5000".to_string(),
590 required_margin_percent: "5.0000".to_string(),
591 base_asset: Ustr::from("BTC"),
592 quote_asset: Ustr::from("USDT"),
593 margin_asset: Ustr::from("USDT"),
594 price_precision: PRICE_PRECISION as i32,
595 quantity_precision: SIZE_PRECISION as i32,
596 base_asset_precision: 8,
597 quote_precision: 8,
598 underlying_type: Some("COIN".to_string()),
599 underlying_sub_type: vec!["PoW".to_string()],
600 settle_plan: None,
601 trigger_protect: Some("0.0500".to_string()),
602 liquidation_fee: Some("0.012500".to_string()),
603 market_take_bound: Some("0.05".to_string()),
604 order_types: vec!["LIMIT".to_string(), "MARKET".to_string()],
605 time_in_force: vec!["GTC".to_string(), "IOC".to_string()],
606 filters: vec![
607 json!({
608 "filterType": "PRICE_FILTER",
609 "tickSize": "0.00000001",
610 "maxPrice": "1000000",
611 "minPrice": "0.00000001"
612 }),
613 json!({
614 "filterType": "LOT_SIZE",
615 "stepSize": "0.001",
616 "maxQty": "1000",
617 "minQty": "0.001"
618 }),
619 ],
620 }
621 }
622
623 fn sample_instrument() -> InstrumentAny {
624 let ts = UnixNanos::from(1_700_000_000_000_000_000u64);
625 parse_usdm_instrument(&sample_futures_symbol(), ts, ts).unwrap()
626 }
627
628 fn load_market_fixture<T: DeserializeOwned>(filename: &str) -> T {
629 let path = format!("futures/market_data_json/{filename}");
630 serde_json::from_str(&load_fixture_string(&path))
631 .unwrap_or_else(|e| panic!("Failed to parse fixture {path}: {e}"))
632 }
633
634 #[rstest]
635 fn test_parse_agg_trade() {
636 let instrument = sample_instrument();
637 let msg: BinanceFuturesAggTradeMsg = load_market_fixture("agg_trade_stream.json");
638 let ts_init = UnixNanos::from(1_700_000_001_000_000_000u64);
639
640 let trade = parse_agg_trade(&msg, &instrument, ts_init).unwrap();
641
642 assert_eq!(trade.instrument_id, instrument.id());
643 assert_eq!(trade.price, Price::new(0.001, PRICE_PRECISION));
644 assert_eq!(trade.size, Quantity::new(100.0, SIZE_PRECISION));
645 assert_eq!(trade.aggressor_side, AggressorSide::Sell);
646 assert_eq!(trade.trade_id, TradeId::new("5933014"));
647 assert_eq!(trade.ts_event, UnixNanos::from(123_456_785_000_000u64));
648 assert_eq!(trade.ts_init, ts_init);
649 }
650
651 #[rstest]
652 #[case::negative(-1)]
653 #[case::overflow(i64::MAX)]
654 fn test_parse_agg_trade_falls_back_for_invalid_timestamp(#[case] trade_time: i64) {
655 let instrument = sample_instrument();
656 let mut msg: BinanceFuturesAggTradeMsg = load_market_fixture("agg_trade_stream.json");
657 msg.trade_time = trade_time;
658
659 let ts_init = UnixNanos::from(1);
660 let trade = parse_agg_trade(&msg, &instrument, ts_init).unwrap();
661
662 assert_eq!(trade.ts_event, ts_init);
663 assert_eq!(trade.ts_init, ts_init);
664 }
665
666 #[rstest]
667 fn test_parse_trade() {
668 let instrument = sample_instrument();
669 let msg: BinanceFuturesTradeMsg = load_market_fixture("trade_stream.json");
670 let ts_init = UnixNanos::from(1_794_270_806_238_000_000u64);
671
672 let trade = parse_trade(&msg, &instrument, ts_init).unwrap().unwrap();
673
674 assert_eq!(trade.instrument_id, instrument.id());
675 assert_eq!(trade.price, Price::new(75047.30, PRICE_PRECISION));
676 assert_eq!(trade.size, Quantity::new(0.201, SIZE_PRECISION));
677 assert_eq!(trade.aggressor_side, AggressorSide::Sell);
678 assert_eq!(trade.trade_id, TradeId::new("8251028467"));
679 assert_eq!(
680 trade.ts_event,
681 UnixNanos::from(1_794_270_806_233_000_000u64)
682 );
683 assert_eq!(trade.ts_init, ts_init);
684 }
685
686 #[rstest]
687 fn test_parse_trade_skips_na_message() {
688 let instrument = sample_instrument();
689 let msg: BinanceFuturesTradeMsg = load_market_fixture("trade_stream_na.json");
690
691 let trade = parse_trade(&msg, &instrument, UnixNanos::from(1)).unwrap();
692
693 assert_eq!(msg.trade_type, BinanceFuturesTradeType::Na);
694 assert_eq!(msg.price, "0");
695 assert_eq!(msg.quantity, "0");
696 assert_eq!(trade, None);
697 }
698
699 #[rstest]
700 #[case::rpi(BinanceFuturesTradeType::Rpi, Some(TradeId::new("8251028467")))]
701 #[case::insurance_fund(BinanceFuturesTradeType::InsuranceFund, None)]
702 #[case::adl(BinanceFuturesTradeType::Adl, None)]
703 fn test_parse_trade_emits_order_book_trades_only(
704 #[case] trade_type: BinanceFuturesTradeType,
705 #[case] expected_trade_id: Option<TradeId>,
706 ) {
707 let instrument = sample_instrument();
708 let mut msg: BinanceFuturesTradeMsg = load_market_fixture("trade_stream.json");
709 msg.trade_type = trade_type;
710
711 let trade = parse_trade(&msg, &instrument, UnixNanos::from(1)).unwrap();
712
713 assert_eq!(trade.map(|trade| trade.trade_id), expected_trade_id);
714 }
715
716 #[rstest]
717 fn test_parse_trade_rejects_unknown_trade_type() {
718 let instrument = sample_instrument();
719 let mut msg: BinanceFuturesTradeMsg = load_market_fixture("trade_stream.json");
720 msg.trade_type = BinanceFuturesTradeType::Unknown;
721
722 let result = parse_trade(&msg, &instrument, UnixNanos::from(1));
723
724 assert!(matches!(
725 result,
726 Err(BinanceWsError::ParseError(ref message))
727 if message == "unknown trade type for BTCUSDT trade 8251028467"
728 ));
729 }
730
731 #[rstest]
732 fn test_parse_trade_rejects_market_trade_without_quantity() {
733 let instrument = sample_instrument();
734 let mut msg: BinanceFuturesTradeMsg = load_market_fixture("trade_stream.json");
735 msg.quantity = "0".to_string();
736
737 let result = parse_trade(&msg, &instrument, UnixNanos::from(1));
738
739 assert!(matches!(result, Err(BinanceWsError::ParseError(_))));
740 }
741
742 #[rstest]
743 fn test_parse_book_ticker() {
744 let instrument = sample_instrument();
745 let msg: BinanceFuturesBookTickerMsg = load_market_fixture("book_ticker_stream.json");
746 let ts_init = UnixNanos::from(1_700_000_001_000_000_000u64);
747
748 let quote = parse_book_ticker(&msg, &instrument, ts_init).unwrap();
749
750 assert_eq!(quote.instrument_id, instrument.id());
751 assert_eq!(quote.bid_price, Price::new(25.3519, PRICE_PRECISION));
752 assert_eq!(quote.ask_price, Price::new(25.3652, PRICE_PRECISION));
753 assert_eq!(quote.bid_size, Quantity::new(31.21, SIZE_PRECISION));
754 assert_eq!(quote.ask_size, Quantity::new(40.66, SIZE_PRECISION));
755 assert_eq!(
756 quote.ts_event,
757 UnixNanos::from(1_568_014_460_891_000_000u64)
758 );
759 assert_eq!(quote.ts_init, ts_init);
760 }
761
762 #[rstest]
763 fn test_parse_depth_update() {
764 let instrument = sample_instrument();
765 let msg: BinanceFuturesDepthUpdateMsg = load_market_fixture("depth_update_stream.json");
766 let ts_init = UnixNanos::from(1_700_000_001_000_000_000u64);
767
768 let deltas = parse_depth_update(&msg, &instrument, ts_init).unwrap();
769
770 assert_eq!(deltas.instrument_id, instrument.id());
771 assert_eq!(deltas.deltas.len(), 2);
772 assert_eq!(deltas.sequence, 160);
773 assert_eq!(deltas.ts_event, UnixNanos::from(123_456_788_000_000u64));
774 assert_eq!(deltas.ts_init, ts_init);
775 assert_eq!(deltas.deltas[0].action, BookAction::Update);
776 assert_eq!(deltas.deltas[0].order.side, OrderSide::Buy.into());
777 assert_eq!(
778 deltas.deltas[0].order.price,
779 Price::new(0.0024, PRICE_PRECISION)
780 );
781 assert_eq!(
782 deltas.deltas[0].order.size,
783 Quantity::new(10.0, SIZE_PRECISION)
784 );
785 assert_eq!(deltas.deltas[1].action, BookAction::Update);
786 assert_eq!(deltas.deltas[1].order.side, OrderSide::Sell.into());
787 assert_eq!(
788 deltas.deltas[1].order.price,
789 Price::new(0.0026, PRICE_PRECISION)
790 );
791 assert_eq!(
792 deltas.deltas[1].order.size,
793 Quantity::new(100.0, SIZE_PRECISION)
794 );
795 assert_eq!(deltas.deltas[1].flags, RecordFlag::F_LAST as u8);
796 }
797
798 #[rstest]
799 fn test_parse_depth_update_without_levels_returns_error() {
800 let instrument = sample_instrument();
801 let mut msg: BinanceFuturesDepthUpdateMsg = load_market_fixture("depth_update_stream.json");
802 msg.bids.clear();
803 msg.asks.clear();
804
805 let result = parse_depth_update(&msg, &instrument, UnixNanos::from(1));
806
807 assert!(matches!(result, Err(BinanceWsError::ParseError(_))));
808 }
809
810 #[rstest]
811 #[case::five(5)]
812 #[case::ten(10)]
813 #[case::twenty(20)]
814 fn test_parse_depth_snapshot_replaces_levels(#[case] depth: usize) {
815 let instrument = sample_instrument();
816 let mut msg: BinanceFuturesDepthUpdateMsg = load_market_fixture("depth_update_stream.json");
817 let ts_init = UnixNanos::from(1_700_000_001_000_000_000u64);
818 let mut book = OrderBook::new(instrument.id(), BookType::L2_MBP);
819
820 for offset in [0, 100] {
821 msg.bids = (0..depth)
822 .map(|i| [(1000 - offset - i).to_string(), "2.000".into()])
823 .collect();
824 msg.asks = (0..depth)
825 .map(|i| [(2000 + offset + i).to_string(), "3.000".into()])
826 .collect();
827 let snapshot = parse_depth_snapshot(&msg, &instrument, ts_init).unwrap();
828 let mut expected = vec![OrderBookDelta::clear(
829 instrument.id(),
830 msg.final_update_id,
831 snapshot.ts_event,
832 ts_init,
833 )];
834
835 for (side, levels) in [(OrderSide::Buy, &msg.bids), (OrderSide::Sell, &msg.asks)] {
836 for level in levels {
837 expected.push(OrderBookDelta::new(
838 instrument.id(),
839 BookAction::Add,
840 BookOrder::new(
841 side,
842 Price::from_str(&format!("{}.00000000", level[0])).unwrap(),
843 Quantity::from_str(&level[1]).unwrap(),
844 0,
845 ),
846 RecordFlag::F_SNAPSHOT as u8,
847 msg.final_update_id,
848 UnixNanos::from(123_456_788_000_000u64),
849 ts_init,
850 ));
851 }
852 }
853
854 expected.last_mut().unwrap().flags =
855 RecordFlag::F_SNAPSHOT as u8 | RecordFlag::F_LAST as u8;
856 assert_eq!(snapshot.instrument_id, instrument.id());
857 assert_eq!(snapshot.sequence, msg.final_update_id);
858 assert_eq!(snapshot.deltas, expected);
859 book.apply_deltas(&snapshot).unwrap();
860 assert_eq!(book.bids(None).count(), depth);
861 assert_eq!(book.asks(None).count(), depth);
862 for (actual, input) in book.bids(None).zip(&msg.bids) {
863 assert_eq!(
864 actual.price.value.as_decimal(),
865 Decimal::from_str(&input[0]).unwrap()
866 );
867 assert_eq!(actual.size_decimal(), dec!(2));
868 }
869
870 for (actual, input) in book.asks(None).zip(&msg.asks) {
871 assert_eq!(
872 actual.price.value.as_decimal(),
873 Decimal::from_str(&input[0]).unwrap()
874 );
875 assert_eq!(actual.size_decimal(), dec!(3));
876 }
877 }
878
879 msg.bids.clear();
880 msg.asks.clear();
881 let empty = parse_depth_snapshot(&msg, &instrument, ts_init).unwrap();
882 book.apply_deltas(&empty).unwrap();
883 assert_eq!(empty.deltas.len(), 1);
884 assert_eq!(
885 empty.deltas[0].flags,
886 RecordFlag::F_SNAPSHOT as u8 | RecordFlag::F_LAST as u8
887 );
888 assert_eq!(book.bids(None).count(), 0);
889 assert_eq!(book.asks(None).count(), 0);
890 }
891
892 #[rstest]
893 fn test_market_data_parsers_preserve_decimal_prices() {
894 let instrument = sample_instrument();
895 let ts_init = UnixNanos::from(1);
896 let price = "123456789.12345678";
897 let mut agg: BinanceFuturesAggTradeMsg = load_market_fixture("agg_trade_stream.json");
898 agg.price = price.to_string();
899 let mut trade: BinanceFuturesTradeMsg = load_market_fixture("trade_stream.json");
900 trade.price = price.to_string();
901 let mut book: BinanceFuturesBookTickerMsg = load_market_fixture("book_ticker_stream.json");
902 book.best_bid_price = price.to_string();
903 book.best_ask_price = "123456789.87654321".to_string();
904 let mut depth: BinanceFuturesDepthUpdateMsg =
905 load_market_fixture("depth_update_stream.json");
906 depth.bids[0][0] = price.to_string();
907 depth.asks[0][0] = book.best_ask_price.clone();
908 depth.asks[0][1] = "0.000".to_string();
909
910 let agg = parse_agg_trade(&agg, &instrument, ts_init).unwrap();
911 let trade = parse_trade(&trade, &instrument, ts_init).unwrap().unwrap();
912 let book = parse_book_ticker(&book, &instrument, ts_init).unwrap();
913 let depth = parse_depth_update(&depth, &instrument, ts_init).unwrap();
914
915 assert_eq!(agg.price, Price::from(price));
916 assert_eq!(trade.price, Price::from(price));
917 assert_eq!(book.bid_price, Price::from(price));
918 assert_eq!(book.ask_price, Price::from("123456789.87654321"));
919 assert_eq!(depth.deltas[0].order.price, Price::from(price));
920 assert_eq!(
921 depth.deltas[1].order.price,
922 Price::from("123456789.87654321")
923 );
924 assert_eq!(depth.deltas[1].order.size, Quantity::from("0.000"));
925 assert_eq!(depth.deltas[1].action, BookAction::Delete);
926 }
927
928 #[rstest]
929 fn test_parse_mark_price() {
930 let instrument = sample_instrument();
931 let msg: BinanceFuturesMarkPriceMsg = load_market_fixture("mark_price_stream.json");
932 let ts_init = UnixNanos::from(1_700_000_001_000_000_000u64);
933
934 let (mark, index, funding, custom) = parse_mark_price(&msg, &instrument, ts_init).unwrap();
935
936 assert_eq!(mark.instrument_id, instrument.id());
937 assert_eq!(mark.value, Price::new(11794.15, PRICE_PRECISION));
938 assert_eq!(index.value, Price::new(11784.62659091, PRICE_PRECISION));
939 assert_eq!(mark.ts_event, UnixNanos::from(1_562_305_380_000_000_000u64));
940 assert_eq!(funding.instrument_id, instrument.id());
941 assert_eq!(funding.rate.to_string(), "0.00038167");
942 assert_eq!(
943 funding.next_funding_ns,
944 Some(UnixNanos::from(1_562_306_400_000_000_000u64))
945 );
946 assert_eq!(
947 funding.ts_event,
948 UnixNanos::from(1_562_305_380_000_000_000u64)
949 );
950 assert_eq!(funding.ts_init, ts_init);
951 assert_eq!(custom.instrument_id, instrument.id());
952 assert_eq!(custom.mark_price, Price::from("11794.15000000"));
953 assert_eq!(custom.index_price, Price::from("11784.62659091"));
954 assert_eq!(custom.estimated_settle_price, Price::from("11784.25641265"));
955 assert_eq!(custom.funding_rate, dec!(0.00038167));
956 assert_eq!(custom.next_funding_time, funding.next_funding_ns);
957 assert_eq!(custom.ts_event, mark.ts_event);
958 assert_eq!(custom.ts_init, ts_init);
959 }
960
961 #[rstest]
962 #[case::zero(0)]
963 #[case::negative(-1)]
964 fn test_parse_mark_price_preserves_missing_funding_time(#[case] next_funding_time: i64) {
965 let instrument = sample_instrument();
966 let mut msg: BinanceFuturesMarkPriceMsg = load_market_fixture("mark_price_stream.json");
967 msg.next_funding_time = next_funding_time;
968
969 let (_, _, funding, custom) =
970 parse_mark_price(&msg, &instrument, UnixNanos::from(1)).unwrap();
971
972 assert_eq!(funding.next_funding_ns, None);
973 assert_eq!(custom.next_funding_time, None);
974 }
975
976 #[rstest]
977 fn test_parse_kline_closed() {
978 let instrument = sample_instrument();
979 let msg: BinanceFuturesKlineMsg = load_market_fixture("kline_stream_closed.json");
980 let ts_init = UnixNanos::from(1_700_000_001_000_000_000u64);
981
982 let bar = parse_kline(&msg, &instrument, ts_init).unwrap().unwrap();
983
984 assert_eq!(bar.bar_type.instrument_id(), instrument.id());
985 assert_eq!(bar.open, Price::new(0.001, PRICE_PRECISION));
986 assert_eq!(bar.high, Price::new(0.0025, PRICE_PRECISION));
987 assert_eq!(bar.low, Price::new(0.001, PRICE_PRECISION));
988 assert_eq!(bar.close, Price::new(0.002, PRICE_PRECISION));
989 assert_eq!(bar.volume, Quantity::new(1000.0, SIZE_PRECISION));
990 assert_eq!(bar.quote_volume, dec!(1.0000));
991 assert_eq!(bar.count, 100);
992 assert_eq!(bar.taker_buy_base_volume, dec!(500));
993 assert_eq!(bar.taker_buy_quote_volume, dec!(0.500));
994 assert_eq!(bar.ts_event, UnixNanos::from(1_638_747_719_999_000_000u64));
995 assert_eq!(bar.ts_init, ts_init);
996 }
997
998 #[rstest]
999 fn test_parse_kline_open_returns_none() {
1000 let instrument = sample_instrument();
1001 let msg: BinanceFuturesKlineMsg = load_market_fixture("kline_stream_open.json");
1002
1003 let bar = parse_kline(&msg, &instrument, UnixNanos::default()).unwrap();
1004
1005 assert!(bar.is_none());
1006 }
1007
1008 #[rstest]
1009 fn test_mark_price_msg_deserializes_optional_ap() {
1010 let json = r#"{
1011 "e": "markPriceUpdate",
1012 "E": 1562305380000,
1013 "s": "BTCUSDT",
1014 "p": "11794.15000000",
1015 "ap": "11792.85000000",
1016 "i": "11784.62659091",
1017 "P": "11784.25641265",
1018 "r": "0.00038167",
1019 "T": 1562306400000
1020 }"#;
1021
1022 let msg: BinanceFuturesMarkPriceMsg = serde_json::from_str(json).unwrap();
1023 assert_eq!(msg.mark_price_moving_avg.as_deref(), Some("11792.85000000"));
1024
1025 let legacy: BinanceFuturesMarkPriceMsg = load_market_fixture("mark_price_stream.json");
1026 assert!(legacy.mark_price_moving_avg.is_none());
1027 }
1028
1029 #[rstest]
1030 fn test_parse_mark_price_funding_rate_fields() {
1031 let instrument = sample_instrument();
1032 let msg: BinanceFuturesMarkPriceMsg = load_market_fixture("mark_price_stream.json");
1033 let ts_init = UnixNanos::from(1_700_000_001_000_000_000u64);
1034
1035 let (_mark, _index, funding, _custom) =
1036 parse_mark_price(&msg, &instrument, ts_init).unwrap();
1037
1038 assert_eq!(funding.instrument_id, instrument.id());
1039 assert_eq!(funding.rate.to_string(), "0.00038167");
1040 assert!(funding.interval.is_none());
1041 assert_eq!(
1042 funding.next_funding_ns,
1043 Some(UnixNanos::from(1_562_306_400_000_000_000u64))
1044 );
1045 assert_eq!(
1046 funding.ts_event,
1047 UnixNanos::from(1_562_305_380_000_000_000u64)
1048 );
1049 assert_eq!(funding.ts_init, ts_init);
1050 }
1051
1052 #[rstest]
1053 fn test_deserialize_liquidation_msg() {
1054 let msg: BinanceFuturesLiquidationMsg = load_market_fixture("liquidation_stream.json");
1055
1056 assert_eq!(msg.event_type, "forceOrder");
1057 assert_eq!(msg.event_time, 1_568_014_460_893);
1058 assert_eq!(msg.order.symbol, Ustr::from("BTCUSDT"));
1059 assert_eq!(msg.order.side, BinanceSide::Sell);
1060 assert_eq!(msg.order.original_qty, "0.014");
1061 assert_eq!(msg.order.average_price, "9910.12345678");
1062 assert_eq!(msg.order.status, BinanceOrderStatus::Filled);
1063 assert_eq!(msg.order.accumulated_qty, "0.014");
1064 assert_eq!(msg.order.trade_time, 1_568_014_460_893);
1065 }
1066
1067 #[rstest]
1068 fn test_deserialize_ticker_msg() {
1069 let msg: BinanceFuturesTickerMsg = load_market_fixture("ticker_stream.json");
1070
1071 assert_eq!(msg.event_type, "24hrTicker");
1072 assert_eq!(msg.symbol, Ustr::from("BTCUSDT"));
1073 assert_eq!(msg.price_change, "-131.40000000");
1074 assert_eq!(msg.price_change_percent, "-0.786");
1075 assert_eq!(msg.weighted_avg_price, "16628.97377498");
1076 assert_eq!(msg.last_price, "16584.60000000");
1077 assert_eq!(msg.open_price, "16716.00000000");
1078 assert_eq!(msg.high_price, "16764.89000000");
1079 assert_eq!(msg.low_price, "16456.51000000");
1080 assert_eq!(msg.volume, "122474.816");
1081 assert_eq!(msg.quote_volume, "2036102085.69746400");
1082 assert_eq!(msg.num_trades, 142853);
1083 }
1084
1085 #[rstest]
1086 fn test_parse_ticker() {
1087 let instrument = sample_instrument();
1088 let msg: BinanceFuturesTickerMsg = load_market_fixture("ticker_stream.json");
1089 let ts_init = UnixNanos::from(1_700_000_001_000_000_000u64);
1090
1091 let ticker = parse_ticker(&msg, &instrument, ts_init).unwrap();
1092
1093 assert_eq!(ticker.instrument_id, instrument.id());
1094 assert_eq!(ticker.price_change, dec!(-131.40000000));
1095 assert_eq!(ticker.price_change_percent, dec!(-0.786));
1096 assert_eq!(ticker.weighted_avg_price, dec!(16628.97377498));
1097 assert_eq!(ticker.last_price, dec!(16584.60000000));
1098 assert_eq!(ticker.last_qty, dec!(0.002));
1099 assert_eq!(ticker.open_price, dec!(16716.00000000));
1100 assert_eq!(ticker.high_price, dec!(16764.89000000));
1101 assert_eq!(ticker.low_price, dec!(16456.51000000));
1102 assert_eq!(ticker.volume, dec!(122474.816));
1103 assert_eq!(ticker.quote_volume, dec!(2036102085.69746400));
1104 assert_eq!(ticker.open_time, UnixNanos::from_millis(1_672_429_382_136));
1105 assert_eq!(ticker.close_time, UnixNanos::from_millis(1_672_515_782_136));
1106 assert_eq!(ticker.first_trade_id, 2_289_691);
1107 assert_eq!(ticker.last_trade_id, 2_432_543);
1108 assert_eq!(ticker.num_trades, 142_853);
1109 assert_eq!(ticker.ts_event, UnixNanos::from_millis(1_672_515_782_136));
1110 assert_eq!(ticker.ts_init, ts_init);
1111 }
1112
1113 #[rstest]
1114 fn test_parse_ticker_rejects_invalid_numeric_field() {
1115 let instrument = sample_instrument();
1116 let mut msg: BinanceFuturesTickerMsg = load_market_fixture("ticker_stream.json");
1117 msg.last_price = "not-a-decimal".to_string();
1118
1119 let result = parse_ticker(&msg, &instrument, UnixNanos::default());
1120
1121 assert!(result.is_err());
1122 }
1123
1124 #[rstest]
1125 fn test_extract_symbol() {
1126 let json = load_json_fixture("futures/market_data_json/book_ticker_stream.json");
1127
1128 let symbol = extract_symbol(&json);
1129
1130 assert_eq!(symbol, Some(Ustr::from("BNBUSDT")));
1131 }
1132
1133 #[rstest]
1134 fn test_extract_event_type() {
1135 let json = load_json_fixture("futures/market_data_json/mark_price_stream.json");
1136
1137 let event_type = extract_event_type(&json);
1138
1139 assert_eq!(event_type, Some(BinanceWsEventType::MarkPriceUpdate));
1140 }
1141
1142 #[rstest]
1143 fn test_extract_event_type_force_order() {
1144 let json = load_json_fixture("futures/market_data_json/liquidation_stream.json");
1145
1146 let event_type = extract_event_type(&json);
1147
1148 assert_eq!(event_type, Some(BinanceWsEventType::ForceOrder));
1149 }
1150
1151 #[rstest]
1152 fn test_extract_event_type_ticker() {
1153 let json = load_json_fixture("futures/market_data_json/ticker_stream.json");
1154
1155 let event_type = extract_event_type(&json);
1156
1157 assert_eq!(event_type, Some(BinanceWsEventType::Ticker24Hr));
1158 }
1159}