market-maker-rs 0.2.0

A Rust library implementing quantitative market making strategies, starting with the Avellaneda-Stoikov model
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
//! Exchange connector trait and core types.
//!
//! This module defines the abstract interface for exchange connectivity,
//! including order submission, cancellation, and market data retrieval.
//!
//! # Design
//!
//! The `ExchangeConnector` trait provides a unified interface for:
//! - Order lifecycle management (submit, cancel, modify)
//! - Order status queries
//! - Market data retrieval (order book snapshots)
//! - Account balance queries
//!
//! The `MarketDataStream` trait handles real-time data subscriptions.
//!
//! # Example
//!
//! ```rust
//! use market_maker_rs::execution::{
//!     OrderRequest, Side, OrderType, TimeInForce
//! };
//! use market_maker_rs::dec;
//!
//! let request = OrderRequest::new(
//!     "BTC-USD",
//!     Side::Buy,
//!     OrderType::Limit,
//!     Some(dec!(50000.0)),
//!     dec!(0.1),
//! );
//!
//! assert_eq!(request.symbol, "BTC-USD");
//! assert_eq!(request.side, Side::Buy);
//! ```

use async_trait::async_trait;
use std::fmt;

use crate::Decimal;
use crate::types::error::MMResult;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Unique identifier for an order.
///
/// Wraps a string identifier that uniquely identifies an order on the exchange.
///
/// # Example
///
/// ```rust
/// use market_maker_rs::execution::OrderId;
///
/// let order_id = OrderId::new("12345");
/// assert_eq!(order_id.as_str(), "12345");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct OrderId(String);

impl OrderId {
    /// Creates a new order ID.
    #[must_use]
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// Returns the order ID as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the OrderId and returns the inner String.
    #[must_use]
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl fmt::Display for OrderId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<String> for OrderId {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for OrderId {
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

/// Order side (buy or sell).
///
/// # Example
///
/// ```rust
/// use market_maker_rs::execution::Side;
///
/// let side = Side::Buy;
/// assert!(side.is_buy());
/// assert!(!side.is_sell());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Side {
    /// Buy order (bid).
    Buy,
    /// Sell order (ask).
    Sell,
}

impl Side {
    /// Returns true if this is a buy order.
    #[must_use]
    pub fn is_buy(&self) -> bool {
        matches!(self, Side::Buy)
    }

    /// Returns true if this is a sell order.
    #[must_use]
    pub fn is_sell(&self) -> bool {
        matches!(self, Side::Sell)
    }

    /// Returns the opposite side.
    #[must_use]
    pub fn opposite(&self) -> Self {
        match self {
            Side::Buy => Side::Sell,
            Side::Sell => Side::Buy,
        }
    }
}

impl fmt::Display for Side {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Side::Buy => write!(f, "Buy"),
            Side::Sell => write!(f, "Sell"),
        }
    }
}

/// Order type.
///
/// # Example
///
/// ```rust
/// use market_maker_rs::execution::OrderType;
///
/// let order_type = OrderType::Limit;
/// assert!(order_type.requires_price());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum OrderType {
    /// Limit order - executes at specified price or better.
    Limit,
    /// Market order - executes immediately at best available price.
    Market,
    /// Post-only order - only adds liquidity, rejected if would take.
    PostOnly,
}

impl OrderType {
    /// Returns true if this order type requires a price.
    #[must_use]
    pub fn requires_price(&self) -> bool {
        matches!(self, OrderType::Limit | OrderType::PostOnly)
    }

    /// Returns true if this is a market order.
    #[must_use]
    pub fn is_market(&self) -> bool {
        matches!(self, OrderType::Market)
    }
}

impl fmt::Display for OrderType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            OrderType::Limit => write!(f, "Limit"),
            OrderType::Market => write!(f, "Market"),
            OrderType::PostOnly => write!(f, "PostOnly"),
        }
    }
}

/// Time in force - how long an order remains active.
///
/// # Example
///
/// ```rust
/// use market_maker_rs::execution::TimeInForce;
///
/// let tif = TimeInForce::GoodTilCancel;
/// assert!(!tif.is_immediate());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Default)]
pub enum TimeInForce {
    /// Good til cancel - remains active until filled or cancelled.
    #[default]
    GoodTilCancel,
    /// Immediate or cancel - fills immediately, cancels unfilled portion.
    ImmediateOrCancel,
    /// Fill or kill - must fill entirely immediately or cancel.
    FillOrKill,
    /// Good til time - remains active until specified timestamp (milliseconds).
    GoodTilTime(u64),
}

