from concurrent.futures import ThreadPoolExecutor from threading import Barrier import tempfile import unittest from pathlib import Path from exchange import Exchange, Rejected class MarketTest(unittest.TestCase): def setUp(self): folder = tempfile.TemporaryDirectory() self.addCleanup(folder.cleanup) self.path = Path(folder.name) / "market.db" self.engine = Exchange(self.path) self.addCleanup(lambda: self.engine.db.close()) self.seq = 0 for account in ("alice", "bob", "carol"): self.cmd("fund", account=account, cents=2000) self.cmd("list", market="E1", rules="YES on official result, NO otherwise; void pays 50 each") self.cmd("split", account="alice", market="E1", qty=10) def cmd(self, op, **body): self.seq += 1 result = self.engine.execute(dict(id=str(self.seq), op=op, **body)) self.check_totals() return result def check_totals(self): state = self.engine.execute({"op": "state"}) live = [r for r in state["orders"] if r["status"] == "live"] reserved = sum(r["price"] * r["remaining"] for r in live if r["side"] == "buy") total = sum(a["cash"] for a in state["accounts"]) + reserved self.assertEqual(total + sum(m["collateral"] for m in state["markets"]), 2000 * len(state["accounts"])) for market in state["markets"]: for outcome in ("YES", "NO"): free = sum(p["quantity"] for p in state["positions"] if (p["market"], p["outcome"]) == (market["id"], outcome)) locked = sum(r["remaining"] for r in live if r["side"] == "sell" and (r["market"], r["outcome"]) == (market["id"], outcome)) self.assertEqual((free + locked) * 100, market["collateral"]) def order(self, account, side, price, qty, **extra): return self.cmd("order", account=account, market="E1", outcome="YES", side=side, price=price, qty=qty, **extra) def test_open_fifo_ioc_and_settlement(self): a = self.order("alice", "sell", 40, 2)["order"] b = self.order("alice", "sell", 40, 5)["order"] self.order("bob", "buy", 60, 4) self.assertEqual(self.engine.execute({"op": "state"})["fills"], []) self.cmd("open", market="E1") fills = self.engine.execute({"op": "state"})["fills"] self.assertEqual([(f["ask"], f["quantity"], f["price"]) for f in fills], [(a, 2, 40), (b, 2, 40)]) self.assertEqual(self.order("carol", "buy", 45, 6, tif="IOC")["filled"], 3) self.order("bob", "buy", 10, 8) self.cmd("close", market="E1") self.assertEqual(self.cmd("resolve", market="E1", winner="YES")["paid"], 1000) cash = {a["id"]: a["cash"] for a in self.engine.execute({"op": "state"})["accounts"]} self.assertEqual(cash, {"alice": 1580, "bob": 2240, "carol": 2180}) def test_restart_retry_and_rejection(self): op = dict(op="order", id="retry", market="E1", outcome="NO", side="sell", price=45, qty=3, account="alice") first = self.engine.execute(op) self.engine.db.close() self.engine = Exchange(self.path) self.assertEqual(self.engine.execute(op), first) with self.assertRaises(Rejected): self.engine.execute(dict(op, qty=4)) before = self.engine.execute({"op": "state"}) with self.assertRaises(Rejected): self.order("bob", "buy", 100, 21) with self.assertRaises(Rejected): self.cmd("cancel", account="bob", order=first["order"]) self.assertEqual(before, self.engine.execute({"op": "state"})) self.cmd("cancel", account="alice", order=first["order"]) self.cmd("close", market="E1") self.cmd("resolve", market="E1", winner="VOID") def test_two_connections_cannot_spend_the_same_cash(self): ready = Barrier(2) def submit(key): engine = Exchange(self.path) try: ready.wait(timeout=5) engine.execute(dict(id=key, op="order", account="bob", market="E1", outcome="YES", side="buy", price=90, qty=20)) return True except Rejected: return False finally: engine.db.close() with ThreadPoolExecutor(max_workers=2) as pool: self.assertEqual(sorted(pool.map(submit, ("concurrent-a", "concurrent-b"))), [False, True]) self.check_totals() def test_isolation_and_price_protection(self): self.cmd("list", market="E2", rules="another event") self.cmd("open", market="E2") self.cmd("open", market="E1") self.order("alice", "sell", 65, 7) reply = self.order("bob", "buy", 60, 10, tif="IOC") self.assertEqual(reply["filled"], 0) for market, outcome in (("E1", "NO"), ("E2", "YES")): reply = self.cmd("order", account="carol", market=market, outcome=outcome, side="buy", price=70, qty=2, tif="IOC") self.assertEqual(reply["filled"], 0) if __name__ == "__main__": unittest.main()