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
//! Order flow imbalance analysis.
//!
//! This module provides tools to analyze order flow and detect directional
//! pressure in the market. Order flow analysis helps market makers understand
//! the balance between buying and selling pressure.
//!
//! # Key Metrics
//!
//! - **Buy/Sell Volume**: Aggregate volume by trade direction
//! - **Order Flow Imbalance (OFI)**: Net buying vs selling pressure
//! - **Volume-Weighted Average Price (VWAP)**: By side
//! - **Trade Intensity**: Trades per unit time
//!
//! # Example
//!
//! ```rust
//! use market_maker_rs::analytics::order_flow::{OrderFlowAnalyzer, Trade, TradeSide};
//! use market_maker_rs::dec;
//!
//! let mut analyzer = OrderFlowAnalyzer::new(5000); // 5 second window
//!
//! // Add some trades
//! analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 1000));
//! analyzer.add_trade(Trade::new(dec!(100.1), dec!(5.0), TradeSide::Sell, 2000));
//! analyzer.add_trade(Trade::new(dec!(100.2), dec!(8.0), TradeSide::Buy, 3000));
//!
//! let stats = analyzer.get_stats(4000);
//! assert!(stats.imbalance > dec!(0.0)); // More buying pressure
//! ```

use std::collections::VecDeque;

use crate::Decimal;
use crate::types::error::{MMError, MMResult};

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

/// Trade side classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum TradeSide {
    /// Buyer-initiated trade (market buy).
    Buy,
    /// Seller-initiated trade (market sell).
    Sell,
}

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

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

/// A single trade record for order flow analysis.
///
/// # Example
///
/// ```rust
/// use market_maker_rs::analytics::order_flow::{Trade, TradeSide};
/// use market_maker_rs::dec;
///
/// let trade = Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 1234567890);
/// assert_eq!(trade.notional(), dec!(1000.0));
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Trade {
    /// Trade execution price.
    pub price: Decimal,
    /// Trade size in base units.
    pub size: Decimal,
    /// Trade side (buy or sell).
    pub side: TradeSide,
    /// Trade timestamp in milliseconds.
    pub timestamp: u64,
}

impl Trade {
    /// Creates a new trade record.
    ///
    /// # Arguments
    ///
    /// * `price` - Trade execution price
    /// * `size` - Trade size in base units
    /// * `side` - Trade side (buy or sell)
    /// * `timestamp` - Trade timestamp in milliseconds
    #[must_use]
    pub fn new(price: Decimal, size: Decimal, side: TradeSide, timestamp: u64) -> Self {
        Self {
            price,
            size,
            side,
            timestamp,
        }
    }

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

    /// Returns true if this is a buy trade.
    #[must_use]
    pub fn is_buy(&self) -> bool {
        self.side.is_buy()
    }

    /// Returns true if this is a sell trade.
    #[must_use]
    pub fn is_sell(&self) -> bool {
        self.side.is_sell()
    }
}

/// Order flow statistics for a time window.
///
/// Contains comprehensive metrics about trading activity including
/// volume, trade counts, imbalance, and VWAP by side.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct OrderFlowStats {
    /// Total buy volume in the window.
    pub buy_volume: Decimal,

    /// Total sell volume in the window.
    pub sell_volume: Decimal,

    /// Number of buy trades in the window.
    pub buy_count: u64,

    /// Number of sell trades in the window.
    pub sell_count: u64,

    /// Order flow imbalance: (buy - sell) / (buy + sell).
    /// Range: -1.0 (all sells) to +1.0 (all buys).
    pub imbalance: Decimal,

    /// Net flow: buy_volume - sell_volume.
    pub net_flow: Decimal,

    /// Volume-weighted average price for buy trades.
    /// None if no buy trades in window.
    pub buy_vwap: Option<Decimal>,

    /// Volume-weighted average price for sell trades.
    /// None if no sell trades in window.
    pub sell_vwap: Option<Decimal>,

    /// Total notional traded (buy + sell).
    pub total_notional: Decimal,

    /// Window start timestamp in milliseconds.
    pub window_start: u64,

    /// Window end timestamp in milliseconds.
    pub window_end: u64,
}

