betex 0.4.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
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
//! Hedge calculation for risk-free (or risk-tolerant) cross-matching.
//!
//! This module implements the algorithm to find hedge leg stakes that satisfy
//! the risk constraints for a 3-runner market, for both BACK and LAY user orders.

use crate::book::protocol::command::Side;
use crate::types::{Money, OddsX10000, RunnerId};

fn clamp_i128_to_i64(v: i128) -> i64 {
    if v > i64::MAX as i128 {
        i64::MAX
    } else if v < i64::MIN as i128 {
        i64::MIN
    } else {
        v as i64
    }
}

fn profit_quanta(stake: Money, odds: OddsX10000) -> i64 {
    // Keep this consistent with the engine's settlement/PnL math:
    // profit = stake * (odds - 1) = stake * (odds_x10000 - 10_000) / 10_000
    let stake_i = stake.0 as i128;
    let odds_i = odds.0 as i128;
    let profit = (stake_i * (odds_i - 10_000)) / 10_000;
    clamp_i128_to_i64(profit)
}

/// A calculated hedge leg for cross-matching.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HedgeLeg {
    /// Runner to hedge on
    pub runner_id: RunnerId,
    /// Odds to place the hedge at
    pub odds: OddsX10000,
    /// Stake for this hedge leg
    pub stake: Money,
    /// Side of the hedge order (opposite of user's side on target runner)
    pub side: Side,
}

/// Result of hedge calculation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HedgeResult {
    /// Successfully found hedge legs that satisfy constraints.
    Success {
        /// Hedge legs to execute
        legs: Vec<HedgeLeg>,
        /// Worst-case P&L across all outcomes (should be >= -tolerance)
        worst_case_pnl: Money,
    },
    /// No valid hedge exists within risk tolerance.
    NoSolution { reason: &'static str },
}

/// Input for hedge calculation.
#[derive(Debug, Clone)]
pub struct HedgeInput {
    /// Runner the user is betting on
    pub target_runner: RunnerId,
    /// User's side (Back or Lay)
    pub user_side: Side,
    /// User's odds
    pub user_odds: OddsX10000,
    /// User's stake
    pub user_stake: Money,
    /// Other runners with their best prices and available liquidity.
    /// For BACK user orders: best BACK prices (what house can LAY against)
    /// For LAY user orders: best LAY prices (what house can BACK against)
    pub other_runners: Vec<(RunnerId, OddsX10000, Money)>, // (runner, odds, available_size)
    /// Maximum allowed loss (from RiskTolerance.effective_tolerance)
    pub max_loss: Money,
}

/// Calculate hedge legs for a 3-runner cross-match.
///
/// Dispatches to the appropriate algorithm based on user's side.
pub fn calculate_3runner_hedge(input: &HedgeInput) -> HedgeResult {
    // Validate we have exactly 2 other runners
    if input.other_runners.len() != 2 {
        return HedgeResult::NoSolution {
            reason: "Expected exactly 2 other runners for 3-runner market",
        };
    }

    match input.user_side {
        Side::Yes => calculate_back_hedge(input),
        Side::No => calculate_lay_hedge(input),
    }
}

