Port the simulator to a Rust workspace and document each crate
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
mod order;
|
||||
pub use order::{Fill, Order, Side};
|
||||
use std::cmp::Reverse;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Phase {
|
||||
Opening,
|
||||
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;
|
||||
}
|
||||
let clearing = (phase == Phase::Opening).then(|| {
|
||||
(0..=100)
|
||||
.min_by_key(|&p| {
|
||||
let demand: i128 = bids
|
||||
.iter()
|
||||
.filter(|o| o.price >= p)
|
||||
.map(|o| i128::from(o.remaining))
|
||||
.sum();
|
||||
let supply: i128 = asks
|
||||
.iter()
|
||||
.filter(|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) {
|
||||
break;
|
||||
}
|
||||
let price = clearing.unwrap_or(if bid.seq < ask.seq {
|
||||
bid.price
|
||||
} else {
|
||||
ask.price
|
||||
});
|
||||
let quantity = bid.remaining.min(ask.remaining);
|
||||
fills.push(Fill {
|
||||
bid: bid.seq,
|
||||
ask: ask.seq,
|
||||
price,
|
||||
quantity,
|
||||
});
|
||||
bid.remaining -= quantity;
|
||||
ask.remaining -= quantity;
|
||||
if bid.remaining == 0 {
|
||||
b += 1;
|
||||
}
|
||||
if ask.remaining == 0 {
|
||||
a += 1;
|
||||
}
|
||||
}
|
||||
fills
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum Side {
|
||||
Buy,
|
||||
Sell,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Order {
|
||||
pub seq: i64,
|
||||
pub side: Side,
|
||||
pub price: i64,
|
||||
pub remaining: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Fill {
|
||||
pub bid: i64,
|
||||
pub ask: i64,
|
||||
pub price: i64,
|
||||
pub quantity: i64,
|
||||
}
|
||||
Reference in New Issue
Block a user