betex 0.7.5

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
//! 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)
}