/// Calculate hedge for a user BACK order.
///
/// User backs runner A at odds `a` for stake `s`.
/// House LAYs A (matches user), then LAYs other runners as hedge.
///
/// P&L:
/// - P_A = -L + tB + tC  (house loses liability, wins hedge stakes)
/// - P_B = s + tC - tB*(oB-1)  (house wins user stake, wins tC, pays out on B)
/// - P_C = s + tB - tC*(oC-1)  (house wins user stake, wins tB, pays out on C)
///
/// Constraints:
/// - tB + tC >= L - slack  (cover liability minus allowed loss if A wins)
/// - tB <= (s + tC + slack) / (oB - 1)  (limit loss if B wins)
/// - tC <= (s + tB + slack) / (oC - 1)  (limit loss if C wins)
fn calculate_back_hedge(input: &HedgeInput) -> HedgeResult {
    let (runner_b, odds_b, size_b) = input.other_runners[0];
    let (runner_c, odds_c, size_c) = input.other_runners[1];

    let ob = odds_b.to_decimal();
    let oc = odds_c.to_decimal();

    if ob <= 1.0 || oc <= 1.0 {
        return HedgeResult::NoSolution {
            reason: "Invalid odds (must be > 1.0)",
        };
    }

    let s = input.user_stake.0 as f64;
    let slack = input.max_loss.0 as f64;

    // Liability if A wins: L = s * (a - 1)
    let liability = profit_quanta(input.user_stake, input.user_odds) as f64;

    // Minimum hedge required: L - slack (can accept up to slack loss if A wins)
    // P_A = -L + tB + tC >= -slack => tB + tC >= L - slack
    let min_hedge_required = (liability - slack).max(0.0);

    // For a hedge target T, the stake bounds are:
    // From P_B: tB <= (s + T + slack) / oB
    // From P_C: tC <= (s + T + slack) / oC
    // Also from P_C rearranged: tB >= ((oC-1)*T - s - slack) / oC (to ensure tC constraint)
    // Also from P_B rearranged: tC >= ((oB-1)*T - s - slack) / oB (to ensure tB constraint)

    // Calculate bounds for target = min_hedge_required
    let target = min_hedge_required;
    let max_tb = (s + target + slack) / ob;
    let max_tc = (s + target + slack) / oc;
    let min_tb = (((oc - 1.0) * target - s - slack) / oc).max(0.0);
    let min_tc = (((ob - 1.0) * target - s - slack) / ob).max(0.0);

    // Check if a valid split exists
    if min_tb > max_tb || min_tc > max_tc || min_tb + min_tc > target {
        return HedgeResult::NoSolution {
            reason: "Insufficient hedge capacity within risk tolerance",
        };
    }

    // Find valid split: tB + tC = target, with min/max bounds
    let (tb, tc) = find_valid_split_with_bounds(target, min_tb, max_tb, min_tc, max_tc);

    if tb < 0.0 || tc < 0.0 {
        return HedgeResult::NoSolution {
            reason: "Could not find non-negative hedge stakes",
        };
    }

    let tb_money = Money((tb.round() as i64).max(0));
    let tc_money = Money((tc.round() as i64).max(0));

    // Check liquidity
    if tb_money.0 > size_b.0 {
        return HedgeResult::NoSolution {
            reason: "Insufficient liquidity on runner B",
        };
    }
    if tc_money.0 > size_c.0 {
        return HedgeResult::NoSolution {
            reason: "Insufficient liquidity on runner C",
        };
    }

    // Calculate worst-case P&L
    let pnl_a = -profit_quanta(input.user_stake, input.user_odds) + tb_money.0 + tc_money.0;
    let pnl_b = input.user_stake.0 + tc_money.0 - profit_quanta(tb_money, odds_b);
    let pnl_c = input.user_stake.0 + tb_money.0 - profit_quanta(tc_money, odds_c);

    let worst_pnl = pnl_a.min(pnl_b).min(pnl_c);

    if worst_pnl < -(input.max_loss.0) {
        return HedgeResult::NoSolution {
            reason: "Calculated hedge exceeds risk tolerance",
        };
    }

    HedgeResult::Success {
        legs: vec![
            HedgeLeg {
                runner_id: runner_b,
                odds: odds_b,
                stake: tb_money,
                side: Side::No, // House LAYs other runners
            },
            HedgeLeg {
                runner_id: runner_c,
                odds: odds_c,
                stake: tc_money,
                side: Side::No,
            },
        ],
        worst_case_pnl: Money(worst_pnl),
    }
}