impl OrderFlowStats {
    /// Returns the total volume (buy + sell).
    #[must_use]
    pub fn total_volume(&self) -> Decimal {
        self.buy_volume + self.sell_volume
    }

    /// Returns the total trade count.
    #[must_use]
    pub fn total_count(&self) -> u64 {
        self.buy_count + self.sell_count
    }

    /// Returns true if flow is bullish (positive imbalance).
    #[must_use]
    pub fn is_bullish(&self) -> bool {
        self.imbalance > Decimal::ZERO
    }

    /// Returns true if flow is bearish (negative imbalance).
    #[must_use]
    pub fn is_bearish(&self) -> bool {
        self.imbalance < Decimal::ZERO
    }

    /// Returns the buy/sell volume ratio.
    /// Returns None if sell_volume is zero.
    #[must_use]
    pub fn volume_ratio(&self) -> Option<Decimal> {
        if self.sell_volume > Decimal::ZERO {
            Some(self.buy_volume / self.sell_volume)
        } else {
            None
        }
    }

    /// Returns the window duration in milliseconds.
    #[must_use]
    pub fn window_duration_ms(&self) -> u64 {
        self.window_end.saturating_sub(self.window_start)
    }
}

impl Default for OrderFlowStats {
    fn default() -> Self {
        Self {
            buy_volume: Decimal::ZERO,
            sell_volume: Decimal::ZERO,
            buy_count: 0,
            sell_count: 0,
            imbalance: Decimal::ZERO,
            net_flow: Decimal::ZERO,
            buy_vwap: None,
            sell_vwap: None,
            total_notional: Decimal::ZERO,
            window_start: 0,
            window_end: 0,
        }
    }
}

/// Order flow analyzer with rolling window.
///
/// Tracks trades in a rolling time window and calculates order flow
/// statistics including volume, imbalance, and VWAP.
///
/// # Example
///
/// ```rust
/// use market_maker_rs::analytics::order_flow::{OrderFlowAnalyzer, Trade, TradeSide};
/// use market_maker_rs::dec;
///
/// let mut analyzer = OrderFlowAnalyzer::new(5000); // 5 second window
///
/// analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 1000));
/// analyzer.add_trade(Trade::new(dec!(99.5), dec!(15.0), TradeSide::Sell, 2000));
///
/// let stats = analyzer.get_stats(3000);
/// println!("Imbalance: {}", stats.imbalance);
/// println!("Net flow: {}", stats.net_flow);
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct OrderFlowAnalyzer {
    /// Rolling window duration in milliseconds.
    window_ms: u64,
    /// Trade buffer using VecDeque for efficient front removal.
    trades: VecDeque<Trade>,
    /// Maximum number of trades to keep (memory management).
    max_trades: usize,
}

impl OrderFlowAnalyzer {
    /// Default maximum number of trades to keep.
    pub const DEFAULT_MAX_TRADES: usize = 10_000;

    /// Creates a new `OrderFlowAnalyzer` with the specified window duration.
    ///
    /// # Arguments
    ///
    /// * `window_ms` - Rolling window duration in milliseconds
    ///
    /// # Example
    ///
    /// ```rust
    /// use market_maker_rs::analytics::order_flow::OrderFlowAnalyzer;
    ///
    /// let analyzer = OrderFlowAnalyzer::new(5000); // 5 second window
    /// ```
    #[must_use]
    pub fn new(window_ms: u64) -> Self {
        Self {
            window_ms,
            trades: VecDeque::new(),
            max_trades: Self::DEFAULT_MAX_TRADES,
        }
    }

    /// Creates a new `OrderFlowAnalyzer` with custom max trades limit.
    ///
    /// # Arguments
    ///
    /// * `window_ms` - Rolling window duration in milliseconds
    /// * `max_trades` - Maximum number of trades to keep in buffer
    #[must_use]
    pub fn with_max_trades(window_ms: u64, max_trades: usize) -> Self {
        Self {
            window_ms,
            trades: VecDeque::new(),
            max_trades,
        }
    }

