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
//! Avellaneda-Stoikov model calculations.
//!
//! This module implements the core mathematical formulas from the
//! Avellaneda-Stoikov (2008) paper on high-frequency trading in a limit order book.
//!
//! ## Mathematical Model
//!
//! The model solves the optimal market making problem using stochastic control theory.
//!
//! ### Reservation Price
//! ```text
//! r = s - q * γ * σ² * (T - t)
//! ```
//! Where:
//! - `s`: mid-price
//! - `q`: inventory position
//! - `γ`: risk aversion
//! - `σ`: volatility
//! - `T - t`: time to terminal
//!
//! ### Optimal Spread
//! ```text
//! δ = γ * σ² * (T - t) + (2/γ) * ln(1 + γ/k)
//! ```
//! Where:
//! - `k`: order intensity parameter

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

const SECONDS_PER_MILLISECOND: Decimal = Decimal::from_parts(1, 0, 0, false, 3); // 0.001
const SECONDS_PER_YEAR: Decimal = Decimal::from_parts(31_536_000, 0, 0, false, 0); // 31_536_000

/// Calculates the reservation price according to the Avellaneda-Stoikov model.
///
/// The reservation price represents the "fair value" adjusted for inventory risk.
/// A market maker with positive inventory (long) will have a reservation price
/// below the mid-price, incentivizing sells. Conversely, negative inventory
/// (short) results in a reservation price above mid, incentivizing buys.
///
/// # Arguments
///
/// * `mid_price` - Current mid-price of the asset
/// * `inventory` - Current inventory position (positive = long, negative = short)
/// * `risk_aversion` - Risk aversion parameter (gamma), must be positive
/// * `volatility` - Volatility estimate (annualized), must be positive
/// * `time_to_terminal_ms` - Time remaining until terminal time, in milliseconds
///
/// # Returns
///
/// The reservation price adjusted for inventory risk.
///
/// # Errors
///
/// Returns `MMError::InvalidMarketState` if:
/// - mid_price is not positive or finite
/// - volatility is not positive or finite
///
/// Returns `MMError::InvalidConfiguration` if:
/// - risk_aversion is not positive or finite
///
/// # Examples
///
/// ```
/// use market_maker_rs::strategy::avellaneda_stoikov::calculate_reservation_price;
/// use market_maker_rs::dec;
///
/// let reservation = calculate_reservation_price(
///     dec!(100.0),  // mid_price
///     dec!(10.0),   // inventory (long)
///     dec!(0.1),    // risk_aversion
///     dec!(0.2),    // volatility (20%)
///     3600000       // 1 hour in ms
/// ).unwrap();
///
/// // With positive inventory, reservation < mid_price
/// assert!(reservation < dec!(100.0));
/// ```
pub fn calculate_reservation_price(
    mid_price: Decimal,
    inventory: Decimal,
    risk_aversion: Decimal,
    volatility: Decimal,
    time_to_terminal_ms: u64,
) -> MMResult<Decimal> {
    // Validate inputs
    if mid_price <= Decimal::ZERO {
        return Err(MMError::InvalidMarketState(
            "mid_price must be positive".to_string(),
        ));
    }

    if volatility <= Decimal::ZERO {
        return Err(MMError::InvalidMarketState(
            "volatility must be positive".to_string(),
        ));
    }

    if risk_aversion <= Decimal::ZERO {
        return Err(MMError::InvalidConfiguration(
            "risk_aversion must be positive".to_string(),
        ));
    }

    // Convert time to years (volatility is annualized)
    let time_to_terminal_ms_dec = Decimal::from(time_to_terminal_ms);
    let time_to_terminal_years =
        (time_to_terminal_ms_dec * SECONDS_PER_MILLISECOND) / SECONDS_PER_YEAR;

    // Formula: r = s - q * γ * σ² * (T - t)
    let volatility_squared = decimal_powi(volatility, 2)?;
    let adjustment = inventory * risk_aversion * volatility_squared * time_to_terminal_years;
    let reservation_price = mid_price - adjustment;

    Ok(reservation_price)
}

