Expire GTD orders before matching, reads and recovery

This commit is contained in:
2026-12-03 04:05:29 +08:00
parent 3bff1c0bc3
commit d43c958ff2
10 changed files with 220 additions and 19 deletions
+3 -2
View File
@@ -42,7 +42,8 @@ impl Filter {
"status='live' AND ?6 IS NULL"
};
let sql = format!(
"SELECT seq,market,outcome,side,price,quantity,remaining,status FROM orders
"SELECT seq,market,outcome,side,price,quantity,remaining,status,
(SELECT expiration FROM order_deadlines d WHERE d.seq=orders.seq) FROM orders
WHERE account=?1 AND (?2 IS NULL OR market=?2) AND (?3 IS NULL OR outcome=?3)
AND seq>?4 AND {scope} ORDER BY seq LIMIT ?5"
);
@@ -71,7 +72,7 @@ impl Filter {
"outcome":row.get::<_,String>(2)?,"side":row.get::<_,String>(3)?,
"price_micros":row.get::<_,i64>(4)?*10000,"original_size":quantity,
"size_matched":quantity-remaining,"open_size":if status=="live"{remaining}else{0},
"status":status}));
"status":status,"expiration":row.get::<_,Option<i64>>(8)?}));
last_id = Some(id);
}
Ok(json!({"orders":orders,"next_after":next_after}))
+46 -5
View File
@@ -16,6 +16,7 @@ pub(crate) struct NewOrder {
pub price: i64,
pub qty: i64,
pub tif: TimeInForce,
pub expiration: Option<i64>,
pub post_only: bool,
}
@@ -28,6 +29,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
price,
qty,
tif,
expiration,
post_only,
} = order;
identifier(&account)?;
@@ -43,9 +45,25 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
"unsupported time in force"
);
ensure!(
!post_only || (stage == "continuous" && tif == TimeInForce::Gtc),
"post-only requires continuous GTC"
!post_only || (stage == "continuous" && matches!(tif, TimeInForce::Gtc | TimeInForce::Gtd)),
"post-only requires continuous GTC or GTD"
);
let deadline = match tif {
TimeInForce::Gtd => {
let expiration =
expiration.ok_or_else(|| anyhow::anyhow!("GTD requires expiration"))?;
let now: i64 = tx.query_row("SELECT unixepoch()", [], |r| r.get(0))?;
ensure!(
expiration >= now + 180,
"GTD expiration must be at least 180 seconds ahead"
);
Some(expiration)
}
_ => {
ensure!(expiration.unwrap_or(0) == 0, "expiration requires GTD");
None
}
};
if side == "buy" {
ledger::cash(tx, &account, -price * qty)?;
} else {
@@ -53,6 +71,12 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
}
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 let Some(deadline) = deadline {
tx.execute(
"INSERT INTO order_deadlines(seq,expiration) VALUES(?,?)",
params![seq, deadline],
)?;
}
if stage == "continuous" {
let incoming = Order {
seq,
@@ -86,7 +110,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
if matches!(tif, TimeInForce::Ioc | TimeInForce::Fak) && remaining > 0 {
release(tx, seq, &account)?;
release(tx, seq, &account, CancelReason::Cancelled)?;
status = "cancelled".into();
}
Ok(json!({"order":seq,"filled":qty-remaining,"status":status}))
@@ -191,13 +215,30 @@ pub(crate) fn settle(
Ok(())
}
pub(crate) fn release(tx: &Transaction, seq: i64, owner: &str) -> Result<i64> {
pub(crate) enum CancelReason {
Cancelled,
Expired,
}
pub(crate) fn release(
tx: &Transaction,
seq: i64,
owner: &str,
reason: CancelReason,
) -> 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])?;
let status = match reason {
CancelReason::Cancelled => "cancelled",
CancelReason::Expired => "expired",
};
tx.execute(
"UPDATE orders SET status=? WHERE seq=?",
params![status, seq],
)?;
Ok(qty)
}
+3 -1
View File
@@ -40,7 +40,8 @@ pub(crate) enum Command {
price: i64,
qty: i64,
#[serde(default)]
tif: TimeInForce,
tif: Option<TimeInForce>,
expiration: Option<i64>,
#[serde(default)]
post_only: bool,
},
@@ -72,6 +73,7 @@ pub(crate) enum Command {
pub(crate) enum TimeInForce {
#[default]
Gtc,
Gtd,
Ioc,
Fak,
Fok,
+38
View File
@@ -0,0 +1,38 @@
use crate::book::{release, CancelReason};
use anyhow::Result;
use rusqlite::{Connection, Transaction, TransactionBehavior};
/// Return a snapshot whose live book was current when the snapshot was acquired.
/// Expirations commit separately so a rejected command cannot revive an order.
pub(crate) fn transaction(
db: &Connection,
behavior: TransactionBehavior,
) -> Result<Transaction<'_>> {
loop {
let tx = Transaction::new_unchecked(db, behavior)?;
let due: bool = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM order_deadlines WHERE pending=1 AND expiration<=unixepoch()+60)",
[], |row| row.get(0),
)?;
if !due {
return Ok(tx);
}
tx.rollback()?;
// Recheck after acquiring the write lock. Other engines can also expire a row.
let write = Transaction::new_unchecked(db, TransactionBehavior::Immediate)?;
let mut stmt = write.prepare(
"SELECT d.seq,o.account FROM order_deadlines d JOIN orders o ON o.seq=d.seq
WHERE d.pending=1 AND d.expiration<=unixepoch()+60 ORDER BY d.expiration,d.seq",
)?;
let due = stmt
.query_map([], |row| {
Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
drop(stmt);
for (seq, owner) in due {
release(&write, seq, &owner, CancelReason::Expired)?;
}
write.commit()?;
}
}
+6 -7
View File
@@ -1,5 +1,6 @@
mod account_orders;
mod catalog;
mod expiry;
mod validation;
use validation::identifier;
mod book;
@@ -21,11 +22,11 @@ pub struct Exchange {
}
impl Exchange {
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
let mut db = Connection::open(path)?;
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"))?;
let tx = db.transaction()?;
let tx = expiry::transaction(&db, TransactionBehavior::Deferred)?;
let books = Books::recover(&tx)?;
tx.commit()?;
Ok(Self { db, books })
@@ -37,13 +38,13 @@ impl Exchange {
Some("catalog" | "history" | "quote" | "book" | "open_orders" | "positions")
) {
let query: catalog::Query = serde_json::from_value(payload)?;
let tx = self.db.transaction()?;
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
let value = query.read(&tx)?;
tx.commit()?;
return Ok(value);
}
if payload == json!({"op":"state"}) {
let tx = self.db.transaction()?;
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
let mut state = Map::new();
for table in [
"accounts",
@@ -78,9 +79,7 @@ impl Exchange {
}
let id = payload["id"].as_str().context("request id required")?;
identifier(id)?;
let tx = self
.db
.transaction_with_behavior(TransactionBehavior::Immediate)?;
let tx = expiry::transaction(&self.db, TransactionBehavior::Immediate)?;
let prior: Option<(String, String)> = tx
.query_row(
"SELECT payload,response FROM requests WHERE id=?",
+11 -3
View File
@@ -111,6 +111,7 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
price,
qty,
tif,
expiration,
post_only,
} => book::submit(
tx,
@@ -122,13 +123,20 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
side,
price,
qty,
tif,
tif: tif.unwrap_or_else(|| {
if expiration.unwrap_or(0) != 0 {
crate::command::TimeInForce::Gtd
} else {
crate::command::TimeInForce::Gtc
}
}),
expiration,
post_only,
},
),
Command::Cancel { order, account } => {
identifier(&account)?;
let qty = book::release(tx, order, &account)?;
let qty = book::release(tx, order, &account, book::CancelReason::Cancelled)?;
Ok(json!({"cancelled":qty}))
}
Command::Open { market } => {
@@ -157,7 +165,7 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
for (seq, account) in orders {
book::release(tx, seq, &account)?;
book::release(tx, seq, &account, book::CancelReason::Cancelled)?;
}
tx.execute("UPDATE markets SET phase='closed' WHERE id=?", [market])?;
Ok(json!({"phase":"closed"}))
+11
View File
@@ -82,3 +82,14 @@ CREATE VIEW IF NOT EXISTS visible_orders AS
SELECT market,CASE outcome WHEN 'YES' THEN 'NO' ELSE 'YES' END,
CASE side WHEN 'buy' THEN 'sell' ELSE 'buy' END,100-price,remaining
FROM orders WHERE status='live';
CREATE TABLE IF NOT EXISTS order_deadlines (
seq INTEGER PRIMARY KEY REFERENCES orders,
expiration INTEGER NOT NULL,
pending INTEGER NOT NULL DEFAULT 1 CHECK(pending IN (0,1))
);
CREATE INDEX IF NOT EXISTS pending_deadlines ON order_deadlines(expiration) WHERE pending=1;
CREATE TRIGGER IF NOT EXISTS finish_deadline AFTER UPDATE OF status ON orders
WHEN OLD.status='live' AND NEW.status<>'live' BEGIN
UPDATE order_deadlines SET pending=0 WHERE seq=NEW.seq;
END;