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
//! Market data types and sources for backtesting.
//!
//! This module provides data structures and traits for historical market data
//! used in backtesting simulations.
//!
//! # Example
//!
//! ```rust
//! use market_maker_rs::backtest::{MarketTick, VecDataSource, HistoricalDataSource};
//! use market_maker_rs::dec;
//!
//! let ticks = vec![
//!     MarketTick::new(1000, dec!(100.0), dec!(1.0), dec!(100.1), dec!(1.0)),
//!     MarketTick::new(1001, dec!(100.1), dec!(1.0), dec!(100.2), dec!(1.0)),
//! ];
//!
//! let mut source = VecDataSource::new(ticks);
//! assert_eq!(source.len(), 2);
//!
//! let tick = source.next_tick().unwrap();
//! assert_eq!(tick.timestamp, 1000);
//! ```

use crate::Decimal;

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

/// Market tick data representing a point-in-time snapshot of the order book.
///
/// Contains bid/ask prices and sizes, plus optional last trade information.
///
/// # Example
///
/// ```rust
/// use market_maker_rs::backtest::MarketTick;
/// use market_maker_rs::dec;
///
/// let tick = MarketTick::new(1000, dec!(100.0), dec!(1.0), dec!(100.1), dec!(1.0));
/// assert_eq!(tick.mid_price(), dec!(100.05));
/// assert_eq!(tick.spread(), dec!(0.1));
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MarketTick {
    /// Timestamp in milliseconds.
    pub timestamp: u64,
    /// Best bid price.
    pub bid_price: Decimal,
    /// Best bid size.
    pub bid_size: Decimal,
    /// Best ask price.
    pub ask_price: Decimal,
    /// Best ask size.
    pub ask_size: Decimal,
    /// Last trade price (if available).
    pub last_price: Option<Decimal>,
    /// Last trade size (if available).
    pub last_size: Option<Decimal>,
}

impl MarketTick {
    /// Creates a new market tick.
    #[must_use]
    pub fn new(
        timestamp: u64,
        bid_price: Decimal,
        bid_size: Decimal,
        ask_price: Decimal,
        ask_size: Decimal,
    ) -> Self {
        Self {
            timestamp,
            bid_price,
            bid_size,
            ask_price,
            ask_size,
            last_price: None,
            last_size: None,
        }
    }

    /// Creates a new market tick with last trade information.
    #[must_use]
    pub fn with_last_trade(
        timestamp: u64,
        bid_price: Decimal,
        bid_size: Decimal,
        ask_price: Decimal,
        ask_size: Decimal,
        last_price: Decimal,
        last_size: Decimal,
    ) -> Self {
        Self {
            timestamp,
            bid_price,
            bid_size,
            ask_price,
            ask_size,
            last_price: Some(last_price),
            last_size: Some(last_size),
        }
    }

    /// Returns the mid price.
    #[must_use]
    pub fn mid_price(&self) -> Decimal {
        (self.bid_price + self.ask_price) / Decimal::TWO
    }

    /// Returns the bid-ask spread.
    #[must_use]
    pub fn spread(&self) -> Decimal {
        self.ask_price - self.bid_price
    }

    /// Returns the spread as a percentage of mid price.
    #[must_use]
    pub fn spread_bps(&self) -> Decimal {
        let mid = self.mid_price();
        if mid > Decimal::ZERO {
            (self.spread() / mid) * Decimal::from(10000)
        } else {
            Decimal::ZERO
        }
    }

    /// Returns the total available liquidity (bid + ask size).
    #[must_use]
    pub fn total_liquidity(&self) -> Decimal {
        self.bid_size + self.ask_size
    }

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

/// OHLCV bar data for candlestick-based analysis.
///
/// # Example
///
/// ```rust
/// use market_maker_rs::backtest::OHLCVBar;
/// use market_maker_rs::dec;
///
/// let bar = OHLCVBar::new(
///     1000,
///     dec!(100.0),
///     dec!(105.0),
///     dec!(99.0),
///     dec!(102.0),
///     dec!(1000.0),
/// );
///
/// assert_eq!(bar.range(), dec!(6.0));
/// assert!(bar.is_bullish());
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct OHLCVBar {
    /// Bar start timestamp in milliseconds.
    pub timestamp: u64,
    /// Opening price.
    pub open: Decimal,
    /// Highest price.
    pub high: Decimal,
    /// Lowest price.
    pub low: Decimal,
    /// Closing price.
    pub close: Decimal,
    /// Total volume.
    pub volume: Decimal,
}

impl OHLCVBar {
    /// Creates a new OHLCV bar.
    #[must_use]
    pub fn new(
        timestamp: u64,
        open: Decimal,
        high: Decimal,
        low: Decimal,
        close: Decimal,
        volume: Decimal,
    ) -> Self {
        Self {
            timestamp,
            open,
            high,
            low,
            close,
            volume,
        }
    }