impl TimeInForce {
    /// Returns true if this time in force requires immediate execution.
    #[must_use]
    pub fn is_immediate(&self) -> bool {
        matches!(
            self,
            TimeInForce::ImmediateOrCancel | TimeInForce::FillOrKill
        )
    }
}

impl fmt::Display for TimeInForce {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TimeInForce::GoodTilCancel => write!(f, "GTC"),
            TimeInForce::ImmediateOrCancel => write!(f, "IOC"),
            TimeInForce::FillOrKill => write!(f, "FOK"),
            TimeInForce::GoodTilTime(ts) => write!(f, "GTT({})", ts),
        }
    }
}

/// Order status with associated data.
///
/// # Example
///
/// ```rust
/// use market_maker_rs::execution::OrderStatus;
/// use market_maker_rs::dec;
///
/// let status = OrderStatus::Open { filled_qty: dec!(0.0) };
/// assert!(status.is_open());
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum OrderStatus {
    /// Order is pending submission.
    Pending,
    /// Order is open on the book.
    Open {
        /// Quantity filled so far.
        filled_qty: Decimal,
    },
    /// Order is partially filled.
    PartiallyFilled {
        /// Quantity filled so far.
        filled_qty: Decimal,
        /// Remaining quantity.
        remaining_qty: Decimal,
    },
    /// Order is completely filled.
    Filled {
        /// Total quantity filled.
        filled_qty: Decimal,
        /// Average fill price.
        avg_price: Decimal,
    },
    /// Order was cancelled.
    Cancelled {
        /// Quantity filled before cancellation.
        filled_qty: Decimal,
    },
    /// Order was rejected.
    Rejected {
        /// Rejection reason.
        reason: String,
    },
}

impl OrderStatus {
    /// Returns true if the order is still active (pending, open, or partially filled).
    #[must_use]
    pub fn is_active(&self) -> bool {
        matches!(
            self,
            OrderStatus::Pending | OrderStatus::Open { .. } | OrderStatus::PartiallyFilled { .. }
        )
    }

    /// Returns true if the order is open on the book.
    #[must_use]
    pub fn is_open(&self) -> bool {
        matches!(
            self,
            OrderStatus::Open { .. } | OrderStatus::PartiallyFilled { .. }
        )
    }

    /// Returns true if the order is terminal (filled, cancelled, or rejected).
    #[must_use]
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            OrderStatus::Filled { .. }
                | OrderStatus::Cancelled { .. }
                | OrderStatus::Rejected { .. }
        )
    }

    /// Returns the filled quantity, if any.
    #[must_use]
    pub fn filled_qty(&self) -> Decimal {
        match self {
            OrderStatus::Pending => Decimal::ZERO,
            OrderStatus::Open { filled_qty } => *filled_qty,
            OrderStatus::PartiallyFilled { filled_qty, .. } => *filled_qty,
            OrderStatus::Filled { filled_qty, .. } => *filled_qty,
            OrderStatus::Cancelled { filled_qty } => *filled_qty,
            OrderStatus::Rejected { .. } => Decimal::ZERO,
        }
    }
}

impl fmt::Display for OrderStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            OrderStatus::Pending => write!(f, "Pending"),
            OrderStatus::Open { filled_qty } => write!(f, "Open(filled={})", filled_qty),
            OrderStatus::PartiallyFilled {
                filled_qty,
                remaining_qty,
            } => write!(
                f,
                "PartiallyFilled(filled={}, remaining={})",
                filled_qty, remaining_qty
            ),
            OrderStatus::Filled {
                filled_qty,
                avg_price,
            } => {
                write!(f, "Filled(qty={}, avg_price={})", filled_qty, avg_price)
            }
            OrderStatus::Cancelled { filled_qty } => write!(f, "Cancelled(filled={})", filled_qty),
            OrderStatus::Rejected { reason } => write!(f, "Rejected({})", reason),
        }
    }
}

