From 12e26d6cc917ed14c119589d4b94858150fa0066 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Thu, 3 Dec 2026 06:24:33 +0800 Subject: [PATCH] Discover auction prices at supply and demand changes on fine tick grids --- crates/matching/README.md | 16 +++- crates/matching/examples/throughput.rs | 13 +++ crates/matching/src/lib.rs | 119 ++++++++++++++++++++++--- crates/matching/src/order.rs | 2 + 4 files changed, 133 insertions(+), 17 deletions(-) diff --git a/crates/matching/README.md b/crates/matching/README.md index 10756ce..2867dd2 100644 --- a/crates/matching/README.md +++ b/crates/matching/README.md @@ -1,6 +1,6 @@ # matching -每个 OrderBook 保存一个交易品的常驻盘口。买卖双方各有一棵按价格、原始受理序号排序的 BTreeMap。价格单位为分,数量单位为份。exchange 按市场和结果持有这些簿,并把已提交的订单余量逐笔应用到对应的树。 +每个 OrderBook 保存一个交易品的常驻盘口。买卖双方各有一棵按价格、原始受理序号排序的 BTreeMap。每本簿的价格均用同一个最小价格步长的整数倍表示,数量单位为份。现有 exchange 以一美分为一步。exchange 按市场和结果持有这些簿,并把已提交的订单余量逐笔应用到对应的树。 ## 文件依赖 @@ -24,10 +24,12 @@ sequenceDiagram B->>M: match_incoming,传入一条新订单 M->>M: 从对手方最优价起遍历,同价按原序号分配 else 盘中按金额买入 - B->>M: match_budget_buy,传入买单序号、最高价、预算分数 + B->>M: match_budget_buy,传入买单序号、最高价、以同一步长折算的总预算 M->>M: 在同一卖盘上逐单扣减可用预算,末档取可负担的整份 else 集合竞价 - B->>M: opening,在本簿现有两侧计算统一成交价 + B->>M: opening,在买一与卖一之间计算统一成交价 + M->>M: 从卖一起,只访问新的卖价或买价之后的第一个价格步长 + M->>M: 最大成交量优先,再取供需差最小者,并列时选最低价 end M-->>B: 返回成交计划,保留已提交盘口 alt SQLite 提交成功 @@ -37,9 +39,15 @@ sequenceDiagram end ``` +## 细步长样例 + +Gamma 市场 559651 的一份公开目录记录中,最小步长为 0.001 美元,买一为 0.012,卖一为 0.013。以这个步长建立内存簿,两个价位分别用整数 12、13 表示。假设盘中在 12 上有两张各 2 份的卖单,在 13 上有一张 2 份卖单,以 13 为限价买入 5 份,会按受理顺序以 12、12、13 成交,合计 61 个步长,即 0.061 美元。这个成交场景使用模拟订单。exchange 的命令、预留资金和持久化价格仍按整分工作,接入细步长需要一起迁移这些字段。[官方目录](https://gamma-api.polymarket.com/markets/559651) + +开盘沿用 Eventbook 的集合竞价规则。若价位 812 有 2 份卖单,812 和 817 分别有 3 份和 2 份买单,在 812 可成交 2 份,需求多出 3 份;在 813 至 817 均可成交 2 份,供需相等。最终以最低的 813 清算。813 上可以没有挂单。遍历工作量取决于订单和有供需变化的价位数,即使最小步长细化,空价位也无需逐档扫描。 + ## 吞吐基准 -在获准的测量机器上执行 `cargo run --release --locked -p matching --example throughput`。用同一工具链、硬件和负载对比基线 ca45f83 与本分支,在基线工作区放入同一个 examples/throughput.rs。程序预热后分别报告七轮的中位和最佳 ops/s,包括无交叉、单笔、扫 32 单、写入并撮合移除一张单,以及 8192 单集合竞价。前三项使用固定盘口,写入场景在每次迭代中实际维护盘口;开盘场景的单位是整次竞价。均为单线程内存测量,SQLite、网关和网络延迟在范围之外。此次未执行 release 测量。 +在获准的测量机器上执行 `cargo run --release --locked -p matching --example throughput`。用同一工具链、硬件和负载对比基线 ca45f83 与本分支,在基线工作区放入同一个 examples/throughput.rs。程序预热后分别报告七轮的中位和最佳 ops/s,包括无交叉、单笔、扫 32 单、写入并撮合移除一张单,以及 8192 单集合竞价。前三项使用固定盘口,写入场景在每次迭代中实际维护盘口;开盘场景的单位是整次竞价。均为单线程内存测量,SQLite、网关和网络延迟在范围之外。另设同样 8192 单的稀疏网格场景。该场景在十个价位上分配订单,价位间距为 1000 步;先核对得到 2049 笔成交才计时,旧基线若不支持该范围则显示跳过。此次未执行 release 测量。 ```mermaid flowchart LR diff --git a/crates/matching/examples/throughput.rs b/crates/matching/examples/throughput.rs index d6e0f74..8c72235 100644 --- a/crates/matching/examples/throughput.rs +++ b/crates/matching/examples/throughput.rs @@ -62,4 +62,17 @@ fn main() { measure("opening/8192-orders", 100, || { black_box(&book).opening().len() }); + // Same order IDs, quantities, and distinct levels over a wider price grid. + let mut sparse = OrderBook::default(); + for seq in 1..=8192 { + let side = if seq <= 4096 { Side::Sell } else { Side::Buy }; + sparse.update(order(seq, side, 500_000 + 1_000 * (seq % 10), 1)); + } + if sparse.opening().len() == 2049 { + measure("opening/8192-orders/sparse-ticks", 100, || { + black_box(&sparse).opening().len() + }); + } else { + eprintln!("opening/8192-orders/sparse-ticks skipped: expected 2049 fills"); + } } diff --git a/crates/matching/src/lib.rs b/crates/matching/src/lib.rs index c0bf66c..27a0501 100644 --- a/crates/matching/src/lib.rs +++ b/crates/matching/src/lib.rs @@ -41,7 +41,8 @@ impl OrderBook { } } - /// Buy whole shares at maker prices, walking the same FIFO ask tree as a limit buy. + /// Buy whole shares at maker prices. Budget and limit use the instrument's + /// integer tick unit (total cash in ticks and ticks per share respectively). pub fn match_budget_buy(&self, seq: i64, limit: i64, budget: i64) -> Vec { let mut cash = budget; let mut capacity = i64::MAX; @@ -78,22 +79,40 @@ impl OrderBook { if bid.price < ask.price { return Vec::new(); } - // Move each price boundary once as the candidate tick rises. + // Every crossed book with positive live quantities executes at least one + // share between its best ask and best bid. Outside, volume is zero. + let mut tick = ask.price; + let mut price = tick; + let mut best_score = None; let mut demand: i128 = self.bids.values().map(|o| i128::from(o.remaining)).sum(); let mut supply = 0i128; let mut bids = self.bids.values().rev().peekable(); let mut asks = self.asks.values().peekable(); - let price = (0..=100) - .min_by_key(|&tick| { - while bids.peek().is_some_and(|o| o.price < tick) { - demand -= i128::from(bids.next().unwrap().remaining); - } - while asks.peek().is_some_and(|o| o.price <= tick) { - supply += i128::from(asks.next().unwrap().remaining); - } - (Reverse(demand.min(supply)), (demand - supply).abs(), tick) - }) - .expect("nonempty tick range"); + loop { + while bids.peek().is_some_and(|o| o.price < tick) { + demand -= i128::from(bids.next().unwrap().remaining); + } + while asks.peek().is_some_and(|o| o.price <= tick) { + supply += i128::from(asks.next().unwrap().remaining); + } + let score = (Reverse(demand.min(supply)), (demand - supply).abs()); + if best_score.map_or(true, |best| score < best) { + price = tick; + best_score = Some(score); + } + + // Supply changes at an ask. Demand changes one tick AFTER a bid. + // Equal scores keep the first (lowest) tick in the interval. + let next_ask = asks.peek().map(|o| o.price); + let after_bid = bids.peek().and_then(|o| o.price.checked_add(1)); + let Some(next) = next_ask.into_iter().chain(after_bid).min() else { + break; + }; + if next > bid.price { + break; + } + tick = next; + } plan(self.bids.values(), self.asks.values(), Some(price)) } } @@ -241,4 +260,78 @@ mod tests { } } } + + #[test] + fn fine_tick_execution_preserves_maker_price_and_fifo() { + let mut book = OrderBook::default(); + let order = |seq, side, price, remaining| Order { + seq, + side, + price, + remaining, + }; + // One tick is $0.001 on this book. + for (seq, price) in [(1, 13), (2, 12), (3, 12)] { + book.update(order(seq, Side::Sell, price, 2)); + } + let incoming = order(4, Side::Buy, 13, 5); + let fills = book.match_incoming(&incoming); + let expected = vec![ + Fill { + bid: 4, + ask: 2, + price: 12, + quantity: 2, + }, + Fill { + bid: 4, + ask: 3, + price: 12, + quantity: 2, + }, + Fill { + bid: 4, + ask: 1, + price: 13, + quantity: 1, + }, + ]; + assert_eq!(fills, expected); + assert_eq!(book.match_budget_buy(4, 13, 61), expected); + assert_eq!(book.match_budget_buy(4, 13, 60), expected[..2]); + assert!(book.match_incoming(&order(5, Side::Buy, 11, 1)).is_empty()); + } + + #[test] + fn clearing_can_fall_one_tick_above_a_bid_without_an_order_at_that_price() { + for (low, high) in [ + (12, 17), + (812, 817), + (120_000, 990_000), + (i64::MAX - 5, i64::MAX), + ] { + let mut book = OrderBook::default(); + for (seq, side, price, remaining) in [ + (1, Side::Sell, low, 2), + (2, Side::Buy, low, 3), + (3, Side::Buy, high, 2), + ] { + book.update(Order { + seq, + side, + price, + remaining, + }); + } + assert_eq!( + book.opening(), + vec![Fill { + bid: 3, + ask: 1, + price: low + 1, + quantity: 2 + }] + ); + } + } } diff --git a/crates/matching/src/order.rs b/crates/matching/src/order.rs index 1c3dd09..06e2a25 100644 --- a/crates/matching/src/order.rs +++ b/crates/matching/src/order.rs @@ -8,6 +8,7 @@ pub enum Side { pub struct Order { pub seq: i64, pub side: Side, + /// Integer price ticks per share, in the same unit throughout this book. pub price: i64, pub remaining: i64, } @@ -16,6 +17,7 @@ pub struct Order { pub struct Fill { pub bid: i64, pub ask: i64, + /// Integer price ticks per share, in the same unit throughout this book. pub price: i64, pub quantity: i64, }