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

1003 lines
40 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);
for market in catalog["markets"].as_array().unwrap() {
let direct = e
.execute(json!({"op":"assets","market":market["market"]}))
.unwrap();
assert_eq!(market["outcomes"], direct["outcomes"]);
assert_eq!(market["outcomes"][0]["label"], market["yes_label"]);
assert_eq!(market["outcomes"][1]["label"], market["no_label"]);
}
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);
}
#[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");
let trades = e
.execute(json!({"op":"trades","account":"bob","asset_id":"eb:NO:e"}))
.unwrap();
let rows = trades["trades"].as_array().unwrap();
assert_eq!(rows.len(), 2);
assert_eq!(rows[0]["role"], "taker");
assert_eq!(rows[0]["kind"], "merge");
assert_eq!(rows[0]["gross_cents"], 450);
assert_eq!(rows[1]["kind"], "mint");
assert_eq!(rows[1]["role"], "auction");
assert_eq!(rows[1]["gross_cents"], 400);
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);
}
#[test]
fn book_groups_direct_and_complementary_remaining_size() {
let dir = tempdir().unwrap();
let path = dir.path().join("depth.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let yes = json!({"op":"book","market":"e","outcome":"YES"});
let no = json!({"op":"book","market":"e","outcome":"NO"});
assert_eq!(e.execute(yes.clone()).unwrap()["asks"], json!([]));
e.execute(json!({"op":"open","id":"open","market":"e"}))
.unwrap();
e.execute(order("direct", "alice", "sell", 60, 3)).unwrap();
let mut mirrored = order("mirrored", "bob", "buy", 40, 4);
mirrored["outcome"] = json!("NO");
let seq = e.execute(mirrored).unwrap()["order"].clone();
e.execute(order("dearer", "alice", "sell", 65, 1)).unwrap();
let levels = e.execute(yes.clone()).unwrap();
assert_eq!(
levels["asks"],
json!([{"price_micros":600000,"size":7},{"price_micros":650000,"size":1}])
);
assert_eq!(levels["bids"], json!([]));
let inverse = e.execute(no.clone()).unwrap();
assert_eq!(
inverse["bids"],
json!([{"price_micros":400000,"size":7},{"price_micros":350000,"size":1}])
);
e.execute(order("partial", "bob", "buy", 60, 2)).unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(e.execute(yes.clone()).unwrap()["asks"][0]["size"], 5);
e.execute(json!({"op":"cancel","id":"withdraw","account":"bob","order":seq}))
.unwrap();
assert_eq!(e.execute(yes).unwrap()["asks"][0]["size"], 1);
assert_eq!(e.execute(no).unwrap()["bids"][0]["size"], 1);
assert!(e
.execute(json!({"op":"book","market":"missing","outcome":"YES"}))
.is_err());
assert!(e
.execute(json!({"op":"book","market":"e","outcome":"other"}))
.is_err());
}
#[test]
fn account_order_pages_track_partial_fills_and_terminal_orders() {
let dir = tempdir().unwrap();
let path = dir.path().join("orders.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(json!({"op":"open","id":"start","market":"e"}))
.unwrap();
let first = e.execute(order("first", "alice", "sell", 60, 5)).unwrap()["order"].clone();
let second = e.execute(order("second", "alice", "sell", 65, 2)).unwrap()["order"].clone();
let buy = e.execute(order("take", "bob", "buy", 60, 2)).unwrap()["order"].clone();
let page = json!({"op":"open_orders","account":"alice","market":"e","outcome":"YES","limit":1});
let result = e.execute(page.clone()).unwrap();
assert_eq!(result["orders"][0]["original_size"], 5);
assert_eq!(result["orders"][0]["size_matched"], 2);
assert_eq!(result["orders"][0]["open_size"], 3);
assert_eq!(result["next_after"], first);
let mut rest = page.clone();
rest["after"] = result["next_after"].clone();
let result = e.execute(rest).unwrap();
assert_eq!(result["orders"][0]["order"], second);
assert!(result["next_after"].is_null());
e.execute(json!({"op":"cancel","id":"remove","account":"alice","order":first}))
.unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
let listed = e.execute(page).unwrap();
assert_eq!(listed["orders"][0]["order"], second);
let lookup = json!({"op":"open_orders","account":"alice","order":first});
let closed = e.execute(lookup.clone()).unwrap();
assert_eq!(closed["orders"][0]["status"], "cancelled");
assert_eq!(closed["orders"][0]["size_matched"], 2);
assert_eq!(closed["orders"][0]["open_size"], 0);
let mut foreign = lookup;
foreign["account"] = json!("bob");
assert_eq!(e.execute(foreign).unwrap()["orders"], json!([]));
let filled = e
.execute(json!({"op":"open_orders","account":"bob","order":buy}))
.unwrap();
assert_eq!(filled["orders"][0]["status"], "filled");
assert_eq!(filled["orders"][0]["size_matched"], 2);
assert_eq!(
e.execute(json!({"op":"open_orders","account":"bob"}))
.unwrap()["orders"],
json!([])
);
}
#[test]
fn portfolio_tracks_reserved_pairs_partial_sale_and_redemption() {
let dir = tempdir().unwrap();
let path = dir.path().join("positions.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(json!({"op":"open","id":"start","market":"e"}))
.unwrap();
let ask = e.execute(order("ask", "alice", "sell", 60, 10)).unwrap();
let list = json!({"op":"positions","account":"alice","market":"e"});
let find_yes = |page: Value| {
page["positions"]
.as_array()
.unwrap()
.iter()
.find(|p| p["outcome"] == "YES")
.unwrap()
.clone()
};
let held = find_yes(e.execute(list.clone()).unwrap());
assert_eq!(held["size"], 10);
assert_eq!(held["available_size"], 0);
assert_eq!(held["reserved_size"], 10);
assert_eq!(held["mergeable"], true);
assert_eq!(held["available_pairs"], 0);
e.execute(order("take", "bob", "buy", 60, 2)).unwrap();
let held = find_yes(e.execute(list.clone()).unwrap());
assert_eq!(held["size"], 8);
assert_eq!(held["reserved_size"], 8);
e.execute(json!({"op":"cancel","id":"free","account":"alice","order":ask["order"]}))
.unwrap();
assert_eq!(
find_yes(e.execute(list.clone()).unwrap())["available_pairs"],
8
);
e.execute(json!({"op":"close","id":"close","market":"e"}))
.unwrap();
e.execute(json!({"op":"finalize","id":"result","market":"e","winner":"YES"}))
.unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(
find_yes(e.execute(list.clone()).unwrap())["payout_cents"],
800
);
let mut page = json!({"op":"positions","account":"alice","status":"REDEEMABLE","limit":1});
let first = e.execute(page.clone()).unwrap();
assert_eq!(first["positions"][0]["outcome"], "YES");
page["after"] = first["next_after"].clone();
let second = e.execute(page).unwrap();
assert_eq!(second["positions"][0]["outcome"], "NO");
assert!(second["next_after"].is_null());
let lost = e
.execute(json!({"op":"positions","account":"alice","status":"REDEEMABLE_LOST"}))
.unwrap();
assert_eq!(lost["positions"][0]["status"], "REDEEMABLE");
assert_eq!(lost["positions"][0]["payout_cents"], 0);
e.execute(json!({"op":"redeem","id":"collect","account":"alice","market":"e"}))
.unwrap();
assert_eq!(e.execute(list).unwrap()["positions"], json!([]));
let closed = e
.execute(json!({"op":"positions","account":"alice","status":"CLOSED"}))
.unwrap();
assert_eq!(closed["positions"].as_array().unwrap().len(), 2);
let other = e
.execute(json!({"op":"positions","account":"bob"}))
.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);
}
#[test]
fn asset_discovery_and_routing_share_one_orderbook_across_restart() {
let dir = tempdir().unwrap();
let path = dir.path().join("assets.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let market = "杯赛:NO:决赛";
e.execute(json!({"op":"list","id":"new","market":market,"rules":"official"}))
.unwrap();
let discovery = json!({"op":"assets","market":market});
let assets = e.execute(discovery.clone()).unwrap()["outcomes"].clone();
let yes = assets[0]["asset_id"].clone();
let no = assets[1]["asset_id"].clone();
assert_ne!(yes, no);
e.execute(json!({"op":"split","id":"pairs","account":"alice","market":market,"qty":3}))
.unwrap();
e.execute(json!({"op":"open","id":"open","market":market}))
.unwrap();
let ask = json!({"op":"order","id":"offer","asset_id":yes,"account":"alice","side":"sell","price":47,"qty":3});
let receipt = e.execute(ask.clone()).unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(e.execute(discovery).unwrap()["outcomes"], assets);
assert_eq!(e.execute(ask).unwrap(), receipt);
let book = e.execute(json!({"op":"book","asset_id":yes})).unwrap();
assert_eq!(
book,
e.execute(json!({"op":"book","market":market,"outcome":"YES"}))
.unwrap()
);
assert_eq!(book["asks"][0]["size"], 3);
let opposite = e.execute(json!({"op":"quote","asset_id":no})).unwrap();
assert_eq!(opposite["best_bid_micros"], 530000);
let mut buy = order("take", "bob", "buy", 47, 2);
buy["market"] = json!(market);
let mut conflicting = buy.clone();
conflicting["asset_id"] = no.clone();
assert!(e.execute(conflicting).is_err());
assert_eq!(e.execute(buy).unwrap()["filled"], 2);
let history = e
.execute(json!({"op":"history","asset_id":yes,"from_ms":0,"to_ms":i64::MAX,"limit":10}))
.unwrap();
assert_eq!(history["points"][0]["quantity"], 2);
assert_eq!(history["asset_id"], yes);
let live = e
.execute(json!({"op":"open_orders","asset_id":yes,"account":"alice"}))
.unwrap();
assert_eq!(live["orders"][0]["open_size"], 1);
assert_eq!(live["orders"][0]["asset_id"], yes);
let held = e
.execute(json!({"op":"positions","market":market,"account":"bob"}))
.unwrap();
assert_eq!(held["positions"][0]["asset_id"], yes);
for asset in ["eb:YES:unlisted", "eb:DRAW:e", "venue:123"] {
assert!(e.execute(json!({"op":"book","asset_id":asset})).is_err());
}
}
#[test]
fn account_fills_page_both_order_legs_and_reconcile_after_restart() {
let dir = tempdir().unwrap();
let path = dir.path().join("trades.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(json!({"op":"open","id":"go","market":"e"}))
.unwrap();
let ask = e.execute(order("offer", "alice", "sell", 47, 4)).unwrap()["order"].clone();
let own = e.execute(order("own", "alice", "buy", 50, 2)).unwrap()["order"].clone();
let buy = order("take", "bob", "buy", 49, 1);
let receipt = e.execute(buy.clone()).unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(e.execute(buy).unwrap(), receipt);
let mut q = json!({"op":"trades","account":"alice","limit":2});
let page = e.execute(q.clone()).unwrap();
let legs = page["trades"].as_array().unwrap();
assert_eq!(legs.len(), 2);
assert_eq!(legs[0]["order"], ask);
assert_eq!(legs[0]["role"], "maker");
assert_eq!(legs[0]["price_micros"], 470000);
assert_eq!(legs[1]["order"], own);
assert_eq!(legs[1]["side"], "buy");
q["after"] = page["next_after"].clone();
let page = e.execute(q).unwrap();
assert!(page["next_after"].is_null());
assert_eq!(page["trades"][0]["execution"], legs[1]["execution"]);
assert_eq!(page["trades"][0]["order"], ask);
let matched = e
.execute(json!({"op":"trades","account":"alice","order":ask}))
.unwrap();
assert_eq!(
matched["trades"]
.as_array()
.unwrap()
.iter()
.map(|r| r["size"].as_i64().unwrap())
.sum::<i64>(),
3
);
assert_eq!(
e.execute(json!({"op":"trades","account":"bob","order":ask}))
.unwrap()["trades"],
json!([])
);
}
#[test]
fn contested_resolution_blocks_both_payout_paths_until_a_verdict() {
let dir = tempdir().unwrap();
let path = dir.path().join("oracle.db");
let mut e = Exchange::open(&path).unwrap();
e.execute(json!({"op":"fund","id":"fund","account":"alice","cents":1000}))
.unwrap();
e.execute(
json!({"op":"list","id":"list","market":"m","rules":"official outcome",
"resolution":{"kind":"optimistic","eligible_at":0}}),
)
.unwrap();
e.execute(json!({"op":"split","id":"split","account":"alice","market":"m","qty":2}))
.unwrap();
e.execute(json!({"op":"close","id":"close","market":"m"}))
.unwrap();
let status = json!({"op":"resolution","market":"m"});
let make = |id: &str| json!({"op":"propose","id":id,"market":"m","winner":"YES","proposer":"alice","evidence":"score sheet"});
let challenge = |id: &str, p: &Value| json!({"op":"dispute","id":id,"market":"m","proposal":p,"challenger":"bob","evidence":"corrected score"});
let first = e.execute(make("p1")).unwrap()["proposal"].clone();
for op in ["finalize", "resolve"] {
assert!(e
.execute(json!({"op":op,"id":op,"market":"m","winner":"YES"}))
.is_err());
}
let c = challenge("d1", &first);
let receipt = e.execute(c.clone()).unwrap();
assert_eq!(receipt["status"], "awaiting_second_proposal");
let second = e.execute(make("p2")).unwrap()["proposal"].clone();
assert!(e.execute(challenge("obsolete", &first)).is_err());
assert_eq!(e.execute(c).unwrap(), receipt);
e.execute(challenge("d2", &second)).unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(
e.execute(status.clone()).unwrap()["status"],
"awaiting_arbitration"
);
let redeem = json!({"op":"redeem","id":"claim","market":"m","account":"alice"});
assert!(e.execute(redeem.clone()).is_err());
let decision = json!({"op":"adjudicate","id":"verdict","market":"m","proposal":second,"verdict":"NO","evidence":"simulated vote record"});
let finalized = e.execute(decision.clone()).unwrap();
assert_eq!(e.execute(decision).unwrap(), finalized);
let resolved = e.execute(status).unwrap();
assert_eq!(resolved["winner"], "NO");
assert_eq!(resolved["proposals"][1]["verdict"], "NO");
assert_eq!(resolved["proposals"][0]["challenger"], "bob");
assert_eq!(e.execute(redeem).unwrap()["paid"], 200);
}
#[test]
fn unchallenged_second_proposal_only_clears_its_own_outcome() {
let dir = tempdir().unwrap();
let path = dir.path().join("unchallenged.db");
let mut e = Exchange::open(&path).unwrap();
e.execute(
json!({"op":"list","id":"list","market":"m","rules":"official",
"resolution":{"kind":"optimistic","eligible_at":0}}),
)
.unwrap();
e.execute(json!({"op":"close","id":"close","market":"m"}))
.unwrap();
let proposal = |id: &str, winner: &str| {
json!({"op":"propose","id":id,"market":"m","winner":winner,
"proposer":"a","evidence":"observed result"})
};
let first = e.execute(proposal("first", "YES")).unwrap();
e.execute(
json!({"op":"dispute","id":"challenge","market":"m","proposal":first["proposal"],
"challenger":"b","evidence":"corrected result"}),
)
.unwrap();
let second = e.execute(proposal("second", "NO")).unwrap();
let finalize =
|winner: &str| json!({"op":"finalize","id":"finish","market":"m","winner":winner});
assert!(e.execute(finalize("NO")).is_err());
let db = rusqlite::Connection::open(&path).unwrap();
db.execute(
"UPDATE resolution_proposals SET proposed_at=unixepoch()-7200 WHERE id=?",
[second["proposal"].as_i64().unwrap()],
)
.unwrap();
assert!(e.execute(finalize("YES")).is_err());
assert_eq!(e.execute(finalize("NO")).unwrap()["winner"], "NO");
}
#[test]
fn twap_market_closes_before_settlement_and_reuses_exact_observations() {
let dir = tempdir().unwrap();
let path = dir.path().join("twap.db");
let mut e = Exchange::open(&path).unwrap();
let db = rusqlite::Connection::open(&path).unwrap();
let now: i64 = db
.query_row("SELECT unixepoch()", [], |r| r.get(0))
.unwrap();
let start = now - 300;
let end = now - 1;
e.execute(json!({"op":"fund","id":"a","account":"alice","cents":1000}))
.unwrap();
e.execute(
json!({"op":"list","id":"l","market":"m","rules":"final >= opening is Up",
"resolution":{"kind":"twap","stream":"test/btc-usd","start_at":start,"end_at":now+600}}),
)
.unwrap();
e.execute(json!({"op":"split","id":"s","market":"m","account":"alice","qty":3}))
.unwrap();
e.execute(json!({"op":"open","id":"o","market":"m"}))
.unwrap();
e.execute(json!({"op":"order","id":"sell","market":"m","account":"alice","side":"sell","outcome":"YES","price":50,"qty":3})).unwrap();
let observe = |id: &str, t: i64, price: &str| {
json!({"op":"observe","id":id,"market":"m","stream":"test/btc-usd",
"price":price,"observed_at":t,"evidence":"simulated-report"})
};
e.execute(observe("initial", start, "0100.0000000000000000010"))
.unwrap();
assert!(e.execute(observe("future", now + 600, "200")).is_err());
db.execute("UPDATE twap_markets SET end_at=? WHERE market='m'", [end])
.unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
let report = json!({"op":"resolution","market":"m"});
assert_eq!(
e.execute(report.clone()).unwrap()["status"],
"awaiting_observations"
);
assert_eq!(state(&mut e)["orders"][0]["status"], "cancelled");
let finish = json!({"op":"finalize","id":"f","market":"m"});
assert!(e.execute(finish.clone()).is_err());
assert!(e
.execute(json!({"op":"resolve","id":"bypass","market":"m","winner":"YES"}))
.is_err());
assert!(e.execute(observe("wrong-time", end - 1, "100")).is_err());
let mut wrong_stream = observe("wrong-stream", end, "100");
wrong_stream["stream"] = json!("test/other");
assert!(e.execute(wrong_stream).is_err());
e.execute(observe("end", end, "100.000000000000000000"))
.unwrap();
e.execute(observe("same", end, "100")).unwrap();
assert!(e.execute(observe("conflict", end, "101")).is_err());
let detail = e.execute(report).unwrap();
assert_eq!(detail["computed_winner"], "NO");
assert_eq!(detail["opening"], "100.000000000000000001");
assert_eq!(e.execute(finish).unwrap()["winner"], "NO");
assert_eq!(
e.execute(json!({"op":"redeem","id":"claim","market":"m","account":"alice"}))
.unwrap()["paid"],
300
);
}