/// Calculate hedge for a user LAY order.
///
/// User lays runner A at odds `a` for stake `s`.
/// House BACKs A (matches user), then BACKs other runners as hedge.
///
/// P&L:
/// - P_A = s*(a-1) - tB - tC  (house wins profit, loses hedge stakes)
/// - P_B = -s + tB*(oB-1) - tC  (house loses user stake, wins on B, loses tC)
/// - P_C = -s - tB + tC*(oC-1)  (house loses user stake, loses tB, wins on C)
///
/// Constraints (MINIMUMS - must hedge enough):
/// - tB + tC <= s*(a-1)  (can't spend more than A-win profit)
/// - tB >= (s + tC - slack) / (oB - 1)
/// - tC >= (s + tB - slack) / (oC - 1)
fn calculate_lay_hedge(input: &HedgeInput) -> HedgeResult {
    let (runner_b, odds_b, size_b) = input.other_runners[0];
    let (runner_c, odds_c, size_c) = input.other_runners[1];

    let ob = odds_b.to_decimal();
    let oc = odds_c.to_decimal();

    if ob <= 1.0 || oc <= 1.0 {
        return HedgeResult::NoSolution {
            reason: "Invalid odds (must be > 1.0)",
        };
    }

    let s = input.user_stake.0 as f64;
    let slack = input.max_loss.0 as f64;

    // Profit if A wins: P = s * (a - 1)
    let profit_if_a_wins = profit_quanta(input.user_stake, input.user_odds) as f64;

    // Maximum total hedge: tB + tC <= profit_if_a_wins
    let max_total = profit_if_a_wins;

    // Minimum stakes required by constraints (accounting for slack)
    // tB >= (s + tC - slack) / (oB - 1)
    // tC >= (s + tB - slack) / (oC - 1)
    //
    // For a symmetric solution where tB = tC = t:
    // t >= (s + t - slack) / (o - 1)  where o is the common odds
    // t * (o - 1) >= s + t - slack
    // t * (o - 2) >= s - slack
    // t >= (s - slack) / (o - 2)  if o > 2
    //
    // For asymmetric case, we solve iteratively.

    // Try to find (tB, tC) that satisfies all constraints
    let result = find_lay_hedge_stakes(s, slack, ob, oc, max_total);

    let (tb, tc) = match result {
        Some((tb, tc)) => (tb, tc),
        None => {
            return HedgeResult::NoSolution {
                reason: "No valid hedge exists for LAY order",
            };
        }
    };

    let profit_budget = profit_quanta(input.user_stake, input.user_odds);
    let tb_floor = tb.floor().max(0.0) as i64;
    let tb_ceil = tb.ceil().max(0.0) as i64;
    let tc_floor = tc.floor().max(0.0) as i64;
    let tc_ceil = tc.ceil().max(0.0) as i64;

    let tb_min = tb_floor.saturating_sub(2);
    let tb_max = tb_ceil.saturating_add(2);
    let tc_min = tc_floor.saturating_sub(2);
    let tc_max = tc_ceil.saturating_add(2);

    let mut best: Option<(Money, Money, i64)> = None; // (tb, tc, worst_pnl)
    let mut blocked_b = false;
    let mut blocked_c = false;
    for tb_i in tb_min..=tb_max {
        for tc_i in tc_min..=tc_max {
            let tb_money = Money(tb_i);
            let tc_money = Money(tc_i);

            if tb_money.0.saturating_add(tc_money.0) > profit_budget {
                continue;
            }

            let pnl_a = profit_budget - tb_money.0 - tc_money.0;
            let pnl_b = -input.user_stake.0 + profit_quanta(tb_money, odds_b) - tc_money.0;
            let pnl_c = -input.user_stake.0 - tb_money.0 + profit_quanta(tc_money, odds_c);
            let worst_pnl = pnl_a.min(pnl_b).min(pnl_c);

            if worst_pnl < -(input.max_loss.0) {
                continue;
            }

            if tb_money.0 > size_b.0 {
                blocked_b = true;
                continue;
            }
            if tc_money.0 > size_c.0 {
                blocked_c = true;
                continue;
            }

            best = match best {
                None => Some((tb_money, tc_money, worst_pnl)),
                Some((best_tb, best_tc, best_worst)) => {
                    let best_total = best_tb.0 + best_tc.0;
                    let total = tb_money.0 + tc_money.0;
                    if worst_pnl > best_worst || (worst_pnl == best_worst && total < best_total) {
                        Some((tb_money, tc_money, worst_pnl))
                    } else {
                        Some((best_tb, best_tc, best_worst))
                    }
                }
            };
        }
    }

    let Some((tb_money, tc_money, worst_pnl)) = best else {
        if blocked_b || blocked_c {
            return HedgeResult::NoSolution {
                reason: "Insufficient liquidity",
            };
        }
        return HedgeResult::NoSolution {
            reason: "Calculated hedge exceeds risk tolerance",
        };
    };

    HedgeResult::Success {
        legs: vec![
            HedgeLeg {
                runner_id: runner_b,
                odds: odds_b,
                stake: tb_money,
                side: Side::Yes, // House BACKs other runners
            },
            HedgeLeg {
                runner_id: runner_c,
                odds: odds_c,
                stake: tc_money,
                side: Side::Yes,
            },
        ],
        worst_case_pnl: Money(worst_pnl),
    }
}

