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