    /// Returns the window duration in milliseconds.
    #[must_use]
    pub fn window_ms(&self) -> u64 {
        self.window_ms
    }

    /// Returns the number of trades currently in the buffer.
    #[must_use]
    pub fn trade_count(&self) -> usize {
        self.trades.len()
    }

    /// Adds a new trade to the analyzer.
    ///
    /// Trades are added to the buffer and will be included in statistics
    /// until they fall outside the rolling window.
    ///
    /// # Arguments
    ///
    /// * `trade` - The trade to add
    pub fn add_trade(&mut self, trade: Trade) {
        self.trades.push_back(trade);

        // Enforce max trades limit
        while self.trades.len() > self.max_trades {
            self.trades.pop_front();
        }
    }

    /// Adds a trade from components.
    ///
    /// Convenience method to add a trade without creating a Trade struct.
    ///
    /// # Arguments
    ///
    /// * `price` - Trade price
    /// * `size` - Trade size
    /// * `side` - Trade side
    /// * `timestamp` - Trade timestamp in milliseconds
    pub fn add_trade_components(
        &mut self,
        price: Decimal,
        size: Decimal,
        side: TradeSide,
        timestamp: u64,
    ) {
        self.add_trade(Trade::new(price, size, side, timestamp));
    }

    /// Gets current order flow statistics for the window.
    ///
    /// Calculates all metrics based on trades within the rolling window
    /// ending at `current_time`.
    ///
    /// # Arguments
    ///
    /// * `current_time` - Current timestamp in milliseconds
    ///
    /// # Returns
    ///
    /// `OrderFlowStats` containing all calculated metrics.
    #[must_use]
    pub fn get_stats(&self, current_time: u64) -> OrderFlowStats {
        let window_start = current_time.saturating_sub(self.window_ms);

        let mut buy_volume = Decimal::ZERO;
        let mut sell_volume = Decimal::ZERO;
        let mut buy_count = 0u64;
        let mut sell_count = 0u64;
        let mut buy_notional = Decimal::ZERO;
        let mut sell_notional = Decimal::ZERO;

        for trade in &self.trades {
            if trade.timestamp >= window_start && trade.timestamp <= current_time {
                let notional = trade.notional();
                match trade.side {
                    TradeSide::Buy => {
                        buy_volume += trade.size;
                        buy_notional += notional;
                        buy_count += 1;
                    }
                    TradeSide::Sell => {
                        sell_volume += trade.size;
                        sell_notional += notional;
                        sell_count += 1;
                    }
                }
            }
        }

        let total_volume = buy_volume + sell_volume;
        let net_flow = buy_volume - sell_volume;
        let imbalance = if total_volume > Decimal::ZERO {
            net_flow / total_volume
        } else {
            Decimal::ZERO
        };

        let buy_vwap = if buy_volume > Decimal::ZERO {
            Some(buy_notional / buy_volume)
        } else {
            None
        };

        let sell_vwap = if sell_volume > Decimal::ZERO {
            Some(sell_notional / sell_volume)
        } else {
            None
        };

        OrderFlowStats {
            buy_volume,
            sell_volume,
            buy_count,
            sell_count,
            imbalance,
            net_flow,
            buy_vwap,
            sell_vwap,
            total_notional: buy_notional + sell_notional,
            window_start,
            window_end: current_time,
        }
    }

    /// Gets the imbalance value directly.
    ///
    /// Convenience method to get just the imbalance without full stats.
    ///
    /// # Arguments
    ///
    /// * `current_time` - Current timestamp in milliseconds
    ///
    /// # Returns
    ///
    /// Imbalance value in range [-1.0, 1.0].
    #[must_use]
    pub fn get_imbalance(&self, current_time: u64) -> Decimal {
        self.get_stats(current_time).imbalance
    }

