Enforce FOK, FAK and post-only constraints before applying fills

This commit is contained in:
2026-12-03 03:45:40 +08:00
parent d6eef2f07f
commit 4eb80fa458
6 changed files with 107 additions and 18 deletions
+34 -12
View File
@@ -1,4 +1,4 @@
use crate::resident::Books;
use crate::{command::TimeInForce, resident::Books};
use crate::{
ledger,
validation::{amount, identifier, phase},
@@ -15,7 +15,8 @@ pub(crate) struct NewOrder {
pub side: String,
pub price: i64,
pub qty: i64,
pub tif: String,
pub tif: TimeInForce,
pub post_only: bool,
}
pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result<Value> {
@@ -27,6 +28,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
price,
qty,
tif,
post_only,
} = order;
identifier(&account)?;
amount(qty)?;
@@ -37,9 +39,13 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
);
ensure!((0..=100).contains(&price), "invalid price");
ensure!(
tif == "GTC" || (tif == "IOC" && stage == "continuous"),
tif == TimeInForce::Gtc || stage == "continuous",
"unsupported time in force"
);
ensure!(
!post_only || (stage == "continuous" && tif == TimeInForce::Gtc),
"post-only requires continuous GTC"
);
if side == "buy" {
ledger::cash(tx, &account, -price * qty)?;
} else {
@@ -48,22 +54,38 @@ 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 stage == "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 incoming = Order {
seq,
side: if side == "buy" { Side::Buy } else { Side::Sell },
price,
remaining: qty,
};
let fills = books
.get(&market, &outcome)
.map(|book| book.match_incoming(&incoming))
.unwrap_or_default();
ensure!(
!post_only || fills.is_empty(),
"post-only order would take liquidity"
);
if tif == TimeInForce::Fok {
ensure!(
fills.iter().map(|fill| fill.quantity).sum::<i64>() == qty,
"FOK cannot fill the entire order"
);
}
ensure!(
tif != TimeInForce::Fak || !fills.is_empty(),
"FAK has no matching liquidity"
);
settle(tx, &market, &outcome, fills)?;
}
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 {
if matches!(tif, TimeInForce::Ioc | TimeInForce::Fak) && remaining > 0 {
release(tx, seq, &account)?;
status = "cancelled".into();
}
+12 -4
View File
@@ -39,8 +39,10 @@ pub(crate) enum Command {
side: String,
price: i64,
qty: i64,
#[serde(default = "gtc")]
tif: String,
#[serde(default)]
tif: TimeInForce,
#[serde(default)]
post_only: bool,
},
Cancel {
account: String,
@@ -65,6 +67,12 @@ pub(crate) enum Command {
winner: String,
},
}
fn gtc() -> String {
"GTC".into()
#[derive(Clone, Copy, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "UPPERCASE")]
pub(crate) enum TimeInForce {
#[default]
Gtc,
Ioc,
Fak,
Fok,
}
+2
View File
@@ -111,6 +111,7 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
price,
qty,
tif,
post_only,
} => book::submit(
tx,
books,
@@ -122,6 +123,7 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
price,
qty,
tif,
post_only,
},
),
Command::Cancel { order, account } => {
+53
View File
@@ -366,3 +366,56 @@ fn explicit_redemption_is_account_scoped_and_restart_safe() {
.all(|p| p["quantity"] == 0));
}
}
#[test]
fn immediate_and_post_only_orders_use_the_committed_depth() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
for (id, price) in [("low", 40), ("high", 41)] {
let mut maker = order(id, "alice", "sell", price, 2);
maker["post_only"] = json!(true);
assert_eq!(e.execute(maker).unwrap()["status"], "live");
}
let before = state(&mut e);
for (id, tif, post, price, qty) in [
("short", "FOK", false, 40, 3),
("cross", "GTC", true, 40, 1),
("wrong-combination", "FAK", true, 40, 1),
("no-fill", "FAK", false, 39, 1),
] {
let mut req = order(id, "bob", "buy", price, qty);
req["post_only"] = json!(post);
req["tif"] = json!(tif);
assert!(e.execute(req).is_err());
assert_eq!(state(&mut e), before);
}
let mut full = order("full", "bob", "buy", 41, 3);
full["tif"] = json!("FOK");
let reply = e.execute(full.clone()).unwrap();
assert_eq!(reply["status"], "filled");
assert_eq!(reply["filled"], 3);
assert_eq!(e.execute(full).unwrap(), reply);
let mut partial = order("partial", "bob", "buy", 41, 3);
partial["tif"] = json!("FAK");
let reply = e.execute(partial).unwrap();
assert_eq!(reply["status"], "cancelled");
assert_eq!(reply["filled"], 1);
let s = state(&mut e);
assert_eq!(s["fills"].as_array().unwrap().len(), 3);
assert_eq!(s["accounts"][1]["cash"], 1838);
}
#[test]
fn rejected_sell_fok_releases_inventory() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
let before = state(&mut e);
let mut sell = order("sell", "alice", "sell", 60, 5);
sell["tif"] = json!("FOK");
assert!(e.execute(sell).is_err());
assert_eq!(state(&mut e), before);
}