From b7579603f93a0aea792ff6b6547f7c634fc9af22 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Thu, 3 Dec 2026 02:47:35 +0800 Subject: [PATCH 1/2] Implement a persistent binary prediction market simulator --- .gitignore | 3 + README.md | 39 +++++++ docs/sequences.md | 265 ++++++++++++++++++++++++++++++++++++++++++++++ exchange.py | 205 +++++++++++++++++++++++++++++++++++ matching.py | 52 +++++++++ schema.sql | 24 +++++ test_exchange.py | 110 +++++++++++++++++++ 7 files changed, 698 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 docs/sequences.md create mode 100644 exchange.py create mode 100644 matching.py create mode 100644 schema.sql create mode 100644 test_exchange.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..23f2f96 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +*.db +*.db-* diff --git a/README.md b/README.md new file mode 100644 index 0000000..05503f8 --- /dev/null +++ b/README.md @@ -0,0 +1,39 @@ +# Eventbook Exchange + +用模拟资金验证预测市场的交易与兑付规则。这个版本是可信操作员使用的单机命令程序。Python 3.10+,只依赖标准库。订单簿由 SQLite 中该合约的有效订单重建,每条命令在一次写事务中完成冻结、成交、余量、余额和回执更新。客户端看到的成功回执均已提交。 + +完整设计见[交易系统时序图](docs/sequences.md)。单机版覆盖本地下单、开盘与连续交易、全额抵押发行和账本兑付。 + +## 跑一笔交易 + +在仓库根目录执行以下示例,每次演示使用一份新的数据库。程序从标准输入逐行接收 JSON,逐行返回结果。模拟货币的单位为分,每对 YES/NO 足额抵押 100 分。 + +```sh +python3 -B exchange.py demo.db <<'ORDERS' +{"id":"1","op":"fund","account":"seller","cents":1000} +{"id":"2","op":"fund","account":"buyer","cents":1000} +{"id":"3","op":"list","market":"game-1","rules":"按比赛官方终局结果判定,主队胜为 YES,其余为 NO,作废每边兑付 50 分"} +{"id":"4","op":"split","account":"seller","market":"game-1","qty":5} +{"id":"5","op":"order","account":"seller","market":"game-1","outcome":"YES","side":"sell","price":55,"qty":5} +{"id":"6","op":"order","account":"buyer","market":"game-1","outcome":"YES","side":"buy","price":60,"qty":3} +{"id":"7","op":"open","market":"game-1"} +{"id":"8","op":"order","account":"buyer","market":"game-1","outcome":"YES","side":"buy","price":55,"qty":4,"tif":"IOC"} +{"id":"9","op":"close","market":"game-1"} +{"id":"10","op":"resolve","market":"game-1","winner":"YES"} +{"op":"state"} +ORDERS +``` + +开盘统一价为 55 分,先成交 3 份。盘中 IOC 吃掉剩余 2 份,取消缺少对手的 2 份。到期卖方有 775 分、买方有 1225 分,两者合计仍是 2000 分。将同样的命令再次提交到同一数据库,可以检验重试后余额保持一致。 + +## 执行规则 + +- 交易品由永久的市场 ID 与结果 YES 或 NO 共同标识。规则随市场上市保存。操作员用 open、close 和 resolve 显式推进交易阶段,VOID 对两个结果各兑付 50 分。 +- 盘前接收和撤销 GTC 限价单。开盘在 0 至 100 的整数价位中依次选最大成交量、最小供需差和最低价。同侧按价格和受理序号分配。连续交易以较早的挂单价成交,支持持续有效的 GTC 和带保护价的 IOC。 +- 撤单提供订单受理时返回的整数 order 字段及账户。已撤销订单的 remaining 记录撤销时的余量,只有 live 订单仍有冻结。账户 cash 和持仓 quantity 均表示可用量。 +- 写请求携带全局唯一的字符串 id,重试时返回初次回执。内容冲突或余额不足时回滚。state 读取所有账户与订单的一致快照,只供本地调试。 +- 首版允许模拟账户自行拆分全额抵押的成套份额。分片主备、跨簿互补撮合、自动裁决、外部执行、链上、篮子发行、Web 和 Bot 属于后续阶段。账户身份由可信调用方指定,程序没有网络监听或真实资产入口。 + +## 检查 + +运行 `python3 -B -m unittest -v`。用例在独立临时数据库中检查统一开盘价、同价排队、部分成交、撤单、价格保护、合约隔离、重启重试、拒单回滚和到期兑付。在各次成功命令后核对现金、冻结额、抵押额和两边份额守恒。 diff --git a/docs/sequences.md b/docs/sequences.md new file mode 100644 index 0000000..0b1413c --- /dev/null +++ b/docs/sequences.md @@ -0,0 +1,265 @@ +# 预测市场交易系统 · 原生 UML 时序图 + +这是一套拟议设计,可用模拟资产独立运行。图 1–3 更新上一版的下单、内存订单簿和故障接管流程。图中的数据库事务假设首版的订单、账本、待处理命令和待发布事件共用一个 PostgreSQL 集群。不同框表示职责,只有需要独立运行时才拆为进程。 + +## 1 · Web 和 Telegram 提交一笔本地委托 + +```mermaid +sequenceDiagram + actor U as 用户 + participant C as Web 或 Telegram Bot + participant G as 接入网关集群 + participant O as 订单服务 + participant D as PostgreSQL + participant Z as ZeroMQ + participant W as 分片主节点 + participant P as 回报推送 + U->>C: 确认限价、数量和执行场所 + C->>G: 账户凭证、客户订单键、交易品 ID + G->>O: 验证身份、限流后提交 + O->>D: 同一事务去重、校验交易状态、冻结资金或持仓、追加带序号的命令 + D-->>O: 提交成功,返回原有或新订单号 + O-->>C: 已受理,可按订单号查询 + O->>Z: 通知相应分片有新命令 + Z-->>W: 唤醒,漏通知时由定期扫描补齐 + W->>D: 顺序读取已受理命令 + W->>W: 计算内存订单簿变更 + W->>D: 校验写入代次和前序号,原子写成交、账本、簿变更和待发事件 + D-->>W: 提交成功后应用内存变更 + P->>D: 按游标取已提交事件 + P-->>C: Web 私有推送或 Bot 通知,可按订单号补查 +``` + +相同客户订单键和内容重试返回原订单,相同键配不同内容拒绝。任一网关实例均可接续会话。Bot 用绑定账户和一次确认令牌识别同一次点击。账户可用额的检查和冻结串行生效,保证两个入口同时下单时不会重复花钱。 + +## 2 · 不同合约如何共用一台内存撮合机 + +```mermaid +sequenceDiagram + participant R as 路由表 + participant W as 分片 S3 的唯一写进程 + participant A as 内存簿 A + participant B as 内存簿 B + participant D as PostgreSQL + R-->>W: 本分片负责 A 和 B,各自有独立的买卖盘 + W->>D: 按序读取买 A 的指令,限价 0.60,数量 10 + W->>A: 用 book_id 定位 A,取最低卖价及同价 FIFO 队列 + A-->>W: 0.60 有 3 份,下一档 0.65 有 7 份 + W->>W: 拟成交 3 份;GTC 余 7 份挂 0.60,IOC 余量撤销 + W->>D: 原子提交成交、余量、新序号及解冻差额 + D-->>W: 已提交 + W->>A: 应用已提交变更 + R-->>W: 下一条命令的 book_id 为 B + W->>B: 只查 B 的价位及时间队列 +``` + +每个簿维护买卖价位、同价 FIFO 和按 order_id 撤单的索引。跨交易品并行靠分片,同一簿内按序处理。若允许互补结果跨簿撮合或整套份额转换,将共享抵押的各簿划到同一撮合组,由同一写入者提交整组变动。 + +## 3 · 已受理订单遇到撮合节点宕机 + +```mermaid +sequenceDiagram + participant O as 旧撮合主节点 + participant C as 集群协调器 + participant D as PostgreSQL 主库 + participant S as 同步备库 + participant N as 新撮合主节点 + O->>D: 以代次 17 尝试提交命令 105 + D->>S: 复制提交日志,按同步持久化策略确认 + C->>D: 在同一权威库比较并更新分片写入代次至 18 + N->>D: 取得新代次,读快照、已提交增量和最后处理序号 + alt 命令 105 已提交 + N->>N: 重建到 105,从 106 继续 + else 最后提交的是 104 + N->>D: 读取待处理的 105,以代次 18 处理一次 + end + O->>D: 迟到的代次 17 请求 + D-->>O: 拒绝旧写入者 +``` + +即使旧进程仍存活,写入事务也要检查代次和前序号。只有包含全部已确认提交的数据库备库才可被提升;无法确认时暂停写入。内存缓存、ZeroMQ 通知和客户端超时都不能决定一单是否成交。 + +## 4 · 上架新产品和扩展多选题 + +```mermaid +sequenceDiagram + participant A as 产品运营 + participant C as 产品目录 + participant D as 规则与注册库 + participant W as 撮合分片 + participant V as Web 与 Bot + A->>C: 定义事件、观察区间、来源、支付规则与选项 + C->>D: 分配稳定 ID,保存规则版本及撮合组 + D-->>W: 按簿 ID、最小价位和交易阶段创建空簿 + D-->>V: 发布交易品、选项和展示顺序 + A->>C: 交易开始后申请新增选项 C + alt 原规则已预留 C 的扩展方式,旧份额按原约定兑付 + C->>D: 原子发布新选项 ID、展示版本及生效序号 + D-->>W: 建新簿,原有订单仍指向原簿 + D-->>V: 更新可选项与显示顺序 + else 新选项改变旧份额的兑付权利 + C->>D: 保留原合约,另建新版事件和新交易品 ID + D-->>V: 分别显示两版及各自的截止和兑付规则 + end +``` + +如果“其他”原指 A、B 以外的所有结果,则旧“其他”已经包含 C。将 C 从中扣除会改变旧份额。首版默认封闭选项,新增独立的是非题可作为新的合约单独上架。 + +## 5 · 首次开盘集合竞价到全天连续交易 + +```mermaid +sequenceDiagram + participant U as 各端用户 + participant O as 订单服务 + participant W as 该簿撮合分片 + participant D as 命令日志与账本 + participant M as 行情服务 + U->>O: 盘前提交或撤销限价单 + O->>D: 校验并依序记录,不即时成交 + W->>D: 读入申报及撤销 + W-->>M: 公布指示成交价和可成交量,可能为空 + O->>D: 时钟触发,将开盘屏障写入同一序列 + W->>W: 对屏障之前的有效申报计算统一开盘价 + alt 买卖相交 + W->>D: 提交统一价成交、剩余挂单、解冻和连续交易状态 + else 无交叉或仅有单边报价 + W->>D: 以无开盘成交进入连续交易,保留有效挂单 + end + D-->>M: 发布结果和新的交易阶段 + U->>O: 开盘后的限价单或带保护价的市价单 +``` + +建议首版只在每个交易品首次开盘竞价。报价遵守支付范围与最小价位,可成交的候选价依次按最大成交量、最小买卖量差、最低候选价排序,最后一项是无参考价时的明确约定。优价优先,同价按受理序号分配;持续有效订单余量进入连续交易。全天交易仍须按合约截止时间封盘。 + +## 6 · 经纪路由、部分成交与撤单竞态 + +```mermaid +sequenceDiagram + participant U as 用户 + participant O as 经纪订单服务 + participant D as 订单库与账本 + participant A as Polymarket 或 Kalshi 适配器 + participant V as 所选场所 + U->>O: 指定外场、限价和数量 10 + O->>D: 校验映射、账户权限及场所可用额,冻结并保存子单 + O->>A: 按子单 ID 投递,绑定执行账户 + A->>V: 使用该场所授权和原生标识提交 + alt 收到场所受理回执 + V-->>A: 场所订单 ID + else 提交超时,状态未知 + A->>V: 按场所支持的订单标识、开放订单和成交查证 + end + V-->>A: 成交 4 份 + A->>D: 按场所成交 ID 去重,登记 4 份及待交割状态 + U->>O: 撤销余量 + O->>A: 请求撤单,保留余量占用 + A->>V: 撤单并查询最终订单与成交明细 + V-->>A: 撤前另成交 1 份,已撤余量 5 + A->>D: 补记 1 份,释放 5 份占用,核对费用与交割状态 + O-->>U: 累计成交 5,已撤 5,可查每笔执行与交割 +``` + +首版每个委托只有一个执行目的地。扩展智能拆单时,活动子单未成交数量加累计成交数量不得超过父单数量;改路前须确认旧子单余量。未知状态留在对账队列。场所保证金和余额分开核算;使用用户自有外场账户时,本地冻结只是预算控制,场所授权和实际余额仍需独立校验。 + +## 7 · 因子更新、篮子申购与二级交易 + +```mermaid +sequenceDiagram + participant F as 因子引擎 + participant B as 篮子管理 + participant E as 经纪执行 + participant D as 资产与份额账本 + participant W as 份额订单簿 + F->>B: 发布带时间戳的因子值、目标权重和模型版本 + B->>B: 检查过期数据、成分可交易性,生成版本化单位篮子 + B->>D: 申购人确认报价,锁定申购资金及篮子版本 + B->>E: 按成分和执行场所分别下单 + E-->>B: 回报各腿成交、费用和交割 + alt 单位篮子齐备并完成交割 + B->>D: 同一事务锁定底层持仓并给申购人记入份额 + D-->>W: 份额可用于二级市场卖单 + else 缺腿、停牌或超过价格保护 + B->>E: 撤余单,按事前约定补腿或平仓 + B->>D: 已买腿留在申购暂记账户,按约定分担费用与损益 + end + W->>D: 二级成交只转让既有份额和对价 +``` + +第一版可以只发布因子与模拟净值。实物持仓型篮子需要独立资产账户、发行与赎回、实际持仓估值及调仓。赎回先锁份额,再按约定交付成分或变现付款,最后核销;同一份额须防止边赎回边卖出。实时因子变化触发重新估值;只有达到调仓条件才产生订单。成分事件兑付后按规则转为现金或更换成分。 + +## 8 · 停盘、结果裁决与兑付 + +```mermaid +sequenceDiagram + participant L as 生命周期服务 + participant W as 撮合与订单服务 + participant R as 结果裁决 + participant D as 账本 + participant C as 用户端 + L->>W: 在合约截止处写入停盘屏障 + W->>D: 处理屏障前命令、撤余单、释放挂单冻结 + L->>R: 请求按上市时锁定的规则取证 + R-->>C: 公布初判、证据和异议截止 + alt 来源缺失或出现异议 + R->>R: 按预定规则复核、延期或作废 + end + R->>D: 提交最终结果与规则版本,按兑付批次去重 + D->>D: 从抵押账户兑付各结果份额,核对总额后关闭合约 + D-->>C: 可查持仓核销与付款流水 +``` + +本图适用于自营上架的本地事件。外场代理单按对应场所的裁决和交割流水对账。两处题目若使用不同判定源或作废条款,即使短期价格一致也可能兑付不同。 + +## 9 · 同一笔成交的本地入账、链上存证与链上资产交割 + +```mermaid +sequenceDiagram + participant W as 撮合与清算 + participant D as 账本与待发事件 + participant S as 结算适配器 + participant H as 链或合约 + participant C as 客户端 + W->>D: 提交成交,按交易品的交割模式处理 + alt 模拟资产在本地交割 + D-->>C: 资金和份额已在本地账本划转 + opt 启用批次存证 + S->>D: 取已提交记录,保存批次明细及包含证明 + S->>H: 提交批次摘要,跟踪确认与重组 + S-->>C: 可验证该记录已被纳入批次 + end + else 自有产品约定链上交割 + D-->>S: 待交割成交 ID、双方授权及已锁定资产 + S->>H: 合约验证授权、防重放,原子交付资金与份额 + alt 达到确认策略 + H-->>S: 已确认资产转移 + S->>D: 按结算 ID 核销在途,确认可用余额 + else 回滚、失败或链重组 + S->>D: 保持在途或标记异常,查链并按规则重试或冲正 + end + D-->>C: 展示成交与交割两个状态 + end +``` + +链上模式的资产锁定和签名授权须在接受可执行订单前建立,过期、撤单和 nonce 要有统一规则。自有结算模块只交割自有产品;外场成交由外场按自身协议交割,适配器跟踪和对账。只存批次摘要能验证包含关系,无法单凭摘要证明资产已转移。 + +## 10 · 没有平台种子资金时,第一份预测合约从哪里来 + +```mermaid +sequenceDiagram + participant A as 用户甲 + participant B as 用户乙 + participant O as 订单服务 + participant W as 同一事件撮合组 + participant D as 抵押与份额账本 + A->>O: 买 10 份 YES,每份限价 0.60 + O->>D: 冻结甲的 6 单位模拟资金,写命令 + W->>D: 暂无可配对订单,记为挂单 + B->>O: 买 10 份 NO,每份限价 0.40 + O->>D: 冻结乙的 4 单位,写命令 + W->>W: 校验二元互补、同一规则和数量,合价 1.00 + W->>D: 原子收取 10 单位抵押,登记甲 10 YES 与乙 10 NO + D-->>A: 持有 10 YES + D-->>B: 持有 10 NO +``` + +例子忽略费用。每对 YES/NO 总兑付固定为 1,作废时也须定义两边合计为 1 的兑付规则。第一版可只做完整抵押拆出成套份额再挂卖;若做图中的互补买单撮合,应预先规定普通卖单与互补单的合并价格优先级、超出 1 的价格改善分配及开盘竞价是否支持互补单。本稿开盘只在单簿集合竞价,互补撮合从连续交易开始启用。 diff --git a/exchange.py b/exchange.py new file mode 100644 index 0000000..de8b182 --- /dev/null +++ b/exchange.py @@ -0,0 +1,205 @@ +"""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() diff --git a/matching.py b/matching.py new file mode 100644 index 0000000..b24d024 --- /dev/null +++ b/matching.py @@ -0,0 +1,52 @@ +"""Pure price/time matching for one instrument; prices are integer cents.""" +from dataclasses import dataclass + + +@dataclass +class Order: + seq: int + account: str + side: str + price: int + remaining: int + + +@dataclass(frozen=True) +class Fill: + bid: Order + ask: Order + price: int + quantity: int + + +def match(orders, *, opening=False): + bids = sorted((o for o in orders if o.side == "buy"), key=lambda o: (-o.price, o.seq)) + asks = sorted((o for o in orders if o.side == "sell"), key=lambda o: (o.price, o.seq)) + if not bids or not asks or bids[0].price < asks[0].price: + return [] + clearing = None + if opening: + # Evaluate every permitted tick, including ticks between submitted prices. + def priority(price): + demand = sum(o.remaining for o in bids if o.price >= price) + supply = sum(o.remaining for o in asks if o.price <= price) + return (-min(demand, supply), abs(demand - supply), price) + clearing = min(range(101), key=priority) + fills = [] + b = a = 0 + while b < len(bids) and a < len(asks): + bid, ask = bids[b], asks[a] + if bid.price < ask.price: + break + if clearing is not None and not ask.price <= clearing <= bid.price: + break + price = clearing + if price is None: + price = bid.price if bid.seq < ask.seq else ask.price + qty = min(bid.remaining, ask.remaining) + fills.append(Fill(bid, ask, price, qty)) + bid.remaining -= qty + ask.remaining -= qty + b += bid.remaining == 0 + a += ask.remaining == 0 + return fills diff --git a/schema.sql b/schema.sql new file mode 100644 index 0000000..1106e02 --- /dev/null +++ b/schema.sql @@ -0,0 +1,24 @@ +CREATE TABLE IF NOT EXISTS accounts ( + id TEXT PRIMARY KEY, cash INTEGER NOT NULL CHECK(cash >= 0) +); +CREATE TABLE IF NOT EXISTS markets ( + id TEXT PRIMARY KEY, rules TEXT NOT NULL, phase TEXT NOT NULL, + collateral INTEGER NOT NULL DEFAULT 0 CHECK(collateral >= 0), winner TEXT +); +CREATE TABLE IF NOT EXISTS positions ( + account TEXT REFERENCES accounts, market TEXT REFERENCES markets, outcome TEXT, + quantity INTEGER NOT NULL CHECK(quantity >= 0), PRIMARY KEY(account,market,outcome) +); +CREATE TABLE IF NOT EXISTS orders ( + seq INTEGER PRIMARY KEY, account TEXT REFERENCES accounts, market TEXT REFERENCES markets, + outcome TEXT NOT NULL, side TEXT NOT NULL, price INTEGER NOT NULL, quantity INTEGER NOT NULL, + remaining INTEGER NOT NULL CHECK(remaining >= 0), status TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS active_book ON orders(market,outcome,seq) WHERE status='live'; +CREATE TABLE IF NOT EXISTS fills ( + seq INTEGER PRIMARY KEY, bid INTEGER REFERENCES orders, ask INTEGER REFERENCES orders, + price INTEGER NOT NULL, quantity INTEGER NOT NULL +); +CREATE TABLE IF NOT EXISTS requests ( + id TEXT PRIMARY KEY, payload TEXT NOT NULL, response TEXT NOT NULL +); diff --git a/test_exchange.py b/test_exchange.py new file mode 100644 index 0000000..154516e --- /dev/null +++ b/test_exchange.py @@ -0,0 +1,110 @@ +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() -- 2.52.0 From 2f3c699e9cc320092037f70d2a485fabcdf7657b Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Thu, 3 Dec 2026 02:53:46 +0800 Subject: [PATCH 2/2] Port the simulator to a Rust workspace and document each crate --- .gitignore | 2 +- Cargo.lock | 448 +++++++++++++++++++ Cargo.toml | 13 + README.md | 16 +- crates/eventbook-cli/Cargo.toml | 9 + crates/eventbook-cli/README.md | 37 ++ crates/eventbook-cli/src/main.rs | 13 + crates/eventbook-cli/src/stream.rs | 41 ++ crates/exchange/Cargo.toml | 14 + crates/exchange/README.md | 53 +++ crates/exchange/src/book.rs | 118 +++++ crates/exchange/src/command.rs | 46 ++ crates/exchange/src/ledger.rs | 28 ++ crates/exchange/src/lib.rs | 82 ++++ crates/exchange/src/market.rs | 123 +++++ schema.sql => crates/exchange/src/schema.sql | 0 crates/exchange/src/validation.rs | 22 + crates/exchange/tests/market.rs | 134 ++++++ crates/matching/Cargo.toml | 4 + crates/matching/README.md | 33 ++ crates/matching/src/lib.rs | 67 +++ crates/matching/src/order.rs | 21 + exchange.py | 205 --------- matching.py | 52 --- test_exchange.py | 110 ----- 25 files changed, 1320 insertions(+), 371 deletions(-) create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 crates/eventbook-cli/Cargo.toml create mode 100644 crates/eventbook-cli/README.md create mode 100644 crates/eventbook-cli/src/main.rs create mode 100644 crates/eventbook-cli/src/stream.rs create mode 100644 crates/exchange/Cargo.toml create mode 100644 crates/exchange/README.md create mode 100644 crates/exchange/src/book.rs create mode 100644 crates/exchange/src/command.rs create mode 100644 crates/exchange/src/ledger.rs create mode 100644 crates/exchange/src/lib.rs create mode 100644 crates/exchange/src/market.rs rename schema.sql => crates/exchange/src/schema.sql (100%) create mode 100644 crates/exchange/src/validation.rs create mode 100644 crates/exchange/tests/market.rs create mode 100644 crates/matching/Cargo.toml create mode 100644 crates/matching/README.md create mode 100644 crates/matching/src/lib.rs create mode 100644 crates/matching/src/order.rs delete mode 100644 exchange.py delete mode 100644 matching.py delete mode 100644 test_exchange.py diff --git a/.gitignore b/.gitignore index 23f2f96..8f26ef2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ -__pycache__/ +/target/ *.db *.db-* diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..a2d6b60 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,448 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519" +dependencies = [ + "cfg-if", + "getrandom", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "cc" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "eventbook-cli" +version = "0.1.0" +dependencies = [ + "anyhow", + "exchange", + "serde_json", +] + +[[package]] +name = "exchange" +version = "0.1.0" +dependencies = [ + "anyhow", + "matching", + "rusqlite", + "serde", + "serde_json", + "tempfile", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashlink" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "matching" +version = "0.1.0" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rusqlite" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zerocopy" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..a619df0 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,13 @@ +[workspace] +members = ["crates/matching", "crates/exchange", "crates/eventbook-cli"] +resolver = "2" + +[workspace.package] +edition = "2021" +version = "0.1.0" + +[workspace.dependencies] +anyhow = "1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +rusqlite = { version = "0.32", features = ["bundled"] } diff --git a/README.md b/README.md index 05503f8..db72e3c 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,25 @@ # Eventbook Exchange -用模拟资金验证预测市场的交易与兑付规则。这个版本是可信操作员使用的单机命令程序。Python 3.10+,只依赖标准库。订单簿由 SQLite 中该合约的有效订单重建,每条命令在一次写事务中完成冻结、成交、余量、余额和回执更新。客户端看到的成功回执均已提交。 +用模拟资金验证预测市场的交易与兑付规则。这个版本是可信操作员使用的单机命令程序。Rust Cargo workspace,SQLite 由 rusqlite 的 bundled 特性提供。订单簿由 SQLite 中该合约的有效订单重建,每条命令在一次写事务中完成冻结、成交、余量、余额和回执更新。客户端看到的成功回执均已提交。 完整设计见[交易系统时序图](docs/sequences.md)。单机版覆盖本地下单、开盘与连续交易、全额抵押发行和账本兑付。 +## Crate 导航 + +| Crate | 职责 | +|---|---| +| [matching](crates/matching/README.md) | 单簿集合竞价与连续撮合 | +| [exchange](crates/exchange/README.md) | 事务、幂等、账户、市场和兑付 | +| [eventbook-cli](crates/eventbook-cli/README.md) | JSON 行式命令入口 | + +每个 crate 的 README 包含文件依赖图和运行时序图。 + ## 跑一笔交易 在仓库根目录执行以下示例,每次演示使用一份新的数据库。程序从标准输入逐行接收 JSON,逐行返回结果。模拟货币的单位为分,每对 YES/NO 足额抵押 100 分。 ```sh -python3 -B exchange.py demo.db <<'ORDERS' +cargo run --locked -p eventbook-cli -- demo.db <<'ORDERS' {"id":"1","op":"fund","account":"seller","cents":1000} {"id":"2","op":"fund","account":"buyer","cents":1000} {"id":"3","op":"list","market":"game-1","rules":"按比赛官方终局结果判定,主队胜为 YES,其余为 NO,作废每边兑付 50 分"} @@ -36,4 +46,4 @@ ORDERS ## 检查 -运行 `python3 -B -m unittest -v`。用例在独立临时数据库中检查统一开盘价、同价排队、部分成交、撤单、价格保护、合约隔离、重启重试、拒单回滚和到期兑付。在各次成功命令后核对现金、冻结额、抵押额和两边份额守恒。 +Rust 工作区的测试入口为 `cargo test --workspace --locked`。集成用例覆盖开盘、盘中成交、隔离、重启、并发冻结和兑付。 diff --git a/crates/eventbook-cli/Cargo.toml b/crates/eventbook-cli/Cargo.toml new file mode 100644 index 0000000..0ef40b3 --- /dev/null +++ b/crates/eventbook-cli/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "eventbook-cli" +edition.workspace = true +version.workspace = true + +[dependencies] +exchange = { path = "../exchange" } +serde_json.workspace = true +anyhow.workspace = true diff --git a/crates/eventbook-cli/README.md b/crates/eventbook-cli/README.md new file mode 100644 index 0000000..e454001 --- /dev/null +++ b/crates/eventbook-cli/README.md @@ -0,0 +1,37 @@ +# eventbook-cli + +可信操作员的 JSON 行命令入口。启动参数指定数据库文件,程序复用同一个 Exchange 连接。标准输入的每一行对应标准输出的一条 JSON 回执。输入结束时进程退出。 + +## 文件依赖 + +箭头从调用文件指向提供功能的文件或 crate。 + +```mermaid +flowchart LR + main["src/main.rs"] -->|把标准输入输出交给 serve| stream["src/stream.rs"] + main -.->|打开数据库| api["exchange crate"] + stream -.->|执行命令| api +``` + +## 一次命令会话 + +```mermaid +sequenceDiagram + actor U as 操作员 + participant C as main.rs + participant S as stream.rs + participant E as Exchange + U->>C: 启动并指定数据库路径 + C->>E: 打开数据库 + C->>S: 传入连接和输入输出流 + loop 输入一行 + U->>S: JSON 命令 + alt JSON 有效 + S->>E: 执行命令 + E-->>S: 业务回执或错误 + else JSON 解析失败 + S->>S: 构造错误回执 + end + S-->>U: 输出一行 JSON 并刷新 + end +``` diff --git a/crates/eventbook-cli/src/main.rs b/crates/eventbook-cli/src/main.rs new file mode 100644 index 0000000..1c3b675 --- /dev/null +++ b/crates/eventbook-cli/src/main.rs @@ -0,0 +1,13 @@ +mod stream; + +use anyhow::{ensure, Context, Result}; +use exchange::Exchange; +use std::{env, io}; + +fn main() -> Result<()> { + let mut args = env::args_os().skip(1); + let path = args.next().context("usage: eventbook-cli DATABASE")?; + ensure!(args.next().is_none(), "usage: eventbook-cli DATABASE"); + let mut exchange = Exchange::open(path)?; + stream::serve(&mut exchange, io::stdin().lock(), io::stdout().lock()) +} diff --git a/crates/eventbook-cli/src/stream.rs b/crates/eventbook-cli/src/stream.rs new file mode 100644 index 0000000..abdb0ab --- /dev/null +++ b/crates/eventbook-cli/src/stream.rs @@ -0,0 +1,41 @@ +use anyhow::Result; +use exchange::Exchange; +use serde_json::{json, Value}; +use std::io::{BufRead, Write}; + +pub(crate) fn serve( + engine: &mut Exchange, + input: impl BufRead, + mut output: impl Write, +) -> Result<()> { + for line in input.lines() { + let line = line?; + let result = serde_json::from_str::(&line) + .map_err(anyhow::Error::from) + .and_then(|v| engine.execute(v)); + let reply = result.unwrap_or_else(|e| json!({"error":e.to_string()})); + serde_json::to_writer(&mut output, &reply)?; + writeln!(output)?; + output.flush()?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn invalid_line_does_not_discard_next_request() { + let mut e = Exchange::open(":memory:").unwrap(); + let mut out = Vec::new(); + serve(&mut e, &b"broken\n{\"op\":\"state\"}\n"[..], &mut out).unwrap(); + let replies: Vec = std::str::from_utf8(&out) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + assert_eq!(replies.len(), 2); + assert!(replies[0]["error"].is_string()); + assert_eq!(replies[1]["orders"], json!([])); + } +} diff --git a/crates/exchange/Cargo.toml b/crates/exchange/Cargo.toml new file mode 100644 index 0000000..1705965 --- /dev/null +++ b/crates/exchange/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "exchange" +edition.workspace = true +version.workspace = true + +[dependencies] +matching = { path = "../matching" } +anyhow.workspace = true +serde.workspace = true +serde_json.workspace = true +rusqlite.workspace = true + +[dev-dependencies] +tempfile = "3" diff --git a/crates/exchange/README.md b/crates/exchange/README.md new file mode 100644 index 0000000..81a798a --- /dev/null +++ b/crates/exchange/README.md @@ -0,0 +1,53 @@ +# exchange + +维护一个 SQLite 模拟市场。每条写命令在同一事务内完成资金或份额预留、订单更新和幂等回执。成交明细由 matching 计算。只读 state 使用一个一致快照。 + +## 文件依赖 + +箭头从使用方指向提供类型或功能的文件。虚线连到 workspace 内的另一个 crate。图中省略标准库及第三方 crate。 + +```mermaid +flowchart LR + test["tests/market.rs"] -->|通过公开 API 驱动市场| api["src/lib.rs"] + api -->|初始化数据库| schema["src/schema.sql"] + api -->|校验请求键| valid["src/validation.rs"] + api -->|解析写命令| cmd["src/command.rs"] + api -->|事务内派发| market["src/market.rs"] + market -->|匹配命令类型| cmd + market -->|检查数量、标识和市场阶段| valid + market -->|下单、撤单与开盘| book["src/book.rs"] + market -->|发行与兑付| ledger["src/ledger.rs"] + book -->|检查订单约束| valid + book -->|预留、交割或释放| ledger + book -.->|计算逐笔成交| matcher["matching crate"] + market -.->|选择开盘阶段| matcher +``` + +## 一笔盘中买单 + +```mermaid +sequenceDiagram + participant C as 调用方 + participant X as Exchange + participant D as SQLite + participant B as book.rs + participant M as matching + C->>X: 提交有请求键的限价买单 + X->>D: 开始写事务,查找历史回执 + alt 请求键已存在 + X-->>C: 内容相同返回原回执,冲突则报错 + else 新请求 + X->>B: 派发下单命令 + B->>D: 校验阶段、冻结买方资金、保存订单 + B->>M: 当前交易品有效订单与连续交易阶段 + M-->>B: 逐笔成交列表 + B->>D: 更新买卖方资产、余量和成交记录 + opt IOC 仍有余量 + B->>D: 撤余单,释放剩余预留 + end + X->>D: 保存回执并提交 + X-->>C: 返回订单号、成交量与状态 + end +``` + +校验、记账或存储失败时事务回滚。停盘会对尚存的挂单执行同样的释放逻辑。裁决后按持仓兑付,并核对总兑付与该市场抵押额一致。 diff --git a/crates/exchange/src/book.rs b/crates/exchange/src/book.rs new file mode 100644 index 0000000..952e00f --- /dev/null +++ b/crates/exchange/src/book.rs @@ -0,0 +1,118 @@ +use crate::{ + ledger, + validation::{amount, identifier, phase}, +}; +use anyhow::{ensure, Result}; +use matching::{cross, Order, Phase, Side}; +use rusqlite::{params, Transaction}; +use serde_json::{json, Value}; + +pub(crate) struct NewOrder { + pub market: String, + pub account: String, + pub outcome: String, + pub side: String, + pub price: i64, + pub qty: i64, + pub tif: String, +} + +pub(crate) fn submit(tx: &Transaction, order: NewOrder) -> Result { + let NewOrder { + market, + account, + outcome, + side, + price, + qty, + tif, + } = order; + identifier(&account)?; + amount(qty)?; + let stage = phase(tx, &market, &["preopen", "continuous"])?; + ensure!( + matches!(outcome.as_str(), "YES" | "NO") && matches!(side.as_str(), "buy" | "sell"), + "invalid instrument or side" + ); + ensure!((0..=100).contains(&price), "invalid price"); + ensure!( + tif == "GTC" || (tif == "IOC" && stage == "continuous"), + "unsupported time in force" + ); + if side == "buy" { + ledger::cash(tx, &account, -price * qty)?; + } else { + ledger::position(tx, &account, &market, &outcome, -qty)?; + } + tx.execute("INSERT INTO orders(account,market,outcome,side,price,quantity,remaining,status) VALUES(?,?,?,?,?,?,?,'live')",params![account,market,outcome,side,price,qty,qty])?; + let seq = tx.last_insert_rowid(); + if stage == "continuous" { + match_book(tx, &market, &outcome, Phase::Continuous)?; + } + let (remaining, mut status): (i64, String) = tx.query_row( + "SELECT remaining,status FROM orders WHERE seq=?", + [seq], + |r| Ok((r.get(0)?, r.get(1)?)), + )?; + if tif == "IOC" && remaining > 0 { + release(tx, seq, &account)?; + status = "cancelled".into(); + } + Ok(json!({"order":seq,"filled":qty-remaining,"status":status})) +} + +pub(crate) fn match_book( + tx: &Transaction, + market: &str, + outcome: &str, + phase: Phase, +) -> Result<()> { + let mut stmt=tx.prepare("SELECT seq,side,price,remaining FROM orders WHERE market=? AND outcome=? AND status='live'")?; + let orders = stmt + .query_map(params![market, outcome], |r| { + Ok(Order { + seq: r.get(0)?, + side: if r.get::<_, String>(1)? == "buy" { + Side::Buy + } else { + Side::Sell + }, + price: r.get(2)?, + remaining: r.get(3)?, + }) + })? + .collect::>>()?; + for f in cross(orders, phase) { + 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], + )?; + 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])?; + } + } + Ok(()) +} + +pub(crate) fn release(tx: &Transaction, seq: i64, owner: &str) -> Result { + let (market,outcome,side,price,qty):(String,String,String,i64,i64)=tx.query_row("SELECT market,outcome,side,price,remaining FROM orders WHERE seq=? AND account=? AND status='live'",params![seq,owner],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?; + if side == "buy" { + ledger::cash(tx, owner, price * qty)?; + } else { + ledger::position(tx, owner, &market, &outcome, qty)?; + } + tx.execute("UPDATE orders SET status='cancelled' WHERE seq=?", [seq])?; + Ok(qty) +} diff --git a/crates/exchange/src/command.rs b/crates/exchange/src/command.rs new file mode 100644 index 0000000..9df5b89 --- /dev/null +++ b/crates/exchange/src/command.rs @@ -0,0 +1,46 @@ +use serde::Deserialize; + +#[derive(Deserialize)] +#[serde(tag = "op", rename_all = "lowercase", deny_unknown_fields)] +pub(crate) enum Command { + Fund { + account: String, + cents: i64, + }, + List { + market: String, + rules: String, + }, + Split { + market: String, + account: String, + qty: i64, + }, + Order { + market: String, + account: String, + outcome: String, + side: String, + price: i64, + qty: i64, + #[serde(default = "gtc")] + tif: String, + }, + Cancel { + account: String, + order: i64, + }, + Open { + market: String, + }, + Close { + market: String, + }, + Resolve { + market: String, + winner: String, + }, +} +fn gtc() -> String { + "GTC".into() +} diff --git a/crates/exchange/src/ledger.rs b/crates/exchange/src/ledger.rs new file mode 100644 index 0000000..ba90906 --- /dev/null +++ b/crates/exchange/src/ledger.rs @@ -0,0 +1,28 @@ +use anyhow::{ensure, Result}; +use rusqlite::{params, Transaction}; + +pub(crate) fn cash(tx: &Transaction, account: &str, delta: i64) -> Result<()> { + ensure!( + tx.execute( + "UPDATE accounts SET cash=cash+? WHERE id=? AND cash+?>=0", + params![delta, account, delta] + )? == 1, + "unknown account or insufficient cash" + ); + Ok(()) +} + +pub(crate) fn position( + tx: &Transaction, + account: &str, + market: &str, + outcome: &str, + delta: i64, +) -> Result<()> { + tx.execute( + "INSERT OR IGNORE INTO positions VALUES(?,?,?,0)", + params![account, market, outcome], + )?; + ensure!(tx.execute("UPDATE positions SET quantity=quantity+? WHERE account=? AND market=? AND outcome=? AND quantity+?>=0",params![delta,account,market,outcome,delta])?==1,"insufficient position"); + Ok(()) +} diff --git a/crates/exchange/src/lib.rs b/crates/exchange/src/lib.rs new file mode 100644 index 0000000..0a176c6 --- /dev/null +++ b/crates/exchange/src/lib.rs @@ -0,0 +1,82 @@ +mod validation; +use validation::identifier; +mod book; +mod command; +mod ledger; +mod market; + +use anyhow::{ensure, Context, Result}; +use rusqlite::{params, types::ValueRef, Connection, OptionalExtension, TransactionBehavior}; +use serde_json::{json, Map, Value}; +use std::{path::Path, time::Duration}; + +pub struct Exchange(Connection); +impl Exchange { + pub fn open(path: impl AsRef) -> Result { + let db = Connection::open(path)?; + db.busy_timeout(Duration::from_secs(10))?; + db.execute_batch("PRAGMA foreign_keys=ON")?; + db.execute_batch(include_str!("schema.sql"))?; + Ok(Self(db)) + } + + pub fn execute(&mut self, payload: Value) -> Result { + if payload == json!({"op":"state"}) { + let tx = self.0.transaction()?; + let mut state = Map::new(); + for table in ["accounts", "markets", "positions", "orders", "fills"] { + let mut stmt = tx.prepare(&format!("SELECT * FROM {table} ORDER BY rowid"))?; + let names: Vec = + stmt.column_names().into_iter().map(str::to_owned).collect(); + let mut rows = stmt.query([])?; + let mut result = Vec::new(); + while let Some(row) = rows.next()? { + let mut obj = Map::new(); + for (i, name) in names.iter().enumerate() { + let v = match row.get_ref(i)? { + ValueRef::Null => Value::Null, + ValueRef::Integer(n) => json!(n), + ValueRef::Text(s) => json!(std::str::from_utf8(s)?), + _ => anyhow::bail!("unexpected column type"), + }; + obj.insert(name.clone(), v); + } + result.push(Value::Object(obj)); + } + state.insert(table.into(), Value::Array(result)); + } + tx.commit()?; + return Ok(Value::Object(state)); + } + let id = payload["id"].as_str().context("request id required")?; + identifier(id)?; + let tx = self + .0 + .transaction_with_behavior(TransactionBehavior::Immediate)?; + let prior: Option<(String, String)> = tx + .query_row( + "SELECT payload,response FROM requests WHERE id=?", + [id], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional()?; + if let Some((saved, reply)) = prior { + ensure!( + serde_json::from_str::(&saved)? == payload, + "request id reused with different content" + ); + return Ok(serde_json::from_str(&reply)?); + } + let mut body = payload.clone(); + body.as_object_mut() + .context("expected object")? + .remove("id"); + let result = market::apply(&tx, serde_json::from_value(body)?)?; + tx.execute( + "INSERT INTO requests VALUES(?,?,?)", + params![id, payload.to_string(), result.to_string()], + )?; + tx.commit()?; + Ok(result) + } +} diff --git a/crates/exchange/src/market.rs b/crates/exchange/src/market.rs new file mode 100644 index 0000000..6fe330d --- /dev/null +++ b/crates/exchange/src/market.rs @@ -0,0 +1,123 @@ +use crate::{ + book, + command::Command, + ledger, + validation::{amount, identifier, phase}, +}; +use anyhow::{ensure, Result}; +use matching::Phase; +use rusqlite::{params, Transaction}; +use serde_json::{json, Value}; + +pub(crate) fn apply(tx: &Transaction, command: Command) -> Result { + match command { + Command::Fund { account, cents } => { + identifier(&account)?; + amount(cents)?; + tx.execute("INSERT INTO accounts VALUES(?,?)", params![account, cents])?; + Ok(json!({"funded":cents})) + } + Command::List { market, rules } => { + identifier(&market)?; + ensure!(!rules.trim().is_empty(), "rules required"); + tx.execute( + "INSERT INTO markets(id,rules,phase) VALUES(?,?,'preopen')", + params![market, rules], + )?; + Ok(json!({"phase":"preopen"})) + } + Command::Split { + market, + account, + qty, + } => { + identifier(&account)?; + amount(qty)?; + phase(tx, &market, &["preopen", "continuous"])?; + ledger::cash(tx, &account, -100 * qty)?; + tx.execute( + "UPDATE markets SET collateral=collateral+? WHERE id=?", + params![100 * qty, market], + )?; + for side in ["YES", "NO"] { + ledger::position(tx, &account, &market, side, qty)?; + } + Ok(json!({"pairs":qty})) + } + Command::Order { + market, + account, + outcome, + side, + price, + qty, + tif, + } => book::submit( + tx, + book::NewOrder { + market, + account, + outcome, + side, + price, + qty, + tif, + }, + ), + Command::Cancel { order, account } => { + identifier(&account)?; + let qty = book::release(tx, order, &account)?; + Ok(json!({"cancelled":qty})) + } + Command::Open { market } => { + phase(tx, &market, &["preopen"])?; + for outcome in ["YES", "NO"] { + book::match_book(tx, &market, outcome, Phase::Opening)?; + } + tx.execute("UPDATE markets SET phase='continuous' WHERE id=?", [market])?; + Ok(json!({"phase":"continuous"})) + } + Command::Close { market } => { + phase(tx, &market, &["preopen", "continuous"])?; + let mut stmt = + tx.prepare("SELECT seq,account FROM orders WHERE market=? AND status='live'")?; + let orders = stmt + .query_map([&market], |r| { + Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)) + })? + .collect::>>()?; + for (seq, account) in orders { + book::release(tx, seq, &account)?; + } + tx.execute("UPDATE markets SET phase='closed' WHERE id=?", [market])?; + Ok(json!({"phase":"closed"})) + } + Command::Resolve { market, winner } => { + phase(tx, &market, &["closed"])?; + ensure!( + matches!(winner.as_str(), "YES" | "NO" | "VOID"), + "invalid winner" + ); + let mut stmt = + tx.prepare("SELECT account,outcome,quantity FROM positions WHERE market=?")?; + let mut rows = stmt.query([&market])?; + let mut total = 0i64; + while let Some(r) = rows.next()? { + let outcome: String = r.get(1)?; + let cents = if winner == "VOID" { + 50 + } else if outcome == winner { + 100 + } else { + 0 + }; + let payout = cents * r.get::<_, i64>(2)?; + ledger::cash(tx, &r.get::<_, String>(0)?, payout)?; + total += payout; + } + ensure!(tx.execute("UPDATE markets SET phase='resolved',collateral=0,winner=? WHERE id=? AND collateral=?",params![winner,market,total])?==1,"collateral mismatch"); + tx.execute("UPDATE positions SET quantity=0 WHERE market=?", [market])?; + Ok(json!({"phase":"resolved","paid":total})) + } + } +} diff --git a/schema.sql b/crates/exchange/src/schema.sql similarity index 100% rename from schema.sql rename to crates/exchange/src/schema.sql diff --git a/crates/exchange/src/validation.rs b/crates/exchange/src/validation.rs new file mode 100644 index 0000000..52a1daa --- /dev/null +++ b/crates/exchange/src/validation.rs @@ -0,0 +1,22 @@ +use anyhow::{ensure, Result}; +use rusqlite::Transaction; +pub(crate) fn identifier(id: &str) -> Result<()> { + ensure!( + !id.trim().is_empty() && id.trim().chars().count() <= 256, + "invalid identifier" + ); + Ok(()) +} +pub(crate) fn amount(n: i64) -> Result<()> { + ensure!((1..=1_000_000_000).contains(&n), "invalid amount"); + Ok(()) +} + +pub(crate) fn phase(tx: &Transaction, market: &str, allowed: &[&str]) -> Result { + identifier(market)?; + let p: String = tx.query_row("SELECT phase FROM markets WHERE id=?", [market], |r| { + r.get(0) + })?; + ensure!(allowed.contains(&p.as_str()), "wrong market phase"); + Ok(p) +} diff --git a/crates/exchange/tests/market.rs b/crates/exchange/tests/market.rs new file mode 100644 index 0000000..876cbc2 --- /dev/null +++ b/crates/exchange/tests/market.rs @@ -0,0 +1,134 @@ +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!([])); +} diff --git a/crates/matching/Cargo.toml b/crates/matching/Cargo.toml new file mode 100644 index 0000000..fd8adfc --- /dev/null +++ b/crates/matching/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "matching" +edition.workspace = true +version.workspace = true diff --git a/crates/matching/README.md b/crates/matching/README.md new file mode 100644 index 0000000..fe9bd13 --- /dev/null +++ b/crates/matching/README.md @@ -0,0 +1,33 @@ +# matching + +输入是一个交易品的有效订单,输出是按执行顺序排列的成交明细。价格单位为分,数量单位为份。调用方提供已验证的订单快照并负责持久化。 + +## 文件依赖 + +箭头从使用方指向定义方。此 crate 只依赖标准库。 + +```mermaid +flowchart LR + engine["src/lib.rs"] -->|读取 Order 和 Side,生成 Fill| model["src/order.rs"] +``` + +## 开盘与盘中撮合 + +两张相同价格的卖单报 2 份和 5 份时,买单吃 4 份会先取较早订单的 2 份,再取下一单的 2 份。 + +```mermaid +sequenceDiagram + participant B as exchange 订单簿 + participant M as matching 撮合函数 + B->>M: 单一市场和结果的有效订单、交易阶段 + M->>M: 买盘按价降序、卖盘按价升序,同价按序号排序 + alt 订单簿没有交叉 + M-->>B: 空成交列表 + else 集合竞价 + M->>M: 遍历整数价位,选最大成交量、最小量差、最低价 + M-->>B: 统一价格下的逐笔成交 + else 连续交易 + M->>M: 依次匹配可交叉订单,按较早一方的挂单价成交 + M-->>B: 买卖订单号、成交价和成交量 + end +``` diff --git a/crates/matching/src/lib.rs b/crates/matching/src/lib.rs new file mode 100644 index 0000000..7deab62 --- /dev/null +++ b/crates/matching/src/lib.rs @@ -0,0 +1,67 @@ +mod order; +pub use order::{Fill, Order, Side}; +use std::cmp::Reverse; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Phase { + Opening, + Continuous, +} + +/// Input is one instrument's validated, positive-quantity live orders. +pub fn cross(orders: Vec, phase: Phase) -> Vec { + let (mut bids, mut asks): (Vec<_>, Vec<_>) = + orders.into_iter().partition(|o| o.side == Side::Buy); + bids.sort_by_key(|o| (Reverse(o.price), o.seq)); + asks.sort_by_key(|o| (o.price, o.seq)); + let mut fills = Vec::new(); + if bids.is_empty() || asks.is_empty() || bids[0].price < asks[0].price { + return fills; + } + let clearing = (phase == Phase::Opening).then(|| { + (0..=100) + .min_by_key(|&p| { + let demand: i128 = bids + .iter() + .filter(|o| o.price >= p) + .map(|o| i128::from(o.remaining)) + .sum(); + let supply: i128 = asks + .iter() + .filter(|o| o.price <= p) + .map(|o| i128::from(o.remaining)) + .sum(); + (Reverse(demand.min(supply)), (demand - supply).abs(), p) + }) + .expect("nonempty tick range") + }); + let (mut b, mut a) = (0, 0); + while b < bids.len() && a < asks.len() { + let bid = &mut bids[b]; + let ask = &mut asks[a]; + if bid.price < ask.price || clearing.is_some_and(|p| p < ask.price || p > bid.price) { + break; + } + let price = clearing.unwrap_or(if bid.seq < ask.seq { + bid.price + } else { + ask.price + }); + let quantity = bid.remaining.min(ask.remaining); + fills.push(Fill { + bid: bid.seq, + ask: ask.seq, + price, + quantity, + }); + bid.remaining -= quantity; + ask.remaining -= quantity; + if bid.remaining == 0 { + b += 1; + } + if ask.remaining == 0 { + a += 1; + } + } + fills +} diff --git a/crates/matching/src/order.rs b/crates/matching/src/order.rs new file mode 100644 index 0000000..1c3dd09 --- /dev/null +++ b/crates/matching/src/order.rs @@ -0,0 +1,21 @@ +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Side { + Buy, + Sell, +} + +#[derive(Clone, Debug)] +pub struct Order { + pub seq: i64, + pub side: Side, + pub price: i64, + pub remaining: i64, +} + +#[derive(Debug, PartialEq, Eq)] +pub struct Fill { + pub bid: i64, + pub ask: i64, + pub price: i64, + pub quantity: i64, +} diff --git a/exchange.py b/exchange.py deleted file mode 100644 index de8b182..0000000 --- a/exchange.py +++ /dev/null @@ -1,205 +0,0 @@ -"""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() diff --git a/matching.py b/matching.py deleted file mode 100644 index b24d024..0000000 --- a/matching.py +++ /dev/null @@ -1,52 +0,0 @@ -"""Pure price/time matching for one instrument; prices are integer cents.""" -from dataclasses import dataclass - - -@dataclass -class Order: - seq: int - account: str - side: str - price: int - remaining: int - - -@dataclass(frozen=True) -class Fill: - bid: Order - ask: Order - price: int - quantity: int - - -def match(orders, *, opening=False): - bids = sorted((o for o in orders if o.side == "buy"), key=lambda o: (-o.price, o.seq)) - asks = sorted((o for o in orders if o.side == "sell"), key=lambda o: (o.price, o.seq)) - if not bids or not asks or bids[0].price < asks[0].price: - return [] - clearing = None - if opening: - # Evaluate every permitted tick, including ticks between submitted prices. - def priority(price): - demand = sum(o.remaining for o in bids if o.price >= price) - supply = sum(o.remaining for o in asks if o.price <= price) - return (-min(demand, supply), abs(demand - supply), price) - clearing = min(range(101), key=priority) - fills = [] - b = a = 0 - while b < len(bids) and a < len(asks): - bid, ask = bids[b], asks[a] - if bid.price < ask.price: - break - if clearing is not None and not ask.price <= clearing <= bid.price: - break - price = clearing - if price is None: - price = bid.price if bid.seq < ask.seq else ask.price - qty = min(bid.remaining, ask.remaining) - fills.append(Fill(bid, ask, price, qty)) - bid.remaining -= qty - ask.remaining -= qty - b += bid.remaining == 0 - a += ask.remaining == 0 - return fills diff --git a/test_exchange.py b/test_exchange.py deleted file mode 100644 index 154516e..0000000 --- a/test_exchange.py +++ /dev/null @@ -1,110 +0,0 @@ -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() -- 2.52.0