/// Calculates the optimal spread according to the Avellaneda-Stoikov model.
///
/// The spread represents the distance between bid and ask quotes.
/// It accounts for both inventory risk (first term) and adverse selection
/// (second term).
///
/// # Arguments
///
/// * `risk_aversion` - Risk aversion parameter (gamma), must be positive
/// * `volatility` - Volatility estimate (annualized), must be positive
/// * `time_to_terminal_ms` - Time remaining until terminal time, in milliseconds
/// * `order_intensity` - Order intensity parameter (k), must be positive
///
/// # Returns
///
/// The optimal spread in price units.
///
/// # Errors
///
/// Returns `MMError::InvalidConfiguration` if any parameter is not positive or finite.
///
/// # Examples
///
/// ```
/// use market_maker_rs::strategy::avellaneda_stoikov::calculate_optimal_spread;
/// use market_maker_rs::dec;
///
/// let spread = calculate_optimal_spread(
///     dec!(0.1),    // risk_aversion
///     dec!(0.2),    // volatility (20%)
///     3600000,      // 1 hour
///     dec!(1.5)     // order_intensity
/// ).unwrap();
///
/// assert!(spread > dec!(0.0));
/// ```
pub fn calculate_optimal_spread(
    risk_aversion: Decimal,
    volatility: Decimal,
    time_to_terminal_ms: u64,
    order_intensity: Decimal,
) -> MMResult<Decimal> {
    // Validate inputs
    if risk_aversion <= Decimal::ZERO {
        return Err(MMError::InvalidConfiguration(
            "risk_aversion must be positive".to_string(),
        ));
    }

    if volatility <= Decimal::ZERO {
        return Err(MMError::InvalidConfiguration(
            "volatility must be positive".to_string(),
        ));
    }

    if order_intensity <= Decimal::ZERO {
        return Err(MMError::InvalidConfiguration(
            "order_intensity must be positive".to_string(),
        ));
    }

    // Convert time to years
    let time_to_terminal_ms_dec = Decimal::from(time_to_terminal_ms);
    let time_to_terminal_years =
        (time_to_terminal_ms_dec * SECONDS_PER_MILLISECOND) / SECONDS_PER_YEAR;

    // Formula: δ = γ * σ² * (T - t) + (2/γ) * ln(1 + γ/k)
    let volatility_squared = decimal_powi(volatility, 2)?;
    let inventory_risk_term = risk_aversion * volatility_squared * time_to_terminal_years;

    let two = Decimal::from(2);
    let one = Decimal::ONE;
    let adverse_selection_inner = one + risk_aversion / order_intensity;
    let adverse_selection_ln = decimal_ln(adverse_selection_inner)?;
    let adverse_selection_term = (two / risk_aversion) * adverse_selection_ln;

    let spread = inventory_risk_term + adverse_selection_term;

    if spread < Decimal::ZERO {
        return Err(MMError::NumericalError(
            "spread calculation resulted in negative value".to_string(),
        ));
    }

    Ok(spread)
}

