betex 0.35.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
//! 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, DateTime, MarketId, Money, OddsX10000, OrderId, RunnerId};
use chrono::Utc;

/// 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.clone()
    }

    /// 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();

        // Enforce deployment cap first, then v1 algorithm constraint.
        if runners.len() > self.config.max_runners {
            return CrossMatchResult::NotPossible {
                reason: "Too many runners for cross-matching",
            };
        }
        if runners.len() != 3 {
            return CrossMatchResult::NotPossible {
                reason: "Cross-matching only supported for 3-runner markets",
            };
        }

        // 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_raw, worst_case_pnl) = match hedge_result {
            HedgeResult::Success {
                legs,
                worst_case_pnl,
            } => (legs, worst_case_pnl),
            HedgeResult::NoSolution { reason } => {
                return CrossMatchResult::NotPossible { reason };
            }
        };
        // Zero-size hedge legs are valid solver output (e.g. already within tolerance),
        // but should not be sent as PlaceOrder commands.
        let hedge_legs: Vec<HedgeLeg> = hedge_legs_raw
            .into_iter()
            .filter(|leg| leg.stake.is_positive())
            .collect();

        // 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(_) => {
                    let compensation_failed = if let Some((start_time, end_time)) =
                        extract_trade_match_window(&all_events)
                    {
                        self.append_compensation_void(
                            book,
                            market_id,
                            Utc::now(),
                            start_time,
                            end_time,
                            &mut all_events,
                        )
                        .is_err()
                    } else {
                        false
                    };
                    return CrossMatchResult::Failed {
                        reason: if compensation_failed {
                            "Hedge leg rejected; compensation void failed"
                        } else {
                            "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.to_string());
        self.next_correlation_id += 1;

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

    fn append_compensation_void(
        &mut self,
        book: &mut Book,
        market_id: MarketId,
        timestamp: DateTime,
        start_time: DateTime,
        end_time: DateTime,
        all_events: &mut Vec<BookEventEnvelope>,
    ) -> Result<(), ()> {
        let correlation_id = crate::types::CorrelationId(self.next_correlation_id.to_string());
        let void_cmd = Command {
            correlation_id: Some(correlation_id),
            metadata: None,
            market_id,
            kind: CommandKind::VoidTrades {
                timestamp,
                start_time,
                end_time,
                void_reason: "Cross-match hedge leg failed".to_string(),
            },
        };
        self.next_correlation_id += 1;
        let (void_events, _) = book.handle(&void_cmd).map_err(|_| ())?;
        book.apply_all_events(&void_events);
        all_events.extend(void_events);
        Ok(())
    }
}

/// Extract matched-trade timestamp window from book events.
fn extract_trade_match_window(events: &[BookEventEnvelope]) -> Option<(DateTime, DateTime)> {
    let mut window: Option<(DateTime, DateTime)> = None;

    for env in events {
        if !matches!(&env.event, BookEvent::TradeMatched { .. }) {
            continue;
        }

        window = Some(match window {
            Some((start, end)) => (start.min(env.timestamp), end.max(env.timestamp)),
            None => (env.timestamp, env.timestamp),
        });
    }

    window
}

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

    fn exec(book: &mut Book, cmd: Command) -> Vec<BookEventEnvelope> {
        let (events, _) = book.handle(&cmd).expect("command should succeed");
        book.apply_all_events(&events);
        events
    }

    #[test]
    fn append_compensation_void_appends_void_event() {
        let market_id = MarketId(7001);
        let mut engine = CrossMatchEngine::new(CrossMatchConfig::default());
        let mut book = Book::new_multi_runner(market_id, [RunnerId(1), RunnerId(2), RunnerId(3)]);
        let mut events = Vec::new();

        let res = engine.append_compensation_void(
            &mut book,
            market_id,
            unix_epoch(),
            unix_epoch(),
            unix_epoch(),
            &mut events,
        );
        assert!(res.is_ok());
        assert!(events.iter().any(|e| {
            matches!(
                e.event,
                BookEvent::VoidTrades {
                    void_reason: ref r,
                    ..
                } if r == "Cross-match hedge leg failed"
            )
        }));
    }

    #[test]
    fn append_compensation_void_returns_error_when_void_rejected() {
        let market_id = MarketId(7002);
        let mut engine = CrossMatchEngine::new(CrossMatchConfig::default());
        let mut book = Book::new_multi_runner(market_id, [RunnerId(1), RunnerId(2), RunnerId(3)]);

        let _ = exec(
            &mut book,
            Command {
                correlation_id: Some(CorrelationId(1.to_string())),
                metadata: None,
                market_id,
                kind: CommandKind::CloseMarket {
                    reason: "TEST_CLOSE".to_string(),
                },
            },
        );

        let mut events = Vec::new();
        let res = engine.append_compensation_void(
            &mut book,
            market_id,
            unix_epoch(),
            unix_epoch(),
            unix_epoch(),
            &mut events,
        );
        assert!(res.is_err(), "void should be rejected on terminal market");
        assert!(events.is_empty());
    }
}