Skip to main content

nautilus_binance/spot/sbe/stream/
trades.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//! Trades stream event decoder.
17//!
18//! Message layout (after 8-byte header):
19//! - eventTime: i64 (microseconds)
20//! - transactTime: i64 (microseconds)
21//! - priceExponent: i8
22//! - qtyExponent: i8
23//! - trades group (groupSizeEncoding: u16 blockLength + u32 numInGroup):
24//!   - id: i64
25//!   - price: i64 (mantissa)
26//!   - qty: i64 (mantissa)
27//!   - isBuyerMaker: u8
28//! - symbol: varString8
29
30use ustr::Ustr;
31
32use super::{MessageHeader, StreamDecodeError};
33use crate::spot::sbe::{cursor::SbeCursor, error::SbeDecodeError};
34
35/// Individual trade within a trades stream event.
36#[derive(Debug, Clone, Copy)]
37pub struct Trade {
38    /// Trade ID.
39    pub id: i64,
40    /// Price mantissa.
41    pub price_mantissa: i64,
42    /// Quantity mantissa.
43    pub qty_mantissa: i64,
44    /// True if buyer is the maker (seller initiated the trade).
45    pub is_buyer_maker: bool,
46}
47
48impl Trade {
49    /// Encoded length per trade entry.
50    pub const ENCODED_LENGTH: usize = 25;
51
52    /// Decode a single trade from cursor.
53    ///
54    /// # Errors
55    ///
56    /// Returns error if buffer is too short.
57    fn decode(cursor: &mut SbeCursor<'_>) -> Result<Self, SbeDecodeError> {
58        Ok(Self {
59            id: cursor.read_i64_le()?,
60            price_mantissa: cursor.read_i64_le()?,
61            qty_mantissa: cursor.read_i64_le()?,
62            is_buyer_maker: cursor.read_u8()? != 0,
63        })
64    }
65}
66
67/// Trades stream event (may contain multiple trades).
68#[derive(Debug, Clone)]
69pub struct TradesStreamEvent {
70    /// Event timestamp in microseconds.
71    pub event_time_us: i64,
72    /// Transaction timestamp in microseconds.
73    pub transact_time_us: i64,
74    /// Price exponent (prices = mantissa * 10^exponent).
75    pub price_exponent: i8,
76    /// Quantity exponent (quantities = mantissa * 10^exponent).
77    pub qty_exponent: i8,
78    /// Trades in this event.
79    pub trades: Vec<Trade>,
80    /// Trading symbol.
81    pub symbol: Ustr,
82}
83
84impl TradesStreamEvent {
85    /// Fixed block length (excluding header, groups, and variable-length data).
86    pub const BLOCK_LENGTH: usize = 18;
87
88    /// Decode from SBE buffer (including 8-byte header).
89    ///
90    /// # Errors
91    ///
92    /// Returns error if buffer is too short, group size exceeds limits,
93    /// or data is otherwise invalid.
94    pub fn decode(buf: &[u8]) -> Result<Self, StreamDecodeError> {
95        let header = MessageHeader::decode(buf)?;
96        header.validate_schema()?;
97        Self::decode_validated(buf)
98    }
99
100    /// Decode from an SBE buffer whose header has already been validated.
101    pub(crate) fn decode_validated(buf: &[u8]) -> Result<Self, StreamDecodeError> {
102        let mut cursor = SbeCursor::new_at(buf, MessageHeader::ENCODED_LENGTH);
103        Self::decode_body(&mut cursor)
104    }
105
106    #[inline]
107    fn decode_body(cursor: &mut SbeCursor<'_>) -> Result<Self, StreamDecodeError> {
108        let event_time_us = cursor.read_i64_le()?;
109        let transact_time_us = cursor.read_i64_le()?;
110        let price_exponent = cursor.read_i8()?;
111        let qty_exponent = cursor.read_i8()?;
112
113        let (block_length, num_in_group) = cursor.read_group_header()?;
114        let trades = cursor.read_group(block_length, num_in_group, Trade::decode)?;
115
116        let symbol = Ustr::from(cursor.read_var_string8_ref()?);
117
118        Ok(Self {
119            event_time_us,
120            transact_time_us,
121            price_exponent,
122            qty_exponent,
123            trades,
124            symbol,
125        })
126    }
127
128    /// Get price as f64 for a trade.
129    #[inline]
130    #[must_use]
131    pub fn trade_price(&self, trade: &Trade) -> f64 {
132        super::mantissa_to_f64(trade.price_mantissa, self.price_exponent)
133    }
134
135    /// Get quantity as f64 for a trade.
136    #[inline]
137    #[must_use]
138    pub fn trade_qty(&self, trade: &Trade) -> f64 {
139        super::mantissa_to_f64(trade.qty_mantissa, self.qty_exponent)
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use rstest::rstest;
146
147    use super::*;
148    use crate::spot::sbe::stream::{STREAM_SCHEMA_ID, template_id};
149
150    fn make_valid_buffer(num_trades: usize) -> Vec<u8> {
151        let trade_block_len = 25u16;
152        let body_size = 18 + 6 + (num_trades * trade_block_len as usize) + 8; // fixed + group header + trades + symbol
153        let mut buf = vec![0u8; 8 + body_size];
154
155        // Header
156        buf[0..2].copy_from_slice(&18u16.to_le_bytes()); // block_length
157        buf[2..4].copy_from_slice(&template_id::TRADES_STREAM_EVENT.to_le_bytes());
158        buf[4..6].copy_from_slice(&STREAM_SCHEMA_ID.to_le_bytes());
159        buf[6..8].copy_from_slice(&0u16.to_le_bytes()); // version
160
161        // Body
162        let body = &mut buf[8..];
163        body[0..8].copy_from_slice(&1000000i64.to_le_bytes()); // event_time_us
164        body[8..16].copy_from_slice(&1000001i64.to_le_bytes()); // transact_time_us
165        body[16] = (-2i8) as u8; // price_exponent
166        body[17] = (-8i8) as u8; // qty_exponent
167
168        // Group header
169        body[18..20].copy_from_slice(&trade_block_len.to_le_bytes());
170        body[20..24].copy_from_slice(&(num_trades as u32).to_le_bytes());
171
172        // Trades
173        let mut offset = 24;
174        for i in 0..num_trades {
175            body[offset..offset + 8].copy_from_slice(&(i as i64 + 1).to_le_bytes()); // id
176            body[offset + 8..offset + 16].copy_from_slice(&4200000i64.to_le_bytes()); // price
177            body[offset + 16..offset + 24].copy_from_slice(&100000000i64.to_le_bytes()); // qty
178            body[offset + 24] = u8::from(i % 2 == 0); // is_buyer_maker
179            offset += trade_block_len as usize;
180        }
181
182        // Symbol: "BTCUSDT"
183        body[offset] = 7;
184        body[offset + 1..offset + 8].copy_from_slice(b"BTCUSDT");
185
186        buf
187    }
188
189    #[rstest]
190    fn test_decode_valid_single_trade() {
191        let buf = make_valid_buffer(1);
192        let event = TradesStreamEvent::decode(&buf).unwrap();
193
194        assert_eq!(event.event_time_us, 1000000);
195        assert_eq!(event.transact_time_us, 1000001);
196        assert_eq!(event.trades.len(), 1);
197        assert_eq!(event.trades[0].id, 1);
198        assert!(event.trades[0].is_buyer_maker);
199        assert_eq!(event.symbol, "BTCUSDT");
200    }
201
202    #[rstest]
203    fn test_decode_valid_multiple_trades() {
204        let buf = make_valid_buffer(5);
205        let event = TradesStreamEvent::decode(&buf).unwrap();
206
207        assert_eq!(event.trades.len(), 5);
208        for (i, trade) in event.trades.iter().enumerate() {
209            assert_eq!(trade.id, i as i64 + 1);
210        }
211    }
212
213    #[rstest]
214    fn test_decode_truncated_trades() {
215        let mut buf = make_valid_buffer(3);
216        buf.truncate(50); // Truncate in the middle of trades
217        let err = TradesStreamEvent::decode(&buf).unwrap_err();
218        assert!(matches!(err, StreamDecodeError::BufferTooShort { .. }));
219    }
220
221    #[rstest]
222    fn test_decode_wrong_schema() {
223        let mut buf = make_valid_buffer(1);
224        buf[4..6].copy_from_slice(&99u16.to_le_bytes());
225        let err = TradesStreamEvent::decode(&buf).unwrap_err();
226        assert!(matches!(err, StreamDecodeError::SchemaMismatch { .. }));
227    }
228
229    #[rstest]
230    fn test_decode_validated_matches_decode() {
231        let buf = make_valid_buffer(3);
232
233        let decode_event = TradesStreamEvent::decode(&buf).unwrap();
234        let validated_event = TradesStreamEvent::decode_validated(&buf).unwrap();
235
236        assert_eq!(validated_event.event_time_us, decode_event.event_time_us);
237        assert_eq!(
238            validated_event.transact_time_us,
239            decode_event.transact_time_us
240        );
241        assert_eq!(validated_event.price_exponent, decode_event.price_exponent);
242        assert_eq!(validated_event.qty_exponent, decode_event.qty_exponent);
243        assert_eq!(validated_event.trades.len(), decode_event.trades.len());
244        assert_eq!(validated_event.symbol, decode_event.symbol);
245    }
246}