Keep per-instrument order books in memory and recover committed orders
This commit is contained in:
+91
-39
@@ -1,6 +1,7 @@
|
||||
mod order;
|
||||
pub use order::{Fill, Order, Side};
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Phase {
|
||||
@@ -8,60 +9,111 @@ pub enum Phase {
|
||||
Continuous,
|
||||
}
|
||||
|
||||
/// Input is one instrument's validated, positive-quantity live orders.
|
||||
pub fn cross(orders: Vec<Order>, phase: Phase) -> Vec<Fill> {
|
||||
let (mut bids, mut asks): (Vec<_>, Vec<_>) =
|
||||
orders.into_iter().partition(|o| o.side == Side::Buy);
|
||||
bids.sort_by_key(|o| (Reverse(o.price), o.seq));
|
||||
asks.sort_by_key(|o| (o.price, o.seq));
|
||||
let mut fills = Vec::new();
|
||||
if bids.is_empty() || asks.is_empty() || bids[0].price < asks[0].price {
|
||||
return fills;
|
||||
/// A single instrument. The second tree key is the persistent acceptance sequence.
|
||||
#[derive(Default)]
|
||||
pub struct OrderBook {
|
||||
bids: BTreeMap<(Reverse<i64>, i64), Order>,
|
||||
asks: BTreeMap<(i64, i64), Order>,
|
||||
}
|
||||
|
||||
impl OrderBook {
|
||||
/// Install a committed quantity. Zero removes the order from its level.
|
||||
pub fn update(&mut self, order: Order) {
|
||||
match order.side {
|
||||
Side::Buy => set(&mut self.bids, (Reverse(order.price), order.seq), order),
|
||||
Side::Sell => set(&mut self.asks, (order.price, order.seq), order),
|
||||
}
|
||||
}
|
||||
let clearing = (phase == Phase::Opening).then(|| {
|
||||
(0..=100)
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.bids.is_empty() && self.asks.is_empty()
|
||||
}
|
||||
|
||||
/// Read only the opposite side and stop at the first untouched price level.
|
||||
pub fn match_incoming(&self, incoming: &Order) -> Vec<Fill> {
|
||||
match incoming.side {
|
||||
Side::Buy => plan(std::iter::once(incoming), self.asks.values(), None),
|
||||
Side::Sell => plan(self.bids.values(), std::iter::once(incoming), None),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn opening(&self) -> Vec<Fill> {
|
||||
let (Some(bid), Some(ask)) = (self.bids.values().next(), self.asks.values().next()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
if bid.price < ask.price {
|
||||
return Vec::new();
|
||||
}
|
||||
let price = (0..=100)
|
||||
.min_by_key(|&p| {
|
||||
let demand: i128 = bids
|
||||
.iter()
|
||||
.filter(|o| o.price >= p)
|
||||
let demand: i128 = self
|
||||
.bids
|
||||
.values()
|
||||
.take_while(|o| o.price >= p)
|
||||
.map(|o| i128::from(o.remaining))
|
||||
.sum();
|
||||
let supply: i128 = asks
|
||||
.iter()
|
||||
.filter(|o| o.price <= p)
|
||||
let supply: i128 = self
|
||||
.asks
|
||||
.values()
|
||||
.take_while(|o| o.price <= p)
|
||||
.map(|o| i128::from(o.remaining))
|
||||
.sum();
|
||||
(Reverse(demand.min(supply)), (demand - supply).abs(), p)
|
||||
})
|
||||
.expect("nonempty tick range")
|
||||
});
|
||||
let (mut b, mut a) = (0, 0);
|
||||
while b < bids.len() && a < asks.len() {
|
||||
let bid = &mut bids[b];
|
||||
let ask = &mut asks[a];
|
||||
if bid.price < ask.price || clearing.is_some_and(|p| p < ask.price || p > bid.price) {
|
||||
.expect("nonempty tick range");
|
||||
plan(self.bids.values(), self.asks.values(), Some(price))
|
||||
}
|
||||
}
|
||||
|
||||
fn set<K: Ord>(side: &mut BTreeMap<K, Order>, key: K, order: Order) {
|
||||
if order.remaining == 0 {
|
||||
side.remove(&key);
|
||||
} else {
|
||||
side.insert(key, order);
|
||||
}
|
||||
}
|
||||
|
||||
fn plan<'a>(
|
||||
bids: impl Iterator<Item = &'a Order>,
|
||||
asks: impl Iterator<Item = &'a Order>,
|
||||
clearing: Option<i64>,
|
||||
) -> Vec<Fill> {
|
||||
let mut bids = bids.cloned();
|
||||
let mut asks = asks.cloned();
|
||||
let mut bid = bids.next();
|
||||
let mut ask = asks.next();
|
||||
let mut fills = Vec::new();
|
||||
while let (Some(b), Some(a)) = (&mut bid, &mut ask) {
|
||||
if b.price < a.price || clearing.is_some_and(|p| p < a.price || p > b.price) {
|
||||
break;
|
||||
}
|
||||
let price = clearing.unwrap_or(if bid.seq < ask.seq {
|
||||
bid.price
|
||||
} else {
|
||||
ask.price
|
||||
});
|
||||
let quantity = bid.remaining.min(ask.remaining);
|
||||
let quantity = b.remaining.min(a.remaining);
|
||||
fills.push(Fill {
|
||||
bid: bid.seq,
|
||||
ask: ask.seq,
|
||||
price,
|
||||
bid: b.seq,
|
||||
ask: a.seq,
|
||||
quantity,
|
||||
price: clearing.unwrap_or(if b.seq < a.seq { b.price } else { a.price }),
|
||||
});
|
||||
bid.remaining -= quantity;
|
||||
ask.remaining -= quantity;
|
||||
if bid.remaining == 0 {
|
||||
b += 1;
|
||||
b.remaining -= quantity;
|
||||
a.remaining -= quantity;
|
||||
if b.remaining == 0 {
|
||||
bid = bids.next();
|
||||
}
|
||||
if ask.remaining == 0 {
|
||||
a += 1;
|
||||
if a.remaining == 0 {
|
||||
ask = asks.next();
|
||||
}
|
||||
}
|
||||
fills
|
||||
}
|
||||
|
||||
/// Batch interface for callers that already have a snapshot.
|
||||
pub fn cross(orders: Vec<Order>, phase: Phase) -> Vec<Fill> {
|
||||
let mut book = OrderBook::default();
|
||||
for order in orders {
|
||||
book.update(order);
|
||||
}
|
||||
match phase {
|
||||
Phase::Opening => book.opening(),
|
||||
Phase::Continuous => plan(book.bids.values(), book.asks.values(), None),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user