diff --git a/.gitignore b/.gitignore index 23f2f96..8f26ef2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ -__pycache__/ +/target/ *.db *.db-* diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..a2d6b60 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,448 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519" +dependencies = [ + "cfg-if", + "getrandom", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "cc" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "eventbook-cli" +version = "0.1.0" +dependencies = [ + "anyhow", + "exchange", + "serde_json", +] + +[[package]] +name = "exchange" +version = "0.1.0" +dependencies = [ + "anyhow", + "matching", + "rusqlite", + "serde", + "serde_json", + "tempfile", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashlink" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "matching" +version = "0.1.0" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rusqlite" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zerocopy" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..a619df0 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,13 @@ +[workspace] +members = ["crates/matching", "crates/exchange", "crates/eventbook-cli"] +resolver = "2" + +[workspace.package] +edition = "2021" +version = "0.1.0" + +[workspace.dependencies] +anyhow = "1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +rusqlite = { version = "0.32", features = ["bundled"] } diff --git a/README.md b/README.md index 05503f8..db72e3c 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,25 @@ # Eventbook Exchange -用模拟资金验证预测市场的交易与兑付规则。这个版本是可信操作员使用的单机命令程序。Python 3.10+,只依赖标准库。订单簿由 SQLite 中该合约的有效订单重建,每条命令在一次写事务中完成冻结、成交、余量、余额和回执更新。客户端看到的成功回执均已提交。 +用模拟资金验证预测市场的交易与兑付规则。这个版本是可信操作员使用的单机命令程序。Rust Cargo workspace,SQLite 由 rusqlite 的 bundled 特性提供。订单簿由 SQLite 中该合约的有效订单重建,每条命令在一次写事务中完成冻结、成交、余量、余额和回执更新。客户端看到的成功回执均已提交。 完整设计见[交易系统时序图](docs/sequences.md)。单机版覆盖本地下单、开盘与连续交易、全额抵押发行和账本兑付。 +## Crate 导航 + +| Crate | 职责 | +|---|---| +| [matching](crates/matching/README.md) | 单簿集合竞价与连续撮合 | +| [exchange](crates/exchange/README.md) | 事务、幂等、账户、市场和兑付 | +| [eventbook-cli](crates/eventbook-cli/README.md) | JSON 行式命令入口 | + +每个 crate 的 README 包含文件依赖图和运行时序图。 + ## 跑一笔交易 在仓库根目录执行以下示例,每次演示使用一份新的数据库。程序从标准输入逐行接收 JSON,逐行返回结果。模拟货币的单位为分,每对 YES/NO 足额抵押 100 分。 ```sh -python3 -B exchange.py demo.db <<'ORDERS' +cargo run --locked -p eventbook-cli -- demo.db <<'ORDERS' {"id":"1","op":"fund","account":"seller","cents":1000} {"id":"2","op":"fund","account":"buyer","cents":1000} {"id":"3","op":"list","market":"game-1","rules":"按比赛官方终局结果判定,主队胜为 YES,其余为 NO,作废每边兑付 50 分"} @@ -36,4 +46,4 @@ ORDERS ## 检查 -运行 `python3 -B -m unittest -v`。用例在独立临时数据库中检查统一开盘价、同价排队、部分成交、撤单、价格保护、合约隔离、重启重试、拒单回滚和到期兑付。在各次成功命令后核对现金、冻结额、抵押额和两边份额守恒。 +Rust 工作区的测试入口为 `cargo test --workspace --locked`。集成用例覆盖开盘、盘中成交、隔离、重启、并发冻结和兑付。 diff --git a/crates/eventbook-cli/Cargo.toml b/crates/eventbook-cli/Cargo.toml new file mode 100644 index 0000000..0ef40b3 --- /dev/null +++ b/crates/eventbook-cli/Cargo.toml @@ -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 diff --git a/crates/eventbook-cli/README.md b/crates/eventbook-cli/README.md new file mode 100644 index 0000000..e454001 --- /dev/null +++ b/crates/eventbook-cli/README.md @@ -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 +``` diff --git a/crates/eventbook-cli/src/main.rs b/crates/eventbook-cli/src/main.rs new file mode 100644 index 0000000..1c3b675 --- /dev/null +++ b/crates/eventbook-cli/src/main.rs @@ -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()) +} diff --git a/crates/eventbook-cli/src/stream.rs b/crates/eventbook-cli/src/stream.rs new file mode 100644 index 0000000..abdb0ab --- /dev/null +++ b/crates/eventbook-cli/src/stream.rs @@ -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::(&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 = 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!([])); + } +} diff --git a/crates/exchange/Cargo.toml b/crates/exchange/Cargo.toml new file mode 100644 index 0000000..1705965 --- /dev/null +++ b/crates/exchange/Cargo.toml @@ -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" diff --git a/crates/exchange/README.md b/crates/exchange/README.md new file mode 100644 index 0000000..81a798a --- /dev/null +++ b/crates/exchange/README.md @@ -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 +``` + +校验、记账或存储失败时事务回滚。停盘会对尚存的挂单执行同样的释放逻辑。裁决后按持仓兑付,并核对总兑付与该市场抵押额一致。 diff --git a/crates/exchange/src/book.rs b/crates/exchange/src/book.rs new file mode 100644 index 0000000..952e00f --- /dev/null +++ b/crates/exchange/src/book.rs @@ -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 { + 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::>>()?; + 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 { + 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) +} diff --git a/crates/exchange/src/command.rs b/crates/exchange/src/command.rs new file mode 100644 index 0000000..9df5b89 --- /dev/null +++ b/crates/exchange/src/command.rs @@ -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() +} diff --git a/crates/exchange/src/ledger.rs b/crates/exchange/src/ledger.rs new file mode 100644 index 0000000..ba90906 --- /dev/null +++ b/crates/exchange/src/ledger.rs @@ -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(()) +} diff --git a/crates/exchange/src/lib.rs b/crates/exchange/src/lib.rs new file mode 100644 index 0000000..0a176c6 --- /dev/null +++ b/crates/exchange/src/lib.rs @@ -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) -> Result { + 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 { + 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 = + 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::(&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) + } +} diff --git a/crates/exchange/src/market.rs b/crates/exchange/src/market.rs new file mode 100644 index 0000000..6fe330d --- /dev/null +++ b/crates/exchange/src/market.rs @@ -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 { + 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::>>()?; + 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})) + } + } +} diff --git a/schema.sql b/crates/exchange/src/schema.sql similarity index 100% rename from schema.sql rename to crates/exchange/src/schema.sql diff --git a/crates/exchange/src/validation.rs b/crates/exchange/src/validation.rs new file mode 100644 index 0000000..52a1daa --- /dev/null +++ b/crates/exchange/src/validation.rs @@ -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 { + 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) +} diff --git a/crates/exchange/tests/market.rs b/crates/exchange/tests/market.rs new file mode 100644 index 0000000..876cbc2 --- /dev/null +++ b/crates/exchange/tests/market.rs @@ -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!([])); +} diff --git a/crates/matching/Cargo.toml b/crates/matching/Cargo.toml new file mode 100644 index 0000000..fd8adfc --- /dev/null +++ b/crates/matching/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "matching" +edition.workspace = true +version.workspace = true diff --git a/crates/matching/README.md b/crates/matching/README.md new file mode 100644 index 0000000..fe9bd13 --- /dev/null +++ b/crates/matching/README.md @@ -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 +``` diff --git a/crates/matching/src/lib.rs b/crates/matching/src/lib.rs new file mode 100644 index 0000000..7deab62 --- /dev/null +++ b/crates/matching/src/lib.rs @@ -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, phase: Phase) -> Vec { + 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 +} diff --git a/crates/matching/src/order.rs b/crates/matching/src/order.rs new file mode 100644 index 0000000..1c3dd09 --- /dev/null +++ b/crates/matching/src/order.rs @@ -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, +} diff --git a/exchange.py b/exchange.py deleted file mode 100644 index de8b182..0000000 --- a/exchange.py +++ /dev/null @@ -1,205 +0,0 @@ -"""Trusted local simulator. One input command commits as a single database transaction.""" -import argparse -import json -from pathlib import Path -import sqlite3 -import sys - -from matching import Order, match - - -class Rejected(ValueError): - pass - - -def require(condition, message): - if not condition: - raise Rejected(message) - - -def amount(value): - require(type(value) is int and 0 < value <= 10**9, "expected positive integer <= 1 billion") - return value - - -def identifier(value): - require(type(value) is str and 0 < len(value.strip()) <= 256, "invalid identifier") - return value - - -class Exchange: - def __init__(self, path): - self.db = sqlite3.connect(path, isolation_level=None, timeout=10) - self.db.row_factory = sqlite3.Row - self.db.execute("PRAGMA foreign_keys=ON") - self.db.executescript(Path(__file__).with_name("schema.sql").read_text()) - - def execute(self, command): - require(isinstance(command, dict), "expected an object") - if command == {"op": "state"}: - self.db.execute("BEGIN") - try: - return {t: [dict(r) for r in self.db.execute(f"SELECT * FROM {t} ORDER BY rowid")] - for t in ("markets", "accounts", "positions", "orders", "fills")} - finally: - self.db.rollback() - body = dict(command) - key = identifier(body.pop("id", None)) - op = body.pop("op", None) - actions = {"fund": self.fund, "list": self.list_market, "split": self.split, - "order": self.order, "cancel": self.cancel, "open": self.open_market, - "close": self.close_market, "resolve": self.resolve} - require(isinstance(op, str) and op in actions, "unknown operation") - payload = json.dumps(command, sort_keys=True, allow_nan=False) - self.db.execute("BEGIN IMMEDIATE") - try: - prior = self.db.execute("SELECT * FROM requests WHERE id=?", (key,)).fetchone() - if prior: - require(prior["payload"] == payload, "request id reused with different content") - result = json.loads(prior["response"]) - else: - result = actions[op](**body) - self.db.execute("INSERT INTO requests VALUES(?,?,?)", (key, payload, json.dumps(result))) - self.db.commit() - return result - except BaseException: - self.db.rollback() - raise - - def fund(self, account, cents): - identifier(account) - amount(cents) - exists = self.db.execute("SELECT 1 FROM accounts WHERE id=?", (account,)).fetchone() - require(not exists, "account already funded") - self.db.execute("INSERT INTO accounts VALUES(?,?)", (account, cents)) - return {"funded": cents} - - def list_market(self, market, rules): - identifier(market) - require(type(rules) is str and rules.strip(), "rules required") - self.db.execute("INSERT INTO markets(id,rules,phase) VALUES(?,?,'preopen')", (market, rules)) - return {"phase": "preopen"} - - def phase(self, market, *allowed): - row = self.db.execute("SELECT phase FROM markets WHERE id=?", (identifier(market),)).fetchone() - require(row and row[0] in allowed, "unknown market or wrong phase") - return row[0] - - def cash(self, account, delta): - updated = self.db.execute("UPDATE accounts SET cash=cash+? WHERE id=? AND cash+?>=0", - (delta, identifier(account), delta)) - require(updated.rowcount == 1, "unknown account or insufficient cash") - - def position(self, account, market, outcome, delta): - self.db.execute("INSERT OR IGNORE INTO positions VALUES(?,?,?,0)", (account, market, outcome)) - updated = self.db.execute("""UPDATE positions SET quantity=quantity+? - WHERE account=? AND market=? AND outcome=? AND quantity+?>=0""", - (delta, account, market, outcome, delta)) - require(updated.rowcount == 1, "insufficient position") - - def split(self, account, market, qty): - self.phase(market, "preopen", "continuous") - value = 100 * amount(qty) - self.cash(account, -value) - self.db.execute("UPDATE markets SET collateral=collateral+? WHERE id=?", (value, market)) - for outcome in ("YES", "NO"): - self.position(account, market, outcome, qty) - return {"pairs": qty} - - def order(self, account, market, outcome, side, price, qty, tif="GTC"): - phase = self.phase(market, "preopen", "continuous") - require(outcome in ("YES", "NO") and side in ("buy", "sell"), "invalid instrument or side") - require(type(price) is int and 0 <= price <= 100, "price outside 0..100 cents") - amount(qty) - require(tif == "GTC" or (tif == "IOC" and phase == "continuous"), "unsupported time in force") - if side == "buy": - self.cash(account, -price * qty) - else: - self.position(identifier(account), market, outcome, -qty) - seq = self.db.execute("""INSERT INTO orders(account,market,outcome,side,price,quantity,remaining,status) - VALUES(?,?,?,?,?,?,?,'live')""", (account, market, outcome, side, price, qty, qty)).lastrowid - if phase == "continuous": - self.cross(market, outcome) - row = self.db.execute("SELECT * FROM orders WHERE seq=?", (seq,)).fetchone() - if tif == "IOC" and row["remaining"]: - self.release(row) - return {"order": seq, "filled": qty - row["remaining"], - "status": "cancelled" if tif == "IOC" and row["remaining"] else row["status"]} - - def cross(self, market, outcome, opening=False): - rows = self.db.execute("""SELECT seq,account,side,price,remaining FROM orders - WHERE market=? AND outcome=? AND status='live'""", (market, outcome)) - orders = [Order(**dict(row)) for row in rows] - for f in match(orders, opening=opening): - self.cash(f.ask.account, f.price * f.quantity) - self.cash(f.bid.account, (f.bid.price - f.price) * f.quantity) - self.position(f.bid.account, market, outcome, f.quantity) - self.db.execute("INSERT INTO fills(bid,ask,price,quantity) VALUES(?,?,?,?)", - (f.bid.seq, f.ask.seq, f.price, f.quantity)) - for seq in (f.bid.seq, f.ask.seq): - self.db.execute("""UPDATE orders SET remaining=remaining-?, - status=CASE WHEN remaining=? THEN 'filled' ELSE 'live' END WHERE seq=?""", - (f.quantity, f.quantity, seq)) - - def release(self, row): - qty = row["remaining"] - if row["side"] == "buy": - self.cash(row["account"], qty * row["price"]) - else: - self.position(row["account"], row["market"], row["outcome"], qty) - self.db.execute("UPDATE orders SET status='cancelled' WHERE seq=?", (row["seq"],)) - - def cancel(self, account, order): - row = self.db.execute("SELECT * FROM orders WHERE seq=? AND account=? AND status='live'", - (amount(order), identifier(account))).fetchone() - require(row, "no live order for account") - self.release(row) - return {"cancelled": row["remaining"]} - - def open_market(self, market): - self.phase(market, "preopen") - for outcome in ("YES", "NO"): - self.cross(market, outcome, opening=True) - self.db.execute("UPDATE markets SET phase='continuous' WHERE id=?", (market,)) - return {"phase": "continuous"} - - def close_market(self, market): - self.phase(market, "continuous", "preopen") - for row in self.db.execute("SELECT * FROM orders WHERE market=? AND status='live'", (market,)).fetchall(): - self.release(row) - self.db.execute("UPDATE markets SET phase='closed' WHERE id=?", (market,)) - return {"phase": "closed"} - - def resolve(self, market, winner): - self.phase(market, "closed") - require(winner in ("YES", "NO", "VOID"), "winner must be YES, NO or VOID") - total = 0 - for row in self.db.execute("SELECT * FROM positions WHERE market=?", (market,)): - per_share = 50 if winner == "VOID" else 100 * (winner == row["outcome"]) - payout = row["quantity"] * per_share - self.cash(row["account"], payout) - total += payout - changed = self.db.execute("""UPDATE markets SET collateral=0,phase='resolved',winner=? - WHERE id=? AND collateral=?""", (winner, market, total)) - require(changed.rowcount == 1, "collateral does not cover payouts exactly") - self.db.execute("UPDATE positions SET quantity=0 WHERE market=?", (market,)) - return {"phase": "resolved", "paid": total} - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument("database") - engine = Exchange(parser.parse_args().database) - try: - for line in sys.stdin: - try: - result = engine.execute(json.loads(line)) - except (ValueError, TypeError, sqlite3.IntegrityError) as exc: - result = {"error": str(exc)} - print(json.dumps(result, ensure_ascii=False), flush=True) - finally: - engine.db.close() - - -if __name__ == "__main__": - main() diff --git a/matching.py b/matching.py deleted file mode 100644 index b24d024..0000000 --- a/matching.py +++ /dev/null @@ -1,52 +0,0 @@ -"""Pure price/time matching for one instrument; prices are integer cents.""" -from dataclasses import dataclass - - -@dataclass -class Order: - seq: int - account: str - side: str - price: int - remaining: int - - -@dataclass(frozen=True) -class Fill: - bid: Order - ask: Order - price: int - quantity: int - - -def match(orders, *, opening=False): - bids = sorted((o for o in orders if o.side == "buy"), key=lambda o: (-o.price, o.seq)) - asks = sorted((o for o in orders if o.side == "sell"), key=lambda o: (o.price, o.seq)) - if not bids or not asks or bids[0].price < asks[0].price: - return [] - clearing = None - if opening: - # Evaluate every permitted tick, including ticks between submitted prices. - def priority(price): - demand = sum(o.remaining for o in bids if o.price >= price) - supply = sum(o.remaining for o in asks if o.price <= price) - return (-min(demand, supply), abs(demand - supply), price) - clearing = min(range(101), key=priority) - fills = [] - b = a = 0 - while b < len(bids) and a < len(asks): - bid, ask = bids[b], asks[a] - if bid.price < ask.price: - break - if clearing is not None and not ask.price <= clearing <= bid.price: - break - price = clearing - if price is None: - price = bid.price if bid.seq < ask.seq else ask.price - qty = min(bid.remaining, ask.remaining) - fills.append(Fill(bid, ask, price, qty)) - bid.remaining -= qty - ask.remaining -= qty - b += bid.remaining == 0 - a += ask.remaining == 0 - return fills diff --git a/test_exchange.py b/test_exchange.py deleted file mode 100644 index 154516e..0000000 --- a/test_exchange.py +++ /dev/null @@ -1,110 +0,0 @@ -from concurrent.futures import ThreadPoolExecutor -from threading import Barrier -import tempfile -import unittest -from pathlib import Path - -from exchange import Exchange, Rejected - - -class MarketTest(unittest.TestCase): - def setUp(self): - folder = tempfile.TemporaryDirectory() - self.addCleanup(folder.cleanup) - self.path = Path(folder.name) / "market.db" - self.engine = Exchange(self.path) - self.addCleanup(lambda: self.engine.db.close()) - self.seq = 0 - for account in ("alice", "bob", "carol"): - self.cmd("fund", account=account, cents=2000) - self.cmd("list", market="E1", rules="YES on official result, NO otherwise; void pays 50 each") - self.cmd("split", account="alice", market="E1", qty=10) - - def cmd(self, op, **body): - self.seq += 1 - result = self.engine.execute(dict(id=str(self.seq), op=op, **body)) - self.check_totals() - return result - - def check_totals(self): - state = self.engine.execute({"op": "state"}) - live = [r for r in state["orders"] if r["status"] == "live"] - reserved = sum(r["price"] * r["remaining"] for r in live if r["side"] == "buy") - total = sum(a["cash"] for a in state["accounts"]) + reserved - self.assertEqual(total + sum(m["collateral"] for m in state["markets"]), 2000 * len(state["accounts"])) - for market in state["markets"]: - for outcome in ("YES", "NO"): - free = sum(p["quantity"] for p in state["positions"] - if (p["market"], p["outcome"]) == (market["id"], outcome)) - locked = sum(r["remaining"] for r in live if r["side"] == "sell" - and (r["market"], r["outcome"]) == (market["id"], outcome)) - self.assertEqual((free + locked) * 100, market["collateral"]) - - def order(self, account, side, price, qty, **extra): - return self.cmd("order", account=account, market="E1", outcome="YES", side=side, price=price, qty=qty, **extra) - - def test_open_fifo_ioc_and_settlement(self): - a = self.order("alice", "sell", 40, 2)["order"] - b = self.order("alice", "sell", 40, 5)["order"] - self.order("bob", "buy", 60, 4) - self.assertEqual(self.engine.execute({"op": "state"})["fills"], []) - self.cmd("open", market="E1") - fills = self.engine.execute({"op": "state"})["fills"] - self.assertEqual([(f["ask"], f["quantity"], f["price"]) for f in fills], [(a, 2, 40), (b, 2, 40)]) - self.assertEqual(self.order("carol", "buy", 45, 6, tif="IOC")["filled"], 3) - self.order("bob", "buy", 10, 8) - self.cmd("close", market="E1") - self.assertEqual(self.cmd("resolve", market="E1", winner="YES")["paid"], 1000) - cash = {a["id"]: a["cash"] for a in self.engine.execute({"op": "state"})["accounts"]} - self.assertEqual(cash, {"alice": 1580, "bob": 2240, "carol": 2180}) - - def test_restart_retry_and_rejection(self): - op = dict(op="order", id="retry", market="E1", outcome="NO", side="sell", price=45, qty=3, account="alice") - first = self.engine.execute(op) - self.engine.db.close() - self.engine = Exchange(self.path) - self.assertEqual(self.engine.execute(op), first) - with self.assertRaises(Rejected): - self.engine.execute(dict(op, qty=4)) - before = self.engine.execute({"op": "state"}) - with self.assertRaises(Rejected): - self.order("bob", "buy", 100, 21) - with self.assertRaises(Rejected): - self.cmd("cancel", account="bob", order=first["order"]) - self.assertEqual(before, self.engine.execute({"op": "state"})) - self.cmd("cancel", account="alice", order=first["order"]) - self.cmd("close", market="E1") - self.cmd("resolve", market="E1", winner="VOID") - - def test_two_connections_cannot_spend_the_same_cash(self): - ready = Barrier(2) - def submit(key): - engine = Exchange(self.path) - try: - ready.wait(timeout=5) - engine.execute(dict(id=key, op="order", account="bob", market="E1", - outcome="YES", side="buy", price=90, qty=20)) - return True - except Rejected: - return False - finally: - engine.db.close() - with ThreadPoolExecutor(max_workers=2) as pool: - self.assertEqual(sorted(pool.map(submit, ("concurrent-a", "concurrent-b"))), [False, True]) - self.check_totals() - - def test_isolation_and_price_protection(self): - self.cmd("list", market="E2", rules="another event") - self.cmd("open", market="E2") - self.cmd("open", market="E1") - self.order("alice", "sell", 65, 7) - reply = self.order("bob", "buy", 60, 10, tif="IOC") - self.assertEqual(reply["filled"], 0) - for market, outcome in (("E1", "NO"), ("E2", "YES")): - reply = self.cmd("order", account="carol", market=market, outcome=outcome, - side="buy", price=70, qty=2, tif="IOC") - self.assertEqual(reply["filled"], 0) - - -if __name__ == "__main__": - unittest.main()