/// Order request for submission to an exchange.
///
/// # Example
///
/// ```rust
/// use market_maker_rs::execution::{OrderRequest, Side, OrderType, TimeInForce};
/// use market_maker_rs::dec;
///
/// let request = OrderRequest::new(
///     "BTC-USD",
///     Side::Buy,
///     OrderType::Limit,
///     Some(dec!(50000.0)),
///     dec!(0.1),
/// );
///
/// assert_eq!(request.symbol, "BTC-USD");
/// assert_eq!(request.quantity, dec!(0.1));
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct OrderRequest {
    /// Trading symbol (e.g., "BTC-USD").
    pub symbol: String,
    /// Order side (buy or sell).
    pub side: Side,
    /// Order type (limit, market, post-only).
    pub order_type: OrderType,
    /// Limit price (required for limit and post-only orders).
    pub price: Option<Decimal>,
    /// Order quantity in base currency.
    pub quantity: Decimal,
    /// Time in force.
    pub time_in_force: TimeInForce,
    /// Client-assigned order ID for tracking.
    pub client_order_id: Option<String>,
}

impl OrderRequest {
    /// Creates a new order request.
    ///
    /// # Arguments
    ///
    /// * `symbol` - Trading symbol
    /// * `side` - Order side
    /// * `order_type` - Order type
    /// * `price` - Limit price (None for market orders)
    /// * `quantity` - Order quantity
    #[must_use]
    pub fn new(
        symbol: impl Into<String>,
        side: Side,
        order_type: OrderType,
        price: Option<Decimal>,
        quantity: Decimal,
    ) -> Self {
        Self {
            symbol: symbol.into(),
            side,
            order_type,
            price,
            quantity,
            time_in_force: TimeInForce::default(),
            client_order_id: None,
        }
    }

    /// Creates a limit buy order.
    #[must_use]
    pub fn limit_buy(symbol: impl Into<String>, price: Decimal, quantity: Decimal) -> Self {
        Self::new(symbol, Side::Buy, OrderType::Limit, Some(price), quantity)
    }

    /// Creates a limit sell order.
    #[must_use]
    pub fn limit_sell(symbol: impl Into<String>, price: Decimal, quantity: Decimal) -> Self {
        Self::new(symbol, Side::Sell, OrderType::Limit, Some(price), quantity)
    }

    /// Creates a market buy order.
    #[must_use]
    pub fn market_buy(symbol: impl Into<String>, quantity: Decimal) -> Self {
        Self::new(symbol, Side::Buy, OrderType::Market, None, quantity)
    }

    /// Creates a market sell order.
    #[must_use]
    pub fn market_sell(symbol: impl Into<String>, quantity: Decimal) -> Self {
        Self::new(symbol, Side::Sell, OrderType::Market, None, quantity)
    }

    /// Sets the time in force.
    #[must_use]
    pub fn with_time_in_force(mut self, tif: TimeInForce) -> Self {
        self.time_in_force = tif;
        self
    }

    /// Sets the client order ID.
    #[must_use]
    pub fn with_client_order_id(mut self, id: impl Into<String>) -> Self {
        self.client_order_id = Some(id.into());
        self
    }

    /// Returns the notional value of the order (price * quantity).
    /// Returns None for market orders without a price.
    #[must_use]
    pub fn notional(&self) -> Option<Decimal> {
        self.price.map(|p| p * self.quantity)
    }
}

/// Order response from an exchange.
///
/// # Example
///
/// ```rust
/// use market_maker_rs::execution::{OrderResponse, OrderId, OrderStatus};
/// use market_maker_rs::dec;
///
/// let response = OrderResponse {
///     order_id: OrderId::new("12345"),
///     client_order_id: Some("my-order-1".to_string()),
///     status: OrderStatus::Open { filled_qty: dec!(0.0) },
///     timestamp: 1234567890,
/// };
///
/// assert!(response.status.is_open());
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct OrderResponse {
    /// Exchange-assigned order ID.
    pub order_id: OrderId,
    /// Client-assigned order ID (if provided).
    pub client_order_id: Option<String>,
    /// Current order status.
    pub status: OrderStatus,
    /// Timestamp of the response in milliseconds.
    pub timestamp: u64,
}

impl OrderResponse {
    /// Creates a new order response.
    #[must_use]
    pub fn new(order_id: OrderId, status: OrderStatus, timestamp: u64) -> Self {
        Self {
            order_id,
            client_order_id: None,
            status,
            timestamp,
        }
    }

