Files
eventbook-exchange/crates/exchange/tests/market.rs
T

422 lines
16 KiB
Rust

use exchange::Exchange;
use serde_json::{json, Value};
use std::sync::{Arc, Barrier};
use tempfile::tempdir;
fn setup(e: &mut Exchange) {
for cmd in [
json!({"op":"fund","id":"a","account":"alice","cents":2000}),
json!({"op":"fund","id":"b","account":"bob","cents":2000}),
json!({"op":"list","id":"m","market":"e","rules":"official result"}),
json!({"op":"split","id":"s","market":"e","account":"alice","qty":10}),
] {
e.execute(cmd).unwrap();
}
}
fn order(id: &str, account: &str, side: &str, price: i64, qty: i64) -> Value {
json!({"id":id,"op":"order","account":account,"side":side,"price":price,"qty":qty,"outcome":"YES","market":"e"})
}
fn state(e: &mut Exchange) -> Value {
e.execute(json!({"op":"state"})).unwrap()
}
#[test]
fn auction_fifo_ioc_close_and_redeem() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(order("ask1", "alice", "sell", 40, 2)).unwrap();
e.execute(order("ask2", "alice", "sell", 40, 5)).unwrap();
e.execute(order("bid", "bob", "buy", 60, 4)).unwrap();
assert_eq!(state(&mut e)["fills"], json!([]));
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
let s = state(&mut e);
assert_eq!(
s["fills"],
json!([{"seq":1,"bid":3,"ask":1,"price":40,"quantity":2},{"seq":2,"bid":3,"ask":2,"price":40,"quantity":2}])
);
let mut ioc = order("sweep", "bob", "buy", 45, 6);
ioc["tif"] = json!("IOC");
assert_eq!(
e.execute(ioc).unwrap(),
json!({"order":4,"filled":3,"status":"cancelled"})
);
e.execute(order("rest", "bob", "buy", 10, 8)).unwrap();
e.execute(json!({"id":"close","op":"close","market":"e"}))
.unwrap();
e.execute(json!({"id":"resolve","op":"resolve","market":"e","winner":"YES"}))
.unwrap();
let s = state(&mut e);
assert_eq!(
s["accounts"],
json!([{"id":"alice","cash":1580},{"id":"bob","cash":2420}])
);
assert_eq!(s["markets"][0]["collateral"], 0);
}
#[test]
fn retries_reopen_and_no_partial_writes() {
let dir = tempdir().unwrap();
let path = dir.path().join("market.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let bid = order("repeat", "bob", "buy", 60, 10);
let reply = e.execute(bid.clone()).unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(e.execute(bid).unwrap(), reply);
let before = state(&mut e);
assert!(e.execute(order("repeat", "bob", "buy", 60, 9)).is_err());
assert!(e.execute(order("big", "bob", "buy", 100, 30)).is_err());
assert!(e
.execute(json!({"id":"cancel","op":"cancel","account":"alice","order":1}))
.is_err());
assert_eq!(state(&mut e), before);
e.execute(json!({"id":"cancel","op":"cancel","account":"bob","order":1}))
.unwrap();
e.execute(json!({"id":"close","op":"close","market":"e"}))
.unwrap();
e.execute(json!({"id":"void","op":"resolve","market":"e","winner":"VOID"}))
.unwrap();
assert_eq!(state(&mut e)["accounts"][0]["cash"], 2000);
}
#[test]
fn concurrent_connections_cannot_double_spend() {
let dir = tempdir().unwrap();
let path = dir.path().join("market.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let gate = Arc::new(Barrier::new(2));
let workers: Vec<_> = ["first", "second"]
.into_iter()
.map(|id| {
let mut db = Exchange::open(&path).unwrap();
let gate = Arc::clone(&gate);
std::thread::spawn(move || {
gate.wait();
db.execute(order(id, "bob", "buy", 90, 20)).is_ok()
})
})
.collect();
assert_eq!(
workers
.into_iter()
.map(|w| w.join().unwrap())
.filter(|v| *v)
.count(),
1
);
assert_eq!(state(&mut e)["accounts"][1]["cash"], 200);
}
#[test]
fn market_outcome_and_limit_are_isolated() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(json!({"id":"m2","op":"list","market":"other","rules":"other"}))
.unwrap();
for m in ["e", "other"] {
e.execute(json!({"id":format!("open-{m}"),"op":"open","market":m}))
.unwrap();
}
e.execute(order("ask", "alice", "sell", 65, 7)).unwrap();
for (market, outcome, price) in [("e", "YES", 60), ("e", "NO", 70), ("other", "YES", 70)] {
let mut bid = order(&format!("{market}-{outcome}"), "bob", "buy", price, 3);
bid["market"] = json!(market);
bid["outcome"] = json!(outcome);
bid["tif"] = json!("IOC");
assert_eq!(e.execute(bid).unwrap()["filled"], 0);
}
assert_eq!(state(&mut e)["fills"], json!([]));
}
#[test]
fn reboot_restores_partial_fifo_and_excludes_cancelled_orders() {
let dir = tempdir().unwrap();
let path = dir.path().join("market.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(order("ask-first", "alice", "sell", 40, 4))
.unwrap();
e.execute(order("ask-second", "alice", "sell", 40, 3))
.unwrap();
e.execute(order("cancel-me", "alice", "sell", 30, 1))
.unwrap();
e.execute(json!({"id":"cancel","op":"cancel","account":"alice","order":3}))
.unwrap();
e.execute(order("bid", "bob", "buy", 40, 2)).unwrap();
drop(e);
let mut e = Exchange::open(&path).unwrap();
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
drop(e);
// A database from the original version has live orders but no revision index.
let legacy = rusqlite::Connection::open(&path).unwrap();
legacy
.execute_batch(
"DROP TRIGGER book_insert; DROP TRIGGER book_update; DROP TABLE book_changes;",
)
.unwrap();
drop(legacy);
let mut e = Exchange::open(&path).unwrap();
e.execute(order("sweep", "bob", "buy", 40, 4)).unwrap();
let s = state(&mut e);
assert_eq!(
s["fills"],
json!([
{"seq":1,"ask":1,"bid":4,"price":40,"quantity":2},
{"seq":2,"ask":1,"bid":5,"price":40,"quantity":2},
{"seq":3,"ask":2,"bid":5,"price":40,"quantity":2}
])
);
}
#[test]
fn two_resident_books_follow_partial_fill_and_cancel() {
let dir = tempdir().unwrap();
let path = dir.path().join("market.db");
let mut a = Exchange::open(&path).unwrap();
setup(&mut a);
let mut b = Exchange::open(&path).unwrap();
a.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
a.execute(order("maker", "alice", "sell", 55, 6)).unwrap();
assert_eq!(
b.execute(order("taker", "bob", "buy", 55, 4)).unwrap()["filled"],
4
);
assert_eq!(
a.execute(json!({"id":"cancel","op":"cancel","order":1,"account":"alice"}))
.unwrap()["cancelled"],
2
);
assert_eq!(
b.execute(order("next", "bob", "buy", 55, 1)).unwrap()["filled"],
0
);
}
#[test]
fn failed_receipt_discards_planned_fill() {
let dir = tempdir().unwrap();
let path = dir.path().join("market.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
e.execute(order("ask", "alice", "sell", 55, 3)).unwrap();
let db = rusqlite::Connection::open(&path).unwrap();
db.execute_batch("CREATE TRIGGER reject_receipt BEFORE INSERT ON requests WHEN NEW.id='retry' BEGIN SELECT RAISE(ABORT,'injected'); END;").unwrap();
let bid = order("retry", "bob", "buy", 55, 3);
let before = state(&mut e);
assert!(e.execute(bid.clone()).is_err());
assert_eq!(state(&mut e), before);
db.execute_batch("DROP TRIGGER reject_receipt").unwrap();
let reply = e.execute(bid.clone()).unwrap();
assert_eq!(reply["filled"], 3);
assert_eq!(e.execute(bid).unwrap(), reply);
assert_eq!(state(&mut e)["fills"].as_array().unwrap().len(), 1);
}
#[test]
fn sports_catalog_and_trade_curve_survive_retries() {
let mut e = Exchange::open(":memory:").unwrap();
let mut catalog = Value::Null;
for line in include_str!("../../../docs/examples/football.jsonl").lines() {
catalog = e.execute(serde_json::from_str(line).unwrap()).unwrap();
}
assert_eq!(catalog["markets"].as_array().unwrap().len(), 6);
setup(&mut e);
e.execute(order("ask", "alice", "sell", 50, 2)).unwrap();
e.execute(order("bid", "bob", "buy", 50, 2)).unwrap();
let open = json!({"op":"open","id":"opening","market":"e"});
e.execute(open.clone()).unwrap();
e.execute(open).unwrap();
let query =
json!({"op":"history","market":"e","outcome":"YES","from_ms":0,"to_ms":i64::MAX,"limit":1});
let page = e.execute(query.clone()).unwrap();
let p = &page["points"][0];
assert_eq!(p["price_micros"], 500000);
assert_eq!(p["quantity"], 2);
let mut next = query;
next["after"] = json!([p["at_ms"], p["fill"]]);
assert_eq!(e.execute(next).unwrap()["points"], json!([]));
}
#[test]
fn displayed_quote_uses_midpoint_through_ten_cents_then_last_fill() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
let quote = json!({"op":"quote","market":"e","outcome":"YES"});
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
assert!(e.execute(quote.clone()).unwrap()["display_price_micros"].is_null());
e.execute(order("maker", "alice", "sell", 40, 1)).unwrap();
e.execute(order("trade", "bob", "buy", 40, 1)).unwrap();
e.execute(order("bid", "bob", "buy", 34, 1)).unwrap();
let ask = e.execute(order("ask", "alice", "sell", 44, 1)).unwrap();
assert_eq!(
e.execute(quote.clone()).unwrap()["display_price_micros"],
390000
);
e.execute(json!({"op":"cancel","id":"withdraw","account":"alice","order":ask["order"]}))
.unwrap();
e.execute(order("wider", "alice", "sell", 45, 1)).unwrap();
let display = e.execute(quote).unwrap();
assert_eq!(display["display_price_micros"], 400000);
assert_eq!(display["source"], "last_trade");
}
#[test]
fn merge_preserves_reservations_and_collateral_after_restart() {
let dir = tempdir().unwrap();
let path = dir.path().join("market.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let mut ask = order("reserved", "alice", "sell", 60, 8);
ask["outcome"] = json!("NO");
let seq = e.execute(ask).unwrap()["order"].clone();
let merge = json!({"op":"merge","id":"merge","market":"e","account":"alice","qty":3});
let before = state(&mut e);
// The YES debit must roll back when the NO side is reserved.
assert!(e.execute(merge.clone()).is_err());
assert_eq!(state(&mut e), before);
e.execute(json!({"op":"cancel","id":"free","account":"alice","order":seq}))
.unwrap();
let reply = e.execute(merge.clone()).unwrap();
assert_eq!(reply, json!({"pairs":3,"released_cents":300}));
drop(e);
let mut e = Exchange::open(&path).unwrap();
assert_eq!(e.execute(merge).unwrap(), reply);
let s = state(&mut e);
assert_eq!(s["accounts"][0]["cash"], 1300);
assert_eq!(s["markets"][0]["collateral"], 700);
assert_eq!(s["positions"].as_array().unwrap().len(), 2);
assert!(s["positions"]
.as_array()
.unwrap()
.iter()
.all(|p| p["quantity"] == 7));
assert_eq!(s["fills"], json!([]));
e.execute(json!({"op":"close","id":"close","market":"e"}))
.unwrap();
e.execute(json!({"op":"merge","id":"pending","market":"e","account":"alice","qty":2}))
.unwrap();
let payout = e
.execute(json!({"op":"resolve","id":"resolve","market":"e","winner":"YES"}))
.unwrap();
assert_eq!(payout["paid"], 500);
assert_eq!(state(&mut e)["accounts"][0]["cash"], 2000);
assert!(e
.execute(json!({"op":"merge","id":"late","market":"e","account":"alice","qty":1}))
.is_err());
}
#[test]
fn explicit_redemption_is_account_scoped_and_restart_safe() {
for (winner, bob_payout, alice_payout) in
[("YES", 300, 700), ("NO", 0, 1000), ("VOID", 150, 850)]
{
let dir = tempdir().unwrap();
let path = dir.path().join("redeem.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let claim = json!({"id":"claim","op":"redeem","market":"e","account":"bob"});
assert!(e.execute(claim.clone()).is_err());
e.execute(order("offer", "alice", "sell", 50, 3)).unwrap();
e.execute(order("buy", "bob", "buy", 50, 3)).unwrap();
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
e.execute(json!({"id":"close","op":"close","market":"e"}))
.unwrap();
let before = state(&mut e);
let final_result = e
.execute(json!({"id":"final","op":"finalize","market":"e","winner":winner}))
.unwrap();
assert_eq!(final_result["outstanding_cents"], 1000);
let after = state(&mut e);
assert_eq!(before["accounts"], after["accounts"]);
assert_eq!(before["positions"], after["positions"]);
assert!(e
.execute(json!({"id":"again","op":"finalize","market":"e","winner":"VOID"}))
.is_err());
let receipt = e.execute(claim.clone()).unwrap();
assert_eq!(receipt["paid"], bob_payout);
drop(e);
let mut e = Exchange::open(&path).unwrap();
assert_eq!(e.execute(claim).unwrap(), receipt);
assert!(e
.execute(json!({"id":"another","op":"redeem","market":"e","account":"bob"}))
.is_err());
assert_eq!(state(&mut e)["markets"][0]["collateral"], alice_payout);
assert_eq!(
e.execute(json!({"id":"alice-claim","op":"redeem","market":"e","account":"alice"}))
.unwrap()["paid"],
alice_payout
);
let final_state = state(&mut e);
assert_eq!(final_state["markets"][0]["collateral"], 0);
assert!(final_state["positions"]
.as_array()
.unwrap()
.iter()
.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);
}