betex 0.5.0

Betfair / Prediction Market Exchange
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
//! Cross-matching engine for multi-runner markets.
//!
//! Cross-matching allows the exchange to fill user orders by creating
//! offsetting positions on other runners. The exchange uses an internal
//! house account to execute hedge legs, ensuring risk stays within
//! configured tolerance.
//!
//! ## Compensation Model
//!
//! Cross-matching follows an **all-or-nothing** model with void-on-failure:
//!
//! 1. The engine attempts to match the user's order and execute hedge legs
//! 2. If any hedge leg fails, all successful trades are voided
//! 3. Events from both the trades and voids are returned in `partial_events`
//!
//! This ensures the house never holds an unhedged position due to partial
//! cross-match failures.
//!
//! ## Risk Tolerance
//!
//! The [`RiskTolerance`] configuration controls how much worst-case loss the
//! house is willing to accept per cross-match:
//!
//! - **Risk-free**: Only accept perfectly hedged positions (worst-case P&L = 0)
//! - **Moderate**: Allow small losses to enable more matches
//! - **Custom**: Specify absolute and/or percentage-based tolerance
//!
//! Higher tolerance enables more cross-matches but increases house exposure.
//!
//! ## Example
//!
//! ```ignore
//! use btx::cross_match::{CrossMatchEngine, CrossMatchConfig, RiskTolerance};
//!
//! let config = CrossMatchConfig {
//!     risk: RiskTolerance::risk_free(),
//!     ..Default::default()
//! };
//! let mut engine = CrossMatchEngine::new(config);
//!
//! // After a user order rests without matching...
//! match engine.attempt_cross_match(&mut book, user_order_id) {
//!     CrossMatchResult::Success { events, hedge_legs, worst_case_pnl } => {
//!         // Cross-match succeeded - events include user match + hedge trades
//!         journal_events(&events);
//!     }
//!     CrossMatchResult::Failed { reason, partial_events } => {
//!         // Hedge leg failed - partial_events include matched trades AND their voids
//!         journal_events(&partial_events);
//!     }
//!     CrossMatchResult::NotPossible { reason } => {
//!         // No cross-match possible (insufficient liquidity, odds don't work, etc.)
//!     }
//! }
//! ```

mod config;
mod hedge;

pub use config::{CrossMatchConfig, RiskTolerance};
pub use hedge::{HedgeInput, HedgeLeg, HedgeResult, calculate_3runner_hedge};

use crate::book::protocol::command::{Command, CommandKind, Persistence, Side, TimeInForce};
use crate::book::{Book, BookEvent, BookEventEnvelope};
use crate::types::{AccountId, MarketId, Money, OddsX10000, OrderId, RunnerId, TradeId};

/// Result of a cross-match attempt.
#[derive(Debug, Clone)]
pub enum CrossMatchResult {
    /// Successfully executed cross-match.
    Success {
        /// All events from the cross-match (user match + hedge legs).
        events: Vec<BookEventEnvelope>,
        /// The hedge legs that were executed.
        hedge_legs: Vec<HedgeLeg>,
        /// Worst-case P&L for the house.
        worst_case_pnl: Money,
    },
    /// No cross-match possible (order remains resting).
    NotPossible { reason: &'static str },
    /// Cross-match attempted but a leg failed.
    Failed {
        reason: &'static str,
        /// Events from legs that did execute (may need compensation).
        partial_events: Vec<BookEventEnvelope>,
    },
}

/// Cross-matching engine.
///
/// Sits above the Book and orchestrates multi-leg cross-match execution.
/// The controller is responsible for transaction semantics (journaling, atomicity).
pub struct CrossMatchEngine {
    config: CrossMatchConfig,
    /// Next correlation id for hedge orders.
    next_correlation_id: u64,
    // TODO: Track aggregate exposure for circuit breaker
    // current_exposure: Money,
}

impl CrossMatchEngine {
    /// Create a new cross-match engine with the given configuration.
    pub fn new(config: CrossMatchConfig) -> Self {
        Self {
            config,
            // Start with high IDs to avoid collision with user orders
            next_correlation_id: 1_000_000_000,
        }
    }

