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
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
//! Shared types for order book implementations.

use crate::{
    book::protocol::{
        command::{Persistence, Side},
        reject::RejectReason,
    },
    types::*,
};
use std::collections::VecDeque;

// ============================================================================
// Market State
// ============================================================================

/// Book-local market states (single market per book).
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
    serde::Serialize,
    serde::Deserialize,
    rkyv::Archive,
    rkyv::Serialize,
    rkyv::Deserialize,
    strum::Display,
    strum::AsRefStr,
)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
pub enum BookMarketState {
    /// Trading is open.
    Open,
    /// Temporarily halted (not matchable)
    Suspended,
    /// Administratively halted (not matchable; cancellations allowed)
    Halted,
    /// Event finished; close batch may still be draining (not matchable)
    Closed,
    /// Deactivated (not matchable; lifecycle behavior mirrors suspended)
    Deactivated,
}

impl BookMarketState {
    /// Whether matching is allowed in this state.
    pub fn is_matchable(self) -> bool {
        matches!(self, Self::Open)
    }

    /// Whether the market is terminal (reject all commands that mutate trading state).
    pub fn is_terminal(self) -> bool {
        matches!(self, Self::Closed)
    }

    /// Whether the market is administratively halted.
    pub fn is_halted(self) -> bool {
        matches!(self, Self::Halted)
    }

    /// An `InPlayCapable` market may only start in `PreAwaitLive` when created `Open`
    /// or `Suspended`; otherwise this defers to `MarketKind::supports_phase`.
    /// Terminal states are never valid.
    pub fn supports_initial_phase_for(
        self,
        market_kind: MarketKind,
        market_phase: MarketPhase,
    ) -> bool {
        if self.is_terminal() {
            return false;
        }
        if market_kind == MarketKind::InPlayCapable && market_phase == MarketPhase::PreAwaitLive {
            return matches!(self, Self::Open | Self::Suspended | Self::Deactivated);
        }
        market_kind.supports_phase(market_phase)
    }
}

#[track_caller]
pub fn assert_kind_supports_phase(market_kind: MarketKind, market_phase: MarketPhase) {
    assert!(
        market_kind.supports_phase(market_phase),
        "market kind {market_kind:?} does not support phase {market_phase:?}"
    );
}

/// Validates whether a phase command may run in the current lifecycle state.
pub fn ensure_phase_command_allowed_state(state: BookMarketState) -> Result<(), RejectReason> {
    match state {
        BookMarketState::Open
        | BookMarketState::Suspended
        | BookMarketState::Halted
        | BookMarketState::Deactivated => Ok(()),
        BookMarketState::Closed => Err(RejectReason::MarketTerminal),
    }
}

/// Rejects order-entry commands when the market is not currently matchable.
pub fn ensure_can_accept_new_orders(state: BookMarketState) -> Result<(), RejectReason> {
    if state.is_matchable() {
        Ok(())
    } else {
        Err(RejectReason::MarketNotOpen)
    }
}

/// Returns `Err(NoChange)` when the book is already in the requested state.
pub fn ensure_state_change(
    current: BookMarketState,
    to: BookMarketState,
) -> Result<(), crate::book::protocol::reject::RejectReason> {
    if current == to {
        return Err(crate::book::protocol::reject::RejectReason::NoChange);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{BookMarketState, ensure_phase_command_allowed_state};
    use crate::{
        book::protocol::reject::RejectReason,
        types::{MarketKind, MarketPhase},
    };

    #[test]
    fn phase_command_allows_pre_close_states() {
        for state in [
            BookMarketState::Open,
            BookMarketState::Suspended,
            BookMarketState::Halted,
            BookMarketState::Deactivated,
        ] {
            assert_eq!(ensure_phase_command_allowed_state(state), Ok(()));
        }
    }

    #[test]
    fn phase_command_rejects_terminal_states() {
        assert_eq!(
            ensure_phase_command_allowed_state(BookMarketState::Closed),
            Err(RejectReason::MarketTerminal)
        );
    }

    #[test]
    fn open_or_suspended_in_play_capable_market_may_start_in_pre_await_live() {
        assert!(
            BookMarketState::Suspended
                .supports_initial_phase_for(MarketKind::InPlayCapable, MarketPhase::PreAwaitLive)
        );
        assert!(
            BookMarketState::Deactivated
                .supports_initial_phase_for(MarketKind::InPlayCapable, MarketPhase::PreAwaitLive)
        );
        assert!(
            BookMarketState::Open
                .supports_initial_phase_for(MarketKind::InPlayCapable, MarketPhase::PreAwaitLive)
        );
        assert!(
            !BookMarketState::Closed
                .supports_initial_phase_for(MarketKind::InPlayCapable, MarketPhase::PreAwaitLive)
        );
    }
}

// ============================================================================
// Batch Process
// ============================================================================

#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    serde::Serialize,
    serde::Deserialize,
    rkyv::Archive,
    rkyv::Serialize,
    rkyv::Deserialize,
)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BatchMode {
    FilteredCancel,
    Close,
    SuspendLapse,
    InPlayLapse,
    RunnerRemovalCancel,
}

