Keep per-instrument order books in memory and recover committed orders
This commit is contained in:
@@ -20,7 +20,10 @@ flowchart LR
|
||||
book -->|检查订单约束| valid
|
||||
book -->|预留、交割或释放| ledger
|
||||
book -.->|计算逐笔成交| matcher["matching crate"]
|
||||
market -.->|选择开盘阶段| matcher
|
||||
api -->|启动恢复和按版本同步| cache["src/resident.rs"]
|
||||
market -->|获取集合竞价盘口| cache
|
||||
book -->|按市场与结果定位对手盘| cache
|
||||
cache -.->|维护每个交易品的 OrderBook| matcher
|
||||
```
|
||||
|
||||
## 一笔盘中买单
|
||||
@@ -37,15 +40,17 @@ sequenceDiagram
|
||||
alt 请求键已存在
|
||||
X-->>C: 内容相同返回原回执,冲突则报错
|
||||
else 新请求
|
||||
X->>D: 在写锁内读取其他连接已提交的订单增量并同步盘口
|
||||
X->>B: 派发下单命令
|
||||
B->>D: 校验阶段、冻结买方资金、保存订单
|
||||
B->>M: 当前交易品有效订单与连续交易阶段
|
||||
B->>M: 向该交易品常驻簿传入新单
|
||||
M-->>B: 逐笔成交列表
|
||||
B->>D: 更新买卖方资产、余量和成交记录
|
||||
opt IOC 仍有余量
|
||||
B->>D: 撤余单,释放剩余预留
|
||||
end
|
||||
X->>D: 保存回执并提交
|
||||
X->>D: 保存回执,取本事务触及订单的最终状态并提交
|
||||
X->>M: 仅在提交成功后更新相应盘口
|
||||
X-->>C: 返回订单号、成交量与状态
|
||||
end
|
||||
```
|
||||
|
||||
+15
-21
@@ -1,9 +1,10 @@
|
||||
use crate::resident::Books;
|
||||
use crate::{
|
||||
ledger,
|
||||
validation::{amount, identifier, phase},
|
||||
};
|
||||
use anyhow::{ensure, Result};
|
||||
use matching::{cross, Order, Phase, Side};
|
||||
use matching::{Fill, Order, Side};
|
||||
use rusqlite::{params, Transaction};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
@@ -17,7 +18,7 @@ pub(crate) struct NewOrder {
|
||||
pub tif: String,
|
||||
}
|
||||
|
||||
pub(crate) fn submit(tx: &Transaction, order: NewOrder) -> Result<Value> {
|
||||
pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result<Value> {
|
||||
let NewOrder {
|
||||
market,
|
||||
account,
|
||||
@@ -47,7 +48,15 @@ pub(crate) fn submit(tx: &Transaction, order: NewOrder) -> Result<Value> {
|
||||
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)?;
|
||||
if let Some(book) = books.get(&market, &outcome) {
|
||||
let incoming = Order {
|
||||
seq,
|
||||
side: if side == "buy" { Side::Buy } else { Side::Sell },
|
||||
price,
|
||||
remaining: qty,
|
||||
};
|
||||
settle(tx, &market, &outcome, book.match_incoming(&incoming))?;
|
||||
}
|
||||
}
|
||||
let (remaining, mut status): (i64, String) = tx.query_row(
|
||||
"SELECT remaining,status FROM orders WHERE seq=?",
|
||||
@@ -61,28 +70,13 @@ pub(crate) fn submit(tx: &Transaction, order: NewOrder) -> Result<Value> {
|
||||
Ok(json!({"order":seq,"filled":qty-remaining,"status":status}))
|
||||
}
|
||||
|
||||
pub(crate) fn match_book(
|
||||
pub(crate) fn settle(
|
||||
tx: &Transaction,
|
||||
market: &str,
|
||||
outcome: &str,
|
||||
phase: Phase,
|
||||
fills: Vec<Fill>,
|
||||
) -> 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) {
|
||||
for f in fills {
|
||||
let (buyer, limit): (String, i64) = tx.query_row(
|
||||
"SELECT account,price FROM orders WHERE seq=?",
|
||||
[f.bid],
|
||||
|
||||
@@ -4,25 +4,33 @@ mod book;
|
||||
mod command;
|
||||
mod ledger;
|
||||
mod market;
|
||||
mod resident;
|
||||
use resident::Books;
|
||||
|
||||
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);
|
||||
pub struct Exchange {
|
||||
db: Connection,
|
||||
books: Books,
|
||||
}
|
||||
impl Exchange {
|
||||
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
|
||||
let db = Connection::open(path)?;
|
||||
let mut 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))
|
||||
let tx = db.transaction()?;
|
||||
let books = Books::recover(&tx)?;
|
||||
tx.commit()?;
|
||||
Ok(Self { db, books })
|
||||
}
|
||||
|
||||
pub fn execute(&mut self, payload: Value) -> Result<Value> {
|
||||
if payload == json!({"op":"state"}) {
|
||||
let tx = self.0.transaction()?;
|
||||
let tx = self.db.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"))?;
|
||||
@@ -51,7 +59,7 @@ impl Exchange {
|
||||
let id = payload["id"].as_str().context("request id required")?;
|
||||
identifier(id)?;
|
||||
let tx = self
|
||||
.0
|
||||
.db
|
||||
.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let prior: Option<(String, String)> = tx
|
||||
.query_row(
|
||||
@@ -71,12 +79,17 @@ impl Exchange {
|
||||
body.as_object_mut()
|
||||
.context("expected object")?
|
||||
.remove("id");
|
||||
let result = market::apply(&tx, serde_json::from_value(body)?)?;
|
||||
let command = serde_json::from_value(body)?;
|
||||
let external = self.books.changes(&tx)?;
|
||||
self.books.apply(external);
|
||||
let result = market::apply(&tx, &self.books, command)?;
|
||||
tx.execute(
|
||||
"INSERT INTO requests VALUES(?,?,?)",
|
||||
params![id, payload.to_string(), result.to_string()],
|
||||
)?;
|
||||
let changes = self.books.changes(&tx)?;
|
||||
tx.commit()?;
|
||||
self.books.apply(changes);
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::resident::Books;
|
||||
use crate::{
|
||||
book,
|
||||
command::Command,
|
||||
@@ -5,11 +6,10 @@ use crate::{
|
||||
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> {
|
||||
pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result<Value> {
|
||||
match command {
|
||||
Command::Fund { account, cents } => {
|
||||
identifier(&account)?;
|
||||
@@ -54,6 +54,7 @@ pub(crate) fn apply(tx: &Transaction, command: Command) -> Result<Value> {
|
||||
tif,
|
||||
} => book::submit(
|
||||
tx,
|
||||
books,
|
||||
book::NewOrder {
|
||||
market,
|
||||
account,
|
||||
@@ -72,7 +73,9 @@ pub(crate) fn apply(tx: &Transaction, command: Command) -> Result<Value> {
|
||||
Command::Open { market } => {
|
||||
phase(tx, &market, &["preopen"])?;
|
||||
for outcome in ["YES", "NO"] {
|
||||
book::match_book(tx, &market, outcome, Phase::Opening)?;
|
||||
if let Some(book) = books.get(&market, outcome) {
|
||||
book::settle(tx, &market, outcome, book.opening())?;
|
||||
}
|
||||
}
|
||||
tx.execute("UPDATE markets SET phase='continuous' WHERE id=?", [market])?;
|
||||
Ok(json!({"phase":"continuous"}))
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
use anyhow::Result;
|
||||
use matching::{Order, OrderBook, Side};
|
||||
use rusqlite::{Row, Transaction};
|
||||
use std::collections::HashMap;
|
||||
|
||||
struct Change {
|
||||
market: String,
|
||||
outcome: String,
|
||||
order: Order,
|
||||
revision: i64,
|
||||
}
|
||||
|
||||
impl Change {
|
||||
fn read(row: &Row<'_>) -> rusqlite::Result<Self> {
|
||||
Ok(Self {
|
||||
market: row.get(0)?,
|
||||
outcome: row.get(1)?,
|
||||
order: Order {
|
||||
seq: row.get(2)?,
|
||||
side: if row.get::<_, String>(3)? == "buy" {
|
||||
Side::Buy
|
||||
} else {
|
||||
Side::Sell
|
||||
},
|
||||
price: row.get(4)?,
|
||||
remaining: row.get(5)?,
|
||||
},
|
||||
revision: row.get(6)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Books {
|
||||
markets: HashMap<String, HashMap<String, OrderBook>>,
|
||||
revision: i64,
|
||||
}
|
||||
|
||||
pub(crate) struct Changes(Vec<Change>);
|
||||
|
||||
impl Books {
|
||||
pub fn get(&self, market: &str, outcome: &str) -> Option<&OrderBook> {
|
||||
self.markets.get(market)?.get(outcome)
|
||||
}
|
||||
|
||||
pub fn recover(tx: &Transaction) -> Result<Self> {
|
||||
let mut books = Self::default();
|
||||
let mut stmt = tx.prepare(
|
||||
"SELECT market,outcome,seq,side,price,remaining,0 FROM orders WHERE status='live'",
|
||||
)?;
|
||||
for row in stmt.query_map([], Change::read)? {
|
||||
books.install(row?);
|
||||
}
|
||||
books.revision = tx.query_row(
|
||||
"SELECT COALESCE(MAX(revision),0) FROM book_changes",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
Ok(books)
|
||||
}
|
||||
|
||||
pub fn changes(&self, tx: &Transaction) -> Result<Changes> {
|
||||
let mut stmt = tx.prepare_cached(
|
||||
"SELECT o.market, o.outcome, o.seq, o.side, o.price,
|
||||
CASE WHEN o.status='live' THEN o.remaining ELSE 0 END, c.revision
|
||||
FROM book_changes c CROSS JOIN orders o ON o.seq=c.seq
|
||||
WHERE c.revision>? ORDER BY c.revision",
|
||||
)?;
|
||||
let rows = stmt
|
||||
.query_map([self.revision], Change::read)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(Changes(rows))
|
||||
}
|
||||
|
||||
pub fn apply(&mut self, changes: Changes) {
|
||||
for change in changes.0 {
|
||||
self.install(change);
|
||||
}
|
||||
}
|
||||
|
||||
fn install(&mut self, change: Change) {
|
||||
let Change {
|
||||
market,
|
||||
outcome,
|
||||
order,
|
||||
revision,
|
||||
} = change;
|
||||
self.revision = revision;
|
||||
let books = self.markets.entry(market.clone()).or_default();
|
||||
let book = books.entry(outcome.clone()).or_default();
|
||||
book.update(order);
|
||||
if book.is_empty() {
|
||||
books.remove(&outcome);
|
||||
}
|
||||
if books.is_empty() {
|
||||
self.markets.remove(&market);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,3 +22,16 @@ CREATE TABLE IF NOT EXISTS fills (
|
||||
CREATE TABLE IF NOT EXISTS requests (
|
||||
id TEXT PRIMARY KEY, payload TEXT NOT NULL, response TEXT NOT NULL
|
||||
);
|
||||
|
||||
-- Keep only the last change per order. Other connections can catch up by revision.
|
||||
CREATE TABLE IF NOT EXISTS book_changes (
|
||||
seq INTEGER PRIMARY KEY REFERENCES orders, revision INTEGER NOT NULL UNIQUE
|
||||
);
|
||||
CREATE TRIGGER IF NOT EXISTS book_insert AFTER INSERT ON orders BEGIN
|
||||
INSERT INTO book_changes(seq, revision)
|
||||
SELECT NEW.seq, COALESCE(MAX(revision), 0) + 1 FROM book_changes;
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS book_update AFTER UPDATE OF remaining,status ON orders BEGIN
|
||||
INSERT OR REPLACE INTO book_changes(seq, revision)
|
||||
SELECT NEW.seq, COALESCE(MAX(revision), 0) + 1 FROM book_changes;
|
||||
END;
|
||||
|
||||
@@ -132,3 +132,91 @@ fn market_outcome_and_limit_are_isolated() {
|
||||
}
|
||||
assert_eq!(state(&mut e)["fills"], json!([]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reboot_restores_partial_fifo_and_excludes_cancelled_orders() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("market.db");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
setup(&mut e);
|
||||
e.execute(order("ask-first", "alice", "sell", 40, 4))
|
||||
.unwrap();
|
||||
e.execute(order("ask-second", "alice", "sell", 40, 3))
|
||||
.unwrap();
|
||||
e.execute(order("cancel-me", "alice", "sell", 30, 1))
|
||||
.unwrap();
|
||||
e.execute(json!({"id":"cancel","op":"cancel","account":"alice","order":3}))
|
||||
.unwrap();
|
||||
e.execute(order("bid", "bob", "buy", 40, 2)).unwrap();
|
||||
drop(e);
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
e.execute(json!({"id":"open","op":"open","market":"e"}))
|
||||
.unwrap();
|
||||
drop(e);
|
||||
// A database from the original version has live orders but no revision index.
|
||||
let legacy = rusqlite::Connection::open(&path).unwrap();
|
||||
legacy
|
||||
.execute_batch(
|
||||
"DROP TRIGGER book_insert; DROP TRIGGER book_update; DROP TABLE book_changes;",
|
||||
)
|
||||
.unwrap();
|
||||
drop(legacy);
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
e.execute(order("sweep", "bob", "buy", 40, 4)).unwrap();
|
||||
let s = state(&mut e);
|
||||
assert_eq!(
|
||||
s["fills"],
|
||||
json!([
|
||||
{"seq":1,"ask":1,"bid":4,"price":40,"quantity":2},
|
||||
{"seq":2,"ask":1,"bid":5,"price":40,"quantity":2},
|
||||
{"seq":3,"ask":2,"bid":5,"price":40,"quantity":2}
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_resident_books_follow_partial_fill_and_cancel() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("market.db");
|
||||
let mut a = Exchange::open(&path).unwrap();
|
||||
setup(&mut a);
|
||||
let mut b = Exchange::open(&path).unwrap();
|
||||
a.execute(json!({"id":"open","op":"open","market":"e"}))
|
||||
.unwrap();
|
||||
a.execute(order("maker", "alice", "sell", 55, 6)).unwrap();
|
||||
assert_eq!(
|
||||
b.execute(order("taker", "bob", "buy", 55, 4)).unwrap()["filled"],
|
||||
4
|
||||
);
|
||||
assert_eq!(
|
||||
a.execute(json!({"id":"cancel","op":"cancel","order":1,"account":"alice"}))
|
||||
.unwrap()["cancelled"],
|
||||
2
|
||||
);
|
||||
assert_eq!(
|
||||
b.execute(order("next", "bob", "buy", 55, 1)).unwrap()["filled"],
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_receipt_discards_planned_fill() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("market.db");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
setup(&mut e);
|
||||
e.execute(json!({"id":"open","op":"open","market":"e"}))
|
||||
.unwrap();
|
||||
e.execute(order("ask", "alice", "sell", 55, 3)).unwrap();
|
||||
let db = rusqlite::Connection::open(&path).unwrap();
|
||||
db.execute_batch("CREATE TRIGGER reject_receipt BEFORE INSERT ON requests WHEN NEW.id='retry' BEGIN SELECT RAISE(ABORT,'injected'); END;").unwrap();
|
||||
let bid = order("retry", "bob", "buy", 55, 3);
|
||||
let before = state(&mut e);
|
||||
assert!(e.execute(bid.clone()).is_err());
|
||||
assert_eq!(state(&mut e), before);
|
||||
db.execute_batch("DROP TRIGGER reject_receipt").unwrap();
|
||||
let reply = e.execute(bid.clone()).unwrap();
|
||||
assert_eq!(reply["filled"], 3);
|
||||
assert_eq!(e.execute(bid).unwrap(), reply);
|
||||
assert_eq!(state(&mut e)["fills"].as_array().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user