Match complementary binary orders and settle paired issuance or merge

This commit is contained in:
2026-12-03 03:49:42 +08:00
parent 4eb80fa458
commit 47d49cb8c9
10 changed files with 238 additions and 38 deletions
+85 -16
View File
@@ -92,6 +92,47 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
Ok(json!({"order":seq,"filled":qty-remaining,"status":status}))
}
struct ExecutedLeg {
seq: i64,
outcome: String,
side: String,
price: i64,
}
fn book_leg(
tx: &Transaction,
market: &str,
view: &str,
fill: &Fill,
seq: i64,
) -> Result<ExecutedLeg> {
let (account, outcome, side, limit): (String, String, String, i64) = tx.query_row(
"SELECT account,outcome,side,price FROM orders
WHERE seq=? AND market=? AND status='live' AND remaining>=?",
params![seq, market, fill.quantity],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
)?;
let price = if outcome == view {
fill.price
} else {
100 - fill.price
};
if side == "buy" {
ensure!(price <= limit, "buy limit exceeded");
ledger::cash(tx, &account, (limit - price) * fill.quantity)?;
ledger::position(tx, &account, market, &outcome, fill.quantity)?;
} else {
ensure!(price >= limit, "sell limit exceeded");
ledger::cash(tx, &account, price * fill.quantity)?;
}
Ok(ExecutedLeg {
seq,
outcome,
side,
price,
})
}
pub(crate) fn settle(
tx: &Transaction,
market: &str,
@@ -99,22 +140,50 @@ pub(crate) fn settle(
fills: Vec<Fill>,
) -> Result<()> {
for f in fills {
let (buyer, limit): (String, i64) = tx.query_row(
"SELECT account,price FROM orders WHERE seq=?",
[f.bid],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
let seller: String =
tx.query_row("SELECT account FROM orders WHERE seq=?", [f.ask], |r| {
r.get(0)
})?;
ledger::cash(tx, &seller, f.price * f.quantity)?;
ledger::cash(tx, &buyer, (limit - f.price) * f.quantity)?;
ledger::position(tx, &buyer, market, outcome, f.quantity)?;
tx.execute(
"INSERT INTO fills(bid,ask,price,quantity) VALUES(?,?,?,?)",
params![f.bid, f.ask, f.price, f.quantity],
)?;
let first = book_leg(tx, market, outcome, &f, f.bid)?;
let second = book_leg(tx, market, outcome, &f, f.ask)?;
if first.outcome == second.outcome {
let (buy, sell) = if first.side == "buy" {
(first, second)
} else {
(second, first)
};
ensure!(buy.side == "buy" && sell.side == "sell", "invalid transfer");
tx.execute("INSERT INTO fills(seq,bid,ask,price,quantity) SELECT id,?1,?2,?3,?4 FROM next_execution",
params![buy.seq,sell.seq,buy.price,f.quantity])?;
} else {
ensure!(first.side == second.side, "invalid complementary legs");
let mint = first.side == "buy";
let delta = if mint {
100 * f.quantity
} else {
-100 * f.quantity
};
ensure!(
tx.execute(
"UPDATE markets SET collateral=collateral+?1 WHERE id=?2 AND collateral+?1>=0",
params![delta, market]
)? == 1,
"insufficient collateral"
);
let (yes, no) = if first.outcome == "YES" {
(first, second)
} else {
(second, first)
};
tx.execute(
"INSERT INTO paired_fills(seq,market,kind,yes_order,no_order,yes_price,quantity)
SELECT id,?1,?2,?3,?4,?5,?6 FROM next_execution",
params![
market,
if mint { "mint" } else { "merge" },
yes.seq,
no.seq,
yes.price,
f.quantity
],
)?;
}
for seq in [f.bid, f.ask] {
tx.execute("UPDATE orders SET remaining=remaining-?1,status=CASE WHEN remaining=?1 THEN 'filled' ELSE 'live' END WHERE seq=?2",params![f.quantity,seq])?;
}
+14 -7
View File
@@ -167,14 +167,21 @@ impl Query {
db.query_row("SELECT phase FROM markets WHERE id=?", [&market], |r| {
r.get(0)
})?;
let (bid,ask):(Option<i64>,Option<i64>)=db.query_row(
"SELECT MAX(CASE WHEN side='buy' THEN price END), MIN(CASE WHEN side='sell' THEN price END)
FROM orders WHERE market=? AND outcome=? AND status='live'",
params![market,outcome], |r|Ok((r.get(0)?,r.get(1)?)))?;
let (bid, ask): (Option<i64>, Option<i64>) = db.query_row(
"SELECT MAX(CASE WHEN side='buy' AND outcome=?1 THEN price
WHEN side='sell' AND outcome<>?1 THEN 100-price END),
MIN(CASE WHEN side='sell' AND outcome=?1 THEN price
WHEN side='buy' AND outcome<>?1 THEN 100-price END)
FROM orders WHERE market=?2 AND status='live'",
params![outcome, market],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
// Fills also cover databases created before timestamped history was introduced.
let last: Option<i64> = db.query_row(
"SELECT (SELECT f.price FROM fills f JOIN orders o ON o.seq=f.bid
WHERE o.market=? AND o.outcome=? ORDER BY f.seq DESC LIMIT 1)",
"SELECT (SELECT price FROM (
SELECT f.seq, f.price FROM fills f JOIN orders o ON o.seq=f.bid WHERE o.market=?1 AND o.outcome=?2
UNION ALL SELECT seq, CASE WHEN ?2='YES' THEN yes_price ELSE 100-yes_price END FROM paired_fills WHERE market=?1
) ORDER BY seq DESC LIMIT 1)",
params![market, outcome],
|r| r.get(0),
)?;
@@ -232,7 +239,7 @@ impl Query {
"invalid history parameters"
);
let (t, id) = after.unwrap_or((-1, 0));
let mut stmt=db.prepare("SELECT at_ms,fill,price_micros,quantity FROM trade_prices WHERE market=? AND outcome=? AND at_ms>=? AND at_ms<? AND (at_ms,fill)>(?,?) ORDER BY at_ms,fill LIMIT ?")?;
let mut stmt=db.prepare("SELECT at_ms,fill,price_micros,quantity FROM outcome_trade_prices WHERE market=? AND outcome=? AND at_ms>=? AND at_ms<? AND (at_ms,fill)>(?,?) ORDER BY at_ms,fill LIMIT ?")?;
let points = stmt
.query_map(
params![market, outcome, from_ms, to_ms, t, id, limit],
+8 -1
View File
@@ -43,7 +43,14 @@ impl Exchange {
if payload == json!({"op":"state"}) {
let tx = self.db.transaction()?;
let mut state = Map::new();
for table in ["accounts", "markets", "positions", "orders", "fills"] {
for table in [
"accounts",
"markets",
"positions",
"orders",
"fills",
"paired_fills",
] {
let mut stmt = tx.prepare(&format!("SELECT * FROM {table} ORDER BY rowid"))?;
let names: Vec<String> =
stmt.column_names().into_iter().map(str::to_owned).collect();
+11 -5
View File
@@ -6,7 +6,7 @@ use crate::{
validation::{amount, identifier, phase},
};
use anyhow::{ensure, Result};
use rusqlite::{params, Transaction};
use rusqlite::{params, OptionalExtension, Transaction};
use serde_json::{json, Value};
pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result<Value> {
@@ -133,10 +133,16 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
}
Command::Open { market } => {
phase(tx, &market, &["preopen"])?;
for outcome in ["YES", "NO"] {
if let Some(book) = books.get(&market, outcome) {
book::settle(tx, &market, outcome, book.opening())?;
}
// Run one auction. Using the earliest order's outcome as the quote unit
// preserves the existing low-tick tie break for a one-outcome auction.
let first:Option<String>=tx.query_row(
"SELECT outcome FROM orders WHERE market=? AND status='live' ORDER BY seq LIMIT 1",
[&market],|r|r.get(0)).optional()?;
if let Some(outcome) = first {
let book = books
.get(&market, &outcome)
.ok_or_else(|| anyhow::anyhow!("missing auction book"))?;
book::settle(tx, &market, &outcome, book.opening())?;
}
tx.execute("UPDATE markets SET phase='continuous' WHERE id=?", [market])?;
Ok(json!({"phase":"continuous"}))
+18 -4
View File
@@ -87,10 +87,24 @@ impl Books {
} = 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);
let complement = if outcome == "YES" { "NO" } else { "YES" };
let reflected = Order {
seq: order.seq,
remaining: order.remaining,
price: 100 - order.price,
side: match order.side {
Side::Buy => Side::Sell,
Side::Sell => Side::Buy,
},
};
// Each view uses its own outcome's price and side. Both entries name the
// same source order, so a match only ever traverses one of the views.
for (name, entry) in [(outcome.as_str(), order), (complement, reflected)] {
let book = books.entry(name.to_owned()).or_default();
book.update(entry);
if book.is_empty() {
books.remove(name);
}
}
if books.is_empty() {
self.markets.remove(&market);
+17
View File
@@ -56,3 +56,20 @@ CREATE TRIGGER IF NOT EXISTS record_trade_price AFTER INSERT ON fills BEGIN
SELECT NEW.seq,market,outcome,CAST(unixepoch('subsec')*1000 AS INTEGER),
NEW.price*10000,NEW.quantity FROM orders WHERE seq=NEW.bid;
END;
CREATE TABLE IF NOT EXISTS paired_fills (
seq INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES markets,
kind TEXT NOT NULL CHECK(kind IN ('mint','merge')),
yes_order INTEGER NOT NULL REFERENCES orders, no_order INTEGER NOT NULL REFERENCES orders,
yes_price INTEGER NOT NULL CHECK(yes_price BETWEEN 0 AND 100),
quantity INTEGER NOT NULL CHECK(quantity>0),
at_ms INTEGER NOT NULL DEFAULT (CAST(unixepoch('subsec')*1000 AS INTEGER))
);
CREATE INDEX IF NOT EXISTS paired_history ON paired_fills(market,at_ms,seq);
CREATE VIEW IF NOT EXISTS next_execution AS
SELECT 1+MAX(COALESCE((SELECT MAX(seq) FROM fills),0),
COALESCE((SELECT MAX(seq) FROM paired_fills),0)) AS id;
CREATE VIEW IF NOT EXISTS outcome_trade_prices AS
SELECT fill,market,outcome,at_ms,price_micros,quantity FROM trade_prices
UNION ALL SELECT seq,market,'YES',at_ms,yes_price*10000,quantity FROM paired_fills
UNION ALL SELECT seq,market,'NO',at_ms,(100-yes_price)*10000,quantity FROM paired_fills;
+74
View File
@@ -419,3 +419,77 @@ fn rejected_sell_fok_releases_inventory() {
assert!(e.execute(sell).is_err());
assert_eq!(state(&mut e), before);
}
#[test]
fn complementary_buyers_create_inventory_then_sellers_release_collateral() {
let dir = tempdir().unwrap();
let path = dir.path().join("paired.db");
let mut e = Exchange::open(&path).unwrap();
for account in ["alice", "bob"] {
e.execute(json!({"op":"fund","id":account,"account":account,"cents":1000}))
.unwrap();
}
e.execute(json!({"op":"list","id":"market","market":"e","rules":"official result"}))
.unwrap();
let mut no = order("first", "bob", "buy", 40, 10);
no["outcome"] = json!("NO");
e.execute(no).unwrap();
e.execute(order("second", "alice", "buy", 60, 10)).unwrap();
e.execute(json!({"op":"open","id":"open","market":"e"}))
.unwrap();
let s = state(&mut e);
assert_eq!(s["paired_fills"].as_array().unwrap().len(), 1);
assert_eq!(s["paired_fills"][0]["kind"], "mint");
assert_eq!(s["markets"][0]["collateral"], 1000);
assert_eq!(s["accounts"][0]["cash"], 400);
assert_eq!(s["accounts"][1]["cash"], 600);
e.execute(order("rest", "alice", "sell", 55, 10)).unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
let quote = e
.execute(json!({"op":"quote","market":"e","outcome":"NO"}))
.unwrap();
assert_eq!(quote["best_bid_micros"], 450000);
let mut sell = order("exit", "bob", "sell", 41, 10);
sell["outcome"] = json!("NO");
sell["tif"] = json!("FOK");
let reply = e.execute(sell.clone()).unwrap();
assert_eq!(reply["filled"], 10);
assert_eq!(e.execute(sell).unwrap(), reply);
let s = state(&mut e);
assert_eq!(s["paired_fills"][1]["kind"], "merge");
assert_eq!(s["markets"][0]["collateral"], 0);
assert_eq!(s["accounts"][0]["cash"], 950);
assert_eq!(s["accounts"][1]["cash"], 1050);
assert!(s["positions"]
.as_array()
.unwrap()
.iter()
.all(|p| p["quantity"] == 0));
let history=e.execute(json!({"op":"history","market":"e","outcome":"NO","from_ms":0,"to_ms":i64::MAX,"limit":3})).unwrap();
assert_eq!(history["points"][0]["price_micros"], 400000);
assert_eq!(history["points"][1]["price_micros"], 450000);
}
#[test]
fn direct_and_complementary_liquidity_share_price_time_priority() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(json!({"op":"open","id":"open","market":"e"}))
.unwrap();
let mut no = order("rest-no", "bob", "buy", 40, 2);
no["outcome"] = json!("NO");
e.execute(no).unwrap(); // projected ask 60, before direct ask at 60
e.execute(order("equal", "alice", "sell", 60, 3)).unwrap();
e.execute(order("better", "alice", "sell", 59, 1)).unwrap();
let mut buy = order("sweep", "alice", "buy", 63, 4);
buy["tif"] = json!("FOK");
assert_eq!(e.execute(buy).unwrap()["filled"], 4);
let s = state(&mut e);
assert_eq!(s["fills"][0]["seq"], 1);
assert_eq!(s["fills"][0]["price"], 59);
assert_eq!(s["paired_fills"][0]["seq"], 2);
assert_eq!(s["paired_fills"][0]["quantity"], 2);
assert_eq!(s["fills"][1]["seq"], 3);
assert_eq!(s["fills"][1]["quantity"], 1);
}