    /// Sets the client order ID.
    #[must_use]
    pub fn with_client_order_id(mut self, id: impl Into<String>) -> Self {
        self.client_order_id = Some(id.into());
        self
    }
}

/// Trade/fill information.
///
/// Represents a single execution (fill) of an order.
///
/// # Example
///
/// ```rust
/// use market_maker_rs::execution::{Fill, OrderId, Side};
/// use market_maker_rs::dec;
///
/// let fill = Fill {
///     order_id: OrderId::new("12345"),
///     trade_id: "trade-1".to_string(),
///     price: dec!(50000.0),
///     quantity: dec!(0.1),
///     side: Side::Buy,
///     timestamp: 1234567890,
///     fee: dec!(0.5),
///     fee_currency: "USD".to_string(),
/// };
///
/// assert_eq!(fill.notional(), dec!(5000.0));
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Fill {
    /// Order ID that was filled.
    pub order_id: OrderId,
    /// Unique trade/execution ID.
    pub trade_id: String,
    /// Fill price.
    pub price: Decimal,
    /// Fill quantity.
    pub quantity: Decimal,
    /// Fill side.
    pub side: Side,
    /// Fill timestamp in milliseconds.
    pub timestamp: u64,
    /// Fee amount.
    pub fee: Decimal,
    /// Fee currency.
    pub fee_currency: String,
}

impl Fill {
    /// Returns the notional value of the fill (price * quantity).
    #[must_use]
    pub fn notional(&self) -> Decimal {
        self.price * self.quantity
    }

    /// Returns the net value after fees.
    /// For buys: notional + fee (cost)
    /// For sells: notional - fee (proceeds)
    #[must_use]
    pub fn net_value(&self) -> Decimal {
        match self.side {
            Side::Buy => self.notional() + self.fee,
            Side::Sell => self.notional() - self.fee,
        }
    }
}

/// Order book price level.
///
/// # Example
///
/// ```rust
/// use market_maker_rs::execution::BookLevel;
/// use market_maker_rs::dec;
///
/// let level = BookLevel::new(dec!(50000.0), dec!(1.5));
/// assert_eq!(level.notional(), dec!(75000.0));
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BookLevel {
    /// Price at this level.
    pub price: Decimal,
    /// Total quantity at this level.
    pub quantity: Decimal,
}

impl BookLevel {
    /// Creates a new book level.
    #[must_use]
    pub fn new(price: Decimal, quantity: Decimal) -> Self {
        Self { price, quantity }
    }

    /// Returns the notional value at this level (price * quantity).
    #[must_use]
    pub fn notional(&self) -> Decimal {
        self.price * self.quantity
    }
}

/// Order book snapshot.
///
/// Contains the current state of the order book for a symbol.
///
/// # Example
///
/// ```rust
/// use market_maker_rs::execution::{OrderBookSnapshot, BookLevel};
/// use market_maker_rs::dec;
///
/// let snapshot = OrderBookSnapshot {
///     symbol: "BTC-USD".to_string(),
///     bids: vec![
///         BookLevel::new(dec!(49990.0), dec!(1.0)),
///         BookLevel::new(dec!(49980.0), dec!(2.0)),
///     ],
///     asks: vec![
///         BookLevel::new(dec!(50010.0), dec!(1.0)),
///         BookLevel::new(dec!(50020.0), dec!(2.0)),
///     ],
///     timestamp: 1234567890,
/// };
///
/// assert_eq!(snapshot.spread(), Some(dec!(20.0)));
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct OrderBookSnapshot {
    /// Trading symbol.
    pub symbol: String,
    /// Bid levels (sorted by price descending).
    pub bids: Vec<BookLevel>,
    /// Ask levels (sorted by price ascending).
    pub asks: Vec<BookLevel>,
    /// Snapshot timestamp in milliseconds.
    pub timestamp: u64,
}

impl OrderBookSnapshot {
    /// Creates a new empty order book snapshot.
    #[must_use]
    pub fn new(symbol: impl Into<String>, timestamp: u64) -> Self {
        Self {
            symbol: symbol.into(),
            bids: Vec::new(),
            asks: Vec::new(),
            timestamp,
        }
    }

