按交易品价格步长优化稀疏盘口的开盘集合竞价 #8
@@ -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 上可以没有挂单。遍历工作量取决于订单和有供需变化的价位数,即使最小步长细化,空价位也无需逐档扫描。若调用方价格单位为分、市场仅允许每 10 分一档,使用 opening_with_step(10),输入委托须已对齐。同样的供需变化在买价 50 分之后要到 60 分才生效。
|
||||
|
||||
## 吞吐基准
|
||||
|
||||
在获准的测量机器上执行 `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
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
+140
-13
@@ -2,6 +2,7 @@ mod order;
|
||||
pub use order::{Fill, Order, Side};
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::BTreeMap;
|
||||
use std::num::NonZeroU32;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Phase {
|
||||
@@ -41,7 +42,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<Fill> {
|
||||
let mut cash = budget;
|
||||
let mut capacity = i64::MAX;
|
||||
@@ -72,28 +74,53 @@ impl OrderBook {
|
||||
}
|
||||
|
||||
pub fn opening(&self) -> Vec<Fill> {
|
||||
self.opening_with_step(NonZeroU32::MIN)
|
||||
}
|
||||
|
||||
/// Orders have already been validated as multiples of this price step.
|
||||
pub fn opening_with_step(&self, step: NonZeroU32) -> 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();
|
||||
}
|
||||
// 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(i64::from(step.get())));
|
||||
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 +268,104 @@ 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
|
||||
}]
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn opening_selects_an_admissible_tick_on_the_configured_grid() {
|
||||
let mut book = OrderBook::default();
|
||||
for (seq, side, price, remaining) in [
|
||||
(1, Side::Sell, 50, 2),
|
||||
(2, Side::Buy, 50, 3),
|
||||
(3, Side::Buy, 70, 2),
|
||||
] {
|
||||
book.update(Order {
|
||||
seq,
|
||||
side,
|
||||
price,
|
||||
remaining,
|
||||
});
|
||||
}
|
||||
assert_eq!(book.opening()[0].price, 51);
|
||||
assert_eq!(
|
||||
book.opening_with_step(NonZeroU32::new(10).unwrap()),
|
||||
vec![Fill {
|
||||
bid: 3,
|
||||
ask: 1,
|
||||
price: 60,
|
||||
quantity: 2
|
||||
}]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user