use crate::market_maker::{
quote_ladder_into, LadderParams, MakerInventory, QuoteParams, MARKET_MAKER_ID,
};
use crate::mathx;
use crate::order_book::{Fill, OrderBook, Side, SubmitOptions};
use crate::rng::Rng;
use crate::types::Difficulty;
pub const BOOK_LEVELS: f64 = 10.0;
pub const INVENTORY_LIMIT_LEVELS: f64 = 12.0;
const FLOW_SLICES: usize = 4;
const GAP_PRESSURE: f64 = 40.0;
const FLOW_LEAN_TILT: f64 = 10.0;
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct CompanyMicrostructure {
pub id: String,
pub sector_volatility: Option<f64>,
pub price: f64,
pub market_cap: f64,
pub beta: Option<f64>,
pub float: Option<f64>,
pub short_interest: Option<f64>,
pub avg_volume: Option<f64>,
pub volume: Option<f64>,
pub shares_outstanding: Option<f64>,
pub maker_inventory: Option<f64>,
}
impl CompanyMicrostructure {
pub fn new(id: impl Into<String>, price: f64, market_cap: f64) -> Self {
CompanyMicrostructure {
id: id.into(),
sector_volatility: None,
price,
market_cap,
beta: None,
float: None,
short_interest: None,
avg_volume: None,
volume: None,
shares_outstanding: None,
maker_inventory: None,
}
}
}
fn truthy(value: Option<f64>) -> Option<f64> {
match value {
Some(x) if x != 0.0 && !x.is_nan() => Some(x),
_ => None,
}
}
pub const SPREAD_SIZE_REFERENCE_B: f64 = 25.0;
pub const SPREAD_SIZE_REFERENCE_BPS: f64 = 5.0;
pub const SPREAD_SIZE_EXPONENT: f64 = 0.455;
pub const SPREAD_SIZE_BOUNDS: (f64, f64) = (1.0, 100.0);
pub fn compute_spread_bps(
company: &CompanyMicrostructure,
vix: f64,
difficulty: Option<Difficulty>,
) -> f64 {
compute_spread_bps_with(company, vix, difficulty, 0.0, SPREAD_SIZE_EXPONENT)
}
pub fn compute_spread_bps_with(
company: &CompanyMicrostructure,
vix: f64,
difficulty: Option<Difficulty>,
size_smoothness: f64,
size_exponent: f64,
) -> f64 {
let mcap_billions = company.market_cap / 1e9;
let stepped = if mcap_billions > 50.0 {
3.0
} else if mcap_billions > 10.0 {
5.0
} else if mcap_billions > 1.0 {
10.0
} else {
30.0
};
let base_bps = if size_smoothness == 0.0 || mcap_billions <= 0.0 {
stepped
} else {
let ratio = mcap_billions / SPREAD_SIZE_REFERENCE_B;
let (lo, hi) = SPREAD_SIZE_BOUNDS;
let smooth = mathx::clamp(
SPREAD_SIZE_REFERENCE_BPS * mathx::pow(ratio, -size_exponent), lo, hi);
(1.0 - size_smoothness) * stepped + size_smoothness * smooth
};
let sector_vol = company.sector_volatility.unwrap_or(1.0);
let beta = company.beta.unwrap_or(1.0);
let vol_multiplier = 0.7 + 0.3 * sector_vol * beta;
let mut vix_multiplier = vix_spread_multiplier(vix);
match difficulty {
Some(Difficulty::Hard) if vix > 25.0 => {
vix_multiplier *= 1.0 + mathx::max(0.0, (vix - 25.0) * 0.05);
}
Some(Difficulty::Expert) if vix > 25.0 => {
vix_multiplier *= 1.0 + mathx::max(0.0, (vix - 25.0) * 0.1);
}
_ => {}
}
let float = mathx::max(1.0, truthy(company.float).unwrap_or(1.0));
let short_interest_ratio = company.short_interest.unwrap_or(0.0) / float;
let short_spread_mult = if short_interest_ratio > 0.15 {
1.0 + (short_interest_ratio - 0.15) * 2.0
} else {
1.0
};
base_bps * vol_multiplier * vix_multiplier * short_spread_mult
}
pub fn vix_spread_multiplier(vix: f64) -> f64 {
1.0 + mathx::max(0.0, (vix - 15.0) / 30.0)
}
pub fn base_quote_size(company: &CompanyMicrostructure) -> f64 {
let avg_vol = truthy(company.avg_volume)
.or_else(|| truthy(company.volume))
.or_else(|| truthy(company.shares_outstanding.map(|s| s * 0.005)))
.unwrap_or(100.0);
mathx::max(1.0, (avg_vol / 100.0).floor())
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct RestingOrder {
pub id: String,
pub side: Side,
pub price: f64,
pub quantity: f64,
pub owner_id: String,
}
impl RestingOrder {
pub fn new(
id: impl Into<String>,
side: Side,
price: f64,
quantity: f64,
owner_id: impl Into<String>,
) -> Self {
RestingOrder { id: id.into(), side, price, quantity, owner_id: owner_id.into() }
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct LiveBookOptions {
pub vix: f64,
pub difficulty: Option<Difficulty>,
pub spread_size_smoothness: f64,
pub spread_size_exponent: f64,
pub levels: f64,
pub resting_orders: Vec<RestingOrder>,
}
impl Default for LiveBookOptions {
fn default() -> Self {
Self {
vix: 15.0,
difficulty: None,
spread_size_smoothness: 0.0,
spread_size_exponent: SPREAD_SIZE_EXPONENT,
levels: BOOK_LEVELS,
resting_orders: Vec::new(),
}
}
}
pub fn build_live_book(company: &CompanyMicrostructure, options: &LiveBookOptions) -> OrderBook {
let mut book = OrderBook::new(company.id.clone(), Some(company.price));
fill_live_book(company, options, &mut book);
book
}
fn fill_live_book(company: &CompanyMicrostructure, options: &LiveBookOptions, book: &mut OrderBook) {
let fair_value = company.price;
if !(fair_value > 0.0) {
return;
}
let spread_bps = compute_spread_bps_with(
company, options.vix, options.difficulty,
options.spread_size_smoothness, options.spread_size_exponent);
let base_size = base_quote_size(company);
LADDER.with(|cell| {
let (bids, asks) = &mut *cell.borrow_mut();
quote_ladder_into(&LadderParams {
quote: QuoteParams {
fair_value,
half_spread_bps: spread_bps / 2.0,
base_size,
inventory: MakerInventory {
position: company.maker_inventory.unwrap_or(0.0),
limit: mathx::max(1.0, base_size * INVENTORY_LIMIT_LEVELS),
},
..QuoteParams::default()
},
levels: options.levels,
level_step: 0.5,
}, bids, asks);
let resting = options.resting_orders.len();
book.bids.reserve(bids.len() + resting);
book.asks.reserve(asks.len() + resting);
for level in bids.iter() {
book.push_maker_level(Side::Buy, level.price, level.size, MARKET_MAKER_ID);
}
for level in asks.iter() {
book.push_maker_level(Side::Sell, level.price, level.size, MARKET_MAKER_ID);
}
});
for o in &options.resting_orders {
book.post_limit(o.side, o.price, o.quantity, &o.owner_id, Some(o.id.clone()));
}
}
std::thread_local! {
static LADDER: std::cell::RefCell<(Vec<crate::market_maker::LadderLevel>, Vec<crate::market_maker::LadderLevel>)> =
const { std::cell::RefCell::new((Vec::new(), Vec::new())) };
static SETTLE_BOOK: std::cell::RefCell<Option<OrderBook>> =
const { std::cell::RefCell::new(None) };
static SETTLE_FILLS: std::cell::RefCell<Vec<crate::order_book::Fill>> =
const { std::cell::RefCell::new(Vec::new()) };
}
struct SettleBook(Option<OrderBook>);
impl SettleBook {
fn take(company: &CompanyMicrostructure) -> Self {
let book = SETTLE_BOOK
.with(|cell| cell.borrow_mut().take())
.map(|mut book| {
book.reset(&company.id, Some(company.price));
book
})
.unwrap_or_else(|| OrderBook::new(company.id.clone(), Some(company.price)));
SettleBook(Some(book))
}
}
impl Drop for SettleBook {
fn drop(&mut self) {
if let Some(book) = self.0.take() {
SETTLE_BOOK.with(|cell| *cell.borrow_mut() = Some(book));
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct SettlementResult {
pub price: f64,
pub traded_volume: f64,
pub traded: bool,
pub maker_inventory_delta: f64,
pub shock: f64,
pub absorbed: f64,
}
pub fn decompose(last_price: f64, model_price: f64, print: f64) -> (f64, f64) {
(
mathx::log(model_price / last_price),
mathx::log(print / model_price),
)
}
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct SettleOptions {
pub vix: f64,
pub difficulty: Option<Difficulty>,
pub flow_lean: Option<f64>,
pub spread_size_smoothness: f64,
pub spread_size_exponent: f64,
pub depth_multiplier: f64,
}
impl Default for SettleOptions {
fn default() -> Self {
Self {
vix: 15.0,
difficulty: None,
flow_lean: None,
spread_size_smoothness: 0.0,
spread_size_exponent: SPREAD_SIZE_EXPONENT,
depth_multiplier: 1.0,
}
}
}
fn scaled_depth(reach: f64, multiplier: f64) -> f64 {
if multiplier == 1.0 {
reach
} else {
reach * multiplier
}
}
pub fn maker_delta_from_fills(fills: &[Fill]) -> f64 {
let mut delta = 0.0;
for f in fills {
if f.maker_id != MARKET_MAKER_ID {
continue;
}
delta += if f.taker_side == Side::Buy {
-f.quantity
} else {
f.quantity
};
}
delta
}
pub fn settle_price_through_book(
company: &CompanyMicrostructure,
fair_value: f64,
tick_volume: f64,
options: &SettleOptions,
rng: &mut impl Rng,
) -> SettlementResult {
let mut unused = Vec::new();
settle_inner(company, fair_value, tick_volume, options, &[], rng, &mut unused)
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct SettledAgentFill {
pub order_id: String,
pub agent: String,
pub side: Side,
pub quantity: f64,
pub price: f64,
pub taker: bool,
pub counterparty: String,
}
pub fn settle_price_through_book_with_orders(
company: &CompanyMicrostructure,
fair_value: f64,
tick_volume: f64,
options: &SettleOptions,
resting: &[RestingOrder],
rng: &mut impl Rng,
) -> (SettlementResult, Vec<SettledAgentFill>) {
let mut fills = Vec::new();
let result = settle_inner(company, fair_value, tick_volume, options, resting, rng, &mut fills);
(result, fills)
}
fn is_agent(owner: &str) -> bool {
owner != MARKET_MAKER_ID
&& owner != "flow"
&& owner != crate::agent_book::DEPTH_OWNER
}
fn opposite(side: Side) -> Side {
match side {
Side::Buy => Side::Sell,
Side::Sell => Side::Buy,
}
}
fn settle_inner(
company: &CompanyMicrostructure,
fair_value: f64,
tick_volume: f64,
options: &SettleOptions,
resting: &[RestingOrder],
rng: &mut impl Rng,
agent_fills: &mut Vec<SettledAgentFill>,
) -> SettlementResult {
let last_price = company.price;
let no_trade = || {
let (shock, absorbed) = decompose(last_price, fair_value, fair_value);
SettlementResult {
price: fair_value,
traded_volume: 0.0,
traded: false,
maker_inventory_delta: 0.0,
shock,
absorbed,
}
};
if !(fair_value > 0.0) || !(last_price > 0.0) || !(tick_volume > 0.0) {
return no_trade();
}
let level_size = mathx::max(1.0, base_quote_size(company));
let levels_needed = mathx::min(
BOOK_LEVELS,
scaled_depth(
mathx::max(2.0, (tick_volume / level_size).ceil() + 1.0),
options.depth_multiplier,
),
);
debug_assert!(
!levels_needed.is_infinite(),
"levels_needed must stay bounded by BOOK_LEVELS, got {levels_needed}"
);
let mut slot = SettleBook::take(company);
let book = slot.0.as_mut().expect("SettleBook::take always holds a book");
fill_live_book(
company,
&LiveBookOptions {
vix: options.vix,
difficulty: options.difficulty,
spread_size_smoothness: options.spread_size_smoothness,
spread_size_exponent: options.spread_size_exponent,
levels: levels_needed,
resting_orders: Vec::new(),
},
book,
);
if book.asks.is_empty() || book.bids.is_empty() {
return no_trade();
}
let flow_bound = if resting.is_empty() {
None
} else {
Some((
book.bids.last().map(|o| o.price),
book.asks.last().map(|o| o.price),
))
};
let mut pre_traded = 0.0;
let mut pre_inventory = 0.0;
for o in resting {
let r = book.submit(
o.side,
o.quantity,
&o.owner_id,
SubmitOptions {
limit_price: Some(o.price),
post_remainder: true,
order_id: Some(o.id.clone()),
skip_own: true,
house_ids: false,
},
);
for f in &r.fills {
pre_traded += f.quantity;
agent_fills.push(SettledAgentFill {
order_id: o.id.clone(),
agent: o.owner_id.clone(),
side: o.side,
quantity: f.quantity,
price: f.price,
taker: true,
counterparty: f.maker_id.to_string(),
});
if is_agent(&f.maker_id) {
agent_fills.push(SettledAgentFill {
order_id: f.maker_order_id.clone(),
agent: f.maker_id.to_string(),
side: opposite(o.side),
quantity: f.quantity,
price: f.price,
taker: false,
counterparty: o.owner_id.clone(),
});
}
}
pre_inventory += maker_delta_from_fills(&r.fills);
}
let gap = (fair_value - last_price) / last_price;
let buy_fraction = mathx::max(
0.05,
mathx::min(
0.95,
0.5 + gap * GAP_PRESSURE + options.flow_lean.unwrap_or(0.0) * FLOW_LEAN_TILT,
),
);
let slice = mathx::max(1.0, (tick_volume / FLOW_SLICES as f64).floor());
let mut traded = 0.0;
let mut maker_inventory_delta = 0.0;
let mut fills = SETTLE_FILLS.with(|cell| std::mem::take(&mut *cell.borrow_mut()));
for _ in 0..FLOW_SLICES {
let side = if rng.next_f64() < buy_fraction {
Side::Buy
} else {
Side::Sell
};
let limit_price = flow_bound.and_then(|(deepest_bid, deepest_ask)| match side {
Side::Buy => deepest_ask,
Side::Sell => deepest_bid,
});
fills.clear();
book.match_into(
side,
slice,
"flow",
SubmitOptions {
limit_price,
post_remainder: false,
order_id: None,
skip_own: false,
house_ids: false,
},
&mut fills,
);
for f in &fills {
traded += f.quantity;
}
maker_inventory_delta += maker_delta_from_fills(&fills);
if !resting.is_empty() {
for f in &fills {
if is_agent(&f.maker_id) {
agent_fills.push(SettledAgentFill {
order_id: f.maker_order_id.clone(),
agent: f.maker_id.to_string(),
side: opposite(side),
quantity: f.quantity,
price: f.price,
taker: false,
counterparty: f.taker_id.to_string(),
});
}
}
}
}
fills.clear();
SETTLE_FILLS.with(|cell| *cell.borrow_mut() = fills);
if !resting.is_empty() {
traded += pre_traded;
maker_inventory_delta += pre_inventory;
}
match book.last_price {
Some(price) if traded != 0.0 => {
let (shock, absorbed) = decompose(last_price, fair_value, price);
SettlementResult {
price,
traded_volume: traded,
traded: true,
maker_inventory_delta,
shock,
absorbed,
}
}
_ => no_trade(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::rng::GameRng;
fn company() -> CompanyMicrostructure {
CompanyMicrostructure {
id: "ACME".to_string(),
sector_volatility: Some(1.0),
price: 100.0,
market_cap: 20e9,
beta: Some(1.0),
float: Some(1e8),
short_interest: Some(0.0),
avg_volume: Some(1e6),
volume: Some(1e6),
shares_outstanding: Some(1e8),
maker_inventory: Some(0.0),
}
}
#[test]
fn a_zero_average_volume_falls_through_rather_than_quoting_one_share() {
let mut c = company();
c.avg_volume = Some(0.0);
c.volume = Some(500_000.0);
assert_eq!(base_quote_size(&c), 5000.0);
}
#[test]
fn a_nan_volume_also_falls_through() {
let mut c = company();
c.avg_volume = Some(f64::NAN);
c.volume = Some(500_000.0);
assert_eq!(base_quote_size(&c), 5000.0);
}
#[test]
fn an_absent_shares_outstanding_lands_on_the_hundred_default() {
let mut c = company();
c.avg_volume = None;
c.volume = None;
c.shares_outstanding = None;
assert_eq!(base_quote_size(&c), 1.0);
}
#[test]
fn a_zero_maker_inventory_is_kept_as_zero_not_treated_as_absent() {
let mut c = company();
c.maker_inventory = Some(0.0);
let flat = build_live_book(&c, &LiveBookOptions::default());
c.maker_inventory = None;
let absent = build_live_book(&c, &LiveBookOptions::default());
assert_eq!(flat.bids[0].price, absent.bids[0].price);
}
#[test]
fn spread_tightens_with_market_cap() {
let mut c = company();
let mut last = f64::INFINITY;
for mcap in [0.5e9, 5e9, 20e9, 100e9] {
c.market_cap = mcap;
let bps = compute_spread_bps(&c, 15.0, None);
assert!(
bps < last,
"spread should tighten as cap rises, got {bps} after {last}"
);
last = bps;
}
}
#[test]
fn vix_stress_widens_the_spread() {
let c = company();
assert!(compute_spread_bps(&c, 40.0, None) > compute_spread_bps(&c, 15.0, None));
}
#[test]
fn expert_punishes_a_vix_spike_harder_than_hard() {
let c = company();
let normal = compute_spread_bps(&c, 40.0, Some(Difficulty::Normal));
let hard = compute_spread_bps(&c, 40.0, Some(Difficulty::Hard));
let expert = compute_spread_bps(&c, 40.0, Some(Difficulty::Expert));
assert!(expert > hard && hard > normal);
}
#[test]
fn a_hard_run_below_the_vix_threshold_falls_through_both_arms() {
let c = company();
assert_eq!(
compute_spread_bps(&c, 20.0, Some(Difficulty::Hard)),
compute_spread_bps(&c, 20.0, None)
);
}
#[test]
fn heavy_short_interest_widens_the_spread_past_the_threshold() {
let mut c = company();
c.float = Some(100.0);
c.short_interest = Some(10.0); let light = compute_spread_bps(&c, 15.0, None);
c.short_interest = Some(50.0); assert!(compute_spread_bps(&c, 15.0, None) > light);
}
#[test]
fn a_zero_float_does_not_divide_by_zero() {
let mut c = company();
c.float = Some(0.0);
c.short_interest = Some(1000.0);
assert!(compute_spread_bps(&c, 15.0, None).is_finite());
}
#[test]
fn a_non_positive_price_yields_an_empty_book() {
for price in [0.0, -10.0, f64::NAN] {
let mut c = company();
c.price = price;
let book = build_live_book(&c, &LiveBookOptions::default());
assert!(
book.bids.is_empty() && book.asks.is_empty(),
"price {price}"
);
}
}
#[test]
fn the_book_is_two_sided_and_uncrossed() {
let book = build_live_book(&company(), &LiveBookOptions::default());
assert_eq!(book.bids.len(), BOOK_LEVELS as usize);
assert_eq!(book.asks.len(), BOOK_LEVELS as usize);
assert!(book.best_bid().unwrap() < book.best_ask().unwrap());
}
#[test]
fn a_resting_order_inside_the_spread_takes_queue_priority() {
let c = company();
let maker_only = build_live_book(&c, &LiveBookOptions::default());
let best_maker_bid = maker_only.best_bid().unwrap();
let book = build_live_book(
&c,
&LiveBookOptions {
resting_orders: vec![RestingOrder {
id: "player-1".to_string(),
side: Side::Buy,
price: best_maker_bid + 0.05,
quantity: 100.0,
owner_id: "player".to_string(),
}],
..Default::default()
},
);
assert_eq!(book.bids[0].owner_id, "player");
}
fn draws_consumed(before: &GameRng, after: &GameRng) -> usize {
let mut probe = before.clone();
for n in 0..64 {
if probe == *after {
return n;
}
probe.next_f64();
}
panic!("generator advanced more than 64 draws");
}
#[test]
fn settlement_consumes_exactly_four_draws() {
let mut rng = GameRng::from_seed(42);
let before = rng.clone();
let out = settle_price_through_book(
&company(),
100.0,
10_000.0,
&SettleOptions::default(),
&mut rng,
);
assert!(out.traded);
assert_eq!(draws_consumed(&before, &rng), 4);
}
#[test]
fn every_early_return_consumes_exactly_zero_draws() {
let cases: Vec<(&str, CompanyMicrostructure, f64, f64)> = vec![
("fair value zero", company(), 0.0, 10_000.0),
("fair value NaN", company(), f64::NAN, 10_000.0),
("tick volume zero", company(), 100.0, 0.0),
("tick volume NaN", company(), 100.0, f64::NAN),
(
"last price zero",
CompanyMicrostructure {
price: 0.0,
..company()
},
100.0,
10_000.0,
),
];
for (note, c, fair_value, tick_volume) in cases {
let mut rng = GameRng::from_seed(42);
let before = rng.clone();
let out = settle_price_through_book(
&c,
fair_value,
tick_volume,
&SettleOptions::default(),
&mut rng,
);
assert!(!out.traded, "{note}: should not trade");
assert_eq!(draws_consumed(&before, &rng), 0, "{note}: should not draw");
}
}
#[test]
fn the_flow_loop_never_breaks_early_even_when_slices_fill_nothing() {
let mut c = company();
c.avg_volume = Some(200.0); let mut rng = GameRng::from_seed(7);
let before = rng.clone();
settle_price_through_book(&c, 100.0, 100_000.0, &SettleOptions::default(), &mut rng);
assert_eq!(draws_consumed(&before, &rng), 4);
}
struct Fixed([f64; 4], usize);
impl Rng for Fixed {
fn next_f64(&mut self) -> f64 {
let v = self.0[self.1];
self.1 += 1;
v
}
fn next_normal(&mut self) -> f64 {
unreachable!("settlement draws uniforms only")
}
}
#[test]
fn the_shipped_depth_multiplier_settles_exactly_as_before() {
for volume in [0.0, 1.0, 10_000.0, 100_000.0, f64::NAN] {
let mut a = GameRng::from_seed(11);
let mut b = GameRng::from_seed(11);
let default = settle_price_through_book(
&company(),
100.0,
volume,
&SettleOptions::default(),
&mut a,
);
let explicit = settle_price_through_book(
&company(),
100.0,
volume,
&SettleOptions {
depth_multiplier: 1.0,
..SettleOptions::default()
},
&mut b,
);
assert_eq!(
default.price.to_bits(),
explicit.price.to_bits(),
"volume {volume}: the shipped multiplier must be a no-op"
);
assert_eq!(a, b, "volume {volume}: and must take the same draws");
}
}
#[test]
fn unbounded_depth_consumes_exactly_four_draws() {
let mut rng = GameRng::from_seed(42);
let before = rng.clone();
let out = settle_price_through_book(
&company(),
100.0,
10_000.0,
&SettleOptions {
depth_multiplier: f64::INFINITY,
..SettleOptions::default()
},
&mut rng,
);
assert!(out.traded);
assert_eq!(draws_consumed(&before, &rng), 4);
}
#[test]
fn unbounded_depth_takes_the_same_early_returns() {
let cases: Vec<(&str, CompanyMicrostructure, f64, f64)> = vec![
("fair value zero", company(), 0.0, 10_000.0),
("fair value NaN", company(), f64::NAN, 10_000.0),
("tick volume zero", company(), 100.0, 0.0),
("tick volume NaN", company(), 100.0, f64::NAN),
(
"last price zero",
CompanyMicrostructure {
price: 0.0,
..company()
},
100.0,
10_000.0,
),
];
for (note, c, fair_value, tick_volume) in cases {
let mut rng = GameRng::from_seed(42);
let before = rng.clone();
let out = settle_price_through_book(
&c,
fair_value,
tick_volume,
&SettleOptions {
depth_multiplier: f64::INFINITY,
..SettleOptions::default()
},
&mut rng,
);
assert!(!out.traded, "{note}: should not trade");
assert_eq!(draws_consumed(&before, &rng), 0, "{note}: should not draw");
}
}
#[test]
fn a_book_already_at_full_depth_prints_the_same_unbounded() {
let deep = settle_price_through_book(
&company(),
101.0,
100_000.0,
&SettleOptions::default(),
&mut Fixed([0.1, 0.2, 0.3, 0.4], 0),
);
let unbounded = settle_price_through_book(
&company(),
101.0,
100_000.0,
&SettleOptions {
depth_multiplier: f64::INFINITY,
..SettleOptions::default()
},
&mut Fixed([0.1, 0.2, 0.3, 0.4], 0),
);
assert_eq!(deep, unbounded);
}
#[test]
fn one_sided_flow_walks_further_when_the_bound_is_lifted() {
let bounded = settle_price_through_book(
&company(),
101.0,
30_000.0,
&SettleOptions::default(),
&mut Fixed([0.1, 0.1, 0.1, 0.1], 0),
);
let unbounded = settle_price_through_book(
&company(),
101.0,
30_000.0,
&SettleOptions {
depth_multiplier: f64::INFINITY,
..SettleOptions::default()
},
&mut Fixed([0.1, 0.1, 0.1, 0.1], 0),
);
assert!(
unbounded.traded_volume > bounded.traded_volume,
"unbounded depth must fill more of the same flow: {} against {}",
unbounded.traded_volume,
bounded.traded_volume
);
assert!(
unbounded.price > bounded.price,
"and the extra fills print higher: {} against {}",
unbounded.price,
bounded.price
);
}
#[test]
fn the_shock_and_the_absorption_sum_to_the_print_move() {
let out = settle_price_through_book(
&company(),
101.0,
30_000.0,
&SettleOptions::default(),
&mut Fixed([0.1, 0.6, 0.1, 0.6], 0),
);
assert!(out.traded);
let moved = mathx::log(out.price / company().price);
assert!(
(out.shock + out.absorbed - moved).abs() < 1e-12,
"shock {} + absorbed {} should be the move {moved}",
out.shock,
out.absorbed
);
}
#[test]
fn a_tick_that_does_not_settle_absorbs_exactly_zero() {
let out = settle_price_through_book(
&company(),
101.0,
0.0,
&SettleOptions::default(),
&mut GameRng::from_seed(3),
);
assert!(!out.traded);
assert_eq!(out.absorbed, 0.0);
assert_eq!(out.shock, mathx::log(101.0 / company().price));
}
#[test]
fn settlement_is_reproducible_from_the_same_seed() {
let run = || {
let mut rng = GameRng::from_seed(99);
settle_price_through_book(
&company(),
101.0,
10_000.0,
&SettleOptions::default(),
&mut rng,
)
};
assert_eq!(run(), run());
}
#[test]
fn a_gap_to_fair_value_biases_flow_toward_closing_it() {
let c = company();
let mut up = GameRng::from_seed(5);
let above =
settle_price_through_book(&c, 110.0, 50_000.0, &SettleOptions::default(), &mut up);
let mut down = GameRng::from_seed(5);
let below =
settle_price_through_book(&c, 90.0, 50_000.0, &SettleOptions::default(), &mut down);
assert!(
above.price > below.price,
"gap pressure should separate the prints: {} vs {}",
above.price,
below.price
);
}
#[test]
fn a_taker_buy_reduces_maker_inventory() {
let fill = |taker_side| Fill {
price: 100.0,
quantity: 50.0,
maker_order_id: "x".to_string(),
maker_id: MARKET_MAKER_ID.into(),
taker_id: "flow".into(),
taker_side,
};
assert_eq!(maker_delta_from_fills(&[fill(Side::Buy)]), -50.0);
assert_eq!(maker_delta_from_fills(&[fill(Side::Sell)]), 50.0);
}
#[test]
fn buy_leaning_flow_drains_maker_inventory_and_sell_leaning_builds_it() {
let mean_delta = |fair_value: f64, flow_lean: f64| {
let mut total = 0.0;
for seed in 0..300u64 {
let mut rng = GameRng::from_seed(seed);
total += settle_price_through_book(
&company(),
fair_value,
50_000.0,
&SettleOptions {
spread_size_smoothness: 0.0,
spread_size_exponent: SPREAD_SIZE_EXPONENT,
flow_lean: Some(flow_lean),
..SettleOptions::default()
},
&mut rng,
)
.maker_inventory_delta;
}
total / 300.0
};
let buying = mean_delta(101.0, 0.02);
let selling = mean_delta(99.0, -0.02);
assert!(
buying < 0.0,
"maker sells into buying flow, mean delta {buying}"
);
assert!(
selling > 0.0,
"maker buys from selling flow, mean delta {selling}"
);
}
#[test]
fn fills_against_other_participants_do_not_touch_maker_inventory() {
let fills = vec![Fill {
price: 100.0,
quantity: 50.0,
maker_order_id: "x".to_string(),
maker_id: "player".into(),
taker_id: "flow".into(),
taker_side: Side::Buy,
}];
assert_eq!(maker_delta_from_fills(&fills), 0.0);
}
fn resting(id: &str, side: Side, price: f64, quantity: f64) -> RestingOrder {
RestingOrder {
id: id.to_string(),
side,
price,
quantity,
owner_id: id.split('-').next().unwrap().to_string(),
}
}
#[test]
fn with_no_orders_the_variant_is_the_shipped_settlement() {
for volume in [0.0, 10_000.0, 100_000.0] {
let mut a = GameRng::from_seed(3);
let mut b = GameRng::from_seed(3);
let x = settle_price_through_book(
&company(), 101.0, volume, &SettleOptions::default(), &mut a);
let (y, fills) = settle_price_through_book_with_orders(
&company(), 101.0, volume, &SettleOptions::default(), &[], &mut b);
assert_eq!(x, y);
assert_eq!(a, b);
assert!(fills.is_empty());
}
}
#[test]
fn the_flow_fills_a_resting_bid_inside_the_spread_first() {
let bid = build_live_book(&company(), &LiveBookOptions::default())
.best_bid()
.unwrap();
let price = bid + 0.01;
let orders = vec![resting("a-0", Side::Buy, price, 3_000.0)];
let (out, fills) = settle_price_through_book_with_orders(
&company(), 99.0, 20_000.0, &SettleOptions::default(), &orders,
&mut Fixed([0.9, 0.9, 0.9, 0.9], 0));
assert!(out.traded);
assert_eq!(fills.len(), 1, "one slice of 5,000 took all 3,000: {fills:?}");
let f = &fills[0];
assert_eq!((f.agent.as_str(), f.side, f.price, f.quantity, f.taker),
("a", Side::Buy, price, 3_000.0, false));
assert_eq!(f.counterparty, "flow");
let mut rng = GameRng::from_seed(42);
let before = rng.clone();
settle_price_through_book_with_orders(
&company(), 99.0, 20_000.0, &SettleOptions::default(), &orders, &mut rng);
assert_eq!(draws_consumed(&before, &rng), 4);
}
#[test]
fn a_slice_smaller_than_the_order_fills_it_in_part() {
let bid = build_live_book(&company(), &LiveBookOptions::default())
.best_bid()
.unwrap();
let orders = vec![resting("a-0", Side::Buy, bid + 0.01, 7_000.0)];
let (_, fills) = settle_price_through_book_with_orders(
&company(), 99.0, 20_000.0, &SettleOptions::default(), &orders,
&mut Fixed([0.9, 0.9, 0.9, 0.9], 0));
let q: Vec<f64> = fills.iter().map(|f| f.quantity).collect();
assert_eq!(q, vec![5_000.0, 2_000.0]);
}
#[test]
fn a_crossed_resting_order_takes_the_ladder_before_the_flow() {
let ask = build_live_book(&company(), &LiveBookOptions::default())
.best_ask()
.unwrap();
let orders = vec![resting("a-0", Side::Buy, ask + 0.05, 1_000.0)];
let (_, fills) = settle_price_through_book_with_orders(
&company(), 100.0, 20_000.0, &SettleOptions::default(), &orders,
&mut Fixed([0.9, 0.9, 0.9, 0.9], 0));
let f = &fills[0];
assert!(f.taker);
assert_eq!((f.price, f.quantity, f.counterparty.as_str()), (ask, 1_000.0, MARKET_MAKER_ID));
}
#[test]
fn an_agents_buy_and_sell_at_one_price_do_not_trade_together() {
let ladder = build_live_book(&company(), &LiveBookOptions::default());
let (bid, ask) = (ladder.best_bid().unwrap(), ladder.best_ask().unwrap());
let p = ((bid + 0.01) * 100.0).round() / 100.0;
assert!(p < ask, "the test needs a spread of two cents: {bid} {ask}");
let orders = vec![
resting("a-0", Side::Buy, p, 1_000.0),
resting("a-1", Side::Sell, p, 1_000.0),
];
let (_, fills) = settle_price_through_book_with_orders(
&company(), 100.0, 4_000.0, &SettleOptions::default(), &orders,
&mut Fixed([0.0, 0.99, 0.99, 0.99], 0));
assert!(fills.iter().all(|f| f.counterparty != "a"), "self-trade: {fills:?}");
assert!(fills.iter().all(|f| !f.taker), "neither order crossed anyone else: {fills:?}");
let sold: f64 = fills.iter().filter(|f| f.order_id == "a-1").map(|f| f.quantity).sum();
let bought: f64 = fills.iter().filter(|f| f.order_id == "a-0").map(|f| f.quantity).sum();
assert_eq!((bought, sold), (1_000.0, 1_000.0), "the flow fills both: {fills:?}");
}
#[test]
fn a_crossing_order_skips_its_own_and_meets_the_next_agent() {
let ladder = build_live_book(&company(), &LiveBookOptions::default());
let (bid, ask) = (ladder.best_bid().unwrap(), ladder.best_ask().unwrap());
let p = ((bid + 0.01) * 100.0).round() / 100.0;
assert!(p < ask);
let orders = vec![
resting("a-0", Side::Buy, p, 1_000.0),
resting("b-0", Side::Buy, p, 600.0),
resting("a-1", Side::Sell, p, 1_000.0),
];
let (_, fills) = settle_price_through_book_with_orders(
&company(), 100.0, 4.0, &SettleOptions::default(), &orders,
&mut Fixed([0.99, 0.99, 0.99, 0.99], 0));
let crossed: Vec<_> = fills.iter().filter(|f| f.taker).collect();
assert_eq!(crossed.len(), 1, "{fills:?}");
assert_eq!(
(crossed[0].order_id.as_str(), crossed[0].counterparty.as_str(), crossed[0].quantity),
("a-1", "b", 600.0)
);
assert!(fills.iter().all(|f| f.order_id != "a-0" || f.counterparty != "a"));
}
#[test]
fn flow_that_empties_the_ladder_does_not_reach_a_bid_past_it() {
let ladder = build_live_book(&company(), &LiveBookOptions::default());
let deepest = ladder.bids.last().unwrap().price;
let held: f64 = ladder.bids.iter().map(|o| o.remaining).sum();
assert!(held < 200_000.0, "the ladder must run dry: {held}");
for price in [4.0, deepest * 0.9, deepest - 0.01] {
let orders = vec![resting("a-0", Side::Buy, price, 5_000.0)];
let (out, fills) = settle_price_through_book_with_orders(
&company(), 99.0, 200_000.0, &SettleOptions::default(), &orders,
&mut Fixed([0.9, 0.9, 0.9, 0.9], 0));
assert!(fills.is_empty(), "a bid at {price} below the ladder filled: {fills:?}");
assert_eq!(out.price, deepest, "the print is the ladder's last price");
let (bare, _) = settle_price_through_book_with_orders(
&company(), 99.0, 200_000.0, &SettleOptions::default(), &[],
&mut Fixed([0.9, 0.9, 0.9, 0.9], 0));
assert_eq!(out, bare);
}
}
#[test]
fn flow_that_empties_the_ladder_does_not_reach_an_offer_past_it() {
let ladder = build_live_book(&company(), &LiveBookOptions::default());
let deepest = ladder.asks.last().unwrap().price;
let orders = vec![resting("a-0", Side::Sell, 1_000.0, 5_000.0)];
let (out, fills) = settle_price_through_book_with_orders(
&company(), 101.0, 200_000.0, &SettleOptions::default(), &orders,
&mut Fixed([0.0, 0.0, 0.0, 0.0], 0));
assert!(fills.is_empty(), "an offer at 10x filled: {fills:?}");
assert_eq!(out.price, deepest);
}
#[test]
fn a_bid_at_the_ladders_last_price_still_fills_behind_the_maker() {
let ladder = build_live_book(&company(), &LiveBookOptions::default());
let deepest = ladder.bids.last().unwrap().price;
let orders = vec![resting("a-0", Side::Buy, deepest, 5_000.0)];
let (_, fills) = settle_price_through_book_with_orders(
&company(), 99.0, 200_000.0, &SettleOptions::default(), &orders,
&mut Fixed([0.9, 0.9, 0.9, 0.9], 0));
let q: f64 = fills.iter().map(|f| f.quantity).sum();
assert_eq!(q, 5_000.0, "{fills:?}");
assert!(fills.iter().all(|f| f.price == deepest && !f.taker));
}
#[test]
fn an_empty_fill_set_yields_positive_zero() {
assert_eq!(maker_delta_from_fills(&[]).to_bits(), 0.0f64.to_bits());
}
}