nautilus_binance/common/sbe/stream/
depth_snapshot.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Depth snapshot stream event decoder.
17//!
18//! Message layout (after 8-byte header):
19//! - eventTime: i64 (microseconds)
20//! - bookUpdateId: i64
21//! - priceExponent: i8
22//! - qtyExponent: i8
23//! - bids group (groupSize16Encoding: u16 blockLength + u16 numInGroup):
24//!   - price: i64 (mantissa)
25//!   - qty: i64 (mantissa)
26//! - asks group (groupSize16Encoding: u16 blockLength + u16 numInGroup):
27//!   - price: i64 (mantissa)
28//!   - qty: i64 (mantissa)
29//! - symbol: varString8
30
31use ustr::Ustr;
32
33use super::{MessageHeader, PriceLevel, StreamDecodeError};
34use crate::common::sbe::cursor::SbeCursor;
35
36/// Depth snapshot stream event (top N levels of order book).
37#[derive(Debug, Clone)]
38pub struct DepthSnapshotStreamEvent {
39    /// Event timestamp in microseconds.
40    pub event_time_us: i64,
41    /// Book update ID for sequencing.
42    pub book_update_id: i64,
43    /// Price exponent (prices = mantissa * 10^exponent).
44    pub price_exponent: i8,
45    /// Quantity exponent (quantities = mantissa * 10^exponent).
46    pub qty_exponent: i8,
47    /// Bid levels (best bid first).
48    pub bids: Vec<PriceLevel>,
49    /// Ask levels (best ask first).
50    pub asks: Vec<PriceLevel>,
51    /// Trading symbol.
52    pub symbol: Ustr,
53}
54
55impl DepthSnapshotStreamEvent {
56    /// Fixed block length (excluding header, groups, and variable-length data).
57    pub const BLOCK_LENGTH: usize = 18;
58
59    /// Decode from SBE buffer (including 8-byte header).
60    ///
61    /// # Errors
62    ///
63    /// Returns error if buffer is too short, group size exceeds limits,
64    /// or data is otherwise invalid.
65    pub fn decode(buf: &[u8]) -> Result<Self, StreamDecodeError> {
66        let header = MessageHeader::decode(buf)?;
67        header.validate_schema()?;
68
69        let mut cursor = SbeCursor::new_at(buf, MessageHeader::ENCODED_LENGTH);
70
71        let event_time_us = cursor.read_i64_le()?;
72        let book_update_id = cursor.read_i64_le()?;
73        let price_exponent = cursor.read_i8()?;
74        let qty_exponent = cursor.read_i8()?;
75
76        let (bid_block_length, num_bids) = cursor.read_group_header_16()?;
77        let bids = cursor.read_group(bid_block_length, u32::from(num_bids), PriceLevel::decode)?;
78
79        let (ask_block_length, num_asks) = cursor.read_group_header_16()?;
80        let asks = cursor.read_group(ask_block_length, u32::from(num_asks), PriceLevel::decode)?;
81
82        let symbol_str = cursor.read_var_string8()?;
83
84        Ok(Self {
85            event_time_us,
86            book_update_id,
87            price_exponent,
88            qty_exponent,
89            bids,
90            asks,
91            symbol: Ustr::from(&symbol_str),
92        })
93    }
94
95    /// Get price as f64 for a level.
96    #[inline]
97    #[must_use]
98    pub fn level_price(&self, level: &PriceLevel) -> f64 {
99        super::mantissa_to_f64(level.price_mantissa, self.price_exponent)
100    }
101
102    /// Get quantity as f64 for a level.
103    #[inline]
104    #[must_use]
105    pub fn level_qty(&self, level: &PriceLevel) -> f64 {
106        super::mantissa_to_f64(level.qty_mantissa, self.qty_exponent)
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use rstest::rstest;
113
114    use super::*;
115    use crate::common::sbe::stream::{STREAM_SCHEMA_ID, template_id};
116
117    fn make_valid_buffer(num_bids: usize, num_asks: usize) -> Vec<u8> {
118        let level_block_len = 16u16;
119        let body_size = 18
120            + 4
121            + (num_bids * level_block_len as usize)
122            + 4
123            + (num_asks * level_block_len as usize)
124            + 8;
125        let mut buf = vec![0u8; 8 + body_size];
126
127        // Header
128        buf[0..2].copy_from_slice(&18u16.to_le_bytes()); // block_length
129        buf[2..4].copy_from_slice(&template_id::DEPTH_SNAPSHOT_STREAM_EVENT.to_le_bytes());
130        buf[4..6].copy_from_slice(&STREAM_SCHEMA_ID.to_le_bytes());
131        buf[6..8].copy_from_slice(&0u16.to_le_bytes()); // version
132
133        // Body
134        let body = &mut buf[8..];
135        body[0..8].copy_from_slice(&1000000i64.to_le_bytes()); // event_time_us
136        body[8..16].copy_from_slice(&12345i64.to_le_bytes()); // book_update_id
137        body[16] = (-2i8) as u8; // price_exponent
138        body[17] = (-8i8) as u8; // qty_exponent
139
140        let mut offset = 18;
141
142        // Bids group header
143        body[offset..offset + 2].copy_from_slice(&level_block_len.to_le_bytes());
144        body[offset + 2..offset + 4].copy_from_slice(&(num_bids as u16).to_le_bytes());
145        offset += 4;
146
147        // Bids
148        for i in 0..num_bids {
149            body[offset..offset + 8].copy_from_slice(&(4200000i64 - i as i64 * 100).to_le_bytes());
150            body[offset + 8..offset + 16].copy_from_slice(&100000000i64.to_le_bytes());
151            offset += level_block_len as usize;
152        }
153
154        // Asks group header
155        body[offset..offset + 2].copy_from_slice(&level_block_len.to_le_bytes());
156        body[offset + 2..offset + 4].copy_from_slice(&(num_asks as u16).to_le_bytes());
157        offset += 4;
158
159        // Asks
160        for i in 0..num_asks {
161            body[offset..offset + 8].copy_from_slice(&(4200100i64 + i as i64 * 100).to_le_bytes());
162            body[offset + 8..offset + 16].copy_from_slice(&200000000i64.to_le_bytes());
163            offset += level_block_len as usize;
164        }
165
166        // Symbol: "BTCUSDT"
167        body[offset] = 7;
168        body[offset + 1..offset + 8].copy_from_slice(b"BTCUSDT");
169
170        buf
171    }
172
173    #[rstest]
174    fn test_decode_valid() {
175        let buf = make_valid_buffer(5, 5);
176        let event = DepthSnapshotStreamEvent::decode(&buf).unwrap();
177
178        assert_eq!(event.event_time_us, 1000000);
179        assert_eq!(event.book_update_id, 12345);
180        assert_eq!(event.bids.len(), 5);
181        assert_eq!(event.asks.len(), 5);
182        assert_eq!(event.symbol, "BTCUSDT");
183    }
184
185    #[rstest]
186    fn test_decode_empty_books() {
187        let buf = make_valid_buffer(0, 0);
188        let event = DepthSnapshotStreamEvent::decode(&buf).unwrap();
189
190        assert!(event.bids.is_empty());
191        assert!(event.asks.is_empty());
192    }
193
194    #[rstest]
195    fn test_decode_truncated() {
196        let mut buf = make_valid_buffer(10, 10);
197        buf.truncate(100); // Truncate in the middle
198        let err = DepthSnapshotStreamEvent::decode(&buf).unwrap_err();
199        assert!(matches!(err, StreamDecodeError::BufferTooShort { .. }));
200    }
201
202    #[rstest]
203    fn test_decode_wrong_schema() {
204        let mut buf = make_valid_buffer(5, 5);
205        buf[4..6].copy_from_slice(&99u16.to_le_bytes());
206        let err = DepthSnapshotStreamEvent::decode(&buf).unwrap_err();
207        assert!(matches!(err, StreamDecodeError::SchemaMismatch { .. }));
208    }
209}