    /// Get the house account ID.
    pub fn house_account(&self) -> AccountId {
        self.config.house_account
    }

    /// Attempt to cross-match a resting user order.
    ///
    /// Supports both BACK and LAY orders:
    /// - BACK: House LAYs target runner, then LAYs other runners as hedge
    /// - LAY: House BACKs target runner, then BACKs other runners as hedge
    ///
    /// # Arguments
    /// * `book` - The order book (will be mutated if cross-match succeeds)
    /// * `user_order_id` - The resting order to cross-match
    ///
    /// # Returns
    /// Result indicating success, not possible, or failure.
    pub fn attempt_cross_match(
        &mut self,
        book: &mut Book,
        user_order_id: OrderId,
    ) -> CrossMatchResult {
        // Get the user's order
        let Some(user_order) = book.get_order(user_order_id) else {
            return CrossMatchResult::NotPossible {
                reason: "Order not found",
            };
        };

        // Check order is still resting
        if !book.is_resting(user_order_id) {
            return CrossMatchResult::NotPossible {
                reason: "Order is not resting",
            };
        }

        let target_runner = user_order.runner_id;
        let user_side = user_order.info.side;
        let user_odds = user_order.price;
        let user_stake = user_order.remaining();

        // Get all runners in the market
        let runners: Vec<RunnerId> = book.runners().collect();

        // Check runner count
        if runners.len() != 3 {
            return CrossMatchResult::NotPossible {
                reason: "Cross-matching only supported for 3-runner markets",
            };
        }
        if runners.len() > self.config.max_runners {
            return CrossMatchResult::NotPossible {
                reason: "Too many runners for cross-matching",
            };
        }

        // Get other runners and their best prices for hedging
        // - For BACK orders: we need BACK liquidity on other runners (house will LAY against it)
        // - For LAY orders: we need LAY liquidity on other runners (house will BACK against it)
        let mut other_runners: Vec<(RunnerId, OddsX10000, Money)> = Vec::new();

        for &runner_id in &runners {
            if runner_id == target_runner {
                continue;
            }

            let best_price = match user_side {
                Side::Yes => {
                    // House needs to LAY other runners, so find BACK orders to match against
                    book.best_lay_price(runner_id)
                }
                Side::No => {
                    // House needs to BACK other runners, so find LAY orders to match against
                    book.best_back_price(runner_id)
                }
            };

            let Some(price_size) = best_price else {
                let reason = match user_side {
                    Side::Yes => "No BACK liquidity on other runners",
                    Side::No => "No LAY liquidity on other runners",
                };
                return CrossMatchResult::NotPossible { reason };
            };

            other_runners.push((runner_id, price_size.price, price_size.size));
        }

        // Calculate hedge
        let tolerance = self.config.risk.effective_tolerance(user_stake);
        let hedge_input = HedgeInput {
            target_runner,
            user_side,
            user_odds,
            user_stake,
            other_runners,
            max_loss: tolerance,
        };

        let hedge_result = calculate_3runner_hedge(&hedge_input);

        let (hedge_legs, worst_case_pnl) = match hedge_result {
            HedgeResult::Success {
                legs,
                worst_case_pnl,
            } => (legs, worst_case_pnl),
            HedgeResult::NoSolution { reason } => {
                return CrossMatchResult::NotPossible { reason };
            }
        };

        // TODO: Check aggregate exposure circuit breaker
        // if self.current_exposure + worst_case_pnl.abs() > self.config.risk.max_total_exposure {
        //     return CrossMatchResult::NotPossible {
        //         reason: "Aggregate exposure limit reached",
        //     };
        // }

        // Build commands for execution
        let market_id = book.market_id();
        let mut commands = Vec::new();

        // 1. House takes opposite side of user's order
        let house_match_side = match user_side {
            Side::Yes => Side::No, // User backs, house lays
            Side::No => Side::Yes, // User lays, house backs
        };

        commands.push(self.make_place_order_cmd(
            market_id,
            target_runner,
            house_match_side,
            user_odds,
            user_stake,
        ));

        // 2. House places hedge legs (side comes from hedge calculation)
        for leg in &hedge_legs {
            commands.push(self.make_place_order_cmd(
                market_id,
                leg.runner_id,
                leg.side,
                leg.odds,
                leg.stake,
            ));
        }

        // Execute all commands sequentially, applying emitted events after each leg.
        let mut all_events: Vec<BookEventEnvelope> = Vec::new();
        for cmd in commands {
            match book.handle(&cmd) {
                Ok((events, _)) => {
                    book.apply_all_events(&events);
                    all_events.extend(events);
                }
                Err(_) => {
                    // Compensate by voiding any trades from successful legs
                    let trade_ids = extract_trade_ids(&all_events);
                    if !trade_ids.is_empty() {
                        let void_cmd = Command {
                            correlation_id: crate::types::CorrelationId(self.next_correlation_id),
                            market_id,
                            kind: CommandKind::VoidTradeIds {
                                trade_ids,
                                reason: "Cross-match hedge leg failed".to_string(),
                            },
                        };
                        self.next_correlation_id += 1;
                        if let Ok((void_events, _)) = book.handle(&void_cmd) {
                            book.apply_all_events(&void_events);
                            all_events.extend(void_events);
                        }
                    }
                    return CrossMatchResult::Failed {
                        reason: "Hedge leg rejected",
                        partial_events: all_events,
                    };
                }
            }
        }

        CrossMatchResult::Success {
            events: all_events,
            hedge_legs,
            worst_case_pnl,
        }
    }