/// Find valid hedge stakes for LAY order.
///
/// Constraints:
/// - tB + tC <= max_total
/// - tB >= (s + tC - slack) / (oB - 1)
/// - tC >= (s + tB - slack) / (oC - 1)
fn find_lay_hedge_stakes(
    s: f64,
    slack: f64,
    ob: f64,
    oc: f64,
    max_total: f64,
) -> Option<(f64, f64)> {
    // Minimum stakes required (assuming the other is 0)
    let min_tb_base = (s - slack) / (ob - 1.0);
    let min_tc_base = (s - slack) / (oc - 1.0);

    // If both minimums are negative (slack > s), any non-negative stake works
    if min_tb_base <= 0.0 && min_tc_base <= 0.0 {
        // Just use symmetric split up to max_total
        let total = max_total.min(s); // Don't need more than s
        return Some((total / 2.0, total / 2.0));
    }

    // Iteratively solve for (tB, tC)
    // Start with minimum requirements and adjust
    let mut tb = min_tb_base.max(0.0);
    let mut tc = min_tc_base.max(0.0);

    // Adjust based on cross-dependencies
    for _ in 0..10 {
        let new_tb = ((s + tc - slack) / (ob - 1.0)).max(0.0);
        let new_tc = ((s + tb - slack) / (oc - 1.0)).max(0.0);

        if (new_tb - tb).abs() < 0.01 && (new_tc - tc).abs() < 0.01 {
            break;
        }

        tb = new_tb;
        tc = new_tc;
    }

    // Check if solution is within budget
    if tb + tc > max_total {
        return None;
    }

    // Check for non-negative
    if tb < 0.0 || tc < 0.0 {
        return None;
    }

    Some((tb, tc))
}

