Skip to main content

nautilus_binance/spot/http/
parse.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//! SBE decode functions for Binance Spot HTTP responses.
17//!
18//! Each function decodes raw SBE bytes into domain types, validating the
19//! message header (schema ID and template ID) before extracting fields.
20
21use rust_decimal::Decimal;
22
23use super::{
24    error::SbeDecodeError,
25    models::{
26        BinanceAccountInfo, BinanceAccountTrade, BinanceAggTrade, BinanceAggTrades, BinanceBalance,
27        BinanceCancelOpenOrdersResponse, BinanceCancelOrderListOrder,
28        BinanceCancelOrderListResponse, BinanceCancelOrderResponse, BinanceDepth,
29        BinanceExchangeInfoSbe, BinanceKline, BinanceKlines, BinanceLotSizeFilterSbe,
30        BinanceNewOrderResponse, BinanceNotionalFilter, BinanceOrderFill, BinanceOrderResponse,
31        BinancePriceFilterSbe, BinancePriceLevel, BinanceSymbolFiltersSbe, BinanceSymbolSbe,
32        BinanceTrade, BinanceTrades,
33    },
34};
35use crate::spot::sbe::{
36    cursor::SbeCursor,
37    spot::{
38        SBE_SCHEMA_ID, account_response_codec::SBE_TEMPLATE_ID as ACCOUNT_TEMPLATE_ID,
39        account_trades_response_codec::SBE_TEMPLATE_ID as ACCOUNT_TRADES_TEMPLATE_ID,
40        account_type::AccountType,
41        agg_trades_response_codec::SBE_TEMPLATE_ID as AGG_TRADES_TEMPLATE_ID, bool_enum::BoolEnum,
42        cancel_open_orders_response_codec::SBE_TEMPLATE_ID as CANCEL_OPEN_ORDERS_TEMPLATE_ID,
43        cancel_order_list_response_codec::SBE_TEMPLATE_ID as CANCEL_ORDER_LIST_TEMPLATE_ID,
44        cancel_order_response_codec::SBE_TEMPLATE_ID as CANCEL_ORDER_TEMPLATE_ID,
45        cancel_replace_order_response_codec::SBE_TEMPLATE_ID as CANCEL_REPLACE_TEMPLATE_ID,
46        cancel_replace_status::CancelReplaceStatus,
47        depth_response_codec::SBE_TEMPLATE_ID as DEPTH_TEMPLATE_ID,
48        exchange_info_response_codec::SBE_TEMPLATE_ID as EXCHANGE_INFO_TEMPLATE_ID,
49        klines_response_codec::SBE_TEMPLATE_ID as KLINES_TEMPLATE_ID,
50        lot_size_filter_codec::SBE_TEMPLATE_ID as LOT_SIZE_FILTER_TEMPLATE_ID,
51        message_header_codec::ENCODED_LENGTH as HEADER_LENGTH,
52        min_notional_filter_codec::SBE_TEMPLATE_ID as MIN_NOTIONAL_FILTER_TEMPLATE_ID,
53        new_order_full_response_codec::SBE_TEMPLATE_ID as NEW_ORDER_FULL_TEMPLATE_ID,
54        notional_filter_codec::SBE_TEMPLATE_ID as NOTIONAL_FILTER_TEMPLATE_ID,
55        order_response_codec::SBE_TEMPLATE_ID as ORDER_TEMPLATE_ID,
56        orders_response_codec::SBE_TEMPLATE_ID as ORDERS_TEMPLATE_ID,
57        ping_response_codec::SBE_TEMPLATE_ID as PING_TEMPLATE_ID,
58        price_filter_codec::SBE_TEMPLATE_ID as PRICE_FILTER_TEMPLATE_ID,
59        server_time_response_codec::SBE_TEMPLATE_ID as SERVER_TIME_TEMPLATE_ID,
60        trades_response_codec::SBE_TEMPLATE_ID as TRADES_TEMPLATE_ID,
61    },
62};
63
64/// SBE message header.
65#[derive(Debug, Clone, Copy)]
66struct MessageHeader {
67    block_length: u16,
68    template_id: u16,
69    schema_id: u16,
70    version: u16,
71}
72
73impl MessageHeader {
74    /// Decode message header using cursor.
75    fn decode_cursor(cursor: &mut SbeCursor<'_>) -> Result<Self, SbeDecodeError> {
76        cursor.require(HEADER_LENGTH)?;
77        let block_length = cursor.read_u16_le()?;
78        let template_id = cursor.read_u16_le()?;
79        let schema_id = cursor.read_u16_le()?;
80        let version = cursor.read_u16_le()?;
81        Ok(Self {
82            block_length,
83            template_id,
84            schema_id,
85            version,
86        })
87    }
88
89    /// Validate the message schema ID.
90    ///
91    /// The exact schema version is intentionally not enforced, matching the
92    /// WebSocket SBE path. Binance evolves the schema additively within a schema ID
93    /// and rolls new versions out gradually, so a single client sees both the current
94    /// and next version during a rollout: 3:4 and 3:5 share identical block layouts,
95    /// differing only by an added `symbolStatus` enum value, and unknown enum values
96    /// decode to their null variant. Enforcing an exact version would hard-fail
97    /// instrument loading on a server-side bump. A different schema ID is a breaking
98    /// change and is still rejected.
99    ///
100    /// The decoders assume block layouts are stable within a schema ID.
101    /// `decode_exchange_info` verifies the symbol block length and fails loudly on a
102    /// mismatch; the market-data decoders read groups at a fixed offset, so a future
103    /// version that adds fixed-block fields to those messages would need them updated
104    /// to advance past the added bytes via `block_length`.
105    fn validate(&self) -> Result<(), SbeDecodeError> {
106        if self.schema_id != SBE_SCHEMA_ID {
107            return Err(SbeDecodeError::SchemaMismatch {
108                expected: SBE_SCHEMA_ID,
109                actual: self.schema_id,
110            });
111        }
112        Ok(())
113    }
114}
115
116/// Decode a ping response.
117///
118/// Ping response has no body (block_length = 0), just validates the header.
119///
120/// # Errors
121///
122/// Returns an error if buffer is too short or schema mismatch.
123pub fn decode_ping(buf: &[u8]) -> Result<(), SbeDecodeError> {
124    let mut cursor = SbeCursor::new(buf);
125    let header = MessageHeader::decode_cursor(&mut cursor)?;
126    header.validate()?;
127
128    if header.template_id != PING_TEMPLATE_ID {
129        return Err(SbeDecodeError::UnknownTemplateId(header.template_id));
130    }
131
132    Ok(())
133}
134
135/// Decode a server time response.
136///
137/// Returns the server time as **microseconds** since epoch (SBE provides
138/// microsecond precision vs JSON's milliseconds).
139///
140/// # Errors
141///
142/// Returns an error if buffer is too short or schema mismatch.
143pub fn decode_server_time(buf: &[u8]) -> Result<i64, SbeDecodeError> {
144    let mut cursor = SbeCursor::new(buf);
145    let header = MessageHeader::decode_cursor(&mut cursor)?;
146    header.validate()?;
147
148    if header.template_id != SERVER_TIME_TEMPLATE_ID {
149        return Err(SbeDecodeError::UnknownTemplateId(header.template_id));
150    }
151
152    cursor.read_i64_le()
153}
154
155const DEPTH_LEVEL_BLOCK_LENGTH: u16 = 16;
156const TRADE_BLOCK_LENGTH: u16 = 42;
157const AGG_TRADE_BLOCK_LENGTH: u16 = 50;
158
159/// Decode a depth response.
160///
161/// Returns the order book depth with bids and asks.
162///
163/// # Errors
164///
165/// Returns an error if:
166/// - The buffer is too short.
167/// - The schema ID or template ID does not match.
168/// - The group count exceeds the limit.
169/// - A group block is shorter than its fixed entry width.
170pub fn decode_depth(buf: &[u8]) -> Result<BinanceDepth, SbeDecodeError> {
171    let mut cursor = SbeCursor::new(buf);
172    let header = MessageHeader::decode_cursor(&mut cursor)?;
173    header.validate()?;
174
175    if header.template_id != DEPTH_TEMPLATE_ID {
176        return Err(SbeDecodeError::UnknownTemplateId(header.template_id));
177    }
178
179    let last_update_id = cursor.read_i64_le()?;
180    let price_exponent = cursor.read_i8()?;
181    let qty_exponent = cursor.read_i8()?;
182
183    let (block_len, count) = read_group_header(&mut cursor, DEPTH_LEVEL_BLOCK_LENGTH)?;
184
185    let bids = cursor.read_group(block_len, count, |c| {
186        let mut c = SbeCursor::new(c.read_bytes(usize::from(DEPTH_LEVEL_BLOCK_LENGTH))?);
187        Ok(BinancePriceLevel {
188            price_mantissa: c.read_i64_le()?,
189            qty_mantissa: c.read_i64_le()?,
190        })
191    })?;
192
193    let (block_len, count) = read_group_header(&mut cursor, DEPTH_LEVEL_BLOCK_LENGTH)?;
194
195    let asks = cursor.read_group(block_len, count, |c| {
196        let mut c = SbeCursor::new(c.read_bytes(usize::from(DEPTH_LEVEL_BLOCK_LENGTH))?);
197        Ok(BinancePriceLevel {
198            price_mantissa: c.read_i64_le()?,
199            qty_mantissa: c.read_i64_le()?,
200        })
201    })?;
202
203    Ok(BinanceDepth {
204        last_update_id,
205        price_exponent,
206        qty_exponent,
207        bids,
208        asks,
209    })
210}
211
212/// Decode a trades response.
213///
214/// Returns the list of trades.
215///
216/// # Errors
217///
218/// Returns an error if:
219/// - The buffer is too short.
220/// - The schema ID or template ID does not match.
221/// - The group count exceeds the limit.
222/// - A group block is shorter than its fixed entry width.
223pub fn decode_trades(buf: &[u8]) -> Result<BinanceTrades, SbeDecodeError> {
224    let mut cursor = SbeCursor::new(buf);
225    let header = MessageHeader::decode_cursor(&mut cursor)?;
226    header.validate()?;
227
228    if header.template_id != TRADES_TEMPLATE_ID {
229        return Err(SbeDecodeError::UnknownTemplateId(header.template_id));
230    }
231
232    let price_exponent = cursor.read_i8()?;
233    let qty_exponent = cursor.read_i8()?;
234
235    let (block_len, count) = read_group_header(&mut cursor, TRADE_BLOCK_LENGTH)?;
236
237    let trades = cursor.read_group(block_len, count, |c| {
238        let mut c = SbeCursor::new(c.read_bytes(usize::from(TRADE_BLOCK_LENGTH))?);
239        Ok(BinanceTrade {
240            id: c.read_i64_le()?,
241            price_mantissa: c.read_i64_le()?,
242            qty_mantissa: c.read_i64_le()?,
243            quote_qty_mantissa: c.read_i64_le()?,
244            time: c.read_i64_le()?,
245            is_buyer_maker: BoolEnum::from(c.read_u8()?) == BoolEnum::True,
246            is_best_match: BoolEnum::from(c.read_u8()?) == BoolEnum::True,
247        })
248    })?;
249
250    Ok(BinanceTrades {
251        price_exponent,
252        qty_exponent,
253        trades,
254    })
255}
256
257/// Decodes an aggregate trades response.
258///
259/// # Errors
260///
261/// Returns an error if:
262/// - The buffer is too short.
263/// - The schema ID or template ID does not match.
264/// - The group count exceeds the limit.
265/// - A group block is shorter than its fixed entry width.
266pub fn decode_agg_trades(buf: &[u8]) -> Result<BinanceAggTrades, SbeDecodeError> {
267    let mut cursor = SbeCursor::new(buf);
268    let header = MessageHeader::decode_cursor(&mut cursor)?;
269    header.validate()?;
270
271    if header.template_id != AGG_TRADES_TEMPLATE_ID {
272        return Err(SbeDecodeError::UnknownTemplateId(header.template_id));
273    }
274
275    let price_exponent = cursor.read_i8()?;
276    let qty_exponent = cursor.read_i8()?;
277    let (block_len, count) = read_group_header(&mut cursor, AGG_TRADE_BLOCK_LENGTH)?;
278
279    let trades = cursor.read_group(block_len, count, |c| {
280        let mut c = SbeCursor::new(c.read_bytes(usize::from(AGG_TRADE_BLOCK_LENGTH))?);
281        Ok(BinanceAggTrade {
282            id: c.read_i64_le()?,
283            price_mantissa: c.read_i64_le()?,
284            qty_mantissa: c.read_i64_le()?,
285            first_trade_id: c.read_i64_le()?,
286            last_trade_id: c.read_i64_le()?,
287            time: c.read_i64_le()?,
288            is_buyer_maker: BoolEnum::from(c.read_u8()?) == BoolEnum::True,
289            is_best_match: BoolEnum::from(c.read_u8()?) == BoolEnum::True,
290        })
291    })?;
292
293    Ok(BinanceAggTrades {
294        price_exponent,
295        qty_exponent,
296        trades,
297    })
298}
299
300fn read_group_header(
301    cursor: &mut SbeCursor<'_>,
302    minimum: u16,
303) -> Result<(u16, u32), SbeDecodeError> {
304    let (block_length, count) = cursor.read_group_header()?;
305    if block_length < minimum {
306        return Err(SbeDecodeError::InvalidBlockLength {
307            expected: minimum,
308            actual: block_length,
309        });
310    }
311
312    Ok((block_length, count))
313}
314
315/// Klines group item block length (from SBE codec).
316const KLINES_BLOCK_LENGTH: u16 = 120;
317
318/// Decode a klines (candlestick) response.
319///
320/// Returns the list of klines with their price and quantity exponents.
321///
322/// # Errors
323///
324/// Returns an error if buffer is too short, schema mismatch, or group size exceeded.
325pub fn decode_klines(buf: &[u8]) -> Result<BinanceKlines, SbeDecodeError> {
326    let mut cursor = SbeCursor::new(buf);
327    let header = MessageHeader::decode_cursor(&mut cursor)?;
328    header.validate()?;
329
330    if header.template_id != KLINES_TEMPLATE_ID {
331        return Err(SbeDecodeError::UnknownTemplateId(header.template_id));
332    }
333
334    let price_exponent = cursor.read_i8()?;
335    let qty_exponent = cursor.read_i8()?;
336
337    let (block_len, count) = cursor.read_group_header()?;
338
339    if block_len != KLINES_BLOCK_LENGTH {
340        return Err(SbeDecodeError::InvalidBlockLength {
341            expected: KLINES_BLOCK_LENGTH,
342            actual: block_len,
343        });
344    }
345
346    let mut klines = Vec::with_capacity(count as usize);
347
348    for _ in 0..count {
349        cursor.require(KLINES_BLOCK_LENGTH as usize)?;
350
351        let open_time = cursor.read_i64_le()?;
352        let open_price = cursor.read_i64_le()?;
353        let high_price = cursor.read_i64_le()?;
354        let low_price = cursor.read_i64_le()?;
355        let close_price = cursor.read_i64_le()?;
356
357        let volume_slice = cursor.read_bytes(16)?;
358        let mut volume = [0u8; 16];
359        volume.copy_from_slice(volume_slice);
360
361        let close_time = cursor.read_i64_le()?;
362
363        let quote_volume_slice = cursor.read_bytes(16)?;
364        let mut quote_volume = [0u8; 16];
365        quote_volume.copy_from_slice(quote_volume_slice);
366
367        let num_trades = cursor.read_i64_le()?;
368
369        let taker_buy_base_volume_slice = cursor.read_bytes(16)?;
370        let mut taker_buy_base_volume = [0u8; 16];
371        taker_buy_base_volume.copy_from_slice(taker_buy_base_volume_slice);
372
373        let taker_buy_quote_volume_slice = cursor.read_bytes(16)?;
374        let mut taker_buy_quote_volume = [0u8; 16];
375        taker_buy_quote_volume.copy_from_slice(taker_buy_quote_volume_slice);
376
377        klines.push(BinanceKline {
378            open_time,
379            open_price,
380            high_price,
381            low_price,
382            close_price,
383            volume,
384            close_time,
385            quote_volume,
386            num_trades,
387            taker_buy_base_volume,
388            taker_buy_quote_volume,
389        });
390    }
391
392    Ok(BinanceKlines {
393        price_exponent,
394        qty_exponent,
395        klines,
396    })
397}
398
399/// Bytes consumed from the fixed block before the end-of-block skip in each decoder.
400/// These represent explicit reads and advances up to the last field we extract.
401const NEW_ORDER_FULL_FIELDS_END: usize = 117;
402const CANCEL_ORDER_FIELDS_END: usize = 109;
403const CANCEL_ORDER_LIST_FIELDS_END: usize = 21;
404const CANCEL_ORDER_LIST_ORDER_FIELDS_END: usize = 8;
405const CANCEL_ORDER_LIST_REPORT_FIELDS_END: usize = 107;
406const CANCEL_ORDER_LIST_REPORT_V0_BLOCK_LENGTH: u16 = 124;
407const CANCEL_ORDER_LIST_REPORT_V1_BLOCK_LENGTH: u16 = 135;
408const ORDER_FIELDS_END: usize = 134;
409
410/// Minimum fixed-block length of an order in `orderResponse` and the
411/// `ordersResponse` group (schema 3:3 baseline).
412const ORDER_MIN_BLOCK_LENGTH: u16 = 162;
413
414/// Sentinel value for a null `expiryReason` in schema 3:4.
415const EXPIRY_REASON_NULL: u8 = 0xff;
416
417/// Schema-3:4 byte offsets of the `expiryReason` field within each fixed block.
418/// Sourced from the SBE codecs: `newOrderFullResponse` puts it at 153,
419/// `orderResponse` / `ordersResponse` at 162.
420const NEW_ORDER_FULL_EXPIRY_REASON_OFFSET: usize = 153;
421const ORDER_EXPIRY_REASON_OFFSET: usize = 162;
422
423/// Reads the schema-3:4 `expiryReason` byte from the fixed block when present.
424///
425/// `fields_end` is the cursor position (in bytes from the start of the block)
426/// after the last field the caller has explicitly parsed. `expiry_reason_offset`
427/// is the field's encoded offset within the block per the SBE schema.
428/// Returns `Ok(None)` when the runtime `block_length` does not span the
429/// `expiryReason` byte (schema 3:3 layouts) or when the byte holds the SBE
430/// null sentinel. In every case the cursor is advanced to the end of the
431/// fixed block.
432fn read_trailing_expiry_reason(
433    cursor: &mut SbeCursor<'_>,
434    block_length: usize,
435    fields_end: usize,
436    expiry_reason_offset: usize,
437) -> Result<Option<u8>, SbeDecodeError> {
438    debug_assert!(fields_end <= expiry_reason_offset);
439    if block_length < fields_end {
440        return Ok(None);
441    }
442    let trailer = block_length - fields_end;
443    if trailer == 0 {
444        return Ok(None);
445    }
446    // Pre-3:4 block: no expiryReason byte at this offset, skip remaining bytes.
447    if block_length <= expiry_reason_offset {
448        cursor.advance(trailer)?;
449        return Ok(None);
450    }
451    let pre = expiry_reason_offset - fields_end;
452    cursor.advance(pre)?;
453    let byte = cursor.read_u8()?;
454    let post = trailer - pre - 1;
455    if post > 0 {
456        cursor.advance(post)?;
457    }
458    Ok((byte != EXPIRY_REASON_NULL).then_some(byte))
459}
460
461/// Decode a new order full response.
462///
463/// # Errors
464///
465/// Returns an error if buffer is too short, schema mismatch, or decode error.
466#[allow(dead_code)]
467pub fn decode_new_order_full(buf: &[u8]) -> Result<BinanceNewOrderResponse, SbeDecodeError> {
468    let mut cursor = SbeCursor::new(buf);
469    let header = MessageHeader::decode_cursor(&mut cursor)?;
470    header.validate()?;
471
472    if header.template_id != NEW_ORDER_FULL_TEMPLATE_ID {
473        return Err(SbeDecodeError::UnknownTemplateId(header.template_id));
474    }
475
476    if usize::from(header.block_length) < NEW_ORDER_FULL_FIELDS_END {
477        return Err(SbeDecodeError::InvalidBlockLength {
478            expected: NEW_ORDER_FULL_FIELDS_END as u16,
479            actual: header.block_length,
480        });
481    }
482
483    cursor.require(header.block_length as usize)?;
484
485    let price_exponent = cursor.read_i8()?;
486    let qty_exponent = cursor.read_i8()?;
487    let order_id = cursor.read_i64_le()?;
488    let order_list_id = cursor.read_optional_i64_le()?;
489    let transact_time = cursor.read_i64_le()?;
490    let price_mantissa = cursor.read_i64_le()?;
491    let orig_qty_mantissa = cursor.read_i64_le()?;
492    let executed_qty_mantissa = cursor.read_i64_le()?;
493    let cummulative_quote_qty_mantissa = cursor.read_i64_le()?;
494    let status = cursor.read_u8()?.into();
495    let time_in_force = cursor.read_u8()?.into();
496    let order_type = cursor.read_u8()?.into();
497    let side = cursor.read_u8()?.into();
498    let stop_price_mantissa = cursor.read_optional_i64_le()?;
499
500    cursor.advance(16)?; // Skip trailing_delta (8) + trailing_time (8)
501    let working_time = cursor.read_optional_i64_le()?;
502
503    cursor.advance(22)?; // Skip iceberg_qty to working_floor
504    let self_trade_prevention_mode = cursor.read_u8()?.into();
505
506    let expiry_reason = read_trailing_expiry_reason(
507        &mut cursor,
508        header.block_length as usize,
509        NEW_ORDER_FULL_FIELDS_END,
510        NEW_ORDER_FULL_EXPIRY_REASON_OFFSET,
511    )?;
512
513    let fills = decode_fills_cursor(&mut cursor)?;
514
515    // Skip prevented matches group
516    let (block_len, count) = cursor.read_group_header()?;
517    cursor.advance(block_len as usize * count as usize)?;
518
519    let symbol = cursor.read_var_string8()?;
520    let client_order_id = cursor.read_var_string8()?;
521
522    Ok(BinanceNewOrderResponse {
523        price_exponent,
524        qty_exponent,
525        order_id,
526        order_list_id,
527        transact_time,
528        price_mantissa,
529        orig_qty_mantissa,
530        executed_qty_mantissa,
531        cummulative_quote_qty_mantissa,
532        status,
533        time_in_force,
534        order_type,
535        side,
536        stop_price_mantissa,
537        working_time,
538        self_trade_prevention_mode,
539        client_order_id,
540        symbol,
541        fills,
542        expiry_reason,
543    })
544}
545
546/// Decodes the replacement order from a successful cancel-replace response.
547///
548/// # Errors
549///
550/// Returns an error if the wrapper is malformed or the replacement is unsuccessful.
551pub fn decode_cancel_replace(buf: &[u8]) -> Result<BinanceNewOrderResponse, SbeDecodeError> {
552    let (_, replacement) = decode_cancel_replace_payloads(buf)?;
553    decode_new_order_full(replacement)
554}
555
556pub(crate) fn decode_cancel_replace_orders(
557    buf: &[u8],
558) -> Result<(BinanceCancelOrderResponse, BinanceNewOrderResponse), SbeDecodeError> {
559    let (cancellation, replacement) = decode_cancel_replace_payloads(buf)?;
560    Ok((
561        decode_cancel_order(cancellation)?,
562        decode_new_order_full(replacement)?,
563    ))
564}
565
566fn decode_cancel_replace_payloads(buf: &[u8]) -> Result<(&[u8], &[u8]), SbeDecodeError> {
567    let mut cursor = SbeCursor::new(buf);
568    let header = MessageHeader::decode_cursor(&mut cursor)?;
569    header.validate()?;
570    if header.template_id != CANCEL_REPLACE_TEMPLATE_ID {
571        return Err(SbeDecodeError::UnknownTemplateId(header.template_id));
572    }
573
574    if header.block_length < 2 {
575        return Err(SbeDecodeError::InvalidBlockLength {
576            expected: 2,
577            actual: header.block_length,
578        });
579    }
580    let cancel_result = cursor.read_u8()?;
581    let new_order_result = cursor.read_u8()?;
582    cursor.advance(usize::from(header.block_length) - 2)?;
583
584    if cancel_result != CancelReplaceStatus::Success as u8
585        || new_order_result != CancelReplaceStatus::Success as u8
586    {
587        return Err(SbeDecodeError::InvalidValue {
588            field: "cancel-replace result",
589        });
590    }
591    let cancel_len = usize::from(cursor.read_u16_le()?);
592    let cancellation = cursor.read_bytes(cancel_len)?;
593    let new_order_len = cursor.read_u32_le()? as usize;
594    let replacement = cursor.read_bytes(new_order_len)?;
595    Ok((cancellation, replacement))
596}
597
598/// Decode a cancel order response.
599///
600/// # Errors
601///
602/// Returns an error if buffer is too short, schema mismatch, or decode error.
603#[allow(dead_code)]
604pub fn decode_cancel_order(buf: &[u8]) -> Result<BinanceCancelOrderResponse, SbeDecodeError> {
605    let mut cursor = SbeCursor::new(buf);
606    let header = MessageHeader::decode_cursor(&mut cursor)?;
607    header.validate()?;
608
609    if header.template_id != CANCEL_ORDER_TEMPLATE_ID {
610        return Err(SbeDecodeError::UnknownTemplateId(header.template_id));
611    }
612
613    if usize::from(header.block_length) < CANCEL_ORDER_FIELDS_END {
614        return Err(SbeDecodeError::InvalidBlockLength {
615            expected: CANCEL_ORDER_FIELDS_END as u16,
616            actual: header.block_length,
617        });
618    }
619
620    cursor.require(header.block_length as usize)?;
621
622    let price_exponent = cursor.read_i8()?;
623    let qty_exponent = cursor.read_i8()?;
624    let order_id = cursor.read_i64_le()?;
625    let order_list_id = cursor.read_optional_i64_le()?;
626    let transact_time = cursor.read_i64_le()?;
627    let price_mantissa = cursor.read_i64_le()?;
628    let orig_qty_mantissa = cursor.read_i64_le()?;
629    let executed_qty_mantissa = cursor.read_i64_le()?;
630    let cummulative_quote_qty_mantissa = cursor.read_i64_le()?;
631    let status = cursor.read_u8()?.into();
632    let time_in_force = cursor.read_u8()?.into();
633    let order_type = cursor.read_u8()?.into();
634    let side = cursor.read_u8()?.into();
635
636    cursor.advance(46)?; // Skip stop_price to working_floor
637    let self_trade_prevention_mode = cursor.read_u8()?.into();
638
639    cursor.advance(header.block_length as usize - CANCEL_ORDER_FIELDS_END)?;
640
641    let symbol = cursor.read_var_string8()?;
642    let orig_client_order_id = cursor.read_var_string8()?;
643    let client_order_id = cursor.read_var_string8()?;
644
645    Ok(BinanceCancelOrderResponse {
646        price_exponent,
647        qty_exponent,
648        order_id,
649        order_list_id,
650        transact_time,
651        price_mantissa,
652        orig_qty_mantissa,
653        executed_qty_mantissa,
654        cummulative_quote_qty_mantissa,
655        status,
656        time_in_force,
657        order_type,
658        side,
659        self_trade_prevention_mode,
660        client_order_id,
661        orig_client_order_id,
662        symbol,
663    })
664}
665
666pub(crate) fn decode_cancel_order_or_list(
667    buf: &[u8],
668) -> Result<BinanceCancelOpenOrdersResponse, SbeDecodeError> {
669    let mut cursor = SbeCursor::new(buf);
670    let header = MessageHeader::decode_cursor(&mut cursor)?;
671    header.validate()?;
672    match header.template_id {
673        CANCEL_ORDER_TEMPLATE_ID => Ok(BinanceCancelOpenOrdersResponse::Order(
674            decode_cancel_order(buf)?,
675        )),
676        CANCEL_ORDER_LIST_TEMPLATE_ID => Ok(BinanceCancelOpenOrdersResponse::OrderList(
677            decode_cancel_order_list(buf)?,
678        )),
679        template_id => Err(SbeDecodeError::UnknownTemplateId(template_id)),
680    }
681}
682
683fn decode_cancel_order_list(buf: &[u8]) -> Result<BinanceCancelOrderListResponse, SbeDecodeError> {
684    let mut cursor = SbeCursor::new(buf);
685    let header = MessageHeader::decode_cursor(&mut cursor)?;
686    header.validate()?;
687    if header.template_id != CANCEL_ORDER_LIST_TEMPLATE_ID {
688        return Err(SbeDecodeError::UnknownTemplateId(header.template_id));
689    }
690
691    if usize::from(header.block_length) < CANCEL_ORDER_LIST_FIELDS_END {
692        return Err(SbeDecodeError::InvalidBlockLength {
693            expected: CANCEL_ORDER_LIST_FIELDS_END as u16,
694            actual: header.block_length,
695        });
696    }
697
698    cursor.require(header.block_length as usize)?;
699    let order_list_id = cursor.read_i64_le()?;
700    let contingency_type = cursor.read_u8()?.into();
701    let list_status_type = cursor.read_u8()?.into();
702    let list_order_status = cursor.read_u8()?.into();
703    let transaction_time = cursor.read_i64_le()?;
704    let price_exponent = cursor.read_i8()?;
705    let qty_exponent = cursor.read_i8()?;
706    cursor.advance(usize::from(header.block_length) - CANCEL_ORDER_LIST_FIELDS_END)?;
707
708    let (order_block_length, order_count) = cursor.read_group_header_16()?;
709    if usize::from(order_block_length) < CANCEL_ORDER_LIST_ORDER_FIELDS_END {
710        return Err(SbeDecodeError::InvalidBlockLength {
711            expected: CANCEL_ORDER_LIST_ORDER_FIELDS_END as u16,
712            actual: order_block_length,
713        });
714    }
715
716    let mut orders = Vec::with_capacity(order_count as usize);
717    for _ in 0..order_count {
718        cursor.require(order_block_length as usize)?;
719        let order_id = cursor.read_i64_le()?;
720        cursor.advance(usize::from(order_block_length) - CANCEL_ORDER_LIST_ORDER_FIELDS_END)?;
721        let symbol = cursor.read_var_string8()?;
722        let client_order_id = cursor.read_var_string8()?;
723        orders.push(BinanceCancelOrderListOrder {
724            symbol,
725            order_id,
726            client_order_id,
727        });
728    }
729
730    let (report_block_length, report_count) = cursor.read_group_header_16()?;
731    let report_min_block_length = if header.version == 0 {
732        CANCEL_ORDER_LIST_REPORT_V0_BLOCK_LENGTH
733    } else {
734        CANCEL_ORDER_LIST_REPORT_V1_BLOCK_LENGTH
735    };
736
737    if report_block_length < report_min_block_length {
738        return Err(SbeDecodeError::InvalidBlockLength {
739            expected: report_min_block_length,
740            actual: report_block_length,
741        });
742    }
743
744    let mut order_reports = Vec::with_capacity(report_count as usize);
745
746    for _ in 0..report_count {
747        cursor.require(report_block_length as usize)?;
748        let order_id = cursor.read_i64_le()?;
749        let order_list_id = cursor.read_optional_i64_le()?;
750        let transact_time = cursor.read_i64_le()?;
751        let price_mantissa = cursor.read_i64_le()?;
752        let orig_qty_mantissa = cursor.read_i64_le()?;
753        let executed_qty_mantissa = cursor.read_i64_le()?;
754        let cummulative_quote_qty_mantissa = cursor.read_i64_le()?;
755        let status = cursor.read_u8()?.into();
756        let time_in_force = cursor.read_u8()?.into();
757        let order_type = cursor.read_u8()?.into();
758        let side = cursor.read_u8()?.into();
759        cursor.advance(46)?;
760        let self_trade_prevention_mode = cursor.read_u8()?.into();
761        cursor.advance(usize::from(report_block_length) - CANCEL_ORDER_LIST_REPORT_FIELDS_END)?;
762        let symbol = cursor.read_var_string8()?;
763        let orig_client_order_id = cursor.read_var_string8()?;
764        let client_order_id = cursor.read_var_string8()?;
765        order_reports.push(BinanceCancelOrderResponse {
766            price_exponent,
767            qty_exponent,
768            order_id,
769            order_list_id,
770            transact_time,
771            price_mantissa,
772            orig_qty_mantissa,
773            executed_qty_mantissa,
774            cummulative_quote_qty_mantissa,
775            status,
776            time_in_force,
777            order_type,
778            side,
779            self_trade_prevention_mode,
780            client_order_id,
781            orig_client_order_id,
782            symbol,
783        });
784    }
785
786    let list_client_order_id = cursor.read_var_string8()?;
787    let symbol = cursor.read_var_string8()?;
788
789    Ok(BinanceCancelOrderListResponse {
790        order_list_id,
791        contingency_type,
792        list_status_type,
793        list_order_status,
794        transaction_time,
795        list_client_order_id,
796        symbol,
797        orders,
798        order_reports,
799    })
800}
801
802/// Decode an order query response.
803///
804/// # Errors
805///
806/// Returns an error if buffer is too short, schema mismatch, or decode error.
807#[allow(dead_code)]
808pub fn decode_order(buf: &[u8]) -> Result<BinanceOrderResponse, SbeDecodeError> {
809    let mut cursor = SbeCursor::new(buf);
810    let header = MessageHeader::decode_cursor(&mut cursor)?;
811    header.validate()?;
812
813    if header.template_id != ORDER_TEMPLATE_ID {
814        return Err(SbeDecodeError::UnknownTemplateId(header.template_id));
815    }
816
817    decode_order_block(&mut cursor, header.block_length)
818}
819
820/// Decode multiple orders response.
821///
822/// # Errors
823///
824/// Returns an error if buffer is too short, schema mismatch, or decode error.
825#[allow(dead_code)]
826pub fn decode_orders(buf: &[u8]) -> Result<Vec<BinanceOrderResponse>, SbeDecodeError> {
827    let mut cursor = SbeCursor::new(buf);
828    let header = MessageHeader::decode_cursor(&mut cursor)?;
829    header.validate()?;
830
831    if header.template_id != ORDERS_TEMPLATE_ID {
832        return Err(SbeDecodeError::UnknownTemplateId(header.template_id));
833    }
834
835    let (block_length, count) = cursor.read_group_header()?;
836    let mut orders = Vec::with_capacity(count as usize);
837
838    for _ in 0..count {
839        orders.push(decode_order_block(&mut cursor, block_length)?);
840    }
841
842    Ok(orders)
843}
844
845/// Decodes one order fixed block plus its trailing var-strings, shared by the
846/// `orderResponse` message and each `ordersResponse` group item.
847fn decode_order_block(
848    cursor: &mut SbeCursor<'_>,
849    block_length: u16,
850) -> Result<BinanceOrderResponse, SbeDecodeError> {
851    if block_length < ORDER_MIN_BLOCK_LENGTH {
852        return Err(SbeDecodeError::InvalidBlockLength {
853            expected: ORDER_MIN_BLOCK_LENGTH,
854            actual: block_length,
855        });
856    }
857
858    cursor.require(block_length as usize)?;
859
860    let price_exponent = cursor.read_i8()?;
861    let qty_exponent = cursor.read_i8()?;
862    let order_id = cursor.read_i64_le()?;
863    let order_list_id = cursor.read_optional_i64_le()?;
864    let price_mantissa = cursor.read_i64_le()?;
865    let orig_qty_mantissa = cursor.read_i64_le()?;
866    let executed_qty_mantissa = cursor.read_i64_le()?;
867    let cummulative_quote_qty_mantissa = cursor.read_i64_le()?;
868    let status = cursor.read_u8()?.into();
869    let time_in_force = cursor.read_u8()?.into();
870    let order_type = cursor.read_u8()?.into();
871    let side = cursor.read_u8()?.into();
872    let stop_price_mantissa = cursor.read_optional_i64_le()?;
873
874    cursor.advance(16)?; // Skip trailing_delta + trailing_time
875    let iceberg_qty_mantissa = cursor.read_optional_i64_le()?;
876    let time = cursor.read_i64_le()?;
877    let update_time = cursor.read_i64_le()?;
878    let is_working = BoolEnum::from(cursor.read_u8()?) == BoolEnum::True;
879    let working_time = cursor.read_optional_i64_le()?;
880    let orig_quote_order_qty_mantissa = cursor.read_i64_le()?;
881
882    cursor.advance(14)?; // Skip strategy_id to working_floor
883    let self_trade_prevention_mode = cursor.read_u8()?.into();
884
885    let expiry_reason = read_trailing_expiry_reason(
886        cursor,
887        block_length as usize,
888        ORDER_FIELDS_END,
889        ORDER_EXPIRY_REASON_OFFSET,
890    )?;
891
892    let symbol = cursor.read_var_string8()?;
893    let client_order_id = cursor.read_var_string8()?;
894
895    Ok(BinanceOrderResponse {
896        price_exponent,
897        qty_exponent,
898        order_id,
899        order_list_id,
900        price_mantissa,
901        orig_qty_mantissa,
902        executed_qty_mantissa,
903        cummulative_quote_qty_mantissa,
904        status,
905        time_in_force,
906        order_type,
907        side,
908        stop_price_mantissa,
909        iceberg_qty_mantissa,
910        time,
911        update_time,
912        is_working,
913        working_time,
914        orig_quote_order_qty_mantissa,
915        self_trade_prevention_mode,
916        client_order_id,
917        symbol,
918        expiry_reason,
919    })
920}
921
922/// Decode cancel open orders response.
923///
924/// Each item contains an embedded cancel-order or cancel-order-list SBE message.
925///
926/// # Errors
927///
928/// Returns an error if buffer is too short, schema mismatch, or decode error.
929#[allow(dead_code)]
930pub fn decode_cancel_open_orders(
931    buf: &[u8],
932) -> Result<Vec<BinanceCancelOpenOrdersResponse>, SbeDecodeError> {
933    let mut cursor = SbeCursor::new(buf);
934    let header = MessageHeader::decode_cursor(&mut cursor)?;
935    header.validate()?;
936
937    if header.template_id != CANCEL_OPEN_ORDERS_TEMPLATE_ID {
938        return Err(SbeDecodeError::UnknownTemplateId(header.template_id));
939    }
940
941    if header.block_length != 0 {
942        return Err(SbeDecodeError::InvalidBlockLength {
943            expected: 0,
944            actual: header.block_length,
945        });
946    }
947
948    let (block_length, count) = cursor.read_group_header()?;
949    if block_length != 0 {
950        return Err(SbeDecodeError::InvalidBlockLength {
951            expected: 0,
952            actual: block_length,
953        });
954    }
955
956    if count == 0 {
957        return Ok(Vec::new());
958    }
959
960    let mut responses = Vec::with_capacity(count as usize);
961
962    // Each group item has block_length=0, followed by u16 length + embedded SBE message
963    for _ in 0..count {
964        let response_len = cursor.read_u16_le()? as usize;
965        let embedded_bytes = cursor.read_bytes(response_len)?;
966        let response = decode_cancel_order_or_list(embedded_bytes)?;
967        responses.push(response);
968    }
969
970    Ok(responses)
971}
972
973/// Account response block length (from SBE codec).
974const ACCOUNT_BLOCK_LENGTH: usize = 64;
975
976/// Balance group item block length (from SBE codec).
977const BALANCE_BLOCK_LENGTH: u16 = 17;
978
979/// Decode account information response.
980///
981/// # Errors
982///
983/// Returns an error if buffer is too short, schema mismatch, or decode error.
984#[allow(dead_code)]
985pub fn decode_account(buf: &[u8]) -> Result<BinanceAccountInfo, SbeDecodeError> {
986    let mut cursor = SbeCursor::new(buf);
987    let header = MessageHeader::decode_cursor(&mut cursor)?;
988    header.validate()?;
989
990    if header.template_id != ACCOUNT_TEMPLATE_ID {
991        return Err(SbeDecodeError::UnknownTemplateId(header.template_id));
992    }
993
994    cursor.require(ACCOUNT_BLOCK_LENGTH)?;
995
996    let commission_exponent = cursor.read_i8()?;
997    let maker_commission_mantissa = cursor.read_i64_le()?;
998    let taker_commission_mantissa = cursor.read_i64_le()?;
999    let buyer_commission_mantissa = cursor.read_i64_le()?;
1000    let seller_commission_mantissa = cursor.read_i64_le()?;
1001    let can_trade = BoolEnum::from(cursor.read_u8()?) == BoolEnum::True;
1002    let can_withdraw = BoolEnum::from(cursor.read_u8()?) == BoolEnum::True;
1003    let can_deposit = BoolEnum::from(cursor.read_u8()?) == BoolEnum::True;
1004    cursor.advance(1)?; // Skip brokered
1005    let require_self_trade_prevention = BoolEnum::from(cursor.read_u8()?) == BoolEnum::True;
1006    let prevent_sor = BoolEnum::from(cursor.read_u8()?) == BoolEnum::True;
1007    let update_time = cursor.read_i64_le()?;
1008    let account_type_enum = AccountType::from(cursor.read_u8()?);
1009    cursor.advance(16)?; // Skip tradeGroupId + uid
1010
1011    let account_type = account_type_enum.to_string();
1012
1013    let (block_length, balance_count) = cursor.read_group_header()?;
1014
1015    if block_length != BALANCE_BLOCK_LENGTH {
1016        return Err(SbeDecodeError::InvalidBlockLength {
1017            expected: BALANCE_BLOCK_LENGTH,
1018            actual: block_length,
1019        });
1020    }
1021
1022    let mut balances = Vec::with_capacity(balance_count as usize);
1023
1024    for _ in 0..balance_count {
1025        cursor.require(block_length as usize)?;
1026
1027        let exponent = cursor.read_i8()?;
1028        let free_mantissa = cursor.read_i64_le()?;
1029        let locked_mantissa = cursor.read_i64_le()?;
1030
1031        let asset = cursor.read_var_string8()?;
1032
1033        balances.push(BinanceBalance {
1034            asset,
1035            free_mantissa,
1036            locked_mantissa,
1037            exponent,
1038        });
1039    }
1040
1041    Ok(BinanceAccountInfo {
1042        commission_exponent,
1043        maker_commission_mantissa,
1044        taker_commission_mantissa,
1045        buyer_commission_mantissa,
1046        seller_commission_mantissa,
1047        can_trade,
1048        can_withdraw,
1049        can_deposit,
1050        require_self_trade_prevention,
1051        prevent_sor,
1052        update_time,
1053        account_type,
1054        balances,
1055    })
1056}
1057
1058/// Account trade group item block length (from SBE codec).
1059const ACCOUNT_TRADE_BLOCK_LENGTH: u16 = 70;
1060
1061/// Decode account trades response.
1062///
1063/// # Errors
1064///
1065/// Returns an error if buffer is too short, schema mismatch, or decode error.
1066#[allow(dead_code)]
1067pub fn decode_account_trades(buf: &[u8]) -> Result<Vec<BinanceAccountTrade>, SbeDecodeError> {
1068    let mut cursor = SbeCursor::new(buf);
1069    let header = MessageHeader::decode_cursor(&mut cursor)?;
1070    header.validate()?;
1071
1072    if header.template_id != ACCOUNT_TRADES_TEMPLATE_ID {
1073        return Err(SbeDecodeError::UnknownTemplateId(header.template_id));
1074    }
1075
1076    let (block_length, trade_count) = cursor.read_group_header()?;
1077
1078    if block_length != ACCOUNT_TRADE_BLOCK_LENGTH {
1079        return Err(SbeDecodeError::InvalidBlockLength {
1080            expected: ACCOUNT_TRADE_BLOCK_LENGTH,
1081            actual: block_length,
1082        });
1083    }
1084
1085    let mut trades = Vec::with_capacity(trade_count as usize);
1086
1087    for _ in 0..trade_count {
1088        cursor.require(block_length as usize)?;
1089
1090        let price_exponent = cursor.read_i8()?;
1091        let qty_exponent = cursor.read_i8()?;
1092        let commission_exponent = cursor.read_i8()?;
1093        let id = cursor.read_i64_le()?;
1094        let order_id = cursor.read_i64_le()?;
1095        let order_list_id = cursor.read_optional_i64_le()?;
1096        let price_mantissa = cursor.read_i64_le()?;
1097        let qty_mantissa = cursor.read_i64_le()?;
1098        let quote_qty_mantissa = cursor.read_i64_le()?;
1099        let commission_mantissa = cursor.read_i64_le()?;
1100        let time = cursor.read_i64_le()?;
1101        let is_buyer = BoolEnum::from(cursor.read_u8()?) == BoolEnum::True;
1102        let is_maker = BoolEnum::from(cursor.read_u8()?) == BoolEnum::True;
1103        let is_best_match = BoolEnum::from(cursor.read_u8()?) == BoolEnum::True;
1104
1105        let symbol = cursor.read_var_string8()?;
1106        let commission_asset = cursor.read_var_string8()?;
1107
1108        trades.push(BinanceAccountTrade {
1109            price_exponent,
1110            qty_exponent,
1111            commission_exponent,
1112            id,
1113            order_id,
1114            order_list_id,
1115            price_mantissa,
1116            qty_mantissa,
1117            quote_qty_mantissa,
1118            commission_mantissa,
1119            time,
1120            is_buyer,
1121            is_maker,
1122            is_best_match,
1123            symbol,
1124            commission_asset,
1125        });
1126    }
1127
1128    Ok(trades)
1129}
1130
1131/// Fills group item block length (from SBE codec).
1132const FILLS_BLOCK_LENGTH: u16 = 42;
1133
1134/// Decode order fills using cursor.
1135fn decode_fills_cursor(
1136    cursor: &mut SbeCursor<'_>,
1137) -> Result<Vec<BinanceOrderFill>, SbeDecodeError> {
1138    let (block_length, count) = cursor.read_group_header()?;
1139
1140    if block_length != FILLS_BLOCK_LENGTH {
1141        return Err(SbeDecodeError::InvalidBlockLength {
1142            expected: FILLS_BLOCK_LENGTH,
1143            actual: block_length,
1144        });
1145    }
1146
1147    let mut fills = Vec::with_capacity(count as usize);
1148
1149    for _ in 0..count {
1150        cursor.require(block_length as usize)?;
1151
1152        let commission_exponent = cursor.read_i8()?;
1153        cursor.advance(1)?; // Skip matchType
1154        let price_mantissa = cursor.read_i64_le()?;
1155        let qty_mantissa = cursor.read_i64_le()?;
1156        let commission_mantissa = cursor.read_i64_le()?;
1157        let trade_id = cursor.read_optional_i64_le()?;
1158        cursor.advance(8)?; // Skip allocId
1159
1160        let commission_asset = cursor.read_var_string8()?;
1161
1162        fills.push(BinanceOrderFill {
1163            price_mantissa,
1164            qty_mantissa,
1165            commission_mantissa,
1166            commission_exponent,
1167            commission_asset,
1168            trade_id,
1169        });
1170    }
1171
1172    Ok(fills)
1173}
1174
1175/// Symbols group block length (from SBE codec).
1176const SYMBOL_BLOCK_LENGTH: usize = 19;
1177
1178/// Decode exchange info response.
1179///
1180/// ExchangeInfo response contains rate limits, exchange filters, symbols, and SOR info.
1181/// We only decode the symbols array which contains instrument definitions.
1182///
1183/// # Errors
1184///
1185/// Returns an error if buffer is too short, schema mismatch, or template ID mismatch.
1186///
1187/// # Panics
1188///
1189/// Panics if filter byte slices cannot be converted to fixed-size arrays, which should not occur if
1190/// the SBE data is well-formed.
1191pub fn decode_exchange_info(buf: &[u8]) -> Result<BinanceExchangeInfoSbe, SbeDecodeError> {
1192    let mut cursor = SbeCursor::new(buf);
1193    let header = MessageHeader::decode_cursor(&mut cursor)?;
1194    header.validate()?;
1195
1196    if header.template_id != EXCHANGE_INFO_TEMPLATE_ID {
1197        return Err(SbeDecodeError::UnknownTemplateId(header.template_id));
1198    }
1199
1200    // Skip rate_limits group
1201    let (rate_limits_block_len, rate_limits_count) = cursor.read_group_header()?;
1202    cursor.advance(rate_limits_block_len as usize * rate_limits_count as usize)?;
1203
1204    // Skip exchange_filters group
1205    let (_exchange_filters_block_len, exchange_filters_count) = cursor.read_group_header()?;
1206    for _ in 0..exchange_filters_count {
1207        // Each filter is a varString8
1208        cursor.read_var_string8()?;
1209    }
1210
1211    // Decode symbols group
1212    let (symbols_block_len, symbols_count) = cursor.read_group_header()?;
1213
1214    if symbols_block_len != SYMBOL_BLOCK_LENGTH as u16 {
1215        return Err(SbeDecodeError::InvalidBlockLength {
1216            expected: SYMBOL_BLOCK_LENGTH as u16,
1217            actual: symbols_block_len,
1218        });
1219    }
1220
1221    let mut symbols = Vec::with_capacity(symbols_count as usize);
1222
1223    for _ in 0..symbols_count {
1224        cursor.require(SYMBOL_BLOCK_LENGTH)?;
1225
1226        // Fixed fields (19 bytes)
1227        let status = cursor.read_u8()?;
1228        let base_asset_precision = cursor.read_u8()?;
1229        let quote_asset_precision = cursor.read_u8()?;
1230        let _base_commission_precision = cursor.read_u8()?;
1231        let _quote_commission_precision = cursor.read_u8()?;
1232        let order_types = cursor.read_u16_le()?;
1233        let iceberg_allowed = cursor.read_u8()? == BoolEnum::True as u8;
1234        let oco_allowed = cursor.read_u8()? == BoolEnum::True as u8;
1235        let oto_allowed = cursor.read_u8()? == BoolEnum::True as u8;
1236        let quote_order_qty_market_allowed = cursor.read_u8()? == BoolEnum::True as u8;
1237        let allow_trailing_stop = cursor.read_u8()? == BoolEnum::True as u8;
1238        let cancel_replace_allowed = cursor.read_u8()? == BoolEnum::True as u8;
1239        let amend_allowed = cursor.read_u8()? == BoolEnum::True as u8;
1240        let is_spot_trading_allowed = cursor.read_u8()? == BoolEnum::True as u8;
1241        let is_margin_trading_allowed = cursor.read_u8()? == BoolEnum::True as u8;
1242        let _default_self_trade_prevention_mode = cursor.read_u8()?;
1243        let _allowed_self_trade_prevention_modes = cursor.read_u8()?;
1244        let _peg_instructions_allowed = cursor.read_u8()?;
1245
1246        let (_filters_block_len, filters_count) = cursor.read_group_header()?;
1247        let mut filters = BinanceSymbolFiltersSbe::default();
1248
1249        for _ in 0..filters_count {
1250            let filter_bytes = cursor.read_var_bytes8()?;
1251
1252            // Filters can have header (8 bytes) or be raw body only,
1253            // detect format by checking if bytes [2..4] contain a valid template_id
1254            let (template_id, offset) = if filter_bytes.len() >= HEADER_LENGTH + 2 {
1255                let potential_template = u16::from_le_bytes([filter_bytes[2], filter_bytes[3]]);
1256                if potential_template == PRICE_FILTER_TEMPLATE_ID
1257                    || potential_template == LOT_SIZE_FILTER_TEMPLATE_ID
1258                    || potential_template == MIN_NOTIONAL_FILTER_TEMPLATE_ID
1259                    || potential_template == NOTIONAL_FILTER_TEMPLATE_ID
1260                {
1261                    (potential_template, HEADER_LENGTH)
1262                } else {
1263                    let raw_template = u16::from_le_bytes([filter_bytes[0], filter_bytes[1]]);
1264                    (raw_template, 2)
1265                }
1266            } else if filter_bytes.len() >= 2 {
1267                let raw_template = u16::from_le_bytes([filter_bytes[0], filter_bytes[1]]);
1268                (raw_template, 2)
1269            } else {
1270                continue;
1271            };
1272
1273            // Filter body layout: exponent(1) + min(8) + max(8) + size(8) = 25 bytes
1274            match template_id {
1275                MIN_NOTIONAL_FILTER_TEMPLATE_ID | NOTIONAL_FILTER_TEMPLATE_ID => {
1276                    let mut filter = SbeCursor::new(&filter_bytes[offset..]);
1277                    let exponent = filter.read_i8()?;
1278                    let min = decode_notional_amount(&mut filter, exponent)?;
1279                    let apply_min_to_market = decode_notional_market_flag(&mut filter)?;
1280                    let (max, apply_max_to_market) = if template_id == NOTIONAL_FILTER_TEMPLATE_ID {
1281                        (
1282                            Some(decode_notional_amount(&mut filter, exponent)?),
1283                            decode_notional_market_flag(&mut filter)?,
1284                        )
1285                    } else {
1286                        (None, false)
1287                    };
1288
1289                    let avg_price_mins = u32::try_from(filter.read_i32_le()?).map_err(|_| {
1290                        SbeDecodeError::InvalidValue {
1291                            field: "avgPriceMins",
1292                        }
1293                    })?;
1294
1295                    filters.notional_filters.push(BinanceNotionalFilter {
1296                        min,
1297                        max,
1298                        apply_min_to_market,
1299                        apply_max_to_market,
1300                        avg_price_mins,
1301                    });
1302                }
1303                PRICE_FILTER_TEMPLATE_ID if filter_bytes.len() >= offset + 25 => {
1304                    let price_exp = filter_bytes[offset] as i8;
1305                    let min_price = i64::from_le_bytes(
1306                        filter_bytes[offset + 1..offset + 9].try_into().unwrap(),
1307                    );
1308                    let max_price = i64::from_le_bytes(
1309                        filter_bytes[offset + 9..offset + 17].try_into().unwrap(),
1310                    );
1311                    let tick_size = i64::from_le_bytes(
1312                        filter_bytes[offset + 17..offset + 25].try_into().unwrap(),
1313                    );
1314                    filters.price_filter = Some(BinancePriceFilterSbe {
1315                        price_exponent: price_exp,
1316                        min_price,
1317                        max_price,
1318                        tick_size,
1319                    });
1320                }
1321                LOT_SIZE_FILTER_TEMPLATE_ID if filter_bytes.len() >= offset + 25 => {
1322                    let qty_exp = filter_bytes[offset] as i8;
1323                    let min_qty = i64::from_le_bytes(
1324                        filter_bytes[offset + 1..offset + 9].try_into().unwrap(),
1325                    );
1326                    let max_qty = i64::from_le_bytes(
1327                        filter_bytes[offset + 9..offset + 17].try_into().unwrap(),
1328                    );
1329                    let step_size = i64::from_le_bytes(
1330                        filter_bytes[offset + 17..offset + 25].try_into().unwrap(),
1331                    );
1332                    filters.lot_size_filter = Some(BinanceLotSizeFilterSbe {
1333                        qty_exponent: qty_exp,
1334                        min_qty,
1335                        max_qty,
1336                        step_size,
1337                    });
1338                }
1339                _ => {}
1340            }
1341        }
1342
1343        // Permission sets nested group
1344        let (_perm_sets_block_len, perm_sets_count) = cursor.read_group_header()?;
1345        let mut permissions = Vec::with_capacity(perm_sets_count as usize);
1346        for _ in 0..perm_sets_count {
1347            // Permissions nested group
1348            let (_perms_block_len, perms_count) = cursor.read_group_header()?;
1349            let mut perm_set = Vec::with_capacity(perms_count as usize);
1350            for _ in 0..perms_count {
1351                let perm = cursor.read_var_string8()?;
1352                perm_set.push(perm);
1353            }
1354            permissions.push(perm_set);
1355        }
1356
1357        // Variable-length strings
1358        let symbol = cursor.read_var_string8()?;
1359        let base_asset = cursor.read_var_string8()?;
1360        let quote_asset = cursor.read_var_string8()?;
1361
1362        symbols.push(BinanceSymbolSbe {
1363            symbol,
1364            base_asset,
1365            quote_asset,
1366            base_asset_precision,
1367            quote_asset_precision,
1368            status,
1369            order_types,
1370            iceberg_allowed,
1371            oco_allowed,
1372            oto_allowed,
1373            quote_order_qty_market_allowed,
1374            allow_trailing_stop,
1375            cancel_replace_allowed,
1376            amend_allowed,
1377            is_spot_trading_allowed,
1378            is_margin_trading_allowed,
1379            filters,
1380            permissions,
1381        });
1382    }
1383
1384    // Skip SOR group (we don't need it)
1385
1386    Ok(BinanceExchangeInfoSbe { symbols })
1387}
1388
1389fn decode_notional_amount(
1390    cursor: &mut SbeCursor<'_>,
1391    exponent: i8,
1392) -> Result<Decimal, SbeDecodeError> {
1393    let mantissa = cursor.read_i64_le()?;
1394    if exponent == i8::MIN || mantissa < 0 {
1395        return Err(SbeDecodeError::InvalidValue { field: "notional" });
1396    }
1397    Decimal::from_scientific(&format!("{mantissa}e{exponent}"))
1398        .map_err(|_| SbeDecodeError::InvalidValue { field: "notional" })
1399}
1400
1401fn decode_notional_market_flag(cursor: &mut SbeCursor<'_>) -> Result<bool, SbeDecodeError> {
1402    match cursor.read_u8()? {
1403        value if value == BoolEnum::False as u8 => Ok(false),
1404        value if value == BoolEnum::True as u8 => Ok(true),
1405        _ => Err(SbeDecodeError::InvalidValue {
1406            field: "notional market flag",
1407        }),
1408    }
1409}
1410
1411#[cfg(test)]
1412mod tests {
1413    use rstest::rstest;
1414
1415    use super::*;
1416    use crate::spot::sbe::spot::{
1417        SBE_SCHEMA_VERSION, WriteBuf,
1418        cancel_order_response_codec::CancelOrderResponseEncoder,
1419        expiry_reason::ExpiryReason,
1420        floor::Floor,
1421        match_type::MatchType,
1422        new_order_full_response_codec::{
1423            NewOrderFullResponseEncoder,
1424            encoder::{FillsEncoder, PreventedMatchesEncoder},
1425        },
1426        order_capacity::OrderCapacity,
1427        order_response_codec::OrderResponseEncoder,
1428        order_side::OrderSide,
1429        order_status::OrderStatus,
1430        order_type::OrderType,
1431        orders_response_codec::{OrdersResponseEncoder, encoder::OrdersEncoder},
1432        self_trade_prevention_mode::SelfTradePreventionMode,
1433        time_in_force::TimeInForce,
1434    };
1435
1436    fn create_header(block_length: u16, template_id: u16, schema_id: u16, version: u16) -> [u8; 8] {
1437        let mut buf = [0u8; 8];
1438        buf[0..2].copy_from_slice(&block_length.to_le_bytes());
1439        buf[2..4].copy_from_slice(&template_id.to_le_bytes());
1440        buf[4..6].copy_from_slice(&schema_id.to_le_bytes());
1441        buf[6..8].copy_from_slice(&version.to_le_bytes());
1442        buf
1443    }
1444
1445    #[rstest]
1446    fn test_decode_ping_valid() {
1447        // Ping: block_length=0, template_id=101, schema_id=3, version=1
1448        let buf = create_header(0, PING_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
1449        decode_ping(&buf).unwrap();
1450    }
1451
1452    #[rstest]
1453    fn test_decode_ping_buffer_too_short() {
1454        let buf = [0u8; 4];
1455        let err = decode_ping(&buf).unwrap_err();
1456        assert!(matches!(err, SbeDecodeError::BufferTooShort { .. }));
1457    }
1458
1459    #[rstest]
1460    fn test_decode_ping_schema_mismatch() {
1461        let buf = create_header(0, PING_TEMPLATE_ID, 99, SBE_SCHEMA_VERSION);
1462        let err = decode_ping(&buf).unwrap_err();
1463        assert!(matches!(err, SbeDecodeError::SchemaMismatch { .. }));
1464    }
1465
1466    #[rstest]
1467    fn test_decode_ping_wrong_template() {
1468        let buf = create_header(0, 999, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
1469        let err = decode_ping(&buf).unwrap_err();
1470        assert!(matches!(err, SbeDecodeError::UnknownTemplateId(999)));
1471    }
1472
1473    #[rstest]
1474    fn test_decode_server_time_valid() {
1475        // ServerTime: block_length=8, template_id=102, schema_id=3, version=1
1476        let header = create_header(
1477            8,
1478            SERVER_TIME_TEMPLATE_ID,
1479            SBE_SCHEMA_ID,
1480            SBE_SCHEMA_VERSION,
1481        );
1482        let timestamp: i64 = 1734300000000; // Example timestamp
1483
1484        let mut buf = Vec::with_capacity(16);
1485        buf.extend_from_slice(&header);
1486        buf.extend_from_slice(&timestamp.to_le_bytes());
1487
1488        let result = decode_server_time(&buf).unwrap();
1489        assert_eq!(result, timestamp);
1490    }
1491
1492    #[rstest]
1493    fn test_decode_server_time_buffer_too_short() {
1494        // Header only, missing body
1495        let buf = create_header(
1496            8,
1497            SERVER_TIME_TEMPLATE_ID,
1498            SBE_SCHEMA_ID,
1499            SBE_SCHEMA_VERSION,
1500        );
1501        let err = decode_server_time(&buf).unwrap_err();
1502        assert!(matches!(err, SbeDecodeError::BufferTooShort { .. }));
1503    }
1504
1505    #[rstest]
1506    fn test_decode_server_time_wrong_template() {
1507        let header = create_header(8, PING_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
1508        let mut buf = Vec::with_capacity(16);
1509        buf.extend_from_slice(&header);
1510        buf.extend_from_slice(&0i64.to_le_bytes());
1511
1512        let err = decode_server_time(&buf).unwrap_err();
1513        assert!(matches!(err, SbeDecodeError::UnknownTemplateId(101)));
1514    }
1515
1516    // Any version within the schema ID must decode. During a rollout one client sees
1517    // both the older version (un-migrated server) and the newer version; future
1518    // additive bumps must keep decoding too.
1519    #[rstest]
1520    #[case(SBE_SCHEMA_VERSION - 1)]
1521    #[case(SBE_SCHEMA_VERSION)]
1522    #[case(SBE_SCHEMA_VERSION + 1)]
1523    #[case(99)]
1524    fn test_decode_server_time_accepts_any_version(#[case] version: u16) {
1525        let header = create_header(8, SERVER_TIME_TEMPLATE_ID, SBE_SCHEMA_ID, version);
1526        let mut buf = Vec::with_capacity(16);
1527        buf.extend_from_slice(&header);
1528        buf.extend_from_slice(&1_700_000_000_000i64.to_le_bytes());
1529
1530        let result = decode_server_time(&buf).unwrap();
1531        assert_eq!(result, 1_700_000_000_000);
1532    }
1533
1534    fn create_group_header(block_length: u16, count: u32) -> [u8; 6] {
1535        let mut buf = [0u8; 6];
1536        buf[0..2].copy_from_slice(&block_length.to_le_bytes());
1537        buf[2..6].copy_from_slice(&count.to_le_bytes());
1538        buf
1539    }
1540
1541    #[rstest]
1542    #[case::bids(DEPTH_TEMPLATE_ID, 16, false)]
1543    #[case::asks(DEPTH_TEMPLATE_ID, 16, true)]
1544    #[case::trades(TRADES_TEMPLATE_ID, 42, false)]
1545    #[case::agg_trades(AGG_TRADES_TEMPLATE_ID, 50, false)]
1546    fn test_market_data_rejects_undersized_groups(
1547        #[case] template: u16,
1548        #[case] minimum: u16,
1549        #[case] asks: bool,
1550        #[values(0, 1, 10_000)] count: u32,
1551    ) {
1552        let fixed_width = if template == DEPTH_TEMPLATE_ID { 10 } else { 2 };
1553
1554        for width in 0..minimum {
1555            let mut buf =
1556                create_header(fixed_width, template, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION).to_vec();
1557            buf.resize(HEADER_LENGTH + usize::from(fixed_width), 0);
1558            if asks {
1559                buf.extend_from_slice(&create_group_header(minimum, 1));
1560                buf.extend_from_slice(&[0; 16]);
1561            }
1562
1563            buf.extend_from_slice(&create_group_header(width, count));
1564            buf.extend_from_slice(&[0; 200]);
1565            let result = match template {
1566                DEPTH_TEMPLATE_ID => decode_depth(&buf).map(|_| ()),
1567                TRADES_TEMPLATE_ID => decode_trades(&buf).map(|_| ()),
1568                AGG_TRADES_TEMPLATE_ID => decode_agg_trades(&buf).map(|_| ()),
1569                _ => unreachable!(),
1570            };
1571
1572            assert_eq!(
1573                result,
1574                Err(SbeDecodeError::InvalidBlockLength {
1575                    expected: minimum,
1576                    actual: width,
1577                })
1578            );
1579        }
1580    }
1581
1582    #[rstest]
1583    #[case::depth(DEPTH_TEMPLATE_ID, 16)]
1584    #[case::trades(TRADES_TEMPLATE_ID, 42)]
1585    #[case::agg_trades(AGG_TRADES_TEMPLATE_ID, 50)]
1586    fn test_market_data_group_extensions(#[case] template: u16, #[case] minimum: u16) {
1587        let fixed_width = if template == DEPTH_TEMPLATE_ID { 10 } else { 2 };
1588        let mut buf =
1589            create_header(fixed_width, template, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION).to_vec();
1590        if template == DEPTH_TEMPLATE_ID {
1591            buf.extend_from_slice(&999i64.to_le_bytes());
1592        }
1593
1594        buf.extend_from_slice(&[(-2i8) as u8, (-8i8) as u8]);
1595
1596        let group_count = if template == DEPTH_TEMPLATE_ID { 2 } else { 1 };
1597        for group in 0..group_count {
1598            buf.extend_from_slice(&create_group_header(minimum + 3, 2));
1599            for entry in 0..2 {
1600                for field in 1..=minimum / 8 {
1601                    let value = i64::from(group * 200 + entry * 100 + field + 100);
1602                    buf.extend_from_slice(&value.to_le_bytes());
1603                }
1604
1605                if template != DEPTH_TEMPLATE_ID {
1606                    buf.extend_from_slice(&[1, 0]);
1607                }
1608
1609                buf.extend_from_slice(&[0xFF; 3]);
1610            }
1611        }
1612
1613        match template {
1614            DEPTH_TEMPLATE_ID => assert_eq!(
1615                decode_depth(&buf).unwrap(),
1616                BinanceDepth {
1617                    last_update_id: 999,
1618                    price_exponent: -2,
1619                    qty_exponent: -8,
1620                    bids: vec![
1621                        BinancePriceLevel {
1622                            price_mantissa: 101,
1623                            qty_mantissa: 102
1624                        },
1625                        BinancePriceLevel {
1626                            price_mantissa: 201,
1627                            qty_mantissa: 202
1628                        }
1629                    ],
1630                    asks: vec![
1631                        BinancePriceLevel {
1632                            price_mantissa: 301,
1633                            qty_mantissa: 302
1634                        },
1635                        BinancePriceLevel {
1636                            price_mantissa: 401,
1637                            qty_mantissa: 402
1638                        }
1639                    ],
1640                }
1641            ),
1642            TRADES_TEMPLATE_ID => assert_eq!(
1643                decode_trades(&buf).unwrap(),
1644                BinanceTrades {
1645                    price_exponent: -2,
1646                    qty_exponent: -8,
1647                    trades: vec![
1648                        BinanceTrade {
1649                            id: 101,
1650                            price_mantissa: 102,
1651                            qty_mantissa: 103,
1652                            quote_qty_mantissa: 104,
1653                            time: 105,
1654                            is_buyer_maker: true,
1655                            is_best_match: false
1656                        },
1657                        BinanceTrade {
1658                            id: 201,
1659                            price_mantissa: 202,
1660                            qty_mantissa: 203,
1661                            quote_qty_mantissa: 204,
1662                            time: 205,
1663                            is_buyer_maker: true,
1664                            is_best_match: false
1665                        }
1666                    ],
1667                }
1668            ),
1669            AGG_TRADES_TEMPLATE_ID => assert_eq!(
1670                decode_agg_trades(&buf).unwrap(),
1671                BinanceAggTrades {
1672                    price_exponent: -2,
1673                    qty_exponent: -8,
1674                    trades: vec![
1675                        BinanceAggTrade {
1676                            id: 101,
1677                            price_mantissa: 102,
1678                            qty_mantissa: 103,
1679                            first_trade_id: 104,
1680                            last_trade_id: 105,
1681                            time: 106,
1682                            is_buyer_maker: true,
1683                            is_best_match: false
1684                        },
1685                        BinanceAggTrade {
1686                            id: 201,
1687                            price_mantissa: 202,
1688                            qty_mantissa: 203,
1689                            first_trade_id: 204,
1690                            last_trade_id: 205,
1691                            time: 206,
1692                            is_buyer_maker: true,
1693                            is_best_match: false
1694                        }
1695                    ],
1696                }
1697            ),
1698            _ => unreachable!(),
1699        }
1700    }
1701
1702    #[rstest]
1703    fn test_decode_depth_valid() {
1704        // Depth: block_length=10, template_id=200
1705        let header = create_header(10, DEPTH_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
1706
1707        let mut buf = Vec::new();
1708        buf.extend_from_slice(&header);
1709
1710        // Block: last_update_id (8) + price_exponent (1) + qty_exponent (1)
1711        let last_update_id: i64 = 123456789;
1712        let price_exponent: i8 = -8;
1713        let qty_exponent: i8 = -8;
1714        buf.extend_from_slice(&last_update_id.to_le_bytes());
1715        buf.push(price_exponent as u8);
1716        buf.push(qty_exponent as u8);
1717
1718        // Bids group: 2 levels
1719        buf.extend_from_slice(&create_group_header(16, 2));
1720        // Bid 1: price=100000000000, qty=50000000
1721        buf.extend_from_slice(&100_000_000_000i64.to_le_bytes());
1722        buf.extend_from_slice(&50_000_000i64.to_le_bytes());
1723        // Bid 2: price=99900000000, qty=30000000
1724        buf.extend_from_slice(&99_900_000_000i64.to_le_bytes());
1725        buf.extend_from_slice(&30_000_000i64.to_le_bytes());
1726
1727        // Asks group: 1 level
1728        buf.extend_from_slice(&create_group_header(16, 1));
1729        // Ask 1: price=100100000000, qty=25000000
1730        buf.extend_from_slice(&100_100_000_000i64.to_le_bytes());
1731        buf.extend_from_slice(&25_000_000i64.to_le_bytes());
1732
1733        let depth = decode_depth(&buf).unwrap();
1734
1735        assert_eq!(depth.last_update_id, 123456789);
1736        assert_eq!(depth.price_exponent, -8);
1737        assert_eq!(depth.qty_exponent, -8);
1738        assert_eq!(depth.bids.len(), 2);
1739        assert_eq!(depth.asks.len(), 1);
1740        assert_eq!(depth.bids[0].price_mantissa, 100_000_000_000);
1741        assert_eq!(depth.bids[0].qty_mantissa, 50_000_000);
1742        assert_eq!(depth.asks[0].price_mantissa, 100_100_000_000);
1743    }
1744
1745    #[rstest]
1746    fn test_decode_depth_empty_book() {
1747        let header = create_header(10, DEPTH_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
1748
1749        let mut buf = Vec::new();
1750        buf.extend_from_slice(&header);
1751        buf.extend_from_slice(&0i64.to_le_bytes()); // last_update_id
1752        buf.push(0); // price_exponent
1753        buf.push(0); // qty_exponent
1754
1755        // Empty bids
1756        buf.extend_from_slice(&create_group_header(16, 0));
1757        // Empty asks
1758        buf.extend_from_slice(&create_group_header(16, 0));
1759
1760        let depth = decode_depth(&buf).unwrap();
1761
1762        assert!(depth.bids.is_empty());
1763        assert!(depth.asks.is_empty());
1764    }
1765
1766    #[rstest]
1767    fn test_decode_trades_valid() {
1768        // Trades: block_length=2, template_id=201
1769        let header = create_header(2, TRADES_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
1770
1771        let mut buf = Vec::new();
1772        buf.extend_from_slice(&header);
1773
1774        // Block: price_exponent (1) + qty_exponent (1)
1775        let price_exponent: i8 = -8;
1776        let qty_exponent: i8 = -8;
1777        buf.push(price_exponent as u8);
1778        buf.push(qty_exponent as u8);
1779
1780        // Trades group: 1 trade (42 bytes each)
1781        buf.extend_from_slice(&create_group_header(42, 1));
1782
1783        // Trade: id(8) + price(8) + qty(8) + quoteQty(8) + time(8) + isBuyerMaker(1) + isBestMatch(1)
1784        let trade_id: i64 = 999;
1785        let price: i64 = 100_000_000_000;
1786        let qty: i64 = 10_000_000;
1787        let quote_qty: i64 = 1_000_000_000_000;
1788        let time: i64 = 1734300000000;
1789        let is_buyer_maker: u8 = 1; // true
1790        let is_best_match: u8 = 1; // true
1791
1792        buf.extend_from_slice(&trade_id.to_le_bytes());
1793        buf.extend_from_slice(&price.to_le_bytes());
1794        buf.extend_from_slice(&qty.to_le_bytes());
1795        buf.extend_from_slice(&quote_qty.to_le_bytes());
1796        buf.extend_from_slice(&time.to_le_bytes());
1797        buf.push(is_buyer_maker);
1798        buf.push(is_best_match);
1799
1800        let trades = decode_trades(&buf).unwrap();
1801
1802        assert_eq!(trades.price_exponent, -8);
1803        assert_eq!(trades.qty_exponent, -8);
1804        assert_eq!(trades.trades.len(), 1);
1805        assert_eq!(trades.trades[0].id, 999);
1806        assert_eq!(trades.trades[0].price_mantissa, 100_000_000_000);
1807        assert!(trades.trades[0].is_buyer_maker);
1808        assert!(trades.trades[0].is_best_match);
1809    }
1810
1811    #[rstest]
1812    fn test_decode_trades_empty() {
1813        let header = create_header(2, TRADES_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
1814
1815        let mut buf = Vec::new();
1816        buf.extend_from_slice(&header);
1817        buf.push(0); // price_exponent
1818        buf.push(0); // qty_exponent
1819
1820        // Empty trades group
1821        buf.extend_from_slice(&create_group_header(42, 0));
1822
1823        let trades = decode_trades(&buf).unwrap();
1824
1825        assert!(trades.trades.is_empty());
1826    }
1827
1828    #[rstest]
1829    fn test_decode_agg_trades_preserves_all_fields() {
1830        let header = create_header(2, AGG_TRADES_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
1831        let mut buf = Vec::new();
1832        buf.extend_from_slice(&header);
1833        buf.push((-7_i8) as u8);
1834        buf.push((-5_i8) as u8);
1835        buf.extend_from_slice(&create_group_header(50, 1));
1836        buf.extend_from_slice(&101_i64.to_le_bytes());
1837        buf.extend_from_slice(&123_456_789_i64.to_le_bytes());
1838        buf.extend_from_slice(&765_432_i64.to_le_bytes());
1839        buf.extend_from_slice(&201_i64.to_le_bytes());
1840        buf.extend_from_slice(&207_i64.to_le_bytes());
1841        buf.extend_from_slice(&1_700_000_000_123_i64.to_le_bytes());
1842        buf.push(1);
1843        buf.push(0);
1844
1845        let trades = decode_agg_trades(&buf).unwrap();
1846
1847        assert_eq!(trades.price_exponent, -7);
1848        assert_eq!(trades.qty_exponent, -5);
1849        assert_eq!(trades.trades.len(), 1);
1850        assert_eq!(trades.trades[0].id, 101);
1851        assert_eq!(trades.trades[0].price_mantissa, 123_456_789);
1852        assert_eq!(trades.trades[0].qty_mantissa, 765_432);
1853        assert_eq!(trades.trades[0].first_trade_id, 201);
1854        assert_eq!(trades.trades[0].last_trade_id, 207);
1855        assert_eq!(trades.trades[0].time, 1_700_000_000_123);
1856        assert!(trades.trades[0].is_buyer_maker);
1857        assert!(!trades.trades[0].is_best_match);
1858    }
1859
1860    #[rstest]
1861    fn test_decode_agg_trades_rejects_wrong_template() {
1862        let header = create_header(2, PING_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
1863        let mut buf = Vec::new();
1864        buf.extend_from_slice(&header);
1865        buf.extend_from_slice(&[0_u8; 2]);
1866
1867        let error = decode_agg_trades(&buf).unwrap_err();
1868
1869        assert!(matches!(error, SbeDecodeError::UnknownTemplateId(101)));
1870    }
1871
1872    #[rstest]
1873    fn test_decode_depth_wrong_template() {
1874        let header = create_header(10, PING_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
1875
1876        let mut buf = Vec::new();
1877        buf.extend_from_slice(&header);
1878        buf.extend_from_slice(&[0u8; 10]); // dummy block
1879
1880        let err = decode_depth(&buf).unwrap_err();
1881        assert!(matches!(err, SbeDecodeError::UnknownTemplateId(101)));
1882    }
1883
1884    #[rstest]
1885    fn test_decode_trades_wrong_template() {
1886        let header = create_header(2, PING_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
1887
1888        let mut buf = Vec::new();
1889        buf.extend_from_slice(&header);
1890        buf.extend_from_slice(&[0u8; 2]); // dummy block
1891
1892        let err = decode_trades(&buf).unwrap_err();
1893        assert!(matches!(err, SbeDecodeError::UnknownTemplateId(101)));
1894    }
1895
1896    fn write_var_string(buf: &mut Vec<u8>, s: &str) {
1897        buf.push(s.len() as u8);
1898        buf.extend_from_slice(s.as_bytes());
1899    }
1900
1901    fn resize_fixed_block(buf: &mut Vec<u8>, block_length: usize) {
1902        let current = usize::from(u16::from_le_bytes([buf[0], buf[1]]));
1903        let block_end = HEADER_LENGTH + current;
1904        let new_end = HEADER_LENGTH + block_length;
1905
1906        if new_end < block_end {
1907            buf.drain(new_end..block_end);
1908        } else {
1909            buf.splice(block_end..block_end, vec![0u8; new_end - block_end]);
1910        }
1911
1912        buf[0..2].copy_from_slice(&(block_length as u16).to_le_bytes());
1913    }
1914
1915    fn build_order_response_buffer(expiry_reason: ExpiryReason) -> Vec<u8> {
1916        let mut bytes = vec![0u8; 256];
1917        let enc = OrderResponseEncoder::default().wrap(WriteBuf::new(&mut bytes), HEADER_LENGTH);
1918        let mut header = enc.header(0);
1919        let mut enc = header.parent().unwrap();
1920        enc.price_exponent(-2);
1921        enc.qty_exponent(-4);
1922        enc.order_id(12345);
1923        enc.order_list_id(99);
1924        enc.price(12_345);
1925        enc.orig_qty(25_000);
1926        enc.executed_qty(10_000);
1927        enc.cummulative_quote_qty(123_450_000);
1928        enc.status(OrderStatus::PartiallyFilled);
1929        enc.time_in_force(TimeInForce::Gtc);
1930        enc.order_type(OrderType::StopLossLimit);
1931        enc.side(OrderSide::Sell);
1932        enc.stop_price(12_000);
1933        enc.trailing_delta(100);
1934        enc.trailing_time(1_700_000_000_000_100);
1935        enc.iceberg_qty(5_000);
1936        enc.time(1_700_000_000_000_000);
1937        enc.update_time(1_700_000_000_000_200);
1938        enc.is_working(BoolEnum::True);
1939        enc.working_time(1_700_000_000_000_300);
1940        enc.orig_quote_order_qty(7_000);
1941        enc.strategy_id(42);
1942        enc.strategy_type(7);
1943        enc.order_capacity(OrderCapacity::Principal);
1944        enc.working_floor(Floor::Sor);
1945        enc.self_trade_prevention_mode(SelfTradePreventionMode::ExpireMaker);
1946        enc.prevented_match_id(77);
1947        enc.prevented_quantity(3);
1948        enc.used_sor(BoolEnum::True);
1949        enc.expiry_reason(expiry_reason);
1950        enc.symbol("BTCUSDT");
1951        enc.client_order_id("my-order-123");
1952        let len = HEADER_LENGTH + enc.encoded_length();
1953        bytes.truncate(len);
1954        bytes
1955    }
1956
1957    fn expected_order_response(expiry_reason: Option<u8>) -> BinanceOrderResponse {
1958        BinanceOrderResponse {
1959            price_exponent: -2,
1960            qty_exponent: -4,
1961            order_id: 12345,
1962            order_list_id: Some(99),
1963            price_mantissa: 12_345,
1964            orig_qty_mantissa: 25_000,
1965            executed_qty_mantissa: 10_000,
1966            cummulative_quote_qty_mantissa: 123_450_000,
1967            status: OrderStatus::PartiallyFilled,
1968            time_in_force: TimeInForce::Gtc,
1969            order_type: OrderType::StopLossLimit,
1970            side: OrderSide::Sell,
1971            stop_price_mantissa: Some(12_000),
1972            iceberg_qty_mantissa: Some(5_000),
1973            time: 1_700_000_000_000_000,
1974            update_time: 1_700_000_000_000_200,
1975            is_working: true,
1976            working_time: Some(1_700_000_000_000_300),
1977            orig_quote_order_qty_mantissa: 7_000,
1978            self_trade_prevention_mode: SelfTradePreventionMode::ExpireMaker,
1979            client_order_id: "my-order-123".to_string(),
1980            symbol: "BTCUSDT".to_string(),
1981            expiry_reason,
1982        }
1983    }
1984
1985    #[rstest]
1986    #[case::pre_v4_no_expiry_reason(162, ExpiryReason::NullVal, None)]
1987    #[case::v4_null_sentinel(163, ExpiryReason::NullVal, None)]
1988    #[case::v4_captures_value(163, ExpiryReason::UnfilledIocQuantityExpired, Some(0x05))]
1989    #[case::future_block_length(167, ExpiryReason::UnfilledIocQuantityExpired, Some(0x05))]
1990    fn test_decode_order_matches_codec(
1991        #[case] block_length: usize,
1992        #[case] expiry_reason: ExpiryReason,
1993        #[case] expected: Option<u8>,
1994    ) {
1995        let mut buf = build_order_response_buffer(expiry_reason);
1996        resize_fixed_block(&mut buf, block_length);
1997
1998        let order = decode_order(&buf).unwrap();
1999
2000        assert_eq!(order, expected_order_response(expected));
2001    }
2002
2003    #[rstest]
2004    fn test_decode_order_rejects_short_block() {
2005        let mut buf = build_order_response_buffer(ExpiryReason::NullVal);
2006        resize_fixed_block(&mut buf, 161);
2007
2008        let error = decode_order(&buf).unwrap_err();
2009
2010        assert_eq!(
2011            error,
2012            SbeDecodeError::InvalidBlockLength {
2013                expected: 162,
2014                actual: 161,
2015            }
2016        );
2017    }
2018
2019    fn build_orders_response_buffer(orders: &[(i64, &str)]) -> Vec<u8> {
2020        let mut bytes = vec![0u8; 512];
2021        let enc = OrdersResponseEncoder::default().wrap(WriteBuf::new(&mut bytes), HEADER_LENGTH);
2022        let mut header = enc.header(0);
2023        let enc = header.parent().unwrap();
2024        let mut group = enc.orders_encoder(orders.len() as u32, OrdersEncoder::default());
2025
2026        for (order_id, client_order_id) in orders {
2027            group.advance().unwrap();
2028            group.order_id(*order_id);
2029            group.iceberg_qty(5_000);
2030            group.time(order_id * 10);
2031            group.update_time(order_id * 10 + 1);
2032            group.is_working(BoolEnum::True);
2033            group.working_time(order_id * 10 + 2);
2034            group.self_trade_prevention_mode(SelfTradePreventionMode::ExpireTaker);
2035            group.expiry_reason(ExpiryReason::NullVal);
2036            group.symbol("BTCUSDT");
2037            group.client_order_id(client_order_id);
2038        }
2039
2040        let enc = group.parent().unwrap();
2041        let len = HEADER_LENGTH + enc.encoded_length();
2042        bytes.truncate(len);
2043        bytes
2044    }
2045
2046    #[rstest]
2047    fn test_decode_orders_matches_codec() {
2048        let expected = [(111, "order-1"), (222, "order-2")];
2049        let buf = build_orders_response_buffer(&expected);
2050
2051        let orders = decode_orders(&buf).unwrap();
2052
2053        assert_eq!(orders.len(), 2);
2054
2055        for (order, (order_id, client_order_id)) in orders.iter().zip(expected) {
2056            assert_eq!(order.order_id, order_id);
2057            assert_eq!(order.iceberg_qty_mantissa, Some(5_000));
2058            assert_eq!(order.time, order_id * 10);
2059            assert_eq!(order.update_time, order_id * 10 + 1);
2060            assert!(order.is_working);
2061            assert_eq!(order.working_time, Some(order_id * 10 + 2));
2062            assert_eq!(
2063                order.self_trade_prevention_mode,
2064                SelfTradePreventionMode::ExpireTaker
2065            );
2066            assert_eq!(order.expiry_reason, None);
2067            assert_eq!(order.symbol, "BTCUSDT");
2068            assert_eq!(order.client_order_id, client_order_id);
2069        }
2070    }
2071
2072    #[rstest]
2073    fn test_decode_orders_multiple() {
2074        // This test verifies cursor advances correctly through multiple orders
2075        let header = create_header(0, ORDERS_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
2076
2077        let mut buf = Vec::new();
2078        buf.extend_from_slice(&header);
2079
2080        // Group header: block_length=162, count=2
2081        buf.extend_from_slice(&create_group_header(ORDER_MIN_BLOCK_LENGTH, 2));
2082
2083        // Order 1
2084        let order1_start = buf.len();
2085        buf.push((-8i8) as u8); // price_exponent
2086        buf.push((-8i8) as u8); // qty_exponent
2087        buf.extend_from_slice(&1001i64.to_le_bytes()); // order_id
2088        buf.extend_from_slice(&i64::MIN.to_le_bytes()); // order_list_id (None)
2089        buf.extend_from_slice(&100_000_000_000i64.to_le_bytes()); // price_mantissa
2090        buf.extend_from_slice(&10_000_000i64.to_le_bytes()); // orig_qty
2091        buf.extend_from_slice(&0i64.to_le_bytes()); // executed_qty
2092        buf.extend_from_slice(&0i64.to_le_bytes()); // cummulative_quote_qty
2093        buf.push(1); // status
2094        buf.push(1); // time_in_force
2095        buf.push(1); // order_type
2096        buf.push(1); // side
2097        buf.extend_from_slice(&i64::MIN.to_le_bytes()); // stop_price (None)
2098        buf.extend_from_slice(&[0u8; 16]); // trailing_delta + trailing_time
2099        buf.extend_from_slice(&i64::MIN.to_le_bytes()); // iceberg_qty (None)
2100        buf.extend_from_slice(&1734300000000i64.to_le_bytes()); // time
2101        buf.extend_from_slice(&1734300000000i64.to_le_bytes()); // update_time
2102        buf.push(1); // is_working
2103        buf.extend_from_slice(&1734300000000i64.to_le_bytes()); // working_time
2104        buf.extend_from_slice(&0i64.to_le_bytes()); // orig_quote_order_qty
2105
2106        // Pad to 162 bytes from order start
2107        while buf.len() - order1_start < ORDER_MIN_BLOCK_LENGTH as usize {
2108            buf.push(0);
2109        }
2110        write_var_string(&mut buf, "BTCUSDT");
2111        write_var_string(&mut buf, "order-1");
2112
2113        // Order 2
2114        let order2_start = buf.len();
2115        buf.push((-8i8) as u8); // price_exponent
2116        buf.push((-8i8) as u8); // qty_exponent
2117        buf.extend_from_slice(&2002i64.to_le_bytes()); // order_id
2118        buf.extend_from_slice(&i64::MIN.to_le_bytes()); // order_list_id (None)
2119        buf.extend_from_slice(&200_000_000_000i64.to_le_bytes()); // price_mantissa
2120        buf.extend_from_slice(&20_000_000i64.to_le_bytes()); // orig_qty
2121        buf.extend_from_slice(&0i64.to_le_bytes()); // executed_qty
2122        buf.extend_from_slice(&0i64.to_le_bytes()); // cummulative_quote_qty
2123        buf.push(1); // status
2124        buf.push(1); // time_in_force
2125        buf.push(1); // order_type
2126        buf.push(2); // side (SELL)
2127        buf.extend_from_slice(&i64::MIN.to_le_bytes()); // stop_price (None)
2128        buf.extend_from_slice(&[0u8; 16]); // trailing_delta + trailing_time
2129        buf.extend_from_slice(&i64::MIN.to_le_bytes()); // iceberg_qty (None)
2130        buf.extend_from_slice(&1734300001000i64.to_le_bytes()); // time
2131        buf.extend_from_slice(&1734300001000i64.to_le_bytes()); // update_time
2132        buf.push(1); // is_working
2133        buf.extend_from_slice(&1734300001000i64.to_le_bytes()); // working_time
2134        buf.extend_from_slice(&0i64.to_le_bytes()); // orig_quote_order_qty
2135
2136        while buf.len() - order2_start < ORDER_MIN_BLOCK_LENGTH as usize {
2137            buf.push(0);
2138        }
2139        write_var_string(&mut buf, "ETHUSDT");
2140        write_var_string(&mut buf, "order-2");
2141
2142        let orders = decode_orders(&buf).unwrap();
2143
2144        assert_eq!(orders.len(), 2);
2145        assert_eq!(orders[0].order_id, 1001);
2146        assert_eq!(orders[0].symbol, "BTCUSDT");
2147        assert_eq!(orders[0].client_order_id, "order-1");
2148        assert_eq!(orders[0].price_mantissa, 100_000_000_000);
2149
2150        assert_eq!(orders[1].order_id, 2002);
2151        assert_eq!(orders[1].symbol, "ETHUSDT");
2152        assert_eq!(orders[1].client_order_id, "order-2");
2153        assert_eq!(orders[1].price_mantissa, 200_000_000_000);
2154    }
2155
2156    #[rstest]
2157    fn test_decode_orders_v4_trailing_expiry_reason() {
2158        // Schema 3:4 appends a 1-byte expiryReason to the orders group fixed block,
2159        // bumping its length 162 -> 163. The decoder must read it via the runtime
2160        // group block_length so the symbol var-string starts at the right offset.
2161        const V4_BLOCK_LENGTH: u16 = 163;
2162        let header = create_header(0, ORDERS_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
2163
2164        let mut buf = Vec::new();
2165        buf.extend_from_slice(&header);
2166        buf.extend_from_slice(&create_group_header(V4_BLOCK_LENGTH, 1));
2167
2168        let order_start = buf.len();
2169        buf.extend_from_slice(&[0u8; ORDER_MIN_BLOCK_LENGTH as usize]);
2170        buf.push(0xFF); // Sentinel for the new expiryReason byte (null/absent)
2171        assert_eq!(buf.len() - order_start, V4_BLOCK_LENGTH as usize);
2172
2173        write_var_string(&mut buf, "BTCUSDT");
2174        write_var_string(&mut buf, "v4-order");
2175
2176        let orders = decode_orders(&buf).unwrap();
2177
2178        assert_eq!(orders.len(), 1);
2179        assert_eq!(orders[0].symbol, "BTCUSDT");
2180        assert_eq!(orders[0].client_order_id, "v4-order");
2181        assert!(orders[0].expiry_reason.is_none());
2182    }
2183
2184    #[rstest]
2185    fn test_decode_orders_pre_v4_block_returns_no_expiry_reason() {
2186        // Schema 3:3 block_length is 162 (no expiryReason byte). The decoder
2187        // must surface `expiry_reason = None` regardless of the trailing
2188        // padding bytes inside the fixed block.
2189        const PRE_V4_BLOCK_LENGTH: u16 = ORDER_MIN_BLOCK_LENGTH;
2190        let header = create_header(0, ORDERS_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
2191
2192        let mut buf = Vec::new();
2193        buf.extend_from_slice(&header);
2194        buf.extend_from_slice(&create_group_header(PRE_V4_BLOCK_LENGTH, 1));
2195
2196        // Fill the fixed block with non-zero, non-0xff padding so the previous
2197        // bug (returning that last byte as expiry_reason) would surface.
2198        buf.extend_from_slice(&[0xAAu8; PRE_V4_BLOCK_LENGTH as usize]);
2199
2200        write_var_string(&mut buf, "BTCUSDT");
2201        write_var_string(&mut buf, "pre-v4-order");
2202
2203        let orders = decode_orders(&buf).unwrap();
2204        assert!(orders[0].expiry_reason.is_none());
2205    }
2206
2207    #[rstest]
2208    fn test_decode_orders_v4_captures_expiry_reason_value() {
2209        // Same layout as the null case, but the trailing byte carries a real
2210        // expiryReason value (0x05 = UnfilledIocQuantityExpired). The decoder
2211        // must surface it on the parsed `BinanceOrderResponse`.
2212        const V4_BLOCK_LENGTH: u16 = 163;
2213        let header = create_header(0, ORDERS_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
2214
2215        let mut buf = Vec::new();
2216        buf.extend_from_slice(&header);
2217        buf.extend_from_slice(&create_group_header(V4_BLOCK_LENGTH, 1));
2218
2219        buf.extend_from_slice(&[0u8; ORDER_MIN_BLOCK_LENGTH as usize]);
2220        buf.push(0x05);
2221
2222        write_var_string(&mut buf, "BTCUSDT");
2223        write_var_string(&mut buf, "v4-expired");
2224
2225        let orders = decode_orders(&buf).unwrap();
2226        assert_eq!(orders[0].expiry_reason, Some(0x05));
2227    }
2228
2229    #[rstest]
2230    fn test_decode_orders_empty() {
2231        let header = create_header(0, ORDERS_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
2232
2233        let mut buf = Vec::new();
2234        buf.extend_from_slice(&header);
2235        buf.extend_from_slice(&create_group_header(ORDER_MIN_BLOCK_LENGTH, 0));
2236
2237        let orders = decode_orders(&buf).unwrap();
2238        assert!(orders.is_empty());
2239    }
2240
2241    #[rstest]
2242    fn test_decode_orders_truncated_var_string() {
2243        let header = create_header(0, ORDERS_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
2244
2245        let mut buf = Vec::new();
2246        buf.extend_from_slice(&header);
2247        buf.extend_from_slice(&create_group_header(ORDER_MIN_BLOCK_LENGTH, 1));
2248
2249        // Pad fixed block to 162 bytes
2250        buf.extend_from_slice(&[0u8; ORDER_MIN_BLOCK_LENGTH as usize]);
2251
2252        // Symbol length says 7 bytes but we only provide 3
2253        buf.push(7); // Length prefix claims "BTCUSDT" (7 chars)
2254        buf.extend_from_slice(b"BTC"); // Only 3 bytes - truncated
2255
2256        let err = decode_orders(&buf).unwrap_err();
2257        assert!(matches!(err, SbeDecodeError::BufferTooShort { .. }));
2258    }
2259
2260    #[rstest]
2261    fn test_decode_orders_invalid_utf8() {
2262        let header = create_header(0, ORDERS_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
2263
2264        let mut buf = Vec::new();
2265        buf.extend_from_slice(&header);
2266        buf.extend_from_slice(&create_group_header(ORDER_MIN_BLOCK_LENGTH, 1));
2267
2268        buf.extend_from_slice(&[0u8; ORDER_MIN_BLOCK_LENGTH as usize]);
2269
2270        // Invalid UTF-8 sequence
2271        buf.push(4);
2272        buf.extend_from_slice(&[0xFF, 0xFE, 0x00, 0x01]);
2273
2274        let err = decode_orders(&buf).unwrap_err();
2275        assert!(matches!(err, SbeDecodeError::InvalidUtf8));
2276    }
2277
2278    #[rstest]
2279    #[case::current(137)]
2280    #[case::future_block_length(141)]
2281    fn test_decode_cancel_order_matches_codec(#[case] block_length: usize) {
2282        let mut buf = create_cancel_order_response_buffer(99999, "BTCUSDT", "orig-id", "new-id");
2283        resize_fixed_block(&mut buf, block_length);
2284
2285        let cancel = decode_cancel_order(&buf).unwrap();
2286
2287        assert_eq!(cancel.order_id, 99999);
2288        assert!(cancel.order_list_id.is_none());
2289        assert_eq!(cancel.transact_time, 1_700_000_000_000_000);
2290        assert_eq!(cancel.status, OrderStatus::Canceled);
2291        assert_eq!(
2292            cancel.self_trade_prevention_mode,
2293            SelfTradePreventionMode::ExpireTaker
2294        );
2295        assert_eq!(cancel.symbol, "BTCUSDT");
2296        assert_eq!(cancel.orig_client_order_id, "orig-id");
2297        assert_eq!(cancel.client_order_id, "new-id");
2298    }
2299
2300    #[rstest]
2301    fn test_decode_account_with_balances() {
2302        let header = create_header(
2303            ACCOUNT_BLOCK_LENGTH as u16,
2304            ACCOUNT_TEMPLATE_ID,
2305            SBE_SCHEMA_ID,
2306            SBE_SCHEMA_VERSION,
2307        );
2308
2309        let mut buf = Vec::new();
2310        buf.extend_from_slice(&header);
2311
2312        // Fixed block (64 bytes)
2313        buf.push((-8i8) as u8); // commission_exponent
2314        buf.extend_from_slice(&100_000i64.to_le_bytes()); // maker_commission
2315        buf.extend_from_slice(&100_000i64.to_le_bytes()); // taker_commission
2316        buf.extend_from_slice(&0i64.to_le_bytes()); // buyer_commission
2317        buf.extend_from_slice(&0i64.to_le_bytes()); // seller_commission
2318        buf.push(1); // can_trade
2319        buf.push(1); // can_withdraw
2320        buf.push(1); // can_deposit
2321        buf.push(0); // brokered
2322        buf.push(0); // require_self_trade_prevention
2323        buf.push(0); // prevent_sor
2324        buf.extend_from_slice(&1734300000000i64.to_le_bytes()); // update_time
2325        buf.push(1); // account_type (SPOT)
2326
2327        // Pad to 64 bytes
2328        while buf.len() < 8 + ACCOUNT_BLOCK_LENGTH {
2329            buf.push(0);
2330        }
2331
2332        // Balances group: 2 balances
2333        buf.extend_from_slice(&create_group_header(BALANCE_BLOCK_LENGTH, 2));
2334
2335        // Balance 1: BTC
2336        buf.push((-8i8) as u8); // exponent
2337        buf.extend_from_slice(&100_000_000i64.to_le_bytes()); // free (1.0 BTC)
2338        buf.extend_from_slice(&50_000_000i64.to_le_bytes()); // locked (0.5 BTC)
2339        write_var_string(&mut buf, "BTC");
2340
2341        // Balance 2: USDT
2342        buf.push((-8i8) as u8); // exponent
2343        buf.extend_from_slice(&1_000_000_000_000i64.to_le_bytes()); // free (10000 USDT)
2344        buf.extend_from_slice(&0i64.to_le_bytes()); // locked
2345        write_var_string(&mut buf, "USDT");
2346
2347        let account = decode_account(&buf).unwrap();
2348
2349        assert!(account.can_trade);
2350        assert!(account.can_withdraw);
2351        assert!(account.can_deposit);
2352        assert_eq!(account.balances.len(), 2);
2353        assert_eq!(account.balances[0].asset, "BTC");
2354        assert_eq!(account.balances[0].free_mantissa, 100_000_000);
2355        assert_eq!(account.balances[0].locked_mantissa, 50_000_000);
2356        assert_eq!(account.balances[1].asset, "USDT");
2357        assert_eq!(account.balances[1].free_mantissa, 1_000_000_000_000);
2358    }
2359
2360    #[rstest]
2361    fn test_decode_account_empty_balances() {
2362        let header = create_header(
2363            ACCOUNT_BLOCK_LENGTH as u16,
2364            ACCOUNT_TEMPLATE_ID,
2365            SBE_SCHEMA_ID,
2366            SBE_SCHEMA_VERSION,
2367        );
2368
2369        let mut buf = Vec::new();
2370        buf.extend_from_slice(&header);
2371
2372        // Minimal fixed block
2373        buf.push((-8i8) as u8);
2374        buf.extend_from_slice(&[0u8; 63]); // Rest of fixed block
2375
2376        // Empty balances group
2377        buf.extend_from_slice(&create_group_header(BALANCE_BLOCK_LENGTH, 0));
2378
2379        let account = decode_account(&buf).unwrap();
2380        assert!(account.balances.is_empty());
2381    }
2382
2383    #[rstest]
2384    fn test_decode_account_trades_multiple() {
2385        let header = create_header(
2386            0,
2387            ACCOUNT_TRADES_TEMPLATE_ID,
2388            SBE_SCHEMA_ID,
2389            SBE_SCHEMA_VERSION,
2390        );
2391
2392        let mut buf = Vec::new();
2393        buf.extend_from_slice(&header);
2394
2395        // Group header: 2 trades
2396        buf.extend_from_slice(&create_group_header(ACCOUNT_TRADE_BLOCK_LENGTH, 2));
2397
2398        // Trade 1
2399        buf.push((-8i8) as u8); // price_exponent
2400        buf.push((-8i8) as u8); // qty_exponent
2401        buf.push((-8i8) as u8); // commission_exponent
2402        buf.extend_from_slice(&1001i64.to_le_bytes()); // id
2403        buf.extend_from_slice(&5001i64.to_le_bytes()); // order_id
2404        buf.extend_from_slice(&i64::MIN.to_le_bytes()); // order_list_id (None)
2405        buf.extend_from_slice(&100_000_000_000i64.to_le_bytes()); // price
2406        buf.extend_from_slice(&10_000_000i64.to_le_bytes()); // qty
2407        buf.extend_from_slice(&1_000_000_000_000i64.to_le_bytes()); // quote_qty
2408        buf.extend_from_slice(&100_000i64.to_le_bytes()); // commission
2409        buf.extend_from_slice(&1734300000000i64.to_le_bytes()); // time
2410        buf.push(1); // is_buyer
2411        buf.push(0); // is_maker
2412        buf.push(1); // is_best_match
2413        write_var_string(&mut buf, "BTCUSDT");
2414        write_var_string(&mut buf, "BNB");
2415
2416        // Trade 2
2417        buf.push((-8i8) as u8);
2418        buf.push((-8i8) as u8);
2419        buf.push((-8i8) as u8);
2420        buf.extend_from_slice(&1002i64.to_le_bytes());
2421        buf.extend_from_slice(&5002i64.to_le_bytes());
2422        buf.extend_from_slice(&i64::MIN.to_le_bytes());
2423        buf.extend_from_slice(&200_000_000_000i64.to_le_bytes());
2424        buf.extend_from_slice(&5_000_000i64.to_le_bytes());
2425        buf.extend_from_slice(&1_000_000_000_000i64.to_le_bytes());
2426        buf.extend_from_slice(&50_000i64.to_le_bytes());
2427        buf.extend_from_slice(&1734300001000i64.to_le_bytes());
2428        buf.push(0); // is_buyer (false = seller)
2429        buf.push(1); // is_maker
2430        buf.push(1); // is_best_match
2431        write_var_string(&mut buf, "ETHUSDT");
2432        write_var_string(&mut buf, "USDT");
2433
2434        let trades = decode_account_trades(&buf).unwrap();
2435
2436        assert_eq!(trades.len(), 2);
2437        assert_eq!(trades[0].id, 1001);
2438        assert_eq!(trades[0].order_id, 5001);
2439        assert!(trades[0].order_list_id.is_none());
2440        assert_eq!(trades[0].symbol, "BTCUSDT");
2441        assert_eq!(trades[0].commission_asset, "BNB");
2442        assert!(trades[0].is_buyer);
2443        assert!(!trades[0].is_maker);
2444
2445        assert_eq!(trades[1].id, 1002);
2446        assert_eq!(trades[1].symbol, "ETHUSDT");
2447        assert_eq!(trades[1].commission_asset, "USDT");
2448        assert!(!trades[1].is_buyer);
2449        assert!(trades[1].is_maker);
2450    }
2451
2452    #[rstest]
2453    fn test_decode_account_trades_empty() {
2454        let header = create_header(
2455            0,
2456            ACCOUNT_TRADES_TEMPLATE_ID,
2457            SBE_SCHEMA_ID,
2458            SBE_SCHEMA_VERSION,
2459        );
2460
2461        let mut buf = Vec::new();
2462        buf.extend_from_slice(&header);
2463        buf.extend_from_slice(&create_group_header(ACCOUNT_TRADE_BLOCK_LENGTH, 0));
2464
2465        let trades = decode_account_trades(&buf).unwrap();
2466        assert!(trades.is_empty());
2467    }
2468
2469    #[rstest]
2470    fn test_decode_exchange_info_single_symbol() {
2471        let header = create_header(
2472            0,
2473            EXCHANGE_INFO_TEMPLATE_ID,
2474            SBE_SCHEMA_ID,
2475            SBE_SCHEMA_VERSION,
2476        );
2477
2478        let mut buf = Vec::new();
2479        buf.extend_from_slice(&header);
2480
2481        // Empty rate_limits group
2482        buf.extend_from_slice(&create_group_header(11, 0));
2483
2484        // Empty exchange_filters group
2485        buf.extend_from_slice(&create_group_header(0, 0));
2486
2487        // Symbols group: 1 symbol with block_length=19
2488        buf.extend_from_slice(&create_group_header(SYMBOL_BLOCK_LENGTH as u16, 1));
2489
2490        // Fixed block (19 bytes)
2491        buf.push(0); // status (Trading)
2492        buf.push(8); // base_asset_precision
2493        buf.push(8); // quote_asset_precision
2494        buf.push(8); // base_commission_precision
2495        buf.push(8); // quote_commission_precision
2496        buf.extend_from_slice(&0b0000_0111u16.to_le_bytes()); // order_types (MARKET|LIMIT|STOP_LOSS)
2497        buf.push(1); // iceberg_allowed (True)
2498        buf.push(1); // oco_allowed (True)
2499        buf.push(0); // oto_allowed (False)
2500        buf.push(1); // quote_order_qty_market_allowed (True)
2501        buf.push(1); // allow_trailing_stop (True)
2502        buf.push(1); // cancel_replace_allowed (True)
2503        buf.push(0); // amend_allowed (False)
2504        buf.push(1); // is_spot_trading_allowed (True)
2505        buf.push(0); // is_margin_trading_allowed (False)
2506        buf.push(0); // default_self_trade_prevention_mode
2507        buf.push(0); // allowed_self_trade_prevention_modes
2508        buf.push(0); // peg_instructions_allowed
2509
2510        // Filters nested group: 0 filters (SBE binary filters are skipped)
2511        buf.extend_from_slice(&create_group_header(0, 0));
2512
2513        // Permission sets nested group: 1 set with 1 permission
2514        buf.extend_from_slice(&create_group_header(0, 1));
2515        buf.extend_from_slice(&create_group_header(0, 1));
2516        write_var_string(&mut buf, "SPOT");
2517
2518        // Variable-length strings
2519        write_var_string(&mut buf, "BTCUSDT");
2520        write_var_string(&mut buf, "BTC");
2521        write_var_string(&mut buf, "USDT");
2522
2523        let info = decode_exchange_info(&buf).unwrap();
2524
2525        assert_eq!(info.symbols.len(), 1);
2526        let symbol = &info.symbols[0];
2527        assert_eq!(symbol.symbol, "BTCUSDT");
2528        assert_eq!(symbol.base_asset, "BTC");
2529        assert_eq!(symbol.quote_asset, "USDT");
2530        assert_eq!(symbol.base_asset_precision, 8);
2531        assert_eq!(symbol.quote_asset_precision, 8);
2532        assert_eq!(symbol.status, 0); // Trading
2533        assert_eq!(symbol.order_types, 0b0000_0111);
2534        assert!(symbol.iceberg_allowed);
2535        assert!(symbol.oco_allowed);
2536        assert!(!symbol.oto_allowed);
2537        assert!(symbol.quote_order_qty_market_allowed);
2538        assert!(symbol.allow_trailing_stop);
2539        assert!(symbol.cancel_replace_allowed);
2540        assert!(!symbol.amend_allowed);
2541        assert!(symbol.is_spot_trading_allowed);
2542        assert!(!symbol.is_margin_trading_allowed);
2543        assert!(symbol.filters.price_filter.is_none()); // No filters in test data
2544        assert!(symbol.filters.lot_size_filter.is_none());
2545        assert_eq!(symbol.permissions.len(), 1);
2546        assert_eq!(symbol.permissions[0], vec!["SPOT"]);
2547    }
2548
2549    #[rstest]
2550    #[case::exponent(0, 128, "notional")]
2551    #[case::minimum(8, 255, "notional")]
2552    #[case::min_flag(9, 255, "notional market flag")]
2553    #[case::maximum(17, 255, "notional")]
2554    #[case::max_flag(18, 255, "notional market flag")]
2555    #[case::average(22, 255, "avgPriceMins")]
2556    fn test_spot_notional_sbe_invalid_fields(
2557        #[case] offset: usize,
2558        #[case] value: u8,
2559        #[case] field: &'static str,
2560    ) {
2561        let mut wire =
2562            include_bytes!("../../../test_data/spot/http_sbe/notional_range.sbe").to_vec();
2563        let header = [23, 0, 6, 0, 3, 0, 5, 0];
2564        let start = wire
2565            .windows(header.len())
2566            .position(|bytes| bytes == header)
2567            .unwrap();
2568        wire[start + header.len() + offset] = value;
2569        assert!(
2570            matches!(decode_exchange_info(&wire), Err(SbeDecodeError::InvalidValue { field: actual }) if actual == field)
2571        );
2572    }
2573
2574    #[rstest]
2575    fn test_spot_notional_sbe_truncated_filter() {
2576        let mut wire =
2577            include_bytes!("../../../test_data/spot/http_sbe/notional_range.sbe").to_vec();
2578        let header = [23, 0, 6, 0, 3, 0, 5, 0];
2579        let start = wire
2580            .windows(header.len())
2581            .position(|bytes| bytes == header)
2582            .unwrap();
2583        wire[start - 1] -= 1;
2584        assert!(matches!(
2585            decode_exchange_info(&wire),
2586            Err(SbeDecodeError::BufferTooShort {
2587                expected: 23,
2588                actual: 22
2589            })
2590        ));
2591    }
2592
2593    #[rstest]
2594    fn test_decode_exchange_info_empty() {
2595        let header = create_header(
2596            0,
2597            EXCHANGE_INFO_TEMPLATE_ID,
2598            SBE_SCHEMA_ID,
2599            SBE_SCHEMA_VERSION,
2600        );
2601
2602        let mut buf = Vec::new();
2603        buf.extend_from_slice(&header);
2604
2605        // Empty rate_limits group
2606        buf.extend_from_slice(&create_group_header(11, 0));
2607
2608        // Empty exchange_filters group
2609        buf.extend_from_slice(&create_group_header(0, 0));
2610
2611        // Empty symbols group
2612        buf.extend_from_slice(&create_group_header(SYMBOL_BLOCK_LENGTH as u16, 0));
2613
2614        let info = decode_exchange_info(&buf).unwrap();
2615        assert!(info.symbols.is_empty());
2616    }
2617
2618    #[rstest]
2619    fn test_decode_exchange_info_wrong_template() {
2620        let header = create_header(0, PING_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
2621
2622        let mut buf = Vec::new();
2623        buf.extend_from_slice(&header);
2624
2625        let err = decode_exchange_info(&buf).unwrap_err();
2626        assert!(matches!(err, SbeDecodeError::UnknownTemplateId(101)));
2627    }
2628
2629    #[rstest]
2630    fn test_decode_exchange_info_multiple_symbols() {
2631        let header = create_header(
2632            0,
2633            EXCHANGE_INFO_TEMPLATE_ID,
2634            SBE_SCHEMA_ID,
2635            SBE_SCHEMA_VERSION,
2636        );
2637
2638        let mut buf = Vec::new();
2639        buf.extend_from_slice(&header);
2640
2641        // Empty rate_limits group
2642        buf.extend_from_slice(&create_group_header(11, 0));
2643
2644        // Empty exchange_filters group
2645        buf.extend_from_slice(&create_group_header(0, 0));
2646
2647        // Symbols group: 2 symbols
2648        buf.extend_from_slice(&create_group_header(SYMBOL_BLOCK_LENGTH as u16, 2));
2649
2650        // Symbol 1: BTCUSDT
2651        buf.push(0); // status
2652        buf.push(8); // base_asset_precision
2653        buf.push(8); // quote_asset_precision
2654        buf.push(8); // base_commission_precision
2655        buf.push(8); // quote_commission_precision
2656        buf.extend_from_slice(&0b0000_0011u16.to_le_bytes()); // order_types
2657        buf.push(1); // iceberg_allowed
2658        buf.push(1); // oco_allowed
2659        buf.push(0); // oto_allowed
2660        buf.push(1); // quote_order_qty_market_allowed
2661        buf.push(1); // allow_trailing_stop
2662        buf.push(1); // cancel_replace_allowed
2663        buf.push(0); // amend_allowed
2664        buf.push(1); // is_spot_trading_allowed
2665        buf.push(0); // is_margin_trading_allowed
2666        buf.push(0); // default_self_trade_prevention_mode
2667        buf.push(0); // allowed_self_trade_prevention_modes
2668        buf.push(0); // peg_instructions_allowed
2669        buf.extend_from_slice(&create_group_header(0, 0)); // No filters
2670        buf.extend_from_slice(&create_group_header(0, 0)); // No permission sets
2671        write_var_string(&mut buf, "BTCUSDT");
2672        write_var_string(&mut buf, "BTC");
2673        write_var_string(&mut buf, "USDT");
2674
2675        // Symbol 2: ETHUSDT
2676        buf.push(0); // status
2677        buf.push(8); // base_asset_precision
2678        buf.push(8); // quote_asset_precision
2679        buf.push(8); // base_commission_precision
2680        buf.push(8); // quote_commission_precision
2681        buf.extend_from_slice(&0b0000_0011u16.to_le_bytes()); // order_types
2682        buf.push(1); // iceberg_allowed
2683        buf.push(1); // oco_allowed
2684        buf.push(0); // oto_allowed
2685        buf.push(1); // quote_order_qty_market_allowed
2686        buf.push(1); // allow_trailing_stop
2687        buf.push(1); // cancel_replace_allowed
2688        buf.push(0); // amend_allowed
2689        buf.push(1); // is_spot_trading_allowed
2690        buf.push(1); // is_margin_trading_allowed
2691        buf.push(0); // default_self_trade_prevention_mode
2692        buf.push(0); // allowed_self_trade_prevention_modes
2693        buf.push(0); // peg_instructions_allowed
2694        buf.extend_from_slice(&create_group_header(0, 0)); // No filters
2695        buf.extend_from_slice(&create_group_header(0, 0)); // No permission sets
2696        write_var_string(&mut buf, "ETHUSDT");
2697        write_var_string(&mut buf, "ETH");
2698        write_var_string(&mut buf, "USDT");
2699
2700        let info = decode_exchange_info(&buf).unwrap();
2701
2702        assert_eq!(info.symbols.len(), 2);
2703        assert_eq!(info.symbols[0].symbol, "BTCUSDT");
2704        assert_eq!(info.symbols[0].base_asset, "BTC");
2705        assert!(!info.symbols[0].is_margin_trading_allowed);
2706
2707        assert_eq!(info.symbols[1].symbol, "ETHUSDT");
2708        assert_eq!(info.symbols[1].base_asset, "ETH");
2709        assert!(info.symbols[1].is_margin_trading_allowed);
2710    }
2711
2712    #[rstest]
2713    fn test_decode_klines_valid() {
2714        let header = create_header(2, KLINES_TEMPLATE_ID, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION);
2715
2716        let mut buf = Vec::new();
2717        buf.extend_from_slice(&header);
2718        buf.push((-2i8) as u8); // price_exponent
2719        buf.push((-4i8) as u8); // qty_exponent
2720        buf.extend_from_slice(&create_group_header(KLINES_BLOCK_LENGTH, 1));
2721        buf.extend_from_slice(&1_700_000_000_000_000i64.to_le_bytes()); // open_time (micros)
2722        buf.extend_from_slice(&12_000i64.to_le_bytes()); // open_price
2723        buf.extend_from_slice(&12_500i64.to_le_bytes()); // high_price
2724        buf.extend_from_slice(&11_900i64.to_le_bytes()); // low_price
2725        buf.extend_from_slice(&12_345i64.to_le_bytes()); // close_price
2726        buf.extend_from_slice(&1_234_500i128.to_le_bytes()); // volume
2727        buf.extend_from_slice(&1_700_000_059_999_000i64.to_le_bytes()); // close_time (micros)
2728        buf.extend_from_slice(&2_345_600i128.to_le_bytes()); // quote_volume
2729        buf.extend_from_slice(&100i64.to_le_bytes()); // num_trades
2730        buf.extend_from_slice(&600_000i128.to_le_bytes()); // taker_buy_base_volume
2731        buf.extend_from_slice(&1_200_000i128.to_le_bytes()); // taker_buy_quote_volume
2732
2733        let klines = decode_klines(&buf).unwrap();
2734
2735        assert_eq!(klines.price_exponent, -2);
2736        assert_eq!(klines.qty_exponent, -4);
2737        assert_eq!(klines.klines.len(), 1);
2738        assert_eq!(klines.klines[0].open_time, 1_700_000_000_000_000);
2739        assert_eq!(klines.klines[0].close_price, 12_345);
2740        assert_eq!(i128::from_le_bytes(klines.klines[0].volume), 1_234_500);
2741        assert_eq!(klines.klines[0].num_trades, 100);
2742    }
2743
2744    fn build_new_order_full_buffer(expiry_reason: ExpiryReason) -> Vec<u8> {
2745        let mut bytes = vec![0u8; 512];
2746        let enc =
2747            NewOrderFullResponseEncoder::default().wrap(WriteBuf::new(&mut bytes), HEADER_LENGTH);
2748        let mut header = enc.header(0);
2749        let mut enc = header.parent().unwrap();
2750        enc.price_exponent(-2);
2751        enc.qty_exponent(-4);
2752        enc.order_id(12345);
2753        enc.order_list_id(99);
2754        enc.transact_time(1_700_000_000_000_000);
2755        enc.price(12_345);
2756        enc.orig_qty(25_000);
2757        enc.executed_qty(10_000);
2758        enc.cummulative_quote_qty(123_450_000);
2759        enc.status(OrderStatus::PartiallyFilled);
2760        enc.time_in_force(TimeInForce::Gtc);
2761        enc.order_type(OrderType::Limit);
2762        enc.side(OrderSide::Buy);
2763        enc.stop_price(12_000);
2764        enc.working_time(1_700_000_000_000_500);
2765        enc.iceberg_qty(5_000);
2766        enc.order_capacity(OrderCapacity::Principal);
2767        enc.working_floor(Floor::Sor);
2768        enc.self_trade_prevention_mode(SelfTradePreventionMode::ExpireMaker);
2769        enc.trade_group_id(1);
2770        enc.used_sor(BoolEnum::True);
2771        enc.expiry_reason(expiry_reason);
2772        let mut fills = enc.fills_encoder(1, FillsEncoder::default());
2773        fills.advance().unwrap();
2774        fills.commission_exponent(-8);
2775        fills.match_type(MatchType::AutoMatch);
2776        fills.price(12_345);
2777        fills.qty(10_000);
2778        fills.commission(10_000);
2779        fills.trade_id(555);
2780        fills.alloc_id(i64::MIN);
2781        fills.commission_asset("USDT");
2782        let enc = fills.parent().unwrap();
2783        let mut prevented = enc.prevented_matches_encoder(0, PreventedMatchesEncoder::default());
2784        let mut enc = prevented.parent().unwrap();
2785        enc.symbol("ETHUSDT");
2786        enc.client_order_id("client-456");
2787        let len = HEADER_LENGTH + enc.encoded_length();
2788        bytes.truncate(len);
2789        bytes
2790    }
2791
2792    #[rstest]
2793    #[case::pre_v4_no_expiry_reason(153, ExpiryReason::NullVal, None)]
2794    #[case::v4_null_sentinel(154, ExpiryReason::NullVal, None)]
2795    #[case::v4_captures_value(154, ExpiryReason::UnfilledIocQuantityExpired, Some(0x05))]
2796    #[case::future_block_length(158, ExpiryReason::UnfilledIocQuantityExpired, Some(0x05))]
2797    fn test_decode_new_order_full_matches_codec(
2798        #[case] block_length: usize,
2799        #[case] expiry_reason: ExpiryReason,
2800        #[case] expected: Option<u8>,
2801    ) {
2802        let mut buf = build_new_order_full_buffer(expiry_reason);
2803        resize_fixed_block(&mut buf, block_length);
2804
2805        let response = decode_new_order_full(&buf).unwrap();
2806
2807        assert_eq!(response.order_id, 12345);
2808        assert_eq!(response.order_list_id, Some(99));
2809        assert_eq!(response.transact_time, 1_700_000_000_000_000);
2810        assert_eq!(response.price_mantissa, 12_345);
2811        assert_eq!(response.orig_qty_mantissa, 25_000);
2812        assert_eq!(response.executed_qty_mantissa, 10_000);
2813        assert_eq!(response.status, OrderStatus::PartiallyFilled);
2814        assert_eq!(response.stop_price_mantissa, Some(12_000));
2815        assert_eq!(response.working_time, Some(1_700_000_000_000_500));
2816        assert_eq!(
2817            response.self_trade_prevention_mode,
2818            SelfTradePreventionMode::ExpireMaker
2819        );
2820        assert_eq!(response.expiry_reason, expected);
2821        assert_eq!(response.symbol, "ETHUSDT");
2822        assert_eq!(response.client_order_id, "client-456");
2823        assert_eq!(response.fills.len(), 1);
2824        assert_eq!(response.fills[0].price_mantissa, 12_345);
2825        assert_eq!(response.fills[0].qty_mantissa, 10_000);
2826        assert_eq!(response.fills[0].trade_id, Some(555));
2827        assert_eq!(response.fills[0].commission_asset, "USDT");
2828    }
2829
2830    #[rstest]
2831    fn test_decode_new_order_full_rejects_short_block() {
2832        let mut buf = build_new_order_full_buffer(ExpiryReason::NullVal);
2833        resize_fixed_block(&mut buf, 116);
2834
2835        let error = decode_new_order_full(&buf).unwrap_err();
2836
2837        assert_eq!(
2838            error,
2839            SbeDecodeError::InvalidBlockLength {
2840                expected: 117,
2841                actual: 116,
2842            }
2843        );
2844    }
2845
2846    #[rstest]
2847    #[case::current(2)]
2848    #[case::extended(5)]
2849    fn test_decode_cancel_replace_nested_order(#[case] block_length: u16) {
2850        let nested = build_new_order_full_buffer(ExpiryReason::NullVal);
2851        let mut buf = create_header(
2852            block_length,
2853            CANCEL_REPLACE_TEMPLATE_ID,
2854            SBE_SCHEMA_ID,
2855            SBE_SCHEMA_VERSION,
2856        )
2857        .to_vec();
2858        buf.resize(HEADER_LENGTH + usize::from(block_length), 0);
2859        buf.extend_from_slice(&3_u16.to_le_bytes());
2860        buf.extend_from_slice(&[11, 22, 33]);
2861        buf.extend_from_slice(&(nested.len() as u32).to_le_bytes());
2862        buf.extend_from_slice(&nested);
2863
2864        let response = decode_cancel_replace(&buf).unwrap();
2865        let expected = decode_new_order_full(&nested).unwrap();
2866        assert_eq!(response, expected);
2867
2868        for end in 0..buf.len() {
2869            assert!(
2870                decode_cancel_replace(&buf[..end]).is_err(),
2871                "Accepted truncated response at {end}"
2872            );
2873        }
2874        buf[HEADER_LENGTH + 1] = CancelReplaceStatus::Failure as u8;
2875        assert!(matches!(
2876            decode_cancel_replace(&buf),
2877            Err(SbeDecodeError::InvalidValue {
2878                field: "cancel-replace result"
2879            })
2880        ));
2881    }
2882
2883    #[rstest]
2884    fn test_decode_cancel_open_orders_valid() {
2885        let response_one = create_cancel_order_response_buffer(111, "ETHUSDT", "orig-1", "new-1");
2886        let response_two = create_cancel_order_response_buffer(222, "BTCUSDT", "orig-2", "new-2");
2887        let buf = create_cancel_open_orders_buffer(&[response_one, response_two]);
2888        let responses = decode_cancel_open_orders(&buf).unwrap();
2889
2890        assert_eq!(responses.len(), 2);
2891        let BinanceCancelOpenOrdersResponse::Order(first) = &responses[0] else {
2892            panic!("Expected ordinary cancel response");
2893        };
2894        assert_eq!(first.order_id, 111);
2895        assert_eq!(first.symbol, "ETHUSDT");
2896        assert_eq!(first.orig_client_order_id, "orig-1");
2897        assert_eq!(first.client_order_id, "new-1");
2898        let BinanceCancelOpenOrdersResponse::Order(second) = &responses[1] else {
2899            panic!("Expected ordinary cancel response");
2900        };
2901        assert_eq!(second.order_id, 222);
2902        assert_eq!(second.symbol, "BTCUSDT");
2903        assert_eq!(second.orig_client_order_id, "orig-2");
2904        assert_eq!(second.client_order_id, "new-2");
2905    }
2906
2907    #[rstest]
2908    fn test_decode_cancel_open_orders_empty() {
2909        let buf = create_cancel_open_orders_buffer(&[]);
2910
2911        let responses = decode_cancel_open_orders(&buf).unwrap();
2912
2913        assert!(responses.is_empty());
2914    }
2915
2916    #[rstest]
2917    #[case::single_order_cancel(true)]
2918    #[case::cancel_all(false)]
2919    fn test_decode_cancel_open_orders_order_list(#[case] single: bool) {
2920        let order_list = create_cancel_order_list_response_buffer();
2921
2922        let responses = if single {
2923            vec![decode_cancel_order_or_list(&order_list).unwrap()]
2924        } else {
2925            let buf = create_cancel_open_orders_buffer(&[order_list]);
2926            decode_cancel_open_orders(&buf).unwrap()
2927        };
2928
2929        let BinanceCancelOpenOrdersResponse::OrderList(response) = &responses[0] else {
2930            panic!("Expected order-list cancel response");
2931        };
2932        assert_eq!(response.order_list_id, 44);
2933        assert_eq!(response.symbol, "BTCUSDT");
2934        assert_eq!(response.list_client_order_id, "list-44");
2935        assert_eq!(response.orders.len(), 2);
2936        assert_eq!(response.orders[0].order_id, 111);
2937        assert_eq!(response.orders[0].client_order_id, "orig-1");
2938        assert_eq!(response.orders[1].order_id, 222);
2939        assert_eq!(response.orders[1].client_order_id, "orig-2");
2940        assert_eq!(response.order_reports.len(), 2);
2941        assert_eq!(response.order_reports[0].order_id, 111);
2942        assert_eq!(response.order_reports[0].order_list_id, Some(44));
2943        assert_eq!(response.order_reports[0].orig_client_order_id, "orig-1");
2944        assert_eq!(response.order_reports[1].order_id, 222);
2945        assert_eq!(response.order_reports[1].orig_client_order_id, "orig-2");
2946    }
2947
2948    #[rstest]
2949    fn test_decode_cancel_open_orders_mixed() {
2950        let order = create_cancel_order_response_buffer(333, "BTCUSDT", "orig-3", "new-3");
2951        let order_list = create_cancel_order_list_response_buffer();
2952        let buf = create_cancel_open_orders_buffer(&[order, order_list]);
2953
2954        let responses = decode_cancel_open_orders(&buf).unwrap();
2955
2956        assert!(matches!(
2957            responses[0],
2958            BinanceCancelOpenOrdersResponse::Order(_)
2959        ));
2960        assert!(matches!(
2961            responses[1],
2962            BinanceCancelOpenOrdersResponse::OrderList(_)
2963        ));
2964    }
2965
2966    #[rstest]
2967    fn test_decode_cancel_open_orders_unknown_embedded_template() {
2968        let unknown = create_header(0, 999, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION).to_vec();
2969        let buf = create_cancel_open_orders_buffer(&[unknown]);
2970
2971        let error = decode_cancel_open_orders(&buf).unwrap_err();
2972
2973        assert_eq!(error, SbeDecodeError::UnknownTemplateId(999));
2974    }
2975
2976    #[rstest]
2977    fn test_decode_cancel_open_orders_truncated_item() {
2978        let mut order_list = create_cancel_order_list_response_buffer();
2979        order_list.pop();
2980        let buf = create_cancel_open_orders_buffer(&[order_list]);
2981
2982        let error = decode_cancel_open_orders(&buf).unwrap_err();
2983
2984        assert!(matches!(error, SbeDecodeError::BufferTooShort { .. }));
2985    }
2986
2987    #[rstest]
2988    fn test_decode_cancel_open_orders_rejects_group_item_block() {
2989        let mut buf = create_cancel_open_orders_buffer(&[]);
2990        buf[8..10].copy_from_slice(&1u16.to_le_bytes());
2991
2992        let error = decode_cancel_open_orders(&buf).unwrap_err();
2993
2994        assert_eq!(
2995            error,
2996            SbeDecodeError::InvalidBlockLength {
2997                expected: 0,
2998                actual: 1,
2999            }
3000        );
3001    }
3002
3003    #[rstest]
3004    fn test_decode_cancel_open_orders_rejects_short_order_list_block() {
3005        let mut order_list = create_cancel_order_list_response_buffer();
3006        order_list[0..2].copy_from_slice(&20u16.to_le_bytes());
3007        let buf = create_cancel_open_orders_buffer(&[order_list]);
3008
3009        let error = decode_cancel_open_orders(&buf).unwrap_err();
3010
3011        assert_eq!(
3012            error,
3013            SbeDecodeError::InvalidBlockLength {
3014                expected: 21,
3015                actual: 20,
3016            }
3017        );
3018    }
3019
3020    #[rstest]
3021    fn test_decode_cancel_open_orders_rejects_short_order_block() {
3022        let mut order = create_cancel_order_response_buffer(111, "BTCUSDT", "orig-1", "new-1");
3023        order[0..2].copy_from_slice(&108u16.to_le_bytes());
3024        let buf = create_cancel_open_orders_buffer(&[order]);
3025
3026        let error = decode_cancel_open_orders(&buf).unwrap_err();
3027
3028        assert_eq!(
3029            error,
3030            SbeDecodeError::InvalidBlockLength {
3031                expected: 109,
3032                actual: 108,
3033            }
3034        );
3035    }
3036
3037    #[rstest]
3038    fn test_decode_cancel_open_orders_rejects_short_order_report_block() {
3039        let mut order_list = create_cancel_order_list_response_buffer();
3040        let report_header = order_list
3041            .windows(4)
3042            .position(|window| window == [135, 0, 2, 0])
3043            .unwrap();
3044        order_list[report_header..report_header + 2].copy_from_slice(&134u16.to_le_bytes());
3045        let buf = create_cancel_open_orders_buffer(&[order_list]);
3046
3047        let error = decode_cancel_open_orders(&buf).unwrap_err();
3048
3049        assert_eq!(
3050            error,
3051            SbeDecodeError::InvalidBlockLength {
3052                expected: 135,
3053                actual: 134,
3054            }
3055        );
3056    }
3057
3058    #[rstest]
3059    fn test_decode_cancel_open_orders_rejects_invalid_utf8() {
3060        let mut order_list = create_cancel_order_list_response_buffer();
3061        let symbol_start = order_list
3062            .windows(b"BTCUSDT".len())
3063            .position(|window| window == b"BTCUSDT")
3064            .unwrap();
3065        order_list[symbol_start] = 0xff;
3066        let buf = create_cancel_open_orders_buffer(&[order_list]);
3067
3068        let error = decode_cancel_open_orders(&buf).unwrap_err();
3069
3070        assert_eq!(error, SbeDecodeError::InvalidUtf8);
3071    }
3072
3073    fn create_cancel_order_response_buffer(
3074        order_id: i64,
3075        symbol: &str,
3076        orig_client_order_id: &str,
3077        client_order_id: &str,
3078    ) -> Vec<u8> {
3079        let mut bytes = vec![0u8; 256];
3080        let enc =
3081            CancelOrderResponseEncoder::default().wrap(WriteBuf::new(&mut bytes), HEADER_LENGTH);
3082        let mut header = enc.header(0);
3083        let mut enc = header.parent().unwrap();
3084        enc.price_exponent(-8);
3085        enc.qty_exponent(-8);
3086        enc.order_id(order_id);
3087        enc.order_list_id(i64::MIN);
3088        enc.transact_time(1_700_000_000_000_000);
3089        enc.price(100_000_000_000);
3090        enc.orig_qty(10_000_000);
3091        enc.executed_qty(10_000_000);
3092        enc.cummulative_quote_qty(1_000_000_000);
3093        enc.status(OrderStatus::Canceled);
3094        enc.time_in_force(TimeInForce::Gtc);
3095        enc.order_type(OrderType::Limit);
3096        enc.side(OrderSide::Buy);
3097        enc.stop_price(3);
3098        enc.self_trade_prevention_mode(SelfTradePreventionMode::ExpireTaker);
3099        enc.symbol(symbol);
3100        enc.orig_client_order_id(orig_client_order_id);
3101        enc.client_order_id(client_order_id);
3102        let len = HEADER_LENGTH + enc.encoded_length();
3103        bytes.truncate(len);
3104        bytes
3105    }
3106
3107    fn create_cancel_order_list_response_buffer() -> Vec<u8> {
3108        const REPORT_BLOCK_LENGTH: usize = 135;
3109
3110        let mut buf = Vec::new();
3111        buf.extend_from_slice(&create_header(
3112            CANCEL_ORDER_LIST_FIELDS_END as u16,
3113            CANCEL_ORDER_LIST_TEMPLATE_ID,
3114            SBE_SCHEMA_ID,
3115            SBE_SCHEMA_VERSION,
3116        ));
3117        buf.extend_from_slice(&44i64.to_le_bytes());
3118        buf.push(1); // contingency_type (OCO)
3119        buf.push(2); // list_status_type (ALL_DONE)
3120        buf.push(2); // list_order_status (ALL_DONE)
3121        buf.extend_from_slice(&1_700_000_000_000_000i64.to_le_bytes());
3122        buf.push((-8i8) as u8);
3123        buf.push((-8i8) as u8);
3124
3125        buf.extend_from_slice(&8u16.to_le_bytes());
3126        buf.extend_from_slice(&2u16.to_le_bytes());
3127        for (order_id, client_order_id) in [(111i64, "orig-1"), (222, "orig-2")] {
3128            buf.extend_from_slice(&order_id.to_le_bytes());
3129            write_var_string(&mut buf, "BTCUSDT");
3130            write_var_string(&mut buf, client_order_id);
3131        }
3132
3133        buf.extend_from_slice(&(REPORT_BLOCK_LENGTH as u16).to_le_bytes());
3134        buf.extend_from_slice(&2u16.to_le_bytes());
3135        for (order_id, orig_client_order_id) in [(111i64, "orig-1"), (222, "orig-2")] {
3136            let report_start = buf.len();
3137            buf.extend_from_slice(&order_id.to_le_bytes());
3138            buf.extend_from_slice(&44i64.to_le_bytes());
3139            buf.extend_from_slice(&1_700_000_000_000_000i64.to_le_bytes());
3140            buf.extend_from_slice(&100_000_000_000i64.to_le_bytes());
3141            buf.extend_from_slice(&10_000_000i64.to_le_bytes());
3142            buf.extend_from_slice(&0i64.to_le_bytes());
3143            buf.extend_from_slice(&0i64.to_le_bytes());
3144            buf.push(3); // status (CANCELED)
3145            buf.push(0); // time_in_force (GTC)
3146            buf.push(1); // order_type (LIMIT)
3147            buf.push(1); // side (SELL)
3148            while buf.len() - report_start < REPORT_BLOCK_LENGTH {
3149                buf.push(0);
3150            }
3151            write_var_string(&mut buf, "BTCUSDT");
3152            write_var_string(&mut buf, orig_client_order_id);
3153            write_var_string(&mut buf, "cancel-44");
3154        }
3155
3156        write_var_string(&mut buf, "list-44");
3157        write_var_string(&mut buf, "BTCUSDT");
3158        buf
3159    }
3160
3161    fn create_cancel_open_orders_buffer(responses: &[Vec<u8>]) -> Vec<u8> {
3162        let mut buf = Vec::new();
3163        buf.extend_from_slice(&create_header(
3164            0,
3165            CANCEL_OPEN_ORDERS_TEMPLATE_ID,
3166            SBE_SCHEMA_ID,
3167            SBE_SCHEMA_VERSION,
3168        ));
3169        buf.extend_from_slice(&create_group_header(0, responses.len() as u32));
3170        for response in responses {
3171            buf.extend_from_slice(&(response.len() as u16).to_le_bytes());
3172            buf.extend_from_slice(response);
3173        }
3174        buf
3175    }
3176}