Port the simulator to a Rust workspace and document each crate

This commit is contained in:
2026-12-03 02:53:46 +08:00
parent b7579603f9
commit 2f3c699e9c
25 changed files with 1320 additions and 371 deletions
+4
View File
@@ -0,0 +1,4 @@
[package]
name = "matching"
edition.workspace = true
version.workspace = true
+33
View File
@@ -0,0 +1,33 @@
# matching
输入是一个交易品的有效订单,输出是按执行顺序排列的成交明细。价格单位为分,数量单位为份。调用方提供已验证的订单快照并负责持久化。
## 文件依赖
箭头从使用方指向定义方。此 crate 只依赖标准库。
```mermaid
flowchart LR
engine["src/lib.rs"] -->|读取 Order 和 Side,生成 Fill| model["src/order.rs"]
```
## 开盘与盘中撮合
两张相同价格的卖单报 2 份和 5 份时,买单吃 4 份会先取较早订单的 2 份,再取下一单的 2 份。
```mermaid
sequenceDiagram
participant B as exchange 订单簿
participant M as matching 撮合函数
B->>M: 单一市场和结果的有效订单、交易阶段
M->>M: 买盘按价降序、卖盘按价升序,同价按序号排序
alt 订单簿没有交叉
M-->>B: 空成交列表
else 集合竞价
M->>M: 遍历整数价位,选最大成交量、最小量差、最低价
M-->>B: 统一价格下的逐笔成交
else 连续交易
M->>M: 依次匹配可交叉订单,按较早一方的挂单价成交
M-->>B: 买卖订单号、成交价和成交量
end
```
+67
View File
@@ -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
}
+21
View File
@@ -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,
}