#[derive(Debug, Clone, PartialEq, Eq, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub enum BatchProcessTarget {
    AllLiveOrders,
    LapseOrders,
    RunnerRemoval {
        runner_ids: Vec<RunnerId>,
    },
    Filtered {
        started_at_ms: i64,
        from_created_at_inclusive_ms: Option<i64>,
        to_created_at_inclusive_ms: Option<i64>,
        account_filter: Option<AccountId>,
        runner_filter: Option<RunnerId>,
    },
}

#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
enum BatchProcessTargetWire {
    AllLiveOrders {},
    LapseOrders {},
    RunnerRemoval {
        runner_ids: Vec<RunnerId>,
    },
    Filtered {
        started_at_ms: i64,
        from_created_at_inclusive_ms: Option<i64>,
        to_created_at_inclusive_ms: Option<i64>,
        account_filter: Option<AccountId>,
        runner_filter: Option<RunnerId>,
    },
}

impl From<&BatchProcessTarget> for BatchProcessTargetWire {
    fn from(target: &BatchProcessTarget) -> Self {
        match target {
            BatchProcessTarget::AllLiveOrders => Self::AllLiveOrders {},
            BatchProcessTarget::LapseOrders => Self::LapseOrders {},
            BatchProcessTarget::RunnerRemoval { runner_ids } => Self::RunnerRemoval {
                runner_ids: runner_ids.clone(),
            },
            BatchProcessTarget::Filtered {
                started_at_ms,
                from_created_at_inclusive_ms,
                to_created_at_inclusive_ms,
                account_filter,
                runner_filter,
            } => Self::Filtered {
                started_at_ms: *started_at_ms,
                from_created_at_inclusive_ms: *from_created_at_inclusive_ms,
                to_created_at_inclusive_ms: *to_created_at_inclusive_ms,
                account_filter: account_filter.clone(),
                runner_filter: *runner_filter,
            },
        }
    }
}

impl From<BatchProcessTargetWire> for BatchProcessTarget {
    fn from(target: BatchProcessTargetWire) -> Self {
        match target {
            BatchProcessTargetWire::AllLiveOrders {} => Self::AllLiveOrders,
            BatchProcessTargetWire::LapseOrders {} => Self::LapseOrders,
            BatchProcessTargetWire::RunnerRemoval { runner_ids } => {
                Self::RunnerRemoval { runner_ids }
            }
            BatchProcessTargetWire::Filtered {
                started_at_ms,
                from_created_at_inclusive_ms,
                to_created_at_inclusive_ms,
                account_filter,
                runner_filter,
            } => Self::Filtered {
                started_at_ms,
                from_created_at_inclusive_ms,
                to_created_at_inclusive_ms,
                account_filter,
                runner_filter,
            },
        }
    }
}

impl serde::Serialize for BatchProcessTarget {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serde::Serialize::serialize(&BatchProcessTargetWire::from(self), serializer)
    }
}

impl<'de> serde::Deserialize<'de> for BatchProcessTarget {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        <BatchProcessTargetWire as serde::Deserialize>::deserialize(deserializer).map(Self::from)
    }
}