/// Calculates optimal bid and ask prices based on the Avellaneda-Stoikov model.
///
/// This is a convenience function that combines reservation price and spread
/// calculations to produce bid/ask quotes.
///
/// # Arguments
///
/// * `mid_price` - Current mid-price
/// * `inventory` - Current inventory position
/// * `risk_aversion` - Risk aversion parameter (gamma)
/// * `volatility` - Volatility estimate (annualized)
/// * `time_to_terminal_ms` - Time to terminal in milliseconds
/// * `order_intensity` - Order intensity parameter (k)
///
/// # Returns
///
/// A tuple `(bid_price, ask_price)`.
///
/// # Errors
///
/// Returns errors from underlying calculations if inputs are invalid.
///
/// # Examples
///
/// ```
/// use market_maker_rs::strategy::avellaneda_stoikov::calculate_optimal_quotes;
/// use market_maker_rs::dec;
///
/// let (bid, ask) = calculate_optimal_quotes(
///     dec!(100.0),  // mid_price
///     dec!(0.0),    // flat inventory
///     dec!(0.1),    // risk_aversion
///     dec!(0.2),    // volatility
///     3600000,      // time_to_terminal_ms
///     dec!(1.5)     // order_intensity
/// ).unwrap();
///
/// assert!(bid < ask);
/// assert!(bid < dec!(100.0));
/// assert!(ask > dec!(100.0));
/// ```
pub fn calculate_optimal_quotes(
    mid_price: Decimal,
    inventory: Decimal,
    risk_aversion: Decimal,
    volatility: Decimal,
    time_to_terminal_ms: u64,
    order_intensity: Decimal,
) -> MMResult<(Decimal, Decimal)> {
    let reservation_price = calculate_reservation_price(
        mid_price,
        inventory,
        risk_aversion,
        volatility,
        time_to_terminal_ms,
    )?;

    let spread = calculate_optimal_spread(
        risk_aversion,
        volatility,
        time_to_terminal_ms,
        order_intensity,
    )?;

    let two = Decimal::from(2);
    let half_spread = spread / two;
    let bid_price = reservation_price - half_spread;
    let ask_price = reservation_price + half_spread;

    // Validate quotes
    if bid_price >= ask_price {
        return Err(MMError::InvalidQuoteGeneration(
            "bid price must be less than ask price".to_string(),
        ));
    }

    if bid_price <= Decimal::ZERO {
        return Err(MMError::InvalidQuoteGeneration(
            "bid price must be positive".to_string(),
        ));
    }

    Ok((bid_price, ask_price))
}

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

    #[test]
    fn test_reservation_price_flat_inventory() {
        let result =
            calculate_reservation_price(dec!(100.0), Decimal::ZERO, dec!(0.1), dec!(0.2), 3600000);
        assert!(result.is_ok());
        let reservation = result.unwrap();
        // With flat inventory, reservation should equal mid_price
        assert!((reservation - dec!(100.0)).abs() < dec!(0.0001));
    }

    #[test]
    fn test_reservation_price_long_inventory() {
        let result =
            calculate_reservation_price(dec!(100.0), dec!(10.0), dec!(0.1), dec!(0.2), 3600000);
        assert!(result.is_ok());
        let reservation = result.unwrap();
        // With positive inventory, reservation < mid_price
        assert!(reservation < dec!(100.0));
    }

    #[test]
    fn test_reservation_price_short_inventory() {
        let result =
            calculate_reservation_price(dec!(100.0), dec!(-10.0), dec!(0.1), dec!(0.2), 3600000);
        assert!(result.is_ok());
        let reservation = result.unwrap();
        // With negative inventory, reservation > mid_price
        assert!(reservation > dec!(100.0));
    }

    #[test]
    fn test_reservation_price_invalid_mid_price() {
        let result =
            calculate_reservation_price(dec!(-100.0), Decimal::ZERO, dec!(0.1), dec!(0.2), 3600000);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            MMError::InvalidMarketState(_)
        ));
    }

    #[test]
    fn test_reservation_price_invalid_volatility() {
        let result =
            calculate_reservation_price(dec!(100.0), Decimal::ZERO, dec!(0.1), dec!(-0.2), 3600000);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            MMError::InvalidMarketState(_)
        ));
    }

    #[test]
    fn test_reservation_price_invalid_risk_aversion() {
        let result =
            calculate_reservation_price(dec!(100.0), Decimal::ZERO, dec!(-0.1), dec!(0.2), 3600000);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            MMError::InvalidConfiguration(_)
        ));
    }

    #[test]
    fn test_reservation_price_invalid_inventory() {
        // Decimal doesn't have NAN, so this test is less relevant
        // But we keep it to test the structure, using a zero inventory
        let result =
            calculate_reservation_price(dec!(100.0), Decimal::ZERO, dec!(0.1), dec!(0.2), 3600000);
        assert!(result.is_ok());
    }

    #[test]
    fn test_reservation_price_non_finite_result() {
        // Very large inventory - Decimal has different overflow behavior than f64
        // Using more reasonable extreme values that won't cause overflow
        let result = calculate_reservation_price(
            dec!(100.0),
            dec!(1000000),
            dec!(1000),
            dec!(1000),
            u64::MAX,
        );
        // Decimal will produce a result (possibly very large or very negative)
        // Unlike f64 which would produce infinity
        let _ = result;
    }

    #[test]
    fn test_optimal_spread_positive() {
        let result = calculate_optimal_spread(dec!(0.1), dec!(0.2), 3600000, dec!(1.5));
        assert!(result.is_ok());
        let spread = result.unwrap();
        assert!(spread > Decimal::ZERO);
    }

    #[test]
    fn test_optimal_spread_increases_with_volatility() {
        let spread1 = calculate_optimal_spread(dec!(0.1), dec!(0.1), 3600000, dec!(1.5)).unwrap();
        let spread2 = calculate_optimal_spread(dec!(0.1), dec!(0.3), 3600000, dec!(1.5)).unwrap();
        assert!(spread2 > spread1);
    }

    #[test]
    fn test_optimal_spread_invalid_risk_aversion() {
        let result = calculate_optimal_spread(dec!(-0.1), dec!(0.2), 3600000, dec!(1.5));
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            MMError::InvalidConfiguration(_)
        ));
    }

    #[test]
    fn test_optimal_spread_invalid_volatility() {
        let result = calculate_optimal_spread(dec!(0.1), dec!(-0.2), 3600000, dec!(1.5));
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            MMError::InvalidConfiguration(_)
        ));
    }

    #[test]
    fn test_optimal_spread_invalid_order_intensity() {
        let result = calculate_optimal_spread(dec!(0.1), dec!(0.2), 3600000, dec!(-1.5));
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            MMError::InvalidConfiguration(_)
        ));
    }

    #[test]
    fn test_optimal_spread_non_finite_result() {
        // Very large volatility - Decimal handles large numbers better
        let result = calculate_optimal_spread(
            dec!(0.1),
            Decimal::from_parts(u32::MAX, 0, 0, false, 10),
            3600000,
            dec!(1.5),
        );
        // May succeed or error - just checking it doesn't panic
        let _ = result;
    }

    #[test]
    fn test_optimal_spread_negative_result() {
        // Aunque matemáticamente el spread no debería ser negativo,
        // probamos el path de error con valores extremos
        // La fórmula: δ = γ * σ² * (T - t) + (2/γ) * ln(1 + γ/k)
        // Es muy difícil hacer que esto sea negativo con valores válidos
        // Este test verifica que el código maneja el caso correctamente
        let result = calculate_optimal_spread(
            dec!(0.0001),
            dec!(0.0001),
            1,             // tiempo muy pequeño
            dec!(1000000), // k muy grande
        );
        // El resultado debería ser válido o dar error numérico, pero no negativo
        // Error es aceptable en casos extremos
        if let Ok(spread) = result {
            assert!(spread >= Decimal::ZERO);
        }
    }

    #[test]
    fn test_optimal_quotes_valid() {
        let result = calculate_optimal_quotes(
            dec!(100.0),
            Decimal::ZERO,
            dec!(0.1),
            dec!(0.2),
            3600000,
            dec!(1.5),
        );
        assert!(result.is_ok());
        let (bid, ask) = result.unwrap();
        assert!(bid < ask);
        assert!(bid < dec!(100.0));
        assert!(ask > dec!(100.0));
        assert!(bid > Decimal::ZERO);
    }

    #[test]
    fn test_optimal_quotes_with_positive_inventory() {
        let (bid_flat, ask_flat) = calculate_optimal_quotes(
            dec!(100.0),
            Decimal::ZERO,
            dec!(0.1),
            dec!(0.2),
            3600000,
            dec!(1.5),
        )
        .unwrap();
        let (bid_long, ask_long) = calculate_optimal_quotes(
            dec!(100.0),
            dec!(10.0),
            dec!(0.1),
            dec!(0.2),
            3600000,
            dec!(1.5),
        )
        .unwrap();

        // With long inventory, both quotes should be lower
        assert!(bid_long < bid_flat);
        assert!(ask_long < ask_flat);
    }

    #[test]
    fn test_optimal_quotes_with_negative_inventory() {
        let (bid_flat, ask_flat) = calculate_optimal_quotes(
            dec!(100.0),
            Decimal::ZERO,
            dec!(0.1),
            dec!(0.2),
            3600000,
            dec!(1.5),
        )
        .unwrap();
        let (bid_short, ask_short) = calculate_optimal_quotes(
            dec!(100.0),
            dec!(-10.0),
            dec!(0.1),
            dec!(0.2),
            3600000,
            dec!(1.5),
        )
        .unwrap();

        // With short inventory, both quotes should be higher
        assert!(bid_short > bid_flat);
        assert!(ask_short > ask_flat);
    }

    #[test]
    fn test_optimal_quotes_spread_positive() {
        let (bid, ask) = calculate_optimal_quotes(
            dec!(100.0),
            Decimal::ZERO,
            dec!(0.1),
            dec!(0.2),
            3600000,
            dec!(1.5),
        )
        .unwrap();
        assert!(ask - bid > Decimal::ZERO);
    }

    #[test]
    fn test_optimal_quotes_negative_bid_error() {
        // With very low mid price and large negative inventory, bid can become negative
        let result = calculate_optimal_quotes(
            dec!(0.5),
            dec!(-1000.0),
            dec!(1.0),
            dec!(1.0),
            36000000,
            dec!(0.1),
        );
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            MMError::InvalidQuoteGeneration(_)
        ));
    }

    #[test]
    fn test_optimal_quotes_bid_exceeds_ask_error() {
        // Extreme parameters that could theoretically cause bid >= ask
        let result = calculate_optimal_quotes(
            dec!(100.0),
            Decimal::from_parts(u32::MAX, u32::MAX, 0, false, 0),
            dec!(0.0000000001),
            dec!(0.001),
            1,
            Decimal::from_parts(u32::MAX, u32::MAX, 0, false, 0),
        );
        // If the model produces invalid quotes, it should error
        if let Err(err) = result {
            // Could be InvalidQuoteGeneration or some other error from validation
            assert!(matches!(
                err,
                MMError::InvalidQuoteGeneration(_)
                    | MMError::InvalidMarketState(_)
                    | MMError::InvalidConfiguration(_)
                    | MMError::NumericalError(_)
            ));
        }
    }
}