    fn make_place_order_cmd(
        &mut self,
        market_id: MarketId,
        runner_id: RunnerId,
        side: Side,
        price: OddsX10000,
        stake: Money,
    ) -> Command {
        let correlation_id = crate::types::CorrelationId(self.next_correlation_id);
        self.next_correlation_id += 1;

        Command {
            correlation_id,
            market_id,
            kind: CommandKind::PlaceOrder {
                runner_id,
                account_id: self.config.house_account,
                client_order_id: None,
                side,
                odds: price,
                stake,
                persistence: Persistence::Lapse,
                time_in_force: TimeInForce::FillOrKill { min_fill: None },
            },
        }
    }
}

/// Extract trade IDs from book events.
fn extract_trade_ids(events: &[BookEventEnvelope]) -> Vec<TradeId> {
    events
        .iter()
        .filter_map(|env| match &env.event {
            BookEvent::TradeMatched { trade_id, .. } => Some(*trade_id),
            _ => None,
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::book::protocol::command::{Command, CommandKind, Persistence, TimeInForce};
    use crate::book::{Book, BookEvent};
    use crate::types::{ClientOrderId, CorrelationId};

    fn setup_3runner_book() -> Book {
        Book::new(MarketId(1), vec![RunnerId(1), RunnerId(2), RunnerId(3)])
    }

    #[allow(clippy::too_many_arguments)]
    fn place_order(
        book: &mut Book,
        cmd_id: u64,
        client_order_id: u64,
        account_id: u64,
        runner_id: u32,
        side: Side,
        odds: f64,
        stake_cents: i64,
    ) -> OrderId {
        let cmd = Command {
            correlation_id: CorrelationId(cmd_id),
            market_id: book.market_id(),
            kind: CommandKind::PlaceOrder {
                runner_id: RunnerId(runner_id),
                account_id: AccountId(account_id),
                client_order_id: Some(ClientOrderId(client_order_id)),
                side,
                odds: OddsX10000::from_decimal(odds),
                stake: Money::from_cents(stake_cents),
                persistence: Persistence::Persist,
                time_in_force: TimeInForce::Gtc,
            },
        };
        let (events, _) = book.handle(&cmd).expect("place order should succeed");
        book.apply_all_events(&events);
        events
            .iter()
            .find_map(|env| match env.event {
                BookEvent::OrderAccepted { order_id, .. } => Some(order_id),
                _ => None,
            })
            .expect("expected OrderAccepted")
    }

    // ==================== BACK ORDER TESTS ====================

    #[test]
    fn test_back_cross_match_basic_success() {
        let mut book = setup_3runner_book();

        // Setup: Place BACK orders on runners 2 and 3 (liquidity for house to LAY against)
        place_order(&mut book, 1, 100, 10, 2, Side::Yes, 4.00, 50_000); // $500 on Draw
        place_order(&mut book, 2, 101, 11, 3, Side::Yes, 4.00, 50_000); // $500 on Chelsea

        // User places BACK on runner 1 (Man Utd) - no direct LAY liquidity
        let user_order_id = place_order(&mut book, 3, 200, 20, 1, Side::Yes, 2.00, 10_000);

        // Verify order is resting
        assert!(book.is_resting(user_order_id));

        // Attempt cross-match
        let config = CrossMatchConfig {
            risk: RiskTolerance::risk_free(),
            ..Default::default()
        };
        let mut engine = CrossMatchEngine::new(config);

        let result = engine.attempt_cross_match(&mut book, user_order_id);

        match result {
            CrossMatchResult::Success {
                events,
                hedge_legs,
                worst_case_pnl,
            } => {
                assert!(!events.is_empty(), "Should have events");
                assert_eq!(hedge_legs.len(), 2, "Should have 2 hedge legs");
                assert_eq!(worst_case_pnl, Money(0), "Should be risk-free");

                // Verify hedge legs are LAY orders
                for leg in &hedge_legs {
                    assert_eq!(leg.side, Side::No);
                }

                // Verify hedge leg stakes (should be $50 each for symmetric odds)
                let total_hedge: i64 = hedge_legs.iter().map(|l| l.stake.0).sum();
                assert_eq!(
                    total_hedge,
                    Money::from_cents(10_000).0,
                    "Hedge should cover $100 liability"
                );
            }
            CrossMatchResult::NotPossible { reason } => {
                panic!("Cross-match should succeed, got: {}", reason);
            }
            CrossMatchResult::Failed { reason, .. } => {
                panic!("Cross-match failed: {}", reason);
            }
        }
    }

    #[test]
    fn test_back_cross_match_no_liquidity() {
        let mut book = setup_3runner_book();

        // User places BACK on runner 1 - but no liquidity on other runners
        let user_order_id = place_order(&mut book, 1, 200, 20, 1, Side::Yes, 2.00, 10_000);

        let config = CrossMatchConfig::default();
        let mut engine = CrossMatchEngine::new(config);

        let result = engine.attempt_cross_match(&mut book, user_order_id);

        match result {
            CrossMatchResult::NotPossible { reason } => {
                assert!(
                    reason.contains("liquidity"),
                    "Should fail due to no liquidity"
                );
            }
            _ => panic!("Should fail due to no liquidity"),
        }
    }

    #[test]
    fn test_cross_match_not_3_runners() {
        // Create a 2-runner market
        let mut book = Book::new(MarketId(1), vec![RunnerId(1), RunnerId(2)]);

        let user_order_id = place_order(&mut book, 1, 200, 20, 1, Side::Yes, 2.00, 10_000);

        let config = CrossMatchConfig::default();
        let mut engine = CrossMatchEngine::new(config);

        let result = engine.attempt_cross_match(&mut book, user_order_id);

        match result {
            CrossMatchResult::NotPossible { reason } => {
                assert!(
                    reason.contains("3-runner"),
                    "Should fail due to runner count"
                );
            }
            _ => panic!("Should fail due to runner count"),
        }
    }

    #[test]
    fn test_cross_match_order_not_found() {
        let mut book = setup_3runner_book();
        let mut engine = CrossMatchEngine::new(CrossMatchConfig::default());

        let result = engine.attempt_cross_match(&mut book, OrderId(999));

        match result {
            CrossMatchResult::NotPossible { reason } => {
                assert_eq!(reason, "Order not found");
            }
            _ => panic!("Expected Order not found"),
        }
    }

    #[test]
    fn test_cross_match_max_runners_limit() {
        let mut book = setup_3runner_book();

        let user_order_id = place_order(&mut book, 1, 200, 20, 1, Side::Yes, 2.00, 10_000);

        let config = CrossMatchConfig {
            max_runners: 2,
            ..CrossMatchConfig::default()
        };
        let mut engine = CrossMatchEngine::new(config);

        let result = engine.attempt_cross_match(&mut book, user_order_id);

        match result {
            CrossMatchResult::NotPossible { reason } => {
                assert_eq!(reason, "Too many runners for cross-matching");
            }
            _ => panic!("Expected max runner limit rejection"),
        }
    }

    // ==================== LAY ORDER TESTS ====================

    #[test]
    fn test_lay_cross_match_basic_success() {
        let mut book = setup_3runner_book();

        // Setup: Place LAY orders on runners 2 and 3 (liquidity for house to BACK against)
        place_order(&mut book, 1, 100, 10, 2, Side::No, 4.00, 50_000); // LAY Draw @ 4.00
        place_order(&mut book, 2, 101, 11, 3, Side::No, 4.00, 50_000); // LAY Chelsea @ 4.00

        // User places LAY on runner 1 (Man Utd) - no direct BACK liquidity
        let user_order_id = place_order(&mut book, 3, 200, 20, 1, Side::No, 2.00, 10_000);

        // Verify order is resting
        assert!(book.is_resting(user_order_id));

        // Attempt cross-match
        let config = CrossMatchConfig {
            risk: RiskTolerance::risk_free(),
            ..Default::default()
        };
        let mut engine = CrossMatchEngine::new(config);

        let result = engine.attempt_cross_match(&mut book, user_order_id);

        match result {
            CrossMatchResult::Success {
                events,
                hedge_legs,
                worst_case_pnl,
            } => {
                assert!(!events.is_empty(), "Should have events");
                assert_eq!(hedge_legs.len(), 2, "Should have 2 hedge legs");
                assert!(worst_case_pnl.0 >= 0, "Should be risk-free or better");

                // Verify hedge legs are BACK orders
                for leg in &hedge_legs {
                    assert_eq!(leg.side, Side::Yes);
                }

                // Verify total hedge is within profit budget
                let total_hedge: i64 = hedge_legs.iter().map(|l| l.stake.0).sum();
                // Profit if A wins = 100 * (2-1) = $100, hedge must be <= $100
                assert!(
                    total_hedge <= Money::from_cents(10_000).0,
                    "Hedge should be within profit budget"
                );
            }
            CrossMatchResult::NotPossible { reason } => {
                panic!("Cross-match should succeed, got: {}", reason);
            }
            CrossMatchResult::Failed { reason, .. } => {
                panic!("Cross-match failed: {}", reason);
            }
        }
    }

    #[test]
    fn test_lay_cross_match_no_liquidity() {
        let mut book = setup_3runner_book();

        // User places LAY on runner 1 - but no LAY liquidity on other runners
        let user_order_id = place_order(&mut book, 1, 200, 20, 1, Side::No, 2.00, 10_000);

        let config = CrossMatchConfig::default();
        let mut engine = CrossMatchEngine::new(config);

        let result = engine.attempt_cross_match(&mut book, user_order_id);

        match result {
            CrossMatchResult::NotPossible { reason } => {
                assert!(
                    reason.contains("liquidity"),
                    "Should fail due to no liquidity"
                );
            }
            _ => panic!("Should fail due to no liquidity"),
        }
    }

    #[test]
    fn test_lay_cross_match_low_odds_no_solution() {
        let mut book = setup_3runner_book();

        // Setup: LAY orders on other runners at 2.00
        place_order(&mut book, 1, 100, 10, 2, Side::No, 2.00, 50_000);
        place_order(&mut book, 2, 101, 11, 3, Side::No, 2.00, 50_000);

        // User lays at very low odds - profit budget is small
        let user_order_id = place_order(&mut book, 3, 200, 20, 1, Side::No, 1.10, 10_000);

        let config = CrossMatchConfig {
            risk: RiskTolerance::risk_free(),
            ..Default::default()
        };
        let mut engine = CrossMatchEngine::new(config);

        let result = engine.attempt_cross_match(&mut book, user_order_id);

        // Should fail - profit budget ($10) is too small to hedge $100 liability
        match result {
            CrossMatchResult::NotPossible { .. } => {
                // Expected
            }
            CrossMatchResult::Success { worst_case_pnl, .. } => {
                // If it succeeds, must be risk-free
                assert!(worst_case_pnl.0 >= 0);
            }
            _ => {}
        }
    }

    #[test]
    fn test_lay_cross_match_with_tolerance() {
        let mut book = setup_3runner_book();

        // Setup: LAY orders on other runners at 3.00
        place_order(&mut book, 1, 100, 10, 2, Side::No, 3.00, 50_000);
        place_order(&mut book, 2, 101, 11, 3, Side::No, 3.00, 50_000);

        // User lays at low odds with some tolerance
        let user_order_id = place_order(&mut book, 3, 200, 20, 1, Side::No, 1.50, 10_000);

        let config = CrossMatchConfig {
            risk: RiskTolerance::moderate(), // Allow some loss
            ..Default::default()
        };
        let mut engine = CrossMatchEngine::new(config);

        let result = engine.attempt_cross_match(&mut book, user_order_id);

        match result {
            CrossMatchResult::Success { worst_case_pnl, .. } => {
                // Should be within moderate tolerance
                assert!(worst_case_pnl.0 >= -10_000, "Should be within tolerance");
            }
            CrossMatchResult::NotPossible { .. } => {
                // May still fail depending on exact math
            }
            _ => {}
        }
    }

    #[test]
    fn test_hedge_failure_voids_successful_trades() {
        let mut book = setup_3runner_book();

        // Setup: BACK liquidity on runner 2 (ample) and runner 3 (very small)
        // When hedge calculation runs, it will see both as having liquidity,
        // but when executing, runner 3's small liquidity won't fill the required stake.
        place_order(&mut book, 1, 100, 10, 2, Side::Yes, 4.00, 50_000); // $500 on runner 2
        place_order(&mut book, 2, 101, 11, 3, Side::Yes, 4.00, 100); // Only $1 on runner 3

        // User places BACK on runner 1 - $100 stake
        let user_order_id = place_order(&mut book, 3, 200, 20, 1, Side::Yes, 2.00, 10_000);

        // Verify order is resting
        assert!(book.is_resting(user_order_id));

        let config = CrossMatchConfig {
            risk: RiskTolerance::risk_free(),
            ..Default::default()
        };
        let mut engine = CrossMatchEngine::new(config);

        let result = engine.attempt_cross_match(&mut book, user_order_id);

        // The cross-match should fail because runner 3 doesn't have enough liquidity
        // to fill the hedge leg
        match result {
            CrossMatchResult::Failed {
                reason,
                partial_events,
            } => {
                assert_eq!(reason, "Hedge leg rejected");
                // Verify that any trades from successful legs were voided
                let trade_voids: Vec<_> = partial_events
                    .iter()
                    .filter(|e| matches!(e.event, BookEvent::TradeVoided { .. }))
                    .collect();
                let trades_matched: Vec<_> = partial_events
                    .iter()
                    .filter(|e| matches!(e.event, BookEvent::TradeMatched { .. }))
                    .collect();
                // If trades were matched before failure, they should be voided
                if !trades_matched.is_empty() {
                    assert_eq!(
                        trade_voids.len(),
                        trades_matched.len(),
                        "Each matched trade should have a corresponding void"
                    );
                }
            }
            CrossMatchResult::NotPossible { reason } => {
                // This is also acceptable if the hedge calculation detects insufficient liquidity
                assert!(
                    reason.contains("liquidity") || reason.contains("solution"),
                    "Expected liquidity or solution related reason, got: {}",
                    reason
                );
            }
            CrossMatchResult::Success { .. } => {
                panic!("Expected failure due to insufficient liquidity on runner 3");
            }
        }
    }
}