/// Find a valid (tB, tC) split for BACK hedging such that:
/// tB + tC = target, min_tb <= tB <= max_tb, and min_tc <= tC <= max_tc.
fn find_valid_split_with_bounds(
    target: f64,
    min_tb: f64,
    max_tb: f64,
    min_tc: f64,
    max_tc: f64,
) -> (f64, f64) {
    // tB + tC = target, so tC = target - tB
    // Valid range for tB: [max(min_tb, target - max_tc), min(max_tb, target - min_tc)]
    let tb_lower = min_tb.max(target - max_tc);
    let tb_upper = max_tb.min(target - min_tc);

    if tb_lower > tb_upper {
        return (-1.0, -1.0); // No solution
    }

    // Pick tB in the middle of the valid range for balanced allocation
    let tb = (tb_lower + tb_upper) / 2.0;
    let tc = target - tb;

    (tb, tc)
}

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

    fn odds(decimal: f64) -> OddsX10000 {
        OddsX10000::from_decimal(decimal)
    }

    fn cents(cents: i64) -> Money {
        Money::from_cents(cents)
    }

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

    #[test]
    fn test_back_worked_example_risk_free() {
        // From the spec: User backs Man Utd @ 2.00 for $100
        // Available: Lay Draw @ 4.00, Lay Chelsea @ 4.00
        let input = HedgeInput {
            target_runner: RunnerId(1),
            user_side: Side::Yes,
            user_odds: odds(2.00),
            user_stake: Money::from_cents(10_000), // $100 (Money is quanta; cents -> quanta)
            other_runners: vec![
                (RunnerId(2), odds(4.00), Money::from_cents(50_000)), // Draw
                (RunnerId(3), odds(4.00), Money::from_cents(50_000)), // Chelsea
            ],
            max_loss: Money(0), // Risk-free
        };

        let result = calculate_3runner_hedge(&input);

        match result {
            HedgeResult::Success {
                legs,
                worst_case_pnl,
            } => {
                assert_eq!(legs.len(), 2);
                assert_eq!(legs[0].stake, Money::from_cents(5_000)); // $50
                assert_eq!(legs[1].stake, Money::from_cents(5_000)); // $50
                assert_eq!(legs[0].side, Side::No);
                assert_eq!(legs[1].side, Side::No);
                assert_eq!(worst_case_pnl, Money(0));
            }
            HedgeResult::NoSolution { reason } => {
                panic!("Expected success, got: {}", reason);
            }
        }
    }

    #[test]
    fn test_back_no_solution_when_odds_too_low() {
        let input = HedgeInput {
            target_runner: RunnerId(1),
            user_side: Side::Yes,
            user_odds: odds(2.14),
            user_stake: Money::from_cents(10_000),
            other_runners: vec![
                (RunnerId(2), odds(3.40), Money::from_cents(50_000)),
                (RunnerId(3), odds(4.20), Money::from_cents(50_000)),
            ],
            max_loss: Money(0),
        };

        let result = calculate_3runner_hedge(&input);

        match result {
            HedgeResult::Success { worst_case_pnl, .. } => {
                assert!(worst_case_pnl.0 >= 0, "Should be risk-free");
            }
            HedgeResult::NoSolution { .. } => {
                // Expected - no risk-free solution exists
            }
        }
    }

    #[test]
    fn test_back_with_tolerance_enables_more_matches() {
        let input = HedgeInput {
            target_runner: RunnerId(1),
            user_side: Side::Yes,
            user_odds: odds(2.14),
            user_stake: cents(10_000),
            other_runners: vec![
                (RunnerId(2), odds(3.40), cents(50_000)),
                (RunnerId(3), odds(4.20), cents(50_000)),
            ],
            max_loss: cents(500), // $5 tolerance
        };

        let result = calculate_3runner_hedge(&input);

        match result {
            HedgeResult::Success { worst_case_pnl, .. } => {
                assert!(
                    worst_case_pnl.0 >= -cents(500).0,
                    "Should be within tolerance"
                );
            }
            HedgeResult::NoSolution { .. } => {
                // May still fail
            }
        }
    }

    #[test]
    fn test_back_insufficient_liquidity() {
        let input = HedgeInput {
            target_runner: RunnerId(1),
            user_side: Side::Yes,
            user_odds: odds(2.00),
            user_stake: cents(10_000),
            other_runners: vec![
                (RunnerId(2), odds(4.00), cents(1_000)),
                (RunnerId(3), odds(4.00), cents(1_000)),
            ],
            max_loss: Money(0),
        };

        let result = calculate_3runner_hedge(&input);

        match result {
            HedgeResult::NoSolution { reason } => {
                assert!(reason.contains("liquidity"), "Should fail due to liquidity");
            }
            HedgeResult::Success { .. } => {
                panic!("Should have failed due to insufficient liquidity");
            }
        }
    }

    #[test]
    fn test_back_asymmetric_odds() {
        // User backs A @ 2.00 for $100 => liability = $100
        // Odds B = 3.00, C = 6.00 (asymmetric)
        // With tolerance = $10, we only need to hedge $90 (liability - tolerance)
        let input = HedgeInput {
            target_runner: RunnerId(1),
            user_side: Side::Yes,
            user_odds: odds(2.00),
            user_stake: cents(10_000),
            other_runners: vec![
                (RunnerId(2), odds(3.00), cents(100_000)),
                (RunnerId(3), odds(6.00), cents(100_000)),
            ],
            max_loss: cents(1_000), // $10 tolerance
        };

        let result = calculate_3runner_hedge(&input);

        match result {
            HedgeResult::Success {
                legs,
                worst_case_pnl,
            } => {
                let total_stake: i64 = legs.iter().map(|l| l.stake.0).sum();
                // With $10 tolerance, hedge = liability - tolerance = $90
                assert!(
                    total_stake >= cents(9_000).0,
                    "Should cover liability minus tolerance"
                );
                assert!(
                    worst_case_pnl.0 >= -cents(1_000).0,
                    "Should be within tolerance"
                );
            }
            HedgeResult::NoSolution { reason } => {
                panic!("Expected success, got: {}", reason);
            }
        }
    }

    #[test]
    fn test_back_partial_coverage_with_tolerance() {
        // User backs A @ 2.00 for $100 => liability = $100
        // Tolerance = $50 => only need $50 hedge coverage (liability - tolerance)
        // Available liquidity: $40 each = $80 total
        // This should SUCCEED because $80 > $50 minimum required
        let input = HedgeInput {
            target_runner: RunnerId(1),
            user_side: Side::Yes,
            user_odds: odds(2.00),
            user_stake: cents(10_000), // $100
            other_runners: vec![
                (RunnerId(2), odds(4.00), cents(4_000)), // Only $40 available
                (RunnerId(3), odds(4.00), cents(4_000)), // Only $40 available
            ],
            max_loss: cents(5_000), // $50 tolerance
        };

        let result = calculate_3runner_hedge(&input);

        match result {
            HedgeResult::Success {
                legs,
                worst_case_pnl,
            } => {
                let total_stake: i64 = legs.iter().map(|l| l.stake.0).sum();
                // Should hedge $50 (liability - tolerance), not full $100
                assert_eq!(
                    total_stake,
                    cents(5_000).0,
                    "Should hedge liability minus tolerance"
                );
                // Worst case is if A wins: -100 + 50 = -50, within tolerance
                assert!(
                    worst_case_pnl.0 >= -cents(5_000).0,
                    "Should be within tolerance"
                );
            }
            HedgeResult::NoSolution { reason } => {
                panic!("Should succeed with partial coverage, got: {}", reason);
            }
        }
    }

    #[test]
    fn test_back_tolerance_exceeds_liability() {
        // User backs A @ 1.50 for $100 => liability = $50
        // Tolerance = $100 => no hedge needed at all (liability - tolerance = -50 => 0)
        let input = HedgeInput {
            target_runner: RunnerId(1),
            user_side: Side::Yes,
            user_odds: odds(1.50),
            user_stake: cents(10_000), // $100
            other_runners: vec![
                (RunnerId(2), odds(4.00), cents(1_000)), // Minimal liquidity
                (RunnerId(3), odds(4.00), cents(1_000)),
            ],
            max_loss: cents(10_000), // $100 tolerance (exceeds $50 liability)
        };

        let result = calculate_3runner_hedge(&input);

        match result {
            HedgeResult::Success {
                legs,
                worst_case_pnl,
            } => {
                let total_stake: i64 = legs.iter().map(|l| l.stake.0).sum();
                // min_hedge_required = max(50 - 100, 0) = 0
                assert_eq!(total_stake, 0, "Should require zero hedge");
                assert!(
                    worst_case_pnl.0 >= -cents(10_000).0,
                    "Should be within tolerance"
                );
            }
            HedgeResult::NoSolution { reason } => {
                panic!("Should succeed with zero hedge, got: {}", reason);
            }
        }
    }

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

    #[test]
    fn test_lay_worked_example_risk_free() {
        // User lays Man Utd @ 2.00 for $100
        // Available: Back Draw @ 4.00, Back Chelsea @ 4.00
        let input = HedgeInput {
            target_runner: RunnerId(1),
            user_side: Side::No,
            user_odds: odds(2.00),
            user_stake: cents(10_000), // $100
            other_runners: vec![
                (RunnerId(2), odds(4.00), cents(50_000)), // Draw
                (RunnerId(3), odds(4.00), cents(50_000)), // Chelsea
            ],
            max_loss: Money(0), // Risk-free
        };

        let result = calculate_3runner_hedge(&input);

        match result {
            HedgeResult::Success {
                legs,
                worst_case_pnl,
            } => {
                assert_eq!(legs.len(), 2);
                // House BACKs other runners
                assert_eq!(legs[0].side, Side::Yes);
                assert_eq!(legs[1].side, Side::Yes);
                // Verify stakes are within budget (profit if A wins = $100)
                let total_stake: i64 = legs.iter().map(|l| l.stake.0).sum();
                assert!(
                    total_stake <= cents(10_000).0,
                    "Should not exceed profit budget"
                );
                assert!(worst_case_pnl.0 >= 0, "Should be risk-free");
            }
            HedgeResult::NoSolution { reason } => {
                panic!("Expected success, got: {}", reason);
            }
        }
    }

    #[test]
    fn test_lay_symmetric_odds() {
        // User lays A @ 2.00 for $100 (liability = $100)
        // If A wins: house wins $100
        // If A loses: house loses $100, needs hedge profit
        //
        // With odds 4.00 on B and C, backing $50 each:
        // - If B wins: profit = 50*(4-1) = 150, minus tC = 50 - s = 100 = 0
        // - If C wins: profit = 50*(4-1) = 150, minus tB = 50 - s = 100 = 0
        let input = HedgeInput {
            target_runner: RunnerId(1),
            user_side: Side::No,
            user_odds: odds(2.00),
            user_stake: cents(10_000),
            other_runners: vec![
                (RunnerId(2), odds(4.00), cents(50_000)),
                (RunnerId(3), odds(4.00), cents(50_000)),
            ],
            max_loss: Money(0),
        };

        let result = calculate_3runner_hedge(&input);

        match result {
            HedgeResult::Success {
                legs,
                worst_case_pnl,
            } => {
                // With symmetric odds @ 4.00, expect $50 each
                // min_t = (s - slack) / (o - 1) = 100 / 3 = 33.33
                // Total = 66.67 which is < 100 budget
                let total_stake: i64 = legs.iter().map(|l| l.stake.0).sum();
                assert!(total_stake <= cents(10_000).0, "Within budget");
                assert!(worst_case_pnl.0 >= 0, "Risk-free");
            }
            HedgeResult::NoSolution { reason } => {
                panic!("Expected success, got: {}", reason);
            }
        }
    }

    #[test]
    fn test_lay_insufficient_liquidity() {
        let input = HedgeInput {
            target_runner: RunnerId(1),
            user_side: Side::No,
            user_odds: odds(2.00),
            user_stake: cents(10_000),
            other_runners: vec![
                (RunnerId(2), odds(4.00), cents(1_000)), // Only $10 available
                (RunnerId(3), odds(4.00), cents(1_000)),
            ],
            max_loss: Money(0),
        };

        let result = calculate_3runner_hedge(&input);

        match result {
            HedgeResult::NoSolution { reason } => {
                assert!(reason.contains("liquidity"), "Should fail due to liquidity");
            }
            HedgeResult::Success { .. } => {
                panic!("Should have failed due to insufficient liquidity");
            }
        }
    }

    #[test]
    fn test_lay_low_odds_no_solution() {
        // User lays A @ 1.50 for $100
        // Profit if A wins = 100 * 0.5 = $50 (budget for hedges)
        // But need hedges that pay out $100 if B or C wins
        // With odds 2.00, need stake >= 100 / 1 = $100, but budget is only $50
        let input = HedgeInput {
            target_runner: RunnerId(1),
            user_side: Side::No,
            user_odds: odds(1.50),
            user_stake: cents(10_000),
            other_runners: vec![
                (RunnerId(2), odds(2.00), cents(50_000)),
                (RunnerId(3), odds(2.00), cents(50_000)),
            ],
            max_loss: Money(0),
        };

        let result = calculate_3runner_hedge(&input);

        // This should fail - budget too small for required hedges
        match result {
            HedgeResult::NoSolution { .. } => {
                // Expected
            }
            HedgeResult::Success { worst_case_pnl, .. } => {
                // If it succeeds, P&L should be >= 0
                assert!(worst_case_pnl.0 >= 0);
            }
        }
    }

    #[test]
    fn test_lay_with_tolerance() {
        // Harder scenario that needs tolerance
        let input = HedgeInput {
            target_runner: RunnerId(1),
            user_side: Side::No,
            user_odds: odds(1.50),
            user_stake: cents(10_000),
            other_runners: vec![
                (RunnerId(2), odds(3.00), cents(50_000)),
                (RunnerId(3), odds(3.00), cents(50_000)),
            ],
            max_loss: cents(1_000), // $10 tolerance
        };

        let result = calculate_3runner_hedge(&input);

        match result {
            HedgeResult::Success { worst_case_pnl, .. } => {
                assert!(
                    worst_case_pnl.0 >= -cents(1_000).0,
                    "Should be within tolerance"
                );
            }
            HedgeResult::NoSolution { .. } => {
                // May still fail
            }
        }
    }
}