    /// Checks if flow is significantly bullish.
    ///
    /// # Arguments
    ///
    /// * `threshold` - Minimum imbalance to consider bullish (e.g., 0.3)
    /// * `current_time` - Current timestamp in milliseconds
    ///
    /// # Returns
    ///
    /// True if imbalance exceeds the threshold.
    #[must_use]
    pub fn is_bullish(&self, threshold: Decimal, current_time: u64) -> bool {
        self.get_imbalance(current_time) >= threshold
    }

    /// Checks if flow is significantly bearish.
    ///
    /// # Arguments
    ///
    /// * `threshold` - Minimum negative imbalance to consider bearish (e.g., -0.3)
    /// * `current_time` - Current timestamp in milliseconds
    ///
    /// # Returns
    ///
    /// True if imbalance is below the threshold.
    #[must_use]
    pub fn is_bearish(&self, threshold: Decimal, current_time: u64) -> bool {
        self.get_imbalance(current_time) <= threshold
    }

    /// Clears old trades outside the window.
    ///
    /// Call this periodically to manage memory usage.
    ///
    /// # Arguments
    ///
    /// * `current_time` - Current timestamp in milliseconds
    pub fn cleanup(&mut self, current_time: u64) {
        let window_start = current_time.saturating_sub(self.window_ms);
        while let Some(trade) = self.trades.front() {
            if trade.timestamp < window_start {
                self.trades.pop_front();
            } else {
                break;
            }
        }
    }

    /// Gets trade intensity (trades per second).
    ///
    /// # Arguments
    ///
    /// * `current_time` - Current timestamp in milliseconds
    ///
    /// # Returns
    ///
    /// Number of trades per second in the current window.
    #[must_use]
    pub fn trade_intensity(&self, current_time: u64) -> Decimal {
        let stats = self.get_stats(current_time);
        let window_seconds = Decimal::from(self.window_ms) / Decimal::from(1000);
        if window_seconds > Decimal::ZERO {
            Decimal::from(stats.total_count()) / window_seconds
        } else {
            Decimal::ZERO
        }
    }

    /// Gets volume intensity (volume per second).
    ///
    /// # Arguments
    ///
    /// * `current_time` - Current timestamp in milliseconds
    ///
    /// # Returns
    ///
    /// Total volume per second in the current window.
    #[must_use]
    pub fn volume_intensity(&self, current_time: u64) -> Decimal {
        let stats = self.get_stats(current_time);
        let window_seconds = Decimal::from(self.window_ms) / Decimal::from(1000);
        if window_seconds > Decimal::ZERO {
            stats.total_volume() / window_seconds
        } else {
            Decimal::ZERO
        }
    }

    /// Clears all trades from the analyzer.
    pub fn clear(&mut self) {
        self.trades.clear();
    }

    /// Gets the most recent trade if any.
    #[must_use]
    pub fn last_trade(&self) -> Option<&Trade> {
        self.trades.back()
    }

    /// Gets the oldest trade in the buffer if any.
    #[must_use]
    pub fn first_trade(&self) -> Option<&Trade> {
        self.trades.front()
    }
}

/// Builder for `OrderFlowAnalyzer` with validation.
#[derive(Debug, Clone)]
pub struct OrderFlowAnalyzerBuilder {
    window_ms: u64,
    max_trades: usize,
}

impl OrderFlowAnalyzerBuilder {
    /// Creates a new builder with default values.
    #[must_use]
    pub fn new() -> Self {
        Self {
            window_ms: 5000,
            max_trades: OrderFlowAnalyzer::DEFAULT_MAX_TRADES,
        }
    }

    /// Sets the window duration in milliseconds.
    #[must_use]
    pub fn window_ms(mut self, window_ms: u64) -> Self {
        self.window_ms = window_ms;
        self
    }

    /// Sets the maximum number of trades to keep.
    #[must_use]
    pub fn max_trades(mut self, max_trades: usize) -> Self {
        self.max_trades = max_trades;
        self
    }

