Keep per-instrument order books in memory and recover committed orders

This commit is contained in:
2026-12-03 03:01:52 +08:00
parent d2361f158b
commit 417692633f
11 changed files with 402 additions and 127 deletions
+15 -21
View File
@@ -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],
+19 -6
View File
@@ -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)
}
}
+6 -3
View File
@@ -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"}))
+99
View File
@@ -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);
}
}
}
+13
View File
@@ -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;