    /// Returns the best bid price.
    #[must_use]
    pub fn best_bid(&self) -> Option<Decimal> {
        self.bids.first().map(|l| l.price)
    }

    /// Returns the best ask price.
    #[must_use]
    pub fn best_ask(&self) -> Option<Decimal> {
        self.asks.first().map(|l| l.price)
    }

    /// Returns the mid price.
    #[must_use]
    pub fn mid_price(&self) -> Option<Decimal> {
        match (self.best_bid(), self.best_ask()) {
            (Some(bid), Some(ask)) => Some((bid + ask) / Decimal::from(2)),
            _ => None,
        }
    }

    /// Returns the spread (best ask - best bid).
    #[must_use]
    pub fn spread(&self) -> Option<Decimal> {
        match (self.best_bid(), self.best_ask()) {
            (Some(bid), Some(ask)) => Some(ask - bid),
            _ => None,
        }
    }

    /// Returns the spread as a percentage of mid price.
    #[must_use]
    pub fn spread_bps(&self) -> Option<Decimal> {
        match (self.spread(), self.mid_price()) {
            (Some(spread), Some(mid)) if mid > Decimal::ZERO => {
                Some(spread / mid * Decimal::from(10000))
            }
            _ => None,
        }
    }

    /// Returns total bid depth (sum of all bid quantities).
    #[must_use]
    pub fn bid_depth(&self) -> Decimal {
        self.bids.iter().map(|l| l.quantity).sum()
    }

    /// Returns total ask depth (sum of all ask quantities).
    #[must_use]
    pub fn ask_depth(&self) -> Decimal {
        self.asks.iter().map(|l| l.quantity).sum()
    }

    /// Returns the imbalance ratio: (bid_depth - ask_depth) / (bid_depth + ask_depth).
    #[must_use]
    pub fn imbalance(&self) -> Decimal {
        let bid_depth = self.bid_depth();
        let ask_depth = self.ask_depth();
        let total = bid_depth + ask_depth;
        if total > Decimal::ZERO {
            (bid_depth - ask_depth) / total
        } else {
            Decimal::ZERO
        }
    }
}

/// Exchange connector trait for order management.
///
/// This trait defines the interface for interacting with an exchange,
/// including order submission, cancellation, and status queries.
///
/// # Implementation Notes
///
/// - All methods are async and return `MMResult<T>`
/// - Implementations should be `Send + Sync` for use with async runtimes
/// - Consider implementing retry logic for transient failures
#[async_trait]
pub trait ExchangeConnector: Send + Sync {
    /// Submits a new order to the exchange.
    ///
    /// # Arguments
    ///
    /// * `request` - The order request to submit
    ///
    /// # Returns
    ///
    /// The order response with the assigned order ID and initial status.
    async fn submit_order(&self, request: OrderRequest) -> MMResult<OrderResponse>;

    /// Cancels an existing order.
    ///
    /// # Arguments
    ///
    /// * `order_id` - The ID of the order to cancel
    ///
    /// # Returns
    ///
    /// The order response with the final status.
    async fn cancel_order(&self, order_id: &OrderId) -> MMResult<OrderResponse>;

    /// Modifies an existing order (cancel and replace).
    ///
    /// # Arguments
    ///
    /// * `order_id` - The ID of the order to modify
    /// * `new_price` - New price (None to keep current)
    /// * `new_quantity` - New quantity (None to keep current)
    ///
    /// # Returns
    ///
    /// The order response for the new order.
    async fn modify_order(
        &self,
        order_id: &OrderId,
        new_price: Option<Decimal>,
        new_quantity: Option<Decimal>,
    ) -> MMResult<OrderResponse>;

    /// Gets the current status of an order.
    ///
    /// # Arguments
    ///
    /// * `order_id` - The ID of the order to query
    ///
    /// # Returns
    ///
    /// The current order response.
    async fn get_order_status(&self, order_id: &OrderId) -> MMResult<OrderResponse>;

    /// Gets all open orders for a symbol.
    ///
    /// # Arguments
    ///
    /// * `symbol` - The trading symbol
    ///
    /// # Returns
    ///
    /// A list of all open orders.
    async fn get_open_orders(&self, symbol: &str) -> MMResult<Vec<OrderResponse>>;