    /// Builds the `OrderFlowAnalyzer` with validation.
    ///
    /// # Errors
    ///
    /// Returns `MMError::InvalidConfiguration` if window_ms is 0.
    pub fn build(self) -> MMResult<OrderFlowAnalyzer> {
        if self.window_ms == 0 {
            return Err(MMError::InvalidConfiguration(
                "window_ms must be positive".to_string(),
            ));
        }

        if self.max_trades == 0 {
            return Err(MMError::InvalidConfiguration(
                "max_trades must be positive".to_string(),
            ));
        }

        Ok(OrderFlowAnalyzer {
            window_ms: self.window_ms,
            trades: VecDeque::new(),
            max_trades: self.max_trades,
        })
    }
}

impl Default for OrderFlowAnalyzerBuilder {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_trade_creation() {
        let trade = Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 1000);

        assert_eq!(trade.price, dec!(100.0));
        assert_eq!(trade.size, dec!(10.0));
        assert_eq!(trade.side, TradeSide::Buy);
        assert_eq!(trade.timestamp, 1000);
        assert_eq!(trade.notional(), dec!(1000.0));
        assert!(trade.is_buy());
        assert!(!trade.is_sell());
    }

    #[test]
    fn test_trade_side() {
        assert!(TradeSide::Buy.is_buy());
        assert!(!TradeSide::Buy.is_sell());
        assert!(!TradeSide::Sell.is_buy());
        assert!(TradeSide::Sell.is_sell());
    }

    #[test]
    fn test_empty_analyzer() {
        let analyzer = OrderFlowAnalyzer::new(5000);
        let stats = analyzer.get_stats(10_000);

        assert_eq!(stats.buy_volume, Decimal::ZERO);
        assert_eq!(stats.sell_volume, Decimal::ZERO);
        assert_eq!(stats.buy_count, 0);
        assert_eq!(stats.sell_count, 0);
        assert_eq!(stats.imbalance, Decimal::ZERO);
        assert_eq!(stats.net_flow, Decimal::ZERO);
        assert!(stats.buy_vwap.is_none());
        assert!(stats.sell_vwap.is_none());
    }

    #[test]
    fn test_single_buy_trade() {
        let mut analyzer = OrderFlowAnalyzer::new(5000);
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 1000));

        let stats = analyzer.get_stats(3000);

        assert_eq!(stats.buy_volume, dec!(10.0));
        assert_eq!(stats.sell_volume, Decimal::ZERO);
        assert_eq!(stats.buy_count, 1);
        assert_eq!(stats.sell_count, 0);
        assert_eq!(stats.imbalance, Decimal::ONE);
        assert_eq!(stats.net_flow, dec!(10.0));
        assert_eq!(stats.buy_vwap, Some(dec!(100.0)));
        assert!(stats.sell_vwap.is_none());
    }

    #[test]
    fn test_single_sell_trade() {
        let mut analyzer = OrderFlowAnalyzer::new(5000);
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Sell, 1000));

        let stats = analyzer.get_stats(3000);

        assert_eq!(stats.buy_volume, Decimal::ZERO);
        assert_eq!(stats.sell_volume, dec!(10.0));
        assert_eq!(stats.imbalance, -Decimal::ONE);
        assert_eq!(stats.net_flow, dec!(-10.0));
        assert!(stats.buy_vwap.is_none());
        assert_eq!(stats.sell_vwap, Some(dec!(100.0)));
    }

    #[test]
    fn test_balanced_flow() {
        let mut analyzer = OrderFlowAnalyzer::new(5000);
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 1000));
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Sell, 2000));

        let stats = analyzer.get_stats(3000);

        assert_eq!(stats.buy_volume, dec!(10.0));
        assert_eq!(stats.sell_volume, dec!(10.0));
        assert_eq!(stats.imbalance, Decimal::ZERO);
        assert_eq!(stats.net_flow, Decimal::ZERO);
    }

    #[test]
    fn test_imbalanced_flow_bullish() {
        let mut analyzer = OrderFlowAnalyzer::new(5000);
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(15.0), TradeSide::Buy, 1000));
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(5.0), TradeSide::Sell, 2000));

        let stats = analyzer.get_stats(3000);

        // (15 - 5) / (15 + 5) = 10 / 20 = 0.5
        assert_eq!(stats.imbalance, dec!(0.5));
        assert_eq!(stats.net_flow, dec!(10.0));
        assert!(stats.is_bullish());
        assert!(!stats.is_bearish());
    }

    #[test]
    fn test_imbalanced_flow_bearish() {
        let mut analyzer = OrderFlowAnalyzer::new(5000);
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(5.0), TradeSide::Buy, 1000));
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(15.0), TradeSide::Sell, 2000));

        let stats = analyzer.get_stats(3000);

        // (5 - 15) / (5 + 15) = -10 / 20 = -0.5
        assert_eq!(stats.imbalance, dec!(-0.5));
        assert_eq!(stats.net_flow, dec!(-10.0));
        assert!(!stats.is_bullish());
        assert!(stats.is_bearish());
    }

    #[test]
    fn test_window_expiration() {
        let mut analyzer = OrderFlowAnalyzer::new(5000);

        // Trade at t=1000
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 1000));
        // Trade at t=8000 (outside 5s window from t=10000)
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(5.0), TradeSide::Sell, 8000));

        // At t=10000, window is [5000, 10000], so only second trade is included
        let stats = analyzer.get_stats(10_000);

        assert_eq!(stats.buy_volume, Decimal::ZERO);
        assert_eq!(stats.sell_volume, dec!(5.0));
        assert_eq!(stats.buy_count, 0);
        assert_eq!(stats.sell_count, 1);
    }

    #[test]
    fn test_vwap_calculation() {
        let mut analyzer = OrderFlowAnalyzer::new(5000);

        // Buy trades: 10 @ 100, 20 @ 102
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 1000));
        analyzer.add_trade(Trade::new(dec!(102.0), dec!(20.0), TradeSide::Buy, 2000));

        // Sell trades: 5 @ 99, 15 @ 101
        analyzer.add_trade(Trade::new(dec!(99.0), dec!(5.0), TradeSide::Sell, 3000));
        analyzer.add_trade(Trade::new(dec!(101.0), dec!(15.0), TradeSide::Sell, 4000));

        let stats = analyzer.get_stats(5000);

        // Buy VWAP: (10*100 + 20*102) / 30 = (1000 + 2040) / 30 = 3040 / 30 = 101.333...
        let expected_buy_vwap = dec!(3040) / dec!(30);
        assert_eq!(stats.buy_vwap, Some(expected_buy_vwap));

        // Sell VWAP: (5*99 + 15*101) / 20 = (495 + 1515) / 20 = 2010 / 20 = 100.5
        assert_eq!(stats.sell_vwap, Some(dec!(100.5)));
    }

    #[test]
    fn test_cleanup() {
        let mut analyzer = OrderFlowAnalyzer::new(5000);

        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 1000));
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 2000));
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 8000));

        assert_eq!(analyzer.trade_count(), 3);

        // Cleanup at t=10000, window is [5000, 10000]
        analyzer.cleanup(10_000);

        // Only trade at t=8000 should remain
        assert_eq!(analyzer.trade_count(), 1);
    }

    #[test]
    fn test_is_bullish_bearish() {
        let mut analyzer = OrderFlowAnalyzer::new(5000);

        analyzer.add_trade(Trade::new(dec!(100.0), dec!(20.0), TradeSide::Buy, 1000));
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(5.0), TradeSide::Sell, 2000));

        // Imbalance = (20-5)/(20+5) = 0.6
        assert!(analyzer.is_bullish(dec!(0.5), 3000));
        assert!(!analyzer.is_bullish(dec!(0.7), 3000));
        assert!(!analyzer.is_bearish(dec!(-0.5), 3000));
    }

    #[test]
    fn test_trade_intensity() {
        let mut analyzer = OrderFlowAnalyzer::new(5000); // 5 second window

        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 1000));
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 2000));
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Sell, 3000));
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Sell, 4000));

        // 4 trades in 5 seconds = 0.8 trades/second
        let intensity = analyzer.trade_intensity(5000);
        assert_eq!(intensity, dec!(0.8));
    }

    #[test]
    fn test_volume_intensity() {
        let mut analyzer = OrderFlowAnalyzer::new(5000); // 5 second window

        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 1000));
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(15.0), TradeSide::Sell, 2000));

        // 25 volume in 5 seconds = 5 volume/second
        let intensity = analyzer.volume_intensity(5000);
        assert_eq!(intensity, dec!(5));
    }

    #[test]
    fn test_add_trade_components() {
        let mut analyzer = OrderFlowAnalyzer::new(5000);

        analyzer.add_trade_components(dec!(100.0), dec!(10.0), TradeSide::Buy, 1000);

        let stats = analyzer.get_stats(2000);
        assert_eq!(stats.buy_volume, dec!(10.0));
    }

    #[test]
    fn test_max_trades_limit() {
        let mut analyzer = OrderFlowAnalyzer::with_max_trades(5000, 3);

        analyzer.add_trade(Trade::new(dec!(100.0), dec!(1.0), TradeSide::Buy, 1000));
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(2.0), TradeSide::Buy, 2000));
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(3.0), TradeSide::Buy, 3000));
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(4.0), TradeSide::Buy, 4000));

        // Should only keep last 3 trades
        assert_eq!(analyzer.trade_count(), 3);

        // First trade (size=1) should be removed
        let stats = analyzer.get_stats(5000);
        assert_eq!(stats.buy_volume, dec!(9.0)); // 2 + 3 + 4
    }

    #[test]
    fn test_builder_valid() {
        let analyzer = OrderFlowAnalyzerBuilder::new()
            .window_ms(10_000)
            .max_trades(5000)
            .build();

        assert!(analyzer.is_ok());
        let analyzer = analyzer.unwrap();
        assert_eq!(analyzer.window_ms(), 10_000);
    }

    #[test]
    fn test_builder_invalid_window() {
        let result = OrderFlowAnalyzerBuilder::new().window_ms(0).build();
        assert!(result.is_err());
    }

    #[test]
    fn test_builder_invalid_max_trades() {
        let result = OrderFlowAnalyzerBuilder::new().max_trades(0).build();
        assert!(result.is_err());
    }

    #[test]
    fn test_order_flow_stats_helpers() {
        let stats = OrderFlowStats {
            buy_volume: dec!(100.0),
            sell_volume: dec!(50.0),
            buy_count: 10,
            sell_count: 5,
            imbalance: dec!(0.333),
            net_flow: dec!(50.0),
            buy_vwap: Some(dec!(100.0)),
            sell_vwap: Some(dec!(99.0)),
            total_notional: dec!(15000.0),
            window_start: 1000,
            window_end: 6000,
        };

        assert_eq!(stats.total_volume(), dec!(150.0));
        assert_eq!(stats.total_count(), 15);
        assert!(stats.is_bullish());
        assert!(!stats.is_bearish());
        assert_eq!(stats.volume_ratio(), Some(dec!(2.0)));
        assert_eq!(stats.window_duration_ms(), 5000);
    }

    #[test]
    fn test_last_first_trade() {
        let mut analyzer = OrderFlowAnalyzer::new(5000);

        assert!(analyzer.last_trade().is_none());
        assert!(analyzer.first_trade().is_none());

        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 1000));
        analyzer.add_trade(Trade::new(dec!(101.0), dec!(20.0), TradeSide::Sell, 2000));

        assert_eq!(analyzer.first_trade().unwrap().price, dec!(100.0));
        assert_eq!(analyzer.last_trade().unwrap().price, dec!(101.0));
    }

    #[test]
    fn test_clear() {
        let mut analyzer = OrderFlowAnalyzer::new(5000);

        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 1000));
        analyzer.add_trade(Trade::new(dec!(100.0), dec!(10.0), TradeSide::Sell, 2000));

        assert_eq!(analyzer.trade_count(), 2);

        analyzer.clear();

        assert_eq!(analyzer.trade_count(), 0);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serialization() {
        let trade = Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 1000);

        let json = serde_json::to_string(&trade).unwrap();
        let deserialized: Trade = serde_json::from_str(&json).unwrap();

        assert_eq!(trade, deserialized);
    }
}