use crate::market::TickCompany;
use crate::market_maker::MARKET_MAKER_ID;
use crate::mathx;
use crate::microstructure::{build_live_book, LiveBookOptions, BOOK_LEVELS};
use crate::order_book::{BookOrder, OrderBook, Side};
use crate::params::ModelParams;
pub const DEPTH_OWNER: &str = "depth";
pub const FLOW_OWNER: &str = "flow";
pub const RANGE_OWNER: &str = "range";
pub const AGENT_BOOK_CAP: usize = 4096;
pub const DEPTH_LEVEL_RATIO: f64 = 1.25;
const DEPTH_GRID_FLOOR: f64 = 1e-4;
pub const TAKEN_MAKER_BID: usize = 0;
pub const TAKEN_MAKER_ASK: usize = 1;
pub const TAKEN_DEPTH_BID: usize = 2;
pub const TAKEN_DEPTH_ASK: usize = 3;
pub const TAKEN_MAKER_INVENTORY: usize = 4;
pub const TAKEN_WIDTH: usize = 5;
pub const MEMORY_FAST: usize = 0;
pub const MEMORY_SLOW: usize = 1;
pub const MEMORY_BOOKED: usize = 2;
pub const MEMORY_PAID: usize = 3;
pub const MEMORY_FLOW: usize = 4;
pub const MEMORY_WIDTH: usize = 5;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RestMode {
Queue,
Range,
}
impl RestMode {
pub fn as_str(self) -> &'static str {
match self {
RestMode::Queue => "queue",
RestMode::Range => "range",
}
}
pub fn parse(s: &str) -> Option<Self> {
match s {
"queue" => Some(RestMode::Queue),
"range" => Some(RestMode::Range),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct AgentOrder {
pub id: String,
pub agent: String,
pub ticker: String,
pub side: Side,
pub limit: f64,
pub quantity: f64,
pub remaining: f64,
pub sequence: u64,
pub mode: RestMode,
}
impl AgentOrder {
pub fn new(
id: impl Into<String>,
agent: impl Into<String>,
ticker: impl Into<String>,
side: Side,
limit: f64,
quantity: f64,
mode: RestMode,
) -> Self {
AgentOrder {
id: id.into(),
agent: agent.into(),
ticker: ticker.into(),
side,
limit,
quantity,
remaining: quantity,
sequence: 0,
mode,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Liquidity {
Taker,
Maker,
Range,
}
impl Liquidity {
pub fn as_str(self) -> &'static str {
match self {
Liquidity::Taker => "taker",
Liquidity::Maker => "maker",
Liquidity::Range => "range",
}
}
pub fn parse(s: &str) -> Option<Self> {
match s {
"taker" => Some(Liquidity::Taker),
"maker" => Some(Liquidity::Maker),
"range" => Some(Liquidity::Range),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct AgentFill {
pub agent: String,
pub order_id: String,
pub ticker: String,
pub side: Side,
pub quantity: f64,
pub price: f64,
pub liquidity: Liquidity,
pub counterparty: String,
pub reference: f64,
pub day: i64,
pub tick: u32,
pub sequence: u64,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct AgentImpact {
pub agent: String,
pub ticker: String,
pub bought: f64,
pub sold: f64,
pub permanent: f64,
pub transient: Option<f64>,
pub day: i64,
pub tick: u32,
}
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct BookState {
pub taken: Vec<[f64; TAKEN_WIDTH]>,
pub orders: Vec<AgentOrder>,
pub flow: Vec<(String, String, f64, f64)>,
pub fills: Vec<AgentFill>,
pub impacts: Vec<AgentImpact>,
pub sequence: u64,
pub fill_sequence: u64,
pub memory: Vec<[f64; MEMORY_WIDTH]>,
}
impl BookState {
pub fn is_pristine(&self) -> bool {
self.sequence == 0
&& self.fill_sequence == 0
&& self.orders.is_empty()
&& self.flow.is_empty()
&& self.fills.is_empty()
&& self.impacts.is_empty()
&& self.taken.iter().all(|row| row.iter().all(|v| *v == 0.0))
&& self.memory.iter().all(|row| row.iter().all(|v| *v == 0.0))
}
pub fn fit(&mut self, companies: usize) {
if self.taken.len() < companies {
self.taken.resize(companies, [0.0; TAKEN_WIDTH]);
}
}
pub fn add_house_flow(
&mut self,
companies: usize,
index: usize,
side: Side,
quantity: f64,
price: f64,
reference: f64,
) {
if !(quantity > 0.0) {
return;
}
if self.memory.len() < companies {
self.memory.resize(companies, [0.0; MEMORY_WIDTH]);
}
if let Some(row) = self.memory.get_mut(index) {
row[MEMORY_FLOW] += match side {
Side::Buy => quantity,
Side::Sell => -quantity,
};
if price > 0.0 && reference > 0.0 {
row[MEMORY_PAID] += quantity * mathx::log(price / reference).abs();
}
}
}
pub fn add_flow(&mut self, agent: &str, ticker: &str, side: Side, quantity: f64) {
let (b, s) = match side {
Side::Buy => (quantity, 0.0),
Side::Sell => (0.0, quantity),
};
match self
.flow
.iter_mut()
.find(|(a, t, _, _)| a == agent && t == ticker)
{
Some(row) => {
row.2 += b;
row.3 += s;
}
None => self.flow.push((agent.to_string(), ticker.to_string(), b, s)),
}
}
}
pub fn daily_sigma(company: &TickCompany, market_sigma_daily: f64) -> f64 {
let beta = company.stock.beta.unwrap_or(1.0);
let idio = mathx::max(0.0, company.stock.garch_variance);
let market = beta * market_sigma_daily;
mathx::sqrt(idio + market * market)
}
pub fn daily_volume(company: &TickCompany) -> f64 {
let truthy = |v: f64| if v != 0.0 && !v.is_nan() { Some(v) } else { None };
truthy(company.stock.avg_volume)
.or_else(|| truthy(company.stock.volume))
.or_else(|| truthy(company.stock.shares_outstanding * 0.005))
.unwrap_or(100.0)
}
fn cents_away(price: f64, side: Side) -> f64 {
let cents = price * 100.0;
match side {
Side::Sell => (cents - 1e-7).ceil() / 100.0,
Side::Buy => (cents + 1e-7).floor() / 100.0,
}
}
pub fn append_latent_depth(
book: &mut OrderBook,
side: Side,
touch: f64,
sigma: f64,
volume: f64,
params: &ModelParams,
from: f64,
) {
let y = params.book_depth_coefficient;
let (delta, reach) = depth_shape(params);
let reach = reach * volume;
if !(y > 0.0) || !(volume > 0.0) || !(touch > 0.0) || !(sigma > 0.0) {
return;
}
let floor = volume * DEPTH_GRID_FLOOR;
let mut bounds = vec![reach];
while let Some(&last) = bounds.last() {
let next = last / DEPTH_LEVEL_RATIO;
if next < floor {
break;
}
bounds.push(next);
}
bounds.reverse();
let nest = params.book_depth_nesting;
let ladder: Vec<(f64, f64)> = if nest > 0.0 {
let orders = match side {
Side::Buy => &book.bids,
Side::Sell => &book.asks,
};
orders.iter().map(|o| (o.price, o.remaining)).collect()
} else {
Vec::new()
};
let mut placed = 0.0;
let mut pending: Option<(f64, f64)> = None;
let mut levels: Vec<(f64, f64)> = Vec::new();
for bound in bounds {
let distance = if from > 0.0 {
y * sigma * (mathx::pow(from + bound / volume, delta) - mathx::pow(from, delta))
} else {
y * sigma * mathx::pow(bound / volume, delta)
};
let raw = match side {
Side::Sell => touch * (1.0 + distance),
Side::Buy => touch * (1.0 - distance),
};
let price = cents_away(raw, side);
if !(price > 0.0) {
break;
}
let bound = if nest > 0.0 {
let ahead: f64 = ladder
.iter()
.filter(|(p, _)| match side {
Side::Sell => *p <= price,
Side::Buy => *p >= price,
})
.map(|(_, q)| *q)
.sum();
mathx::max(placed, bound - nest * ahead)
} else {
bound
};
let shares = bound.floor() - placed;
if !(shares >= 1.0) {
continue;
}
placed += shares;
pending = match pending {
Some((p, q)) if p == price => Some((p, q + shares)),
Some(level) => {
levels.push(level);
Some((price, shares))
}
None => Some((price, shares)),
};
}
if let Some(level) = pending {
levels.push(level);
}
for (price, shares) in levels {
book.rest_limit(side, price, shares, DEPTH_OWNER);
}
}
pub fn depth_shape(params: &ModelParams) -> (f64, f64) {
let delta = if params.book_depth_exponent == 0.0 { 0.5 } else { params.book_depth_exponent };
let reach = if params.book_depth_reach == 0.0 { 1.0 } else { params.book_depth_reach };
(delta, reach)
}
pub fn memory_position(params: &ModelParams, row: &[f64; MEMORY_WIDTH]) -> f64 {
let w = params.impact_memory_slow_weight;
if w == 0.0 {
row[MEMORY_FAST]
} else {
(1.0 - w) * row[MEMORY_FAST] + w * row[MEMORY_SLOW]
}
}
pub fn memory_displacement(params: &ModelParams, m: f64, sigma: f64) -> f64 {
let y = params.impact_memory_coefficient;
if !(y > 0.0) || m == 0.0 || !(sigma > 0.0) {
return 0.0;
}
let (delta, _) = depth_shape(params);
let a = m.abs();
let star = params.impact_memory_crossover;
let h = if star > 0.0 && a < star {
a * mathx::pow(star, delta - 1.0)
} else {
mathx::pow(a, delta)
};
let d = y * sigma * h;
if m > 0.0 { d } else { -d }
}
pub fn memory_decay(h: f64) -> f64 {
if h > 0.0 { mathx::pow(0.5, 1.0 / h) } else { 1.0 }
}
pub fn memory_point(params: &ModelParams, booked: f64, sigma: f64) -> f64 {
let yb = params.book_depth_coefficient;
if booked == 0.0 || !(yb > 0.0) || !(sigma > 0.0) || !(params.impact_memory_coefficient > 0.0) {
return 0.0;
}
let (delta, _) = depth_shape(params);
mathx::pow(booked.abs() / (yb * sigma), 1.0 / delta)
}
pub fn memory_inverse(params: &ModelParams, d: f64, sigma: f64) -> f64 {
let y = params.impact_memory_coefficient;
if !(y > 0.0) || d == 0.0 || !(sigma > 0.0) {
return 0.0;
}
let (delta, _) = depth_shape(params);
let a = d.abs() / (y * sigma);
let star = params.impact_memory_crossover;
let m = if star > 0.0 && a < mathx::pow(star, delta) {
a / mathx::pow(star, delta - 1.0)
} else {
mathx::pow(a, 1.0 / delta)
};
if d > 0.0 { m } else { -m }
}
struct MemoryBound<'a> {
params: &'a ModelParams,
sigma: f64,
volume: f64,
reference: f64,
position: f64,
booked: f64,
}
impl MemoryBound<'_> {
fn price(&self, side: Side, q: f64) -> f64 {
let m = match side {
Side::Sell => self.position + q / self.volume,
Side::Buy => self.position - q / self.volume,
};
let d = memory_displacement(self.params, m, self.sigma);
self.reference * mathx::exp(d - self.booked)
}
fn reach(&self, side: Side, price: f64) -> f64 {
let x = mathx::log(price / self.reference) + self.booked;
let m = memory_inverse(self.params, x, self.sigma);
match side {
Side::Sell => (m - self.position) * self.volume,
Side::Buy => (self.position - m) * self.volume,
}
}
fn apply(&self, orders: Vec<BookOrder>, side: Side, company_id: &str) -> Vec<BookOrder> {
let worse = |a: f64, b: f64| match side {
Side::Sell => mathx::max(a, b),
Side::Buy => mathx::min(a, b),
};
let step = self.volume * DEPTH_GRID_FLOOR;
let mut out: Vec<BookOrder> = Vec::with_capacity(orders.len());
let mut placed = 0.0;
let mut last: Option<f64> = None;
let mut pieces: Vec<(f64, f64)> = Vec::new();
for o in orders {
let mut left = o.remaining;
let within = mathx::max(0.0, mathx::min(left, self.reach(side, o.price) - placed));
pieces.clear();
if within > 0.0 {
pieces.push((o.price, within));
left -= within;
placed += within;
}
while left > 1e-9 {
let span = mathx::max(step, 0.25 * placed);
let take = mathx::min(left, span);
placed += take;
left -= take;
let bound = cents_away(self.price(side, placed), side);
pieces.push((worse(o.price, bound), take));
}
for (k, &(price, shares)) in pieces.iter().enumerate() {
let price = match last {
Some(prev) => worse(price, prev),
None => price,
};
last = Some(price);
out.push(if k == 0 {
BookOrder {
price,
quantity: shares,
remaining: shares,
..o.clone()
}
} else {
o.piece(k as u32, price, shares, company_id)
});
}
}
out
}
}
pub fn remove_front(book: &mut OrderBook, side: Side, owner: &str, quantity: f64) {
if !(quantity > 0.0) {
return;
}
let orders = match side {
Side::Buy => &mut book.bids,
Side::Sell => &mut book.asks,
};
let mut left = quantity;
for o in orders.iter_mut() {
if !(left > 0.0) {
break;
}
if o.owner_id != owner {
continue;
}
let take = mathx::min(o.remaining, left);
o.remaining -= take;
left -= take;
}
orders.retain(|o| o.remaining > 0.0);
}
#[non_exhaustive]
pub struct AgentBookInputs<'a> {
pub company: &'a TickCompany,
pub vix: f64,
pub params: &'a ModelParams,
pub market_sigma_daily: f64,
pub taken: [f64; TAKEN_WIDTH],
pub memory: [f64; MEMORY_WIDTH],
pub orders: &'a [AgentOrder],
pub exclude_agent: Option<&'a str>,
}
impl<'a> AgentBookInputs<'a> {
pub fn new(
company: &'a TickCompany,
vix: f64,
params: &'a ModelParams,
market_sigma_daily: f64,
) -> Self {
AgentBookInputs {
company,
vix,
params,
market_sigma_daily,
taken: [0.0; TAKEN_WIDTH],
memory: [0.0; MEMORY_WIDTH],
orders: &[],
exclude_agent: None,
}
}
}
pub fn maker_ladder(company: &TickCompany, vix: f64, params: &ModelParams) -> OrderBook {
build_live_book(
&company.micro_view(company.stock.price),
&LiveBookOptions {
vix,
spread_size_smoothness: params.spread_size_smoothness,
spread_size_exponent: params.spread_size_exponent,
levels: BOOK_LEVELS,
..Default::default()
},
)
.with_cap(AGENT_BOOK_CAP)
}
pub fn agent_book(inputs: &AgentBookInputs<'_>) -> OrderBook {
let company = inputs.company;
let params = inputs.params;
let mut book = maker_ladder(company, inputs.vix, params);
let mut lean: Option<(Side, f64, f64)> = None;
if params.book_depth_coefficient > 0.0 {
let sigma = daily_sigma(company, inputs.market_sigma_daily);
let volume = daily_volume(company);
let booked = inputs.memory[MEMORY_BOOKED];
let x_m = memory_point(params, booked, sigma);
if x_m > 0.0 {
let side = if booked > 0.0 { Side::Sell } else { Side::Buy };
lean = Some((side, x_m, volume));
}
for side in [Side::Buy, Side::Sell] {
let touch = match side {
Side::Buy => book.best_bid(),
Side::Sell => book.best_ask(),
};
let from = match lean {
Some((s, x, _)) if s == side => x,
_ => 0.0,
};
if let Some(touch) = touch {
append_latent_depth(&mut book, side, touch, sigma, volume, params, from);
}
}
}
let t = inputs.taken;
let depth_front = |side: Side, taken: f64| match lean {
Some((s, x, v)) if s == side => mathx::max(0.0, taken - x * v),
_ => taken,
};
remove_front(&mut book, Side::Buy, MARKET_MAKER_ID, t[TAKEN_MAKER_BID]);
remove_front(&mut book, Side::Sell, MARKET_MAKER_ID, t[TAKEN_MAKER_ASK]);
remove_front(&mut book, Side::Buy, DEPTH_OWNER, depth_front(Side::Buy, t[TAKEN_DEPTH_BID]));
remove_front(&mut book, Side::Sell, DEPTH_OWNER, depth_front(Side::Sell, t[TAKEN_DEPTH_ASK]));
if params.impact_memory_coefficient > 0.0 {
let sigma = daily_sigma(company, inputs.market_sigma_daily);
let volume = daily_volume(company);
let reference = company.stock.price;
if volume > 0.0 && sigma > 0.0 && reference > 0.0 {
let m = memory_position(params, &inputs.memory) + inputs.memory[MEMORY_FLOW] / volume;
let bound = MemoryBound {
params,
sigma,
volume,
reference,
position: m,
booked: inputs.memory[MEMORY_BOOKED],
};
if m > 0.0 {
book.bids = bound.apply(std::mem::take(&mut book.bids), Side::Buy, &book.company_id);
} else if m < 0.0 {
book.asks = bound.apply(std::mem::take(&mut book.asks), Side::Sell, &book.company_id);
}
}
}
for o in inputs.orders {
if o.mode != RestMode::Queue || o.ticker != company.ticker {
continue;
}
if inputs.exclude_agent == Some(o.agent.as_str()) {
continue;
}
book.post_limit(o.side, o.limit, o.remaining, &o.agent, Some(o.id.clone()));
}
book
}
pub fn taken_slot(taker_side: Side, owner: &str) -> Option<usize> {
match (taker_side, owner) {
(Side::Buy, MARKET_MAKER_ID) => Some(TAKEN_MAKER_ASK),
(Side::Sell, MARKET_MAKER_ID) => Some(TAKEN_MAKER_BID),
(Side::Buy, DEPTH_OWNER) => Some(TAKEN_DEPTH_ASK),
(Side::Sell, DEPTH_OWNER) => Some(TAKEN_DEPTH_BID),
_ => None,
}
}
pub fn is_house(owner: &str) -> bool {
owner == MARKET_MAKER_ID || owner == DEPTH_OWNER || owner == FLOW_OWNER || owner == RANGE_OWNER
}
pub fn refill_factor(params: &ModelParams) -> f64 {
let h = params.book_refill_half_life;
if h > 0.0 {
mathx::pow(0.5, 1.0 / h)
} else {
0.0
}
}
pub fn range_reached(side: Side, limit: f64, print: f64) -> bool {
match side {
Side::Buy => print <= limit,
Side::Sell => print >= limit,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::market::{TickCompany, TickStock};
use crate::order_book::SubmitOptions;
fn company(price: f64, adv: f64, garch_variance: f64) -> TickCompany {
TickCompany {
id: "ACME".into(),
ticker: "ACME".into(),
sector: "technology".into(),
is_bankrupt: false,
is_public: true,
stock: TickStock {
price,
previous_close: price,
previous_tick_price: None,
open: price,
high: price,
low: price,
volume: 0.0,
avg_volume: adv,
shares_outstanding: 1e8,
market_cap: price * 1e8,
mispricing_s: None,
mispricing_s_prev_close: None,
mispricing_momentum: None,
maker_inventory: Some(0.0),
garch_variance,
garch_cascade: [0.0; crate::market::garch::CASCADE_MAX],
last_daily_return: None,
beta: Some(1.0),
short_interest: 0.0,
float: 1e8,
fair_value_offset: None,
buyback_log_shares: None,
dividend: None,
},
sector_volatility: Some(1.0),
sector_avg_pe: None,
eps: Some(5.0),
book_value_per_share: Some(20.0),
revenue_growth: Some(0.05),
}
}
fn tail_params(y: f64) -> ModelParams {
let mut p = crate::params::PT_V1;
p.book_depth_coefficient = y;
p.book_depth_exponent = 0.5;
p.book_depth_reach = 1.0;
p
}
fn inputs<'a>(c: &'a TickCompany, p: &'a ModelParams, orders: &'a [AgentOrder]) -> AgentBookInputs<'a> {
AgentBookInputs {
company: c,
vix: 15.0,
params: p,
market_sigma_daily: 0.01,
taken: [0.0; TAKEN_WIDTH],
memory: [0.0; MEMORY_WIDTH],
orders,
exclude_agent: None,
}
}
fn memory_params(y_m: f64) -> ModelParams {
let mut p = tail_params(0.75);
p.book_shared = 1.0;
p.impact_memory_coefficient = y_m;
p.impact_memory_half_life = 90.0;
p.impact_memory_crossover = 0.001;
p
}
#[test]
fn the_memory_displacement_is_a_square_root_with_a_linear_foot() {
let p = memory_params(0.6);
let sigma = 0.02;
let d = |m: f64| memory_displacement(&p, m, sigma);
assert!((d(0.1) - 0.6 * sigma * 0.1f64.sqrt()).abs() < 1e-15);
assert!((d(-0.1) + d(0.1)).abs() < 1e-15);
assert!((d(0.0005) - 0.6 * sigma * 0.0005 / 0.001f64.sqrt()).abs() < 1e-15);
assert!((d(0.001 - 1e-12) - d(0.001)).abs() < 1e-12);
for m in [-0.3, -0.01, -0.0002, 0.0002, 0.004, 0.2] {
assert!((memory_inverse(&p, d(m), sigma) - m).abs() < 1e-12, "{m}");
}
let off = memory_params(0.0);
assert_eq!(memory_displacement(&off, 0.1, sigma), 0.0);
assert_eq!(memory_point(&off, 0.01, sigma), 0.0);
assert_eq!(memory_decay(0.0), 1.0);
assert!((memory_decay(90.0).powf(90.0) - 0.5).abs() < 1e-12);
}
#[test]
fn an_empty_memory_leaves_the_book_as_it_was() {
let c = company(50.0, 2e5, 0.0004);
let on = memory_params(0.6);
let mut off = on.clone();
off.impact_memory_coefficient = 0.0;
off.impact_memory_half_life = 0.0;
let a = agent_book(&inputs(&c, &on, &[]));
let b = agent_book(&inputs(&c, &off, &[]));
assert_eq!(a.asks, b.asks);
assert_eq!(a.bids, b.bids);
}
#[test]
fn nesting_makes_the_depth_the_larger_of_ladder_and_law() {
let c = company(50.0, 2e5, 0.0004);
let beside = tail_params(0.75);
let mut nested = beside.clone();
nested.book_depth_nesting = 1.0;
let a = agent_book(&inputs(&c, &beside, &[]));
let b = agent_book(&inputs(&c, &nested, &[]));
let ladder = maker_ladder(&c, 15.0, &beside);
let within = |orders: &[BookOrder], owner: Option<&str>, price: f64| -> f64 {
orders.iter().filter(|o| o.price <= price && owner.is_none_or(|w| o.owner_id == w))
.map(|o| o.remaining).sum()
};
let maker = |bk: &OrderBook| -> Vec<(f64, f64)> {
bk.asks.iter().filter(|o| o.owner_id == MARKET_MAKER_ID).map(|o| (o.price, o.remaining)).collect()
};
assert_eq!(maker(&a), maker(&b));
let mut thinner = false;
for o in &a.asks {
let p = o.price;
let lad = within(&ladder.asks, None, p);
let law_beside = within(&a.asks, Some(DEPTH_OWNER), p);
let total_nested = within(&b.asks, None, p);
assert!(total_nested + 1.0 >= lad.max(law_beside) - 1.0, "{p}");
assert!(total_nested <= lad.max(law_beside) + law_beside * 0.25 + 2.0, "{p}");
if total_nested + 1.0 < within(&a.asks, None, p) {
thinner = true;
}
}
assert!(thinner, "nesting must remove the double-counted front somewhere");
let mut zero = beside.clone();
zero.book_depth_nesting = 0.0;
assert_eq!(agent_book(&inputs(&c, &zero, &[])).asks, a.asks);
}
#[test]
fn a_long_lean_bounds_the_bids_and_continues_the_asks() {
let c = company(50.0, 2e5, 0.0004);
let p = memory_params(0.6);
let sigma = daily_sigma(&c, 0.01);
let m = 0.05;
let booked = memory_displacement(&p, m, sigma);
let mut inp = inputs(&c, &p, &[]);
inp.memory = [m, 0.0, booked, 0.0, 0.0];
let book = agent_book(&inp);
let mut plain = p.clone();
plain.impact_memory_coefficient = 0.0;
plain.impact_memory_half_life = 0.0;
let fresh = agent_book(&inputs(&c, &plain, &[]));
let worst = |b: &OrderBook| b.sweep_cost(Side::Buy, 0.1 * 2e5).unwrap().worst_price;
assert!(worst(&book) < worst(&fresh), "{} {}", worst(&book), worst(&fresh));
let q = m * 2e5;
let got = book.sweep_cost(Side::Sell, q).unwrap().average_price;
let path = 50.0 * (-(booked - 0.6 * sigma * (2.0 / 3.0) * m.sqrt())).exp();
assert!(got <= path + 0.02, "{got} above the path's {path}");
assert!(got < fresh.sweep_cost(Side::Sell, q).unwrap().average_price + 1e-9);
}
#[test]
fn without_the_tail_the_book_is_the_ladder() {
let c = company(100.0, 1e6, 0.0002);
let p = crate::params::PT_V1;
let book = agent_book(&inputs(&c, &p, &[]));
assert_eq!(book.asks.len(), BOOK_LEVELS as usize);
assert_eq!(book.bids.len(), BOOK_LEVELS as usize);
let plain = maker_ladder(&c, 15.0, &p);
assert_eq!(book.asks, plain.asks);
}
#[test]
fn the_latent_pool_reaches_a_days_volume_and_is_monotone() {
let c = company(100.0, 1e6, 0.0002);
let p = tail_params(0.5);
let book = agent_book(&inputs(&c, &p, &[]));
for side in [Side::Buy, Side::Sell] {
let orders = if side == Side::Buy { &book.bids } else { &book.asks };
let latent: Vec<_> = orders.iter().filter(|o| o.owner_id == DEPTH_OWNER).collect();
let total: f64 = latent.iter().map(|o| o.remaining).sum();
assert!(total > 0.99e6 && total <= 1e6, "{side:?} depth {total}");
for w in latent.windows(2) {
match side {
Side::Buy => assert!(w[1].price < w[0].price),
Side::Sell => assert!(w[1].price > w[0].price),
}
}
for w in orders.windows(2) {
match side {
Side::Buy => assert!(w[1].price <= w[0].price),
Side::Sell => assert!(w[1].price >= w[0].price),
}
}
}
}
#[test]
fn no_latent_share_is_cheaper_than_the_law() {
let c = company(50.0, 2e5, 0.0004);
let p = tail_params(0.7);
let book = agent_book(&inputs(&c, &p, &[]));
let sigma = daily_sigma(&c, 0.01);
let touch = book.asks[0].price;
let mut cumulative = 0.0;
for o in book.asks.iter().filter(|o| o.owner_id == DEPTH_OWNER) {
cumulative += o.remaining;
let law = touch * (1.0 + 0.7 * sigma * (cumulative / 2e5).sqrt());
assert!(o.price >= law - 1e-9, "{} below {law} at {cumulative}", o.price);
}
}
#[test]
fn the_book_is_never_dearer_than_the_law_past_a_grid_step() {
let c = company(50.0, 2e5, 0.0004);
let p = tail_params(0.7);
let book = agent_book(&inputs(&c, &p, &[]));
let sigma = daily_sigma(&c, 0.01);
let touch = book.asks[0].price;
for f in [0.01, 0.03, 0.1, 0.3, 0.9] {
let q = f * 2e5;
let worst = book.sweep_cost(Side::Buy, q).unwrap().worst_price;
let law = touch * (1.0 + 0.7 * sigma * (f * DEPTH_LEVEL_RATIO).sqrt());
assert!(worst <= law + 0.01, "{f}: {worst} past {law}");
}
}
#[test]
fn a_large_order_walks_the_tail_instead_of_being_cut_off() {
let c = company(100.0, 1e6, 0.0002);
let off = crate::params::PT_V1;
let on = tail_params(0.5);
let mut cut = agent_book(&inputs(&c, &off, &[]));
let mut deep = agent_book(&inputs(&c, &on, &[]));
let a = cut.submit(Side::Buy, 300_000.0, "a", SubmitOptions::default());
let b = deep.submit(Side::Buy, 300_000.0, "a", SubmitOptions::default());
assert!(a.unfilled > 200_000.0, "the ladder alone holds under 5%: {}", a.unfilled);
assert_eq!(b.unfilled, 0.0);
assert!(b.average_price.unwrap() > a.average_price.unwrap());
}
#[test]
fn taken_volume_comes_off_the_front_of_its_own_layer() {
let c = company(100.0, 1e6, 0.0002);
let p = tail_params(0.5);
let full = agent_book(&inputs(&c, &p, &[]));
let maker = |b: &OrderBook| -> Vec<(f64, f64)> {
b.asks.iter().filter(|o| o.owner_id == MARKET_MAKER_ID)
.map(|o| (o.price, o.remaining)).collect()
};
let latent = |b: &OrderBook| -> Vec<(f64, f64)> {
b.asks.iter().filter(|o| o.owner_id == DEPTH_OWNER)
.map(|o| (o.price, o.remaining)).collect()
};
let first = maker(&full)[0].1;
let mut inp = inputs(&c, &p, &[]);
inp.taken[TAKEN_MAKER_ASK] = first + 10.0;
let less = agent_book(&inp);
assert_eq!(maker(&less)[0], (maker(&full)[1].0, maker(&full)[1].1 - 10.0));
assert_eq!(latent(&less), latent(&full), "the latent pool is its own layer");
assert_eq!(less.bids, full.bids, "the other side is untouched");
}
#[test]
fn a_resting_order_queues_behind_the_maker_at_its_price() {
let c = company(100.0, 1e6, 0.0002);
let p = crate::params::PT_V1;
let ladder = maker_ladder(&c, 15.0, &p);
let touch = ladder.asks[0].price;
let at_touch = ladder.asks[0].remaining;
let orders = vec![AgentOrder {
id: "b-0".into(),
agent: "b".into(),
ticker: "ACME".into(),
side: Side::Sell,
limit: touch,
quantity: 500.0,
remaining: 500.0,
sequence: 0,
mode: RestMode::Queue,
}];
let mut book = agent_book(&inputs(&c, &p, &orders));
assert_eq!(book.asks[0].owner_id, MARKET_MAKER_ID);
assert_eq!(book.asks[1].owner_id, "b");
let r = book.submit(Side::Buy, at_touch + 200.0, "a", SubmitOptions::default());
let from_b: f64 = r.fills.iter().filter(|f| f.maker_id == "b").map(|f| f.quantity).sum();
assert_eq!(from_b, 200.0, "partial: the queue ahead took the rest");
}
#[test]
fn an_agent_never_meets_its_own_orders() {
let c = company(100.0, 1e6, 0.0002);
let p = crate::params::PT_V1;
let orders = vec![AgentOrder {
id: "a-0".into(),
agent: "a".into(),
ticker: "ACME".into(),
side: Side::Sell,
limit: 99.0,
quantity: 5.0,
remaining: 5.0,
sequence: 0,
mode: RestMode::Queue,
}];
let mut inp = inputs(&c, &p, &orders);
inp.exclude_agent = Some("a");
let book = agent_book(&inp);
assert!(book.asks.iter().all(|o| o.owner_id != "a"));
}
#[test]
fn a_range_order_is_not_in_the_book() {
let c = company(100.0, 1e6, 0.0002);
let p = crate::params::PT_V1;
let orders = vec![AgentOrder {
id: "a-0".into(),
agent: "a".into(),
ticker: "ACME".into(),
side: Side::Buy,
limit: 99.99,
quantity: 5.0,
remaining: 5.0,
sequence: 0,
mode: RestMode::Range,
}];
let book = agent_book(&inputs(&c, &p, &orders));
assert!(book.bids.iter().all(|o| o.owner_id == MARKET_MAKER_ID));
}
#[test]
fn the_refill_factor_halves_at_the_half_life() {
let mut p = tail_params(0.5);
p.book_shared = 1.0;
p.book_refill_half_life = 27.0;
let f = refill_factor(&p);
let mut x = 1.0;
for _ in 0..27 {
x *= f;
}
assert!((x - 0.5).abs() < 1e-12, "{x}");
p.book_refill_half_life = 0.0;
assert_eq!(refill_factor(&p), 0.0);
}
#[test]
fn a_pristine_state_says_so_and_a_used_one_does_not() {
let mut s = BookState::default();
s.fit(3);
assert!(s.is_pristine());
s.add_flow("a", "ACME", Side::Buy, 10.0);
assert!(!s.is_pristine());
s.add_flow("a", "ACME", Side::Sell, 4.0);
assert_eq!(s.flow, vec![("a".to_string(), "ACME".to_string(), 10.0, 4.0)]);
}
}