    /// Cancels all open orders for a symbol.
    ///
    /// # Arguments
    ///
    /// * `symbol` - The trading symbol
    ///
    /// # Returns
    ///
    /// A list of cancelled order responses.
    async fn cancel_all_orders(&self, symbol: &str) -> MMResult<Vec<OrderResponse>>;

    /// Gets the current order book snapshot.
    ///
    /// # Arguments
    ///
    /// * `symbol` - The trading symbol
    /// * `depth` - Number of levels to retrieve
    ///
    /// # Returns
    ///
    /// The order book snapshot.
    async fn get_orderbook(&self, symbol: &str, depth: usize) -> MMResult<OrderBookSnapshot>;

    /// Gets the account balance for an asset.
    ///
    /// # Arguments
    ///
    /// * `asset` - The asset symbol (e.g., "BTC", "USD")
    ///
    /// # Returns
    ///
    /// The available balance.
    async fn get_balance(&self, asset: &str) -> MMResult<Decimal>;
}

/// Market data stream trait for real-time data.
///
/// This trait defines the interface for subscribing to and receiving
/// real-time market data updates.
#[async_trait]
pub trait MarketDataStream: Send + Sync {
    /// Subscribes to order book updates for a symbol.
    ///
    /// # Arguments
    ///
    /// * `symbol` - The trading symbol
    async fn subscribe_orderbook(&self, symbol: &str) -> MMResult<()>;

    /// Subscribes to trade stream for a symbol.
    ///
    /// # Arguments
    ///
    /// * `symbol` - The trading symbol
    async fn subscribe_trades(&self, symbol: &str) -> MMResult<()>;

    /// Gets the next order book update (blocking).
    ///
    /// # Returns
    ///
    /// The next order book snapshot.
    async fn next_orderbook_update(&self) -> MMResult<OrderBookSnapshot>;

    /// Gets the next trade (blocking).
    ///
    /// # Returns
    ///
    /// The next fill/trade.
    async fn next_trade(&self) -> MMResult<Fill>;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dec;

    #[test]
    fn test_order_id() {
        let id = OrderId::new("12345");
        assert_eq!(id.as_str(), "12345");
        assert_eq!(id.to_string(), "12345");

        let id2: OrderId = "67890".into();
        assert_eq!(id2.as_str(), "67890");
    }

    #[test]
    fn test_side() {
        assert!(Side::Buy.is_buy());
        assert!(!Side::Buy.is_sell());
        assert!(Side::Sell.is_sell());
        assert!(!Side::Sell.is_buy());
        assert_eq!(Side::Buy.opposite(), Side::Sell);
        assert_eq!(Side::Sell.opposite(), Side::Buy);
    }

    #[test]
    fn test_order_type() {
        assert!(OrderType::Limit.requires_price());
        assert!(OrderType::PostOnly.requires_price());
        assert!(!OrderType::Market.requires_price());
        assert!(OrderType::Market.is_market());
    }

    #[test]
    fn test_time_in_force() {
        assert!(!TimeInForce::GoodTilCancel.is_immediate());
        assert!(TimeInForce::ImmediateOrCancel.is_immediate());
        assert!(TimeInForce::FillOrKill.is_immediate());
        assert!(!TimeInForce::GoodTilTime(1000).is_immediate());
    }

    #[test]
    fn test_order_status() {
        let pending = OrderStatus::Pending;
        assert!(pending.is_active());
        assert!(!pending.is_open());
        assert!(!pending.is_terminal());
        assert_eq!(pending.filled_qty(), Decimal::ZERO);

        let open = OrderStatus::Open {
            filled_qty: dec!(0.5),
        };
        assert!(open.is_active());
        assert!(open.is_open());
        assert!(!open.is_terminal());
        assert_eq!(open.filled_qty(), dec!(0.5));

        let filled = OrderStatus::Filled {
            filled_qty: dec!(1.0),
            avg_price: dec!(100.0),
        };
        assert!(!filled.is_active());
        assert!(!filled.is_open());
        assert!(filled.is_terminal());
        assert_eq!(filled.filled_qty(), dec!(1.0));

        let rejected = OrderStatus::Rejected {
            reason: "test".to_string(),
        };
        assert!(rejected.is_terminal());
        assert_eq!(rejected.filled_qty(), Decimal::ZERO);
    }

