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
+9
View File
@@ -0,0 +1,9 @@
[package]
name = "eventbook-cli"
edition.workspace = true
version.workspace = true
[dependencies]
exchange = { path = "../exchange" }
serde_json.workspace = true
anyhow.workspace = true
+37
View File
@@ -0,0 +1,37 @@
# eventbook-cli
可信操作员的 JSON 行命令入口。启动参数指定数据库文件,程序复用同一个 Exchange 连接。标准输入的每一行对应标准输出的一条 JSON 回执。输入结束时进程退出。
## 文件依赖
箭头从调用文件指向提供功能的文件或 crate。
```mermaid
flowchart LR
main["src/main.rs"] -->|把标准输入输出交给 serve| stream["src/stream.rs"]
main -.->|打开数据库| api["exchange crate"]
stream -.->|执行命令| api
```
## 一次命令会话
```mermaid
sequenceDiagram
actor U as 操作员
participant C as main.rs
participant S as stream.rs
participant E as Exchange
U->>C: 启动并指定数据库路径
C->>E: 打开数据库
C->>S: 传入连接和输入输出流
loop 输入一行
U->>S: JSON 命令
alt JSON 有效
S->>E: 执行命令
E-->>S: 业务回执或错误
else JSON 解析失败
S->>S: 构造错误回执
end
S-->>U: 输出一行 JSON 并刷新
end
```
+13
View File
@@ -0,0 +1,13 @@
mod stream;
use anyhow::{ensure, Context, Result};
use exchange::Exchange;
use std::{env, io};
fn main() -> Result<()> {
let mut args = env::args_os().skip(1);
let path = args.next().context("usage: eventbook-cli DATABASE")?;
ensure!(args.next().is_none(), "usage: eventbook-cli DATABASE");
let mut exchange = Exchange::open(path)?;
stream::serve(&mut exchange, io::stdin().lock(), io::stdout().lock())
}
+41
View File
@@ -0,0 +1,41 @@
use anyhow::Result;
use exchange::Exchange;
use serde_json::{json, Value};
use std::io::{BufRead, Write};
pub(crate) fn serve(
engine: &mut Exchange,
input: impl BufRead,
mut output: impl Write,
) -> Result<()> {
for line in input.lines() {
let line = line?;
let result = serde_json::from_str::<Value>(&line)
.map_err(anyhow::Error::from)
.and_then(|v| engine.execute(v));
let reply = result.unwrap_or_else(|e| json!({"error":e.to_string()}));
serde_json::to_writer(&mut output, &reply)?;
writeln!(output)?;
output.flush()?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn invalid_line_does_not_discard_next_request() {
let mut e = Exchange::open(":memory:").unwrap();
let mut out = Vec::new();
serve(&mut e, &b"broken\n{\"op\":\"state\"}\n"[..], &mut out).unwrap();
let replies: Vec<Value> = std::str::from_utf8(&out)
.unwrap()
.lines()
.map(|line| serde_json::from_str(line).unwrap())
.collect();
assert_eq!(replies.len(), 2);
assert!(replies[0]["error"].is_string());
assert_eq!(replies[1]["orders"], json!([]));
}
}
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "exchange"
edition.workspace = true
version.workspace = true
[dependencies]
matching = { path = "../matching" }
anyhow.workspace = true
serde.workspace = true
serde_json.workspace = true
rusqlite.workspace = true
[dev-dependencies]
tempfile = "3"
+53
View File
@@ -0,0 +1,53 @@
# exchange
维护一个 SQLite 模拟市场。每条写命令在同一事务内完成资金或份额预留、订单更新和幂等回执。成交明细由 matching 计算。只读 state 使用一个一致快照。
## 文件依赖
箭头从使用方指向提供类型或功能的文件。虚线连到 workspace 内的另一个 crate。图中省略标准库及第三方 crate。
```mermaid
flowchart LR
test["tests/market.rs"] -->|通过公开 API 驱动市场| api["src/lib.rs"]
api -->|初始化数据库| schema["src/schema.sql"]
api -->|校验请求键| valid["src/validation.rs"]
api -->|解析写命令| cmd["src/command.rs"]
api -->|事务内派发| market["src/market.rs"]
market -->|匹配命令类型| cmd
market -->|检查数量、标识和市场阶段| valid
market -->|下单、撤单与开盘| book["src/book.rs"]
market -->|发行与兑付| ledger["src/ledger.rs"]
book -->|检查订单约束| valid
book -->|预留、交割或释放| ledger
book -.->|计算逐笔成交| matcher["matching crate"]
market -.->|选择开盘阶段| matcher
```
## 一笔盘中买单
```mermaid
sequenceDiagram
participant C as 调用方
participant X as Exchange
participant D as SQLite
participant B as book.rs
participant M as matching
C->>X: 提交有请求键的限价买单
X->>D: 开始写事务,查找历史回执
alt 请求键已存在
X-->>C: 内容相同返回原回执,冲突则报错
else 新请求
X->>B: 派发下单命令
B->>D: 校验阶段、冻结买方资金、保存订单
B->>M: 当前交易品有效订单与连续交易阶段
M-->>B: 逐笔成交列表
B->>D: 更新买卖方资产、余量和成交记录
opt IOC 仍有余量
B->>D: 撤余单,释放剩余预留
end
X->>D: 保存回执并提交
X-->>C: 返回订单号、成交量与状态
end
```
校验、记账或存储失败时事务回滚。停盘会对尚存的挂单执行同样的释放逻辑。裁决后按持仓兑付,并核对总兑付与该市场抵押额一致。
+118
View File
@@ -0,0 +1,118 @@
use crate::{
ledger,
validation::{amount, identifier, phase},
};
use anyhow::{ensure, Result};
use matching::{cross, Order, Phase, Side};
use rusqlite::{params, Transaction};
use serde_json::{json, Value};
pub(crate) struct NewOrder {
pub market: String,
pub account: String,
pub outcome: String,
pub side: String,
pub price: i64,
pub qty: i64,
pub tif: String,
}
pub(crate) fn submit(tx: &Transaction, order: NewOrder) -> Result<Value> {
let NewOrder {
market,
account,
outcome,
side,
price,
qty,
tif,
} = order;
identifier(&account)?;
amount(qty)?;
let stage = phase(tx, &market, &["preopen", "continuous"])?;
ensure!(
matches!(outcome.as_str(), "YES" | "NO") && matches!(side.as_str(), "buy" | "sell"),
"invalid instrument or side"
);
ensure!((0..=100).contains(&price), "invalid price");
ensure!(
tif == "GTC" || (tif == "IOC" && stage == "continuous"),
"unsupported time in force"
);
if side == "buy" {
ledger::cash(tx, &account, -price * qty)?;
} else {
ledger::position(tx, &account, &market, &outcome, -qty)?;
}
tx.execute("INSERT INTO orders(account,market,outcome,side,price,quantity,remaining,status) VALUES(?,?,?,?,?,?,?,'live')",params![account,market,outcome,side,price,qty,qty])?;
let seq = tx.last_insert_rowid();
if stage == "continuous" {
match_book(tx, &market, &outcome, Phase::Continuous)?;
}
let (remaining, mut status): (i64, String) = tx.query_row(
"SELECT remaining,status FROM orders WHERE seq=?",
[seq],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
if tif == "IOC" && remaining > 0 {
release(tx, seq, &account)?;
status = "cancelled".into();
}
Ok(json!({"order":seq,"filled":qty-remaining,"status":status}))
}
pub(crate) fn match_book(
tx: &Transaction,
market: &str,
outcome: &str,
phase: Phase,
) -> Result<()> {
let mut stmt=tx.prepare("SELECT seq,side,price,remaining FROM orders WHERE market=? AND outcome=? AND status='live'")?;
let orders = stmt
.query_map(params![market, outcome], |r| {
Ok(Order {
seq: r.get(0)?,
side: if r.get::<_, String>(1)? == "buy" {
Side::Buy
} else {
Side::Sell
},
price: r.get(2)?,
remaining: r.get(3)?,
})
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
for f in cross(orders, phase) {
let (buyer, limit): (String, i64) = tx.query_row(
"SELECT account,price FROM orders WHERE seq=?",
[f.bid],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
let seller: String =
tx.query_row("SELECT account FROM orders WHERE seq=?", [f.ask], |r| {
r.get(0)
})?;
ledger::cash(tx, &seller, f.price * f.quantity)?;
ledger::cash(tx, &buyer, (limit - f.price) * f.quantity)?;
ledger::position(tx, &buyer, market, outcome, f.quantity)?;
tx.execute(
"INSERT INTO fills(bid,ask,price,quantity) VALUES(?,?,?,?)",
params![f.bid, f.ask, f.price, f.quantity],
)?;
for seq in [f.bid, f.ask] {
tx.execute("UPDATE orders SET remaining=remaining-?1,status=CASE WHEN remaining=?1 THEN 'filled' ELSE 'live' END WHERE seq=?2",params![f.quantity,seq])?;
}
}
Ok(())
}
pub(crate) fn release(tx: &Transaction, seq: i64, owner: &str) -> Result<i64> {
let (market,outcome,side,price,qty):(String,String,String,i64,i64)=tx.query_row("SELECT market,outcome,side,price,remaining FROM orders WHERE seq=? AND account=? AND status='live'",params![seq,owner],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?;
if side == "buy" {
ledger::cash(tx, owner, price * qty)?;
} else {
ledger::position(tx, owner, &market, &outcome, qty)?;
}
tx.execute("UPDATE orders SET status='cancelled' WHERE seq=?", [seq])?;
Ok(qty)
}
+46
View File
@@ -0,0 +1,46 @@
use serde::Deserialize;
#[derive(Deserialize)]
#[serde(tag = "op", rename_all = "lowercase", deny_unknown_fields)]
pub(crate) enum Command {
Fund {
account: String,
cents: i64,
},
List {
market: String,
rules: String,
},
Split {
market: String,
account: String,
qty: i64,
},
Order {
market: String,
account: String,
outcome: String,
side: String,
price: i64,
qty: i64,
#[serde(default = "gtc")]
tif: String,
},
Cancel {
account: String,
order: i64,
},
Open {
market: String,
},
Close {
market: String,
},
Resolve {
market: String,
winner: String,
},
}
fn gtc() -> String {
"GTC".into()
}
+28
View File
@@ -0,0 +1,28 @@
use anyhow::{ensure, Result};
use rusqlite::{params, Transaction};
pub(crate) fn cash(tx: &Transaction, account: &str, delta: i64) -> Result<()> {
ensure!(
tx.execute(
"UPDATE accounts SET cash=cash+? WHERE id=? AND cash+?>=0",
params![delta, account, delta]
)? == 1,
"unknown account or insufficient cash"
);
Ok(())
}
pub(crate) fn position(
tx: &Transaction,
account: &str,
market: &str,
outcome: &str,
delta: i64,
) -> Result<()> {
tx.execute(
"INSERT OR IGNORE INTO positions VALUES(?,?,?,0)",
params![account, market, outcome],
)?;
ensure!(tx.execute("UPDATE positions SET quantity=quantity+? WHERE account=? AND market=? AND outcome=? AND quantity+?>=0",params![delta,account,market,outcome,delta])?==1,"insufficient position");
Ok(())
}
+82
View File
@@ -0,0 +1,82 @@
mod validation;
use validation::identifier;
mod book;
mod command;
mod ledger;
mod market;
use anyhow::{ensure, Context, Result};
use rusqlite::{params, types::ValueRef, Connection, OptionalExtension, TransactionBehavior};
use serde_json::{json, Map, Value};
use std::{path::Path, time::Duration};
pub struct Exchange(Connection);
impl Exchange {
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
let db = Connection::open(path)?;
db.busy_timeout(Duration::from_secs(10))?;
db.execute_batch("PRAGMA foreign_keys=ON")?;
db.execute_batch(include_str!("schema.sql"))?;
Ok(Self(db))
}
pub fn execute(&mut self, payload: Value) -> Result<Value> {
if payload == json!({"op":"state"}) {
let tx = self.0.transaction()?;
let mut state = Map::new();
for table in ["accounts", "markets", "positions", "orders", "fills"] {
let mut stmt = tx.prepare(&format!("SELECT * FROM {table} ORDER BY rowid"))?;
let names: Vec<String> =
stmt.column_names().into_iter().map(str::to_owned).collect();
let mut rows = stmt.query([])?;
let mut result = Vec::new();
while let Some(row) = rows.next()? {
let mut obj = Map::new();
for (i, name) in names.iter().enumerate() {
let v = match row.get_ref(i)? {
ValueRef::Null => Value::Null,
ValueRef::Integer(n) => json!(n),
ValueRef::Text(s) => json!(std::str::from_utf8(s)?),
_ => anyhow::bail!("unexpected column type"),
};
obj.insert(name.clone(), v);
}
result.push(Value::Object(obj));
}
state.insert(table.into(), Value::Array(result));
}
tx.commit()?;
return Ok(Value::Object(state));
}
let id = payload["id"].as_str().context("request id required")?;
identifier(id)?;
let tx = self
.0
.transaction_with_behavior(TransactionBehavior::Immediate)?;
let prior: Option<(String, String)> = tx
.query_row(
"SELECT payload,response FROM requests WHERE id=?",
[id],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
if let Some((saved, reply)) = prior {
ensure!(
serde_json::from_str::<Value>(&saved)? == payload,
"request id reused with different content"
);
return Ok(serde_json::from_str(&reply)?);
}
let mut body = payload.clone();
body.as_object_mut()
.context("expected object")?
.remove("id");
let result = market::apply(&tx, serde_json::from_value(body)?)?;
tx.execute(
"INSERT INTO requests VALUES(?,?,?)",
params![id, payload.to_string(), result.to_string()],
)?;
tx.commit()?;
Ok(result)
}
}
+123
View File
@@ -0,0 +1,123 @@
use crate::{
book,
command::Command,
ledger,
validation::{amount, identifier, phase},
};
use anyhow::{ensure, Result};
use matching::Phase;
use rusqlite::{params, Transaction};
use serde_json::{json, Value};
pub(crate) fn apply(tx: &Transaction, command: Command) -> Result<Value> {
match command {
Command::Fund { account, cents } => {
identifier(&account)?;
amount(cents)?;
tx.execute("INSERT INTO accounts VALUES(?,?)", params![account, cents])?;
Ok(json!({"funded":cents}))
}
Command::List { market, rules } => {
identifier(&market)?;
ensure!(!rules.trim().is_empty(), "rules required");
tx.execute(
"INSERT INTO markets(id,rules,phase) VALUES(?,?,'preopen')",
params![market, rules],
)?;
Ok(json!({"phase":"preopen"}))
}
Command::Split {
market,
account,
qty,
} => {
identifier(&account)?;
amount(qty)?;
phase(tx, &market, &["preopen", "continuous"])?;
ledger::cash(tx, &account, -100 * qty)?;
tx.execute(
"UPDATE markets SET collateral=collateral+? WHERE id=?",
params![100 * qty, market],
)?;
for side in ["YES", "NO"] {
ledger::position(tx, &account, &market, side, qty)?;
}
Ok(json!({"pairs":qty}))
}
Command::Order {
market,
account,
outcome,
side,
price,
qty,
tif,
} => book::submit(
tx,
book::NewOrder {
market,
account,
outcome,
side,
price,
qty,
tif,
},
),
Command::Cancel { order, account } => {
identifier(&account)?;
let qty = book::release(tx, order, &account)?;
Ok(json!({"cancelled":qty}))
}
Command::Open { market } => {
phase(tx, &market, &["preopen"])?;
for outcome in ["YES", "NO"] {
book::match_book(tx, &market, outcome, Phase::Opening)?;
}
tx.execute("UPDATE markets SET phase='continuous' WHERE id=?", [market])?;
Ok(json!({"phase":"continuous"}))
}
Command::Close { market } => {
phase(tx, &market, &["preopen", "continuous"])?;
let mut stmt =
tx.prepare("SELECT seq,account FROM orders WHERE market=? AND status='live'")?;
let orders = stmt
.query_map([&market], |r| {
Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?))
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
for (seq, account) in orders {
book::release(tx, seq, &account)?;
}
tx.execute("UPDATE markets SET phase='closed' WHERE id=?", [market])?;
Ok(json!({"phase":"closed"}))
}
Command::Resolve { market, winner } => {
phase(tx, &market, &["closed"])?;
ensure!(
matches!(winner.as_str(), "YES" | "NO" | "VOID"),
"invalid winner"
);
let mut stmt =
tx.prepare("SELECT account,outcome,quantity FROM positions WHERE market=?")?;
let mut rows = stmt.query([&market])?;
let mut total = 0i64;
while let Some(r) = rows.next()? {
let outcome: String = r.get(1)?;
let cents = if winner == "VOID" {
50
} else if outcome == winner {
100
} else {
0
};
let payout = cents * r.get::<_, i64>(2)?;
ledger::cash(tx, &r.get::<_, String>(0)?, payout)?;
total += payout;
}
ensure!(tx.execute("UPDATE markets SET phase='resolved',collateral=0,winner=? WHERE id=? AND collateral=?",params![winner,market,total])?==1,"collateral mismatch");
tx.execute("UPDATE positions SET quantity=0 WHERE market=?", [market])?;
Ok(json!({"phase":"resolved","paid":total}))
}
}
}
+24
View File
@@ -0,0 +1,24 @@
CREATE TABLE IF NOT EXISTS accounts (
id TEXT PRIMARY KEY, cash INTEGER NOT NULL CHECK(cash >= 0)
);
CREATE TABLE IF NOT EXISTS markets (
id TEXT PRIMARY KEY, rules TEXT NOT NULL, phase TEXT NOT NULL,
collateral INTEGER NOT NULL DEFAULT 0 CHECK(collateral >= 0), winner TEXT
);
CREATE TABLE IF NOT EXISTS positions (
account TEXT REFERENCES accounts, market TEXT REFERENCES markets, outcome TEXT,
quantity INTEGER NOT NULL CHECK(quantity >= 0), PRIMARY KEY(account,market,outcome)
);
CREATE TABLE IF NOT EXISTS orders (
seq INTEGER PRIMARY KEY, account TEXT REFERENCES accounts, market TEXT REFERENCES markets,
outcome TEXT NOT NULL, side TEXT NOT NULL, price INTEGER NOT NULL, quantity INTEGER NOT NULL,
remaining INTEGER NOT NULL CHECK(remaining >= 0), status TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS active_book ON orders(market,outcome,seq) WHERE status='live';
CREATE TABLE IF NOT EXISTS fills (
seq INTEGER PRIMARY KEY, bid INTEGER REFERENCES orders, ask INTEGER REFERENCES orders,
price INTEGER NOT NULL, quantity INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS requests (
id TEXT PRIMARY KEY, payload TEXT NOT NULL, response TEXT NOT NULL
);
+22
View File
@@ -0,0 +1,22 @@
use anyhow::{ensure, Result};
use rusqlite::Transaction;
pub(crate) fn identifier(id: &str) -> Result<()> {
ensure!(
!id.trim().is_empty() && id.trim().chars().count() <= 256,
"invalid identifier"
);
Ok(())
}
pub(crate) fn amount(n: i64) -> Result<()> {
ensure!((1..=1_000_000_000).contains(&n), "invalid amount");
Ok(())
}
pub(crate) fn phase(tx: &Transaction, market: &str, allowed: &[&str]) -> Result<String> {
identifier(market)?;
let p: String = tx.query_row("SELECT phase FROM markets WHERE id=?", [market], |r| {
r.get(0)
})?;
ensure!(allowed.contains(&p.as_str()), "wrong market phase");
Ok(p)
}
+134
View File
@@ -0,0 +1,134 @@
use exchange::Exchange;
use serde_json::{json, Value};
use std::sync::{Arc, Barrier};
use tempfile::tempdir;
fn setup(e: &mut Exchange) {
for cmd in [
json!({"op":"fund","id":"a","account":"alice","cents":2000}),
json!({"op":"fund","id":"b","account":"bob","cents":2000}),
json!({"op":"list","id":"m","market":"e","rules":"official result"}),
json!({"op":"split","id":"s","market":"e","account":"alice","qty":10}),
] {
e.execute(cmd).unwrap();
}
}
fn order(id: &str, account: &str, side: &str, price: i64, qty: i64) -> Value {
json!({"id":id,"op":"order","account":account,"side":side,"price":price,"qty":qty,"outcome":"YES","market":"e"})
}
fn state(e: &mut Exchange) -> Value {
e.execute(json!({"op":"state"})).unwrap()
}
#[test]
fn auction_fifo_ioc_close_and_redeem() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(order("ask1", "alice", "sell", 40, 2)).unwrap();
e.execute(order("ask2", "alice", "sell", 40, 5)).unwrap();
e.execute(order("bid", "bob", "buy", 60, 4)).unwrap();
assert_eq!(state(&mut e)["fills"], json!([]));
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
let s = state(&mut e);
assert_eq!(
s["fills"],
json!([{"seq":1,"bid":3,"ask":1,"price":40,"quantity":2},{"seq":2,"bid":3,"ask":2,"price":40,"quantity":2}])
);
let mut ioc = order("sweep", "bob", "buy", 45, 6);
ioc["tif"] = json!("IOC");
assert_eq!(
e.execute(ioc).unwrap(),
json!({"order":4,"filled":3,"status":"cancelled"})
);
e.execute(order("rest", "bob", "buy", 10, 8)).unwrap();
e.execute(json!({"id":"close","op":"close","market":"e"}))
.unwrap();
e.execute(json!({"id":"resolve","op":"resolve","market":"e","winner":"YES"}))
.unwrap();
let s = state(&mut e);
assert_eq!(
s["accounts"],
json!([{"id":"alice","cash":1580},{"id":"bob","cash":2420}])
);
assert_eq!(s["markets"][0]["collateral"], 0);
}
#[test]
fn retries_reopen_and_no_partial_writes() {
let dir = tempdir().unwrap();
let path = dir.path().join("market.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let bid = order("repeat", "bob", "buy", 60, 10);
let reply = e.execute(bid.clone()).unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(e.execute(bid).unwrap(), reply);
let before = state(&mut e);
assert!(e.execute(order("repeat", "bob", "buy", 60, 9)).is_err());
assert!(e.execute(order("big", "bob", "buy", 100, 30)).is_err());
assert!(e
.execute(json!({"id":"cancel","op":"cancel","account":"alice","order":1}))
.is_err());
assert_eq!(state(&mut e), before);
e.execute(json!({"id":"cancel","op":"cancel","account":"bob","order":1}))
.unwrap();
e.execute(json!({"id":"close","op":"close","market":"e"}))
.unwrap();
e.execute(json!({"id":"void","op":"resolve","market":"e","winner":"VOID"}))
.unwrap();
assert_eq!(state(&mut e)["accounts"][0]["cash"], 2000);
}
#[test]
fn concurrent_connections_cannot_double_spend() {
let dir = tempdir().unwrap();
let path = dir.path().join("market.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let gate = Arc::new(Barrier::new(2));
let workers: Vec<_> = ["first", "second"]
.into_iter()
.map(|id| {
let mut db = Exchange::open(&path).unwrap();
let gate = Arc::clone(&gate);
std::thread::spawn(move || {
gate.wait();
db.execute(order(id, "bob", "buy", 90, 20)).is_ok()
})
})
.collect();
assert_eq!(
workers
.into_iter()
.map(|w| w.join().unwrap())
.filter(|v| *v)
.count(),
1
);
assert_eq!(state(&mut e)["accounts"][1]["cash"], 200);
}
#[test]
fn market_outcome_and_limit_are_isolated() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(json!({"id":"m2","op":"list","market":"other","rules":"other"}))
.unwrap();
for m in ["e", "other"] {
e.execute(json!({"id":format!("open-{m}"),"op":"open","market":m}))
.unwrap();
}
e.execute(order("ask", "alice", "sell", 65, 7)).unwrap();
for (market, outcome, price) in [("e", "YES", 60), ("e", "NO", 70), ("other", "YES", 70)] {
let mut bid = order(&format!("{market}-{outcome}"), "bob", "buy", price, 3);
bid["market"] = json!(market);
bid["outcome"] = json!(outcome);
bid["tif"] = json!("IOC");
assert_eq!(e.execute(bid).unwrap()["filled"], 0);
}
assert_eq!(state(&mut e)["fills"], json!([]));
}
+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,
}