impl BatchProcessTarget {
    #[inline]
    pub fn is_valid_for_mode(&self, batch_mode: BatchMode) -> bool {
        matches!(
            (batch_mode, self),
            (BatchMode::Close, BatchProcessTarget::AllLiveOrders)
                | (
                    BatchMode::SuspendLapse | BatchMode::InPlayLapse,
                    BatchProcessTarget::LapseOrders
                )
                | (
                    BatchMode::RunnerRemovalCancel,
                    BatchProcessTarget::RunnerRemoval { .. }
                )
                | (
                    BatchMode::FilteredCancel,
                    BatchProcessTarget::Filtered { .. }
                )
        )
    }

    #[inline]
    pub fn assert_valid_for_mode(&self, batch_mode: BatchMode) {
        assert!(
            self.is_valid_for_mode(batch_mode),
            "batch target {:?} is incompatible with batch mode {:?}",
            self,
            batch_mode
        );
    }
}

#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    serde::Serialize,
    serde::Deserialize,
    rkyv::Archive,
    rkyv::Serialize,
    rkyv::Deserialize,
)]
pub enum BatchProcessContext {
    None,
    Close { total_live_orders: u64 },
}

#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    serde::Serialize,
    serde::Deserialize,
    rkyv::Archive,
    rkyv::Serialize,
    rkyv::Deserialize,
)]
pub struct BatchProcessDescriptor {
    pub batch_mode: BatchMode,
    pub batch_max_events: u16,
    pub target: BatchProcessTarget,
    pub detail: Option<String>,
}

impl BatchProcessDescriptor {
    pub fn new(
        batch_mode: BatchMode,
        batch_max_events: u16,
        target: BatchProcessTarget,
        detail: Option<String>,
    ) -> Self {
        target.assert_valid_for_mode(batch_mode);
        Self {
            batch_mode,
            batch_max_events,
            target,
            detail,
        }
    }
}

#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    serde::Serialize,
    serde::Deserialize,
    rkyv::Archive,
    rkyv::Serialize,
    rkyv::Deserialize,
)]
pub struct BatchProcessState {
    pub batch_mode: BatchMode,
    pub batch_max_events: u16,
    pub cursor_after: Option<OrderId>,
    pub processed_total: u64,
    pub chunks_done: u32,
    pub target: BatchProcessTarget,
    pub detail: Option<String>,
    pub context: BatchProcessContext,
}

impl BatchProcessState {
    pub fn close(batch_max_events: u16, total_live_orders: u64) -> Self {
        Self {
            batch_mode: BatchMode::Close,
            batch_max_events,
            cursor_after: None,
            processed_total: 0,
            chunks_done: 0,
            target: BatchProcessTarget::AllLiveOrders,
            detail: None,
            context: BatchProcessContext::Close { total_live_orders },
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub fn cancel(
        batch_max_events: u16,
        started_at_ms: i64,
        from_created_at_inclusive_ms: Option<i64>,
        to_created_at_inclusive_ms: Option<i64>,
        account_filter: Option<AccountId>,
        runner_filter: Option<RunnerId>,
        detail: String,
    ) -> Self {
        Self {
            batch_mode: BatchMode::FilteredCancel,
            batch_max_events,
            cursor_after: None,
            processed_total: 0,
            chunks_done: 0,
            target: BatchProcessTarget::Filtered {
                started_at_ms,
                from_created_at_inclusive_ms,
                to_created_at_inclusive_ms,
                account_filter,
                runner_filter,
            },
            detail: Some(detail),
            context: BatchProcessContext::None,
        }
    }

    pub fn runner_removal(batch_max_events: u16, runner_ids: Vec<RunnerId>) -> Self {
        Self {
            batch_mode: BatchMode::RunnerRemovalCancel,
            batch_max_events,
            cursor_after: None,
            processed_total: 0,
            chunks_done: 0,
            target: BatchProcessTarget::RunnerRemoval { runner_ids },
            detail: None,
            context: BatchProcessContext::None,
        }
    }

    pub fn lapse(batch_max_events: u16, batch_mode: BatchMode) -> Self {
        assert!(matches!(
            batch_mode,
            BatchMode::SuspendLapse | BatchMode::InPlayLapse
        ));
        Self {
            batch_mode,
            batch_max_events,
            cursor_after: None,
            processed_total: 0,
            chunks_done: 0,
            target: BatchProcessTarget::LapseOrders,
            detail: None,
            context: BatchProcessContext::None,
        }
    }

    #[inline]
    pub fn is_close(&self) -> bool {
        self.batch_mode == BatchMode::Close
    }

    #[inline]
    pub fn retarget(
        &mut self,
        batch_mode: BatchMode,
        batch_max_events: u16,
        target: BatchProcessTarget,
        detail: Option<String>,
        context: BatchProcessContext,
    ) {
        target.assert_valid_for_mode(batch_mode);
        self.batch_mode = batch_mode;
        self.batch_max_events = batch_max_events;
        self.cursor_after = None;
        self.processed_total = 0;
        self.chunks_done = 0;
        self.target = target;
        self.detail = detail;
        self.context = context;
    }

    pub fn record_chunk(&mut self, cursor_after: Option<OrderId>, processed_count: u64) {
        self.cursor_after = cursor_after;
        self.processed_total = self.processed_total.saturating_add(processed_count);
        self.chunks_done = self.chunks_done.saturating_add(1);
    }
}

// ============================================================================
// Order Types
// ============================================================================

/// Order lifecycle as owned by the book.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
    serde::Serialize,
    serde::Deserialize,
    rkyv::Archive,
    rkyv::Serialize,
    rkyv::Deserialize,
    strum::Display,
    strum::AsRefStr,
)]
pub enum BookOrderState {
    ExecutableUnmatched,
    ExecutablePartiallyMatched,
    ExecutionComplete,
    Cancelled,
    Lapsed,
}

