"""Trusted local simulator. One input command commits as a single database transaction.""" import argparse import json from pathlib import Path import sqlite3 import sys from matching import Order, match class Rejected(ValueError): pass def require(condition, message): if not condition: raise Rejected(message) def amount(value): require(type(value) is int and 0 < value <= 10**9, "expected positive integer <= 1 billion") return value def identifier(value): require(type(value) is str and 0 < len(value.strip()) <= 256, "invalid identifier") return value class Exchange: def __init__(self, path): self.db = sqlite3.connect(path, isolation_level=None, timeout=10) self.db.row_factory = sqlite3.Row self.db.execute("PRAGMA foreign_keys=ON") self.db.executescript(Path(__file__).with_name("schema.sql").read_text()) def execute(self, command): require(isinstance(command, dict), "expected an object") if command == {"op": "state"}: self.db.execute("BEGIN") try: return {t: [dict(r) for r in self.db.execute(f"SELECT * FROM {t} ORDER BY rowid")] for t in ("markets", "accounts", "positions", "orders", "fills")} finally: self.db.rollback() body = dict(command) key = identifier(body.pop("id", None)) op = body.pop("op", None) actions = {"fund": self.fund, "list": self.list_market, "split": self.split, "order": self.order, "cancel": self.cancel, "open": self.open_market, "close": self.close_market, "resolve": self.resolve} require(isinstance(op, str) and op in actions, "unknown operation") payload = json.dumps(command, sort_keys=True, allow_nan=False) self.db.execute("BEGIN IMMEDIATE") try: prior = self.db.execute("SELECT * FROM requests WHERE id=?", (key,)).fetchone() if prior: require(prior["payload"] == payload, "request id reused with different content") result = json.loads(prior["response"]) else: result = actions[op](**body) self.db.execute("INSERT INTO requests VALUES(?,?,?)", (key, payload, json.dumps(result))) self.db.commit() return result except BaseException: self.db.rollback() raise def fund(self, account, cents): identifier(account) amount(cents) exists = self.db.execute("SELECT 1 FROM accounts WHERE id=?", (account,)).fetchone() require(not exists, "account already funded") self.db.execute("INSERT INTO accounts VALUES(?,?)", (account, cents)) return {"funded": cents} def list_market(self, market, rules): identifier(market) require(type(rules) is str and rules.strip(), "rules required") self.db.execute("INSERT INTO markets(id,rules,phase) VALUES(?,?,'preopen')", (market, rules)) return {"phase": "preopen"} def phase(self, market, *allowed): row = self.db.execute("SELECT phase FROM markets WHERE id=?", (identifier(market),)).fetchone() require(row and row[0] in allowed, "unknown market or wrong phase") return row[0] def cash(self, account, delta): updated = self.db.execute("UPDATE accounts SET cash=cash+? WHERE id=? AND cash+?>=0", (delta, identifier(account), delta)) require(updated.rowcount == 1, "unknown account or insufficient cash") def position(self, account, market, outcome, delta): self.db.execute("INSERT OR IGNORE INTO positions VALUES(?,?,?,0)", (account, market, outcome)) updated = self.db.execute("""UPDATE positions SET quantity=quantity+? WHERE account=? AND market=? AND outcome=? AND quantity+?>=0""", (delta, account, market, outcome, delta)) require(updated.rowcount == 1, "insufficient position") def split(self, account, market, qty): self.phase(market, "preopen", "continuous") value = 100 * amount(qty) self.cash(account, -value) self.db.execute("UPDATE markets SET collateral=collateral+? WHERE id=?", (value, market)) for outcome in ("YES", "NO"): self.position(account, market, outcome, qty) return {"pairs": qty} def order(self, account, market, outcome, side, price, qty, tif="GTC"): phase = self.phase(market, "preopen", "continuous") require(outcome in ("YES", "NO") and side in ("buy", "sell"), "invalid instrument or side") require(type(price) is int and 0 <= price <= 100, "price outside 0..100 cents") amount(qty) require(tif == "GTC" or (tif == "IOC" and phase == "continuous"), "unsupported time in force") if side == "buy": self.cash(account, -price * qty) else: self.position(identifier(account), market, outcome, -qty) seq = self.db.execute("""INSERT INTO orders(account,market,outcome,side,price,quantity,remaining,status) VALUES(?,?,?,?,?,?,?,'live')""", (account, market, outcome, side, price, qty, qty)).lastrowid if phase == "continuous": self.cross(market, outcome) row = self.db.execute("SELECT * FROM orders WHERE seq=?", (seq,)).fetchone() if tif == "IOC" and row["remaining"]: self.release(row) return {"order": seq, "filled": qty - row["remaining"], "status": "cancelled" if tif == "IOC" and row["remaining"] else row["status"]} def cross(self, market, outcome, opening=False): rows = self.db.execute("""SELECT seq,account,side,price,remaining FROM orders WHERE market=? AND outcome=? AND status='live'""", (market, outcome)) orders = [Order(**dict(row)) for row in rows] for f in match(orders, opening=opening): self.cash(f.ask.account, f.price * f.quantity) self.cash(f.bid.account, (f.bid.price - f.price) * f.quantity) self.position(f.bid.account, market, outcome, f.quantity) self.db.execute("INSERT INTO fills(bid,ask,price,quantity) VALUES(?,?,?,?)", (f.bid.seq, f.ask.seq, f.price, f.quantity)) for seq in (f.bid.seq, f.ask.seq): self.db.execute("""UPDATE orders SET remaining=remaining-?, status=CASE WHEN remaining=? THEN 'filled' ELSE 'live' END WHERE seq=?""", (f.quantity, f.quantity, seq)) def release(self, row): qty = row["remaining"] if row["side"] == "buy": self.cash(row["account"], qty * row["price"]) else: self.position(row["account"], row["market"], row["outcome"], qty) self.db.execute("UPDATE orders SET status='cancelled' WHERE seq=?", (row["seq"],)) def cancel(self, account, order): row = self.db.execute("SELECT * FROM orders WHERE seq=? AND account=? AND status='live'", (amount(order), identifier(account))).fetchone() require(row, "no live order for account") self.release(row) return {"cancelled": row["remaining"]} def open_market(self, market): self.phase(market, "preopen") for outcome in ("YES", "NO"): self.cross(market, outcome, opening=True) self.db.execute("UPDATE markets SET phase='continuous' WHERE id=?", (market,)) return {"phase": "continuous"} def close_market(self, market): self.phase(market, "continuous", "preopen") for row in self.db.execute("SELECT * FROM orders WHERE market=? AND status='live'", (market,)).fetchall(): self.release(row) self.db.execute("UPDATE markets SET phase='closed' WHERE id=?", (market,)) return {"phase": "closed"} def resolve(self, market, winner): self.phase(market, "closed") require(winner in ("YES", "NO", "VOID"), "winner must be YES, NO or VOID") total = 0 for row in self.db.execute("SELECT * FROM positions WHERE market=?", (market,)): per_share = 50 if winner == "VOID" else 100 * (winner == row["outcome"]) payout = row["quantity"] * per_share self.cash(row["account"], payout) total += payout changed = self.db.execute("""UPDATE markets SET collateral=0,phase='resolved',winner=? WHERE id=? AND collateral=?""", (winner, market, total)) require(changed.rowcount == 1, "collateral does not cover payouts exactly") self.db.execute("UPDATE positions SET quantity=0 WHERE market=?", (market,)) return {"phase": "resolved", "paid": total} def main(): parser = argparse.ArgumentParser() parser.add_argument("database") engine = Exchange(parser.parse_args().database) try: for line in sys.stdin: try: result = engine.execute(json.loads(line)) except (ValueError, TypeError, sqlite3.IntegrityError) as exc: result = {"error": str(exc)} print(json.dumps(result, ensure_ascii=False), flush=True) finally: engine.db.close() if __name__ == "__main__": main()