    #[test]
    fn test_order_request() {
        let request = OrderRequest::new(
            "BTC-USD",
            Side::Buy,
            OrderType::Limit,
            Some(dec!(50000.0)),
            dec!(0.1),
        );

        assert_eq!(request.symbol, "BTC-USD");
        assert_eq!(request.side, Side::Buy);
        assert_eq!(request.order_type, OrderType::Limit);
        assert_eq!(request.price, Some(dec!(50000.0)));
        assert_eq!(request.quantity, dec!(0.1));
        assert_eq!(request.notional(), Some(dec!(5000.0)));
    }

    #[test]
    fn test_order_request_builders() {
        let buy = OrderRequest::limit_buy("BTC-USD", dec!(50000.0), dec!(0.1));
        assert_eq!(buy.side, Side::Buy);
        assert_eq!(buy.order_type, OrderType::Limit);

        let sell = OrderRequest::limit_sell("BTC-USD", dec!(51000.0), dec!(0.1));
        assert_eq!(sell.side, Side::Sell);

        let market_buy = OrderRequest::market_buy("BTC-USD", dec!(0.1));
        assert_eq!(market_buy.order_type, OrderType::Market);
        assert_eq!(market_buy.price, None);
        assert_eq!(market_buy.notional(), None);
    }

    #[test]
    fn test_fill() {
        let fill = Fill {
            order_id: OrderId::new("12345"),
            trade_id: "trade-1".to_string(),
            price: dec!(50000.0),
            quantity: dec!(0.1),
            side: Side::Buy,
            timestamp: 1000,
            fee: dec!(0.5),
            fee_currency: "USD".to_string(),
        };

        assert_eq!(fill.notional(), dec!(5000.0));
        assert_eq!(fill.net_value(), dec!(5000.5)); // Buy: notional + fee

        let sell_fill = Fill {
            side: Side::Sell,
            ..fill.clone()
        };
        assert_eq!(sell_fill.net_value(), dec!(4999.5)); // Sell: notional - fee
    }

    #[test]
    fn test_book_level() {
        let level = BookLevel::new(dec!(50000.0), dec!(1.5));
        assert_eq!(level.notional(), dec!(75000.0));
    }

    #[test]
    fn test_order_book_snapshot() {
        let snapshot = OrderBookSnapshot {
            symbol: "BTC-USD".to_string(),
            bids: vec![
                BookLevel::new(dec!(49990.0), dec!(1.0)),
                BookLevel::new(dec!(49980.0), dec!(2.0)),
            ],
            asks: vec![
                BookLevel::new(dec!(50010.0), dec!(1.0)),
                BookLevel::new(dec!(50020.0), dec!(2.0)),
            ],
            timestamp: 1000,
        };

        assert_eq!(snapshot.best_bid(), Some(dec!(49990.0)));
        assert_eq!(snapshot.best_ask(), Some(dec!(50010.0)));
        assert_eq!(snapshot.mid_price(), Some(dec!(50000.0)));
        assert_eq!(snapshot.spread(), Some(dec!(20.0)));
        assert_eq!(snapshot.bid_depth(), dec!(3.0));
        assert_eq!(snapshot.ask_depth(), dec!(3.0));
        assert_eq!(snapshot.imbalance(), Decimal::ZERO);
    }

    #[test]
    fn test_order_book_imbalance() {
        let snapshot = OrderBookSnapshot {
            symbol: "BTC-USD".to_string(),
            bids: vec![BookLevel::new(dec!(100.0), dec!(3.0))],
            asks: vec![BookLevel::new(dec!(101.0), dec!(1.0))],
            timestamp: 1000,
        };

        // (3 - 1) / (3 + 1) = 0.5
        assert_eq!(snapshot.imbalance(), dec!(0.5));
    }

    #[test]
    fn test_empty_order_book() {
        let snapshot = OrderBookSnapshot::new("BTC-USD", 1000);

        assert_eq!(snapshot.best_bid(), None);
        assert_eq!(snapshot.best_ask(), None);
        assert_eq!(snapshot.mid_price(), None);
        assert_eq!(snapshot.spread(), None);
        assert_eq!(snapshot.imbalance(), Decimal::ZERO);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serialization() {
        let request = OrderRequest::limit_buy("BTC-USD", dec!(50000.0), dec!(0.1));
        let json = serde_json::to_string(&request).unwrap();
        let deserialized: OrderRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(request, deserialized);
    }
}