/// Signed money for P&L calculations.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    serde::Serialize,
    serde::Deserialize,
    rkyv::Archive,
    rkyv::Serialize,
    rkyv::Deserialize,
)]
pub struct SignedMoney(pub i64);

impl SignedMoney {
    pub fn zero() -> Self {
        Self(0)
    }
}

// ============================================================================
// Book Order
// ============================================================================

/// Canonical order metadata shared across books.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct BookOrderInfo {
    pub order_id: OrderId,
    pub account_id: AccountId,
    pub correlation_id: Option<CorrelationId>,
    pub side: Side,
    pub state: BookOrderState,
    pub created_at: DateTime,
    pub last_updated_at: DateTime,
}

/// Canonical order representation stored by the book.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct BookOrder {
    pub info: BookOrderInfo,
    pub runner_id: RunnerId,
    pub price: OddsX10000,
    pub stake: Money,
    pub matched: Money,
    pub persistence: Persistence,
}

impl BookOrder {
    /// Remaining unmatched stake.
    pub fn remaining(&self) -> Money {
        Money(self.stake.0.saturating_sub(self.matched.0).max(0))
    }
}

// ============================================================================
// Market Depth
// ============================================================================

/// Price and size at a single level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PriceSize {
    pub price: OddsX10000,
    pub size: Money,
}

/// Available prices for a runner.
#[derive(Debug, Clone, Default)]
pub struct RunnerPrices {
    pub runner_id: RunnerId,
    pub available_to_back: Vec<PriceSize>,
    pub available_to_lay: Vec<PriceSize>,
}

/// Price and size for prediction markets (canonical YES-only).
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    serde::Serialize,
    serde::Deserialize,
    rkyv::Archive,
    rkyv::Serialize,
    rkyv::Deserialize,
)]
pub struct BinaryPriceSize {
    pub price_ticks: u16,
    pub size_shares: u64,
}

/// Depth snapshot for a canonical YES-only prediction market.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct BinaryDepth {
    pub max_price_ticks: u16,
    /// Bid levels (highest `price_ticks` first).
    pub bids: Vec<BinaryPriceSize>,
    /// Ask levels (lowest `price_ticks` first).
    pub asks: Vec<BinaryPriceSize>,
}

// ============================================================================
// Price Level (internal)
// ============================================================================

/// Internal per-price FIFO queue.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PriceLevel {
    pub fifo: VecDeque<OrderId>,
    pub total_remaining: Money,
}

impl PriceLevel {
    pub fn new() -> Self {
        Self {
            fifo: VecDeque::new(),
            total_remaining: Money::zero(),
        }
    }
}

impl Default for PriceLevel {
    fn default() -> Self {
        Self::new()
    }
}