Expire GTD orders before matching, reads and recovery
This commit is contained in:
@@ -9,6 +9,8 @@
|
||||
```mermaid
|
||||
flowchart LR
|
||||
test["tests/market.rs"] -->|通过公开 API 驱动市场| api["src/lib.rs"]
|
||||
api -->|启动和请求时检查到期时间| expiry["src/expiry.rs"]
|
||||
expiry -->|释放订单剩余预留| book["src/book.rs"]
|
||||
api -->|初始化数据库| schema["src/schema.sql"]
|
||||
api -->|校验请求键| valid["src/validation.rs"]
|
||||
api -->|解析写命令| cmd["src/command.rs"]
|
||||
@@ -140,3 +142,25 @@ sequenceDiagram
|
||||
C->>E: redeem 主动兑付,再查询 OPEN 和 CLOSED
|
||||
E-->>C: 已退出的份额移入 CLOSED,可领取金额归零
|
||||
```
|
||||
|
||||
## GTD 到期
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as CLI
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
participant B as 常驻盘口
|
||||
C->>E: 提交 GTD,含 Unix 秒时间戳
|
||||
E->>D: 校验申报时间并原子记录委托与期限
|
||||
C->>E: 到达有效截止点后查询或提交新单
|
||||
E->>D: 在写锁下复核到期项,释放余单并提交
|
||||
alt 查询
|
||||
E->>D: 读取更新后的快照
|
||||
else 撮合
|
||||
E->>B: 同步已提交的撤单,再选择对手
|
||||
end
|
||||
E-->>C: 返回查询结果或新单回执
|
||||
```
|
||||
|
||||
没有请求时,模拟 CLI 会等待输入。下一次查询、交易或进程重启会先结清已到期的余单。成交、手动撤单和停盘会同步移除相应的待到期项。
|
||||
|
||||
@@ -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}))
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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()?;
|
||||
}
|
||||
}
|
||||
@@ -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=?",
|
||||
|
||||
@@ -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"}))
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -654,3 +654,74 @@ fn portfolio_tracks_reserved_pairs_partial_sale_and_redemption() {
|
||||
.unwrap();
|
||||
assert_eq!(other["positions"][0]["payout_cents"], 200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gtd_expiry_survives_rejection_and_recovery() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("expiry.db");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
setup(&mut e);
|
||||
e.execute(json!({"op":"open","id":"start","market":"e"}))
|
||||
.unwrap();
|
||||
let db = rusqlite::Connection::open(&path).unwrap();
|
||||
let now: i64 = db
|
||||
.query_row("SELECT unixepoch()", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
let mut ask = order("dated", "alice", "sell", 60, 5);
|
||||
ask["tif"] = json!("GTD");
|
||||
assert!(e.execute(ask.clone()).is_err());
|
||||
ask["expiration"] = json!(now + 179);
|
||||
assert!(e.execute(ask.clone()).is_err());
|
||||
ask["expiration"] = json!(now + 600);
|
||||
ask["post_only"] = json!(true);
|
||||
let receipt = e.execute(ask.clone()).unwrap();
|
||||
let mut bid = order("dated-buy", "bob", "buy", 20, 3);
|
||||
bid["expiration"] = json!(now + 600);
|
||||
let bid_id = e.execute(bid).unwrap()["order"].as_i64().unwrap();
|
||||
e.execute(order("take", "bob", "buy", 60, 2)).unwrap();
|
||||
let ask_id = receipt["order"].as_i64().unwrap();
|
||||
db.execute(
|
||||
"UPDATE order_deadlines SET expiration=unixepoch()+60 WHERE seq=?",
|
||||
[ask_id],
|
||||
)
|
||||
.unwrap();
|
||||
let mut sweep = order("sweep", "bob", "buy", 65, 1);
|
||||
sweep["tif"] = json!("FOK");
|
||||
assert!(e.execute(sweep).is_err());
|
||||
assert_eq!(e.execute(ask).unwrap(), receipt);
|
||||
let lookup = e
|
||||
.execute(json!({"op":"open_orders","account":"alice","order":ask_id}))
|
||||
.unwrap();
|
||||
assert_eq!(lookup["orders"][0]["status"], "expired");
|
||||
assert_eq!(lookup["orders"][0]["size_matched"], 2);
|
||||
assert_eq!(lookup["orders"][0]["open_size"], 0);
|
||||
let held = e
|
||||
.execute(json!({"op":"positions","account":"alice"}))
|
||||
.unwrap();
|
||||
let yes = held["positions"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|r| r["outcome"] == "YES")
|
||||
.unwrap();
|
||||
assert_eq!(yes["available_size"], 8);
|
||||
assert_eq!(yes["reserved_size"], 0);
|
||||
drop(e);
|
||||
db.execute(
|
||||
"UPDATE order_deadlines SET expiration=unixepoch()+59 WHERE seq=?",
|
||||
[bid_id],
|
||||
)
|
||||
.unwrap();
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
let s = state(&mut e);
|
||||
assert_eq!(s["accounts"][1]["cash"], 1880);
|
||||
assert_eq!(s["orders"][1]["status"], "expired");
|
||||
assert_eq!(
|
||||
e.execute(json!({"op":"book","market":"e","outcome":"NO"}))
|
||||
.unwrap()["asks"],
|
||||
json!([])
|
||||
);
|
||||
drop(e);
|
||||
let mut e = Exchange::open(path).unwrap();
|
||||
assert_eq!(state(&mut e)["accounts"][1]["cash"], 1880);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user