    /// Returns the price range (high - low).
    #[must_use]
    pub fn range(&self) -> Decimal {
        self.high - self.low
    }

    /// Returns the body size (|close - open|).
    #[must_use]
    pub fn body(&self) -> Decimal {
        if self.close > self.open {
            self.close - self.open
        } else {
            self.open - self.close
        }
    }

    /// Returns true if the bar is bullish (close > open).
    #[must_use]
    pub fn is_bullish(&self) -> bool {
        self.close > self.open
    }

    /// Returns true if the bar is bearish (close < open).
    #[must_use]
    pub fn is_bearish(&self) -> bool {
        self.close < self.open
    }

    /// Returns the typical price (high + low + close) / 3.
    #[must_use]
    pub fn typical_price(&self) -> Decimal {
        (self.high + self.low + self.close) / Decimal::from(3)
    }

    /// Returns the VWAP approximation using typical price.
    #[must_use]
    pub fn vwap(&self) -> Decimal {
        self.typical_price()
    }
}

/// Trait for historical data sources.
///
/// Provides an iterator-like interface for consuming market data.
pub trait HistoricalDataSource {
    /// Returns the next tick and advances the cursor.
    fn next_tick(&mut self) -> Option<MarketTick>;

    /// Peeks at the next tick without advancing.
    fn peek_tick(&self) -> Option<&MarketTick>;

    /// Resets the data source to the beginning.
    fn reset(&mut self);

    /// Returns the total number of ticks.
    fn len(&self) -> usize;

    /// Returns true if there are no ticks.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the number of remaining ticks.
    fn remaining(&self) -> usize;
}

/// Vector-based historical data source.
///
/// Stores ticks in memory for fast iteration.
///
/// # Example
///
/// ```rust
/// use market_maker_rs::backtest::{MarketTick, VecDataSource, HistoricalDataSource};
/// use market_maker_rs::dec;
///
/// let ticks = vec![
///     MarketTick::new(1000, dec!(100.0), dec!(1.0), dec!(100.1), dec!(1.0)),
///     MarketTick::new(1001, dec!(100.1), dec!(1.0), dec!(100.2), dec!(1.0)),
///     MarketTick::new(1002, dec!(100.2), dec!(1.0), dec!(100.3), dec!(1.0)),
/// ];
///
/// let mut source = VecDataSource::new(ticks);
///
/// // Iterate through ticks
/// while let Some(tick) = source.next_tick() {
///     println!("Tick at {}: mid = {}", tick.timestamp, tick.mid_price());
/// }
///
/// // Reset and iterate again
/// source.reset();
/// assert_eq!(source.remaining(), 3);
/// ```
#[derive(Debug, Clone)]
pub struct VecDataSource {
    ticks: Vec<MarketTick>,
    index: usize,
}

impl VecDataSource {
    /// Creates a new vector data source from a list of ticks.
    #[must_use]
    pub fn new(ticks: Vec<MarketTick>) -> Self {
        Self { ticks, index: 0 }
    }

    /// Creates an empty data source.
    #[must_use]
    pub fn empty() -> Self {
        Self {
            ticks: Vec::new(),
            index: 0,
        }
    }

    /// Returns the current index position.
    #[must_use]
    pub fn current_index(&self) -> usize {
        self.index
    }

    /// Returns a reference to all ticks.
    #[must_use]
    pub fn ticks(&self) -> &[MarketTick] {
        &self.ticks
    }

    /// Returns the tick at a specific index.
    #[must_use]
    pub fn get(&self, index: usize) -> Option<&MarketTick> {
        self.ticks.get(index)
    }

    /// Adds a tick to the data source.
    pub fn push(&mut self, tick: MarketTick) {
        self.ticks.push(tick);
    }

    /// Returns the time range of the data.
    #[must_use]
    pub fn time_range(&self) -> Option<(u64, u64)> {
        if self.ticks.is_empty() {
            None
        } else {
            Some((
                self.ticks.first().unwrap().timestamp,
                self.ticks.last().unwrap().timestamp,
            ))
        }
    }
}

impl HistoricalDataSource for VecDataSource {
    fn next_tick(&mut self) -> Option<MarketTick> {
        if self.index < self.ticks.len() {
            let tick = self.ticks[self.index].clone();
            self.index += 1;
            Some(tick)
        } else {
            None
        }
    }

    fn peek_tick(&self) -> Option<&MarketTick> {
        self.ticks.get(self.index)
    }

    fn reset(&mut self) {
        self.index = 0;
    }

    fn len(&self) -> usize {
        self.ticks.len()
    }

    fn remaining(&self) -> usize {
        self.ticks.len().saturating_sub(self.index)
    }
}

impl Default for VecDataSource {
    fn default() -> Self {
        Self::empty()
    }
}

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

    fn create_test_tick(timestamp: u64, bid: Decimal, ask: Decimal) -> MarketTick {
        MarketTick::new(timestamp, bid, dec!(1.0), ask, dec!(1.0))
    }

    #[test]
    fn test_market_tick_new() {
        let tick = MarketTick::new(1000, dec!(100.0), dec!(1.0), dec!(100.1), dec!(1.0));

        assert_eq!(tick.timestamp, 1000);
        assert_eq!(tick.bid_price, dec!(100.0));
        assert_eq!(tick.ask_price, dec!(100.1));
        assert!(tick.last_price.is_none());
    }

    #[test]
    fn test_market_tick_with_last_trade() {
        let tick = MarketTick::with_last_trade(
            1000,
            dec!(100.0),
            dec!(1.0),
            dec!(100.1),
            dec!(1.0),
            dec!(100.05),
            dec!(0.5),
        );

        assert_eq!(tick.last_price, Some(dec!(100.05)));
        assert_eq!(tick.last_size, Some(dec!(0.5)));
    }

    #[test]
    fn test_market_tick_mid_price() {
        let tick = create_test_tick(1000, dec!(100.0), dec!(100.2));
        assert_eq!(tick.mid_price(), dec!(100.1));
    }

    #[test]
    fn test_market_tick_spread() {
        let tick = create_test_tick(1000, dec!(100.0), dec!(100.2));
        assert_eq!(tick.spread(), dec!(0.2));
    }

    #[test]
    fn test_market_tick_spread_bps() {
        let tick = create_test_tick(1000, dec!(100.0), dec!(100.1));
        // Spread = 0.1, mid = 100.05, bps = (0.1 / 100.05) * 10000 ≈ 9.995
        let bps = tick.spread_bps();
        assert!(bps > dec!(9.0) && bps < dec!(10.0));
    }

    #[test]
    fn test_market_tick_imbalance() {
        let tick = MarketTick::new(1000, dec!(100.0), dec!(2.0), dec!(100.1), dec!(1.0));
        // Imbalance = (2 - 1) / (2 + 1) = 1/3
        let imbalance = tick.imbalance();
        assert!(imbalance > dec!(0.33) && imbalance < dec!(0.34));
    }

    #[test]
    fn test_ohlcv_bar_new() {
        let bar = OHLCVBar::new(
            1000,
            dec!(100.0),
            dec!(105.0),
            dec!(99.0),
            dec!(102.0),
            dec!(1000.0),
        );

        assert_eq!(bar.timestamp, 1000);
        assert_eq!(bar.open, dec!(100.0));
        assert_eq!(bar.high, dec!(105.0));
        assert_eq!(bar.low, dec!(99.0));
        assert_eq!(bar.close, dec!(102.0));
        assert_eq!(bar.volume, dec!(1000.0));
    }

    #[test]
    fn test_ohlcv_bar_range() {
        let bar = OHLCVBar::new(
            1000,
            dec!(100.0),
            dec!(105.0),
            dec!(99.0),
            dec!(102.0),
            dec!(1000.0),
        );
        assert_eq!(bar.range(), dec!(6.0));
    }

    #[test]
    fn test_ohlcv_bar_body() {
        let bullish = OHLCVBar::new(
            1000,
            dec!(100.0),
            dec!(105.0),
            dec!(99.0),
            dec!(103.0),
            dec!(1000.0),
        );
        assert_eq!(bullish.body(), dec!(3.0));

        let bearish = OHLCVBar::new(
            1000,
            dec!(103.0),
            dec!(105.0),
            dec!(99.0),
            dec!(100.0),
            dec!(1000.0),
        );
        assert_eq!(bearish.body(), dec!(3.0));
    }

    #[test]
    fn test_ohlcv_bar_bullish_bearish() {
        let bullish = OHLCVBar::new(
            1000,
            dec!(100.0),
            dec!(105.0),
            dec!(99.0),
            dec!(103.0),
            dec!(1000.0),
        );
        assert!(bullish.is_bullish());
        assert!(!bullish.is_bearish());

        let bearish = OHLCVBar::new(
            1000,
            dec!(103.0),
            dec!(105.0),
            dec!(99.0),
            dec!(100.0),
            dec!(1000.0),
        );
        assert!(!bearish.is_bullish());
        assert!(bearish.is_bearish());
    }

    #[test]
    fn test_ohlcv_bar_typical_price() {
        let bar = OHLCVBar::new(
            1000,
            dec!(100.0),
            dec!(105.0),
            dec!(99.0),
            dec!(102.0),
            dec!(1000.0),
        );
        // Typical = (105 + 99 + 102) / 3 = 102
        assert_eq!(bar.typical_price(), dec!(102.0));
    }

    #[test]
    fn test_vec_data_source_new() {
        let ticks = vec![
            create_test_tick(1000, dec!(100.0), dec!(100.1)),
            create_test_tick(1001, dec!(100.1), dec!(100.2)),
        ];

        let source = VecDataSource::new(ticks);
        assert_eq!(source.len(), 2);
        assert!(!source.is_empty());
    }

    #[test]
    fn test_vec_data_source_empty() {
        let source = VecDataSource::empty();
        assert_eq!(source.len(), 0);
        assert!(source.is_empty());
    }

    #[test]
    fn test_vec_data_source_next_tick() {
        let ticks = vec![
            create_test_tick(1000, dec!(100.0), dec!(100.1)),
            create_test_tick(1001, dec!(100.1), dec!(100.2)),
        ];

        let mut source = VecDataSource::new(ticks);

        let tick1 = source.next_tick().unwrap();
        assert_eq!(tick1.timestamp, 1000);

        let tick2 = source.next_tick().unwrap();
        assert_eq!(tick2.timestamp, 1001);

        assert!(source.next_tick().is_none());
    }

    #[test]
    fn test_vec_data_source_peek_tick() {
        let ticks = vec![
            create_test_tick(1000, dec!(100.0), dec!(100.1)),
            create_test_tick(1001, dec!(100.1), dec!(100.2)),
        ];

        let mut source = VecDataSource::new(ticks);

        // Peek doesn't advance
        let peeked = source.peek_tick().unwrap();
        assert_eq!(peeked.timestamp, 1000);

        let peeked2 = source.peek_tick().unwrap();
        assert_eq!(peeked2.timestamp, 1000);

        // Next advances
        source.next_tick();
        let peeked3 = source.peek_tick().unwrap();
        assert_eq!(peeked3.timestamp, 1001);
    }

    #[test]
    fn test_vec_data_source_reset() {
        let ticks = vec![
            create_test_tick(1000, dec!(100.0), dec!(100.1)),
            create_test_tick(1001, dec!(100.1), dec!(100.2)),
        ];

        let mut source = VecDataSource::new(ticks);

        source.next_tick();
        source.next_tick();
        assert_eq!(source.remaining(), 0);

        source.reset();
        assert_eq!(source.remaining(), 2);
        assert_eq!(source.current_index(), 0);
    }

    #[test]
    fn test_vec_data_source_remaining() {
        let ticks = vec![
            create_test_tick(1000, dec!(100.0), dec!(100.1)),
            create_test_tick(1001, dec!(100.1), dec!(100.2)),
            create_test_tick(1002, dec!(100.2), dec!(100.3)),
        ];

        let mut source = VecDataSource::new(ticks);

        assert_eq!(source.remaining(), 3);
        source.next_tick();
        assert_eq!(source.remaining(), 2);
        source.next_tick();
        assert_eq!(source.remaining(), 1);
        source.next_tick();
        assert_eq!(source.remaining(), 0);
    }

    #[test]
    fn test_vec_data_source_time_range() {
        let ticks = vec![
            create_test_tick(1000, dec!(100.0), dec!(100.1)),
            create_test_tick(2000, dec!(100.1), dec!(100.2)),
            create_test_tick(3000, dec!(100.2), dec!(100.3)),
        ];

        let source = VecDataSource::new(ticks);
        let (start, end) = source.time_range().unwrap();
        assert_eq!(start, 1000);
        assert_eq!(end, 3000);
    }

    #[test]
    fn test_vec_data_source_time_range_empty() {
        let source = VecDataSource::empty();
        assert!(source.time_range().is_none());
    }

    #[test]
    fn test_vec_data_source_push() {
        let mut source = VecDataSource::empty();
        source.push(create_test_tick(1000, dec!(100.0), dec!(100.1)));
        source.push(create_test_tick(1001, dec!(100.1), dec!(100.2)));

        assert_eq!(source.len(), 2);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_market_tick_serialization() {
        let tick = MarketTick::new(1000, dec!(100.0), dec!(1.0), dec!(100.1), dec!(1.0));
        let json = serde_json::to_string(&tick).unwrap();
        let deserialized: MarketTick = serde_json::from_str(&json).unwrap();
        assert_eq!(tick, deserialized);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_ohlcv_bar_serialization() {
        let bar = OHLCVBar::new(
            1000,
            dec!(100.0),
            dec!(105.0),
            dec!(99.0),
            dec!(102.0),
            dec!(1000.0),
        );
        let json = serde_json::to_string(&bar).unwrap();
        let deserialized: OHLCVBar = serde_json::from_str(&json).unwrap();
        assert_eq!(bar, deserialized);
    }
}