From 763b46f43e8d1be8b5b88a1c6d0cf39264a754a6 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Thu, 3 Dec 2026 04:27:01 +0800 Subject: [PATCH] Match immediate buys against a cash budget and price cap --- crates/exchange/README.md | 20 ++++++ crates/exchange/src/account_orders.rs | 6 +- crates/exchange/src/assets.rs | 1 + crates/exchange/src/book.rs | 97 +++++++++++++++++++++++++-- crates/exchange/src/command.rs | 9 +++ crates/exchange/src/market.rs | 19 ++++++ crates/exchange/src/schema.sql | 6 ++ crates/exchange/tests/market.rs | 54 +++++++++++++++ crates/matching/README.md | 3 + crates/matching/src/lib.rs | 30 +++++++++ docs/prediction-parity.md | 8 ++- 11 files changed, 244 insertions(+), 9 deletions(-) diff --git a/crates/exchange/README.md b/crates/exchange/README.md index a7a2455..1eab902 100644 --- a/crates/exchange/README.md +++ b/crates/exchange/README.md @@ -268,3 +268,23 @@ sequenceDiagram E->>B: 同步撤单并移除对应互补挂单 E-->>C: canceled 与 not_canceled ``` + +## 按金额买入 + +```mermaid +sequenceDiagram + participant C as CLI + participant E as Exchange + participant B as 常驻盘口 + participant D as SQLite + C->>E: market_buy 指定预算分数、结果、最高价 + E->>D: 写事务中预留预算,分配订单号 + E->>B: 从最低卖价起按预算计划成交 + alt 无可买份额或 FOK 无法用尽预算 + E->>D: 回滚预留和新单 + else FAK 有成交或 FOK 足额 + E->>D: 逐笔交割、退回未花预算、记录回执 + E->>B: 提交后更新受影响的盘口 + E-->>C: 返回成交份数、实付与未花金额 + end +``` diff --git a/crates/exchange/src/account_orders.rs b/crates/exchange/src/account_orders.rs index 23eceaf..0941d68 100644 --- a/crates/exchange/src/account_orders.rs +++ b/crates/exchange/src/account_orders.rs @@ -43,7 +43,8 @@ impl Filter { }; let sql = format!( "SELECT seq,market,outcome,side,price,quantity,remaining,status, - (SELECT expiration FROM order_deadlines d WHERE d.seq=orders.seq) FROM orders + (SELECT expiration FROM order_deadlines d WHERE d.seq=orders.seq), + b.amount_cents,b.spent_cents FROM orders LEFT JOIN budget_buys b ON b.order_seq=orders.seq WHERE account=?1 AND (?2 IS NULL OR market=?2) AND (?3 IS NULL OR outcome=?3) AND seq>?4 AND {scope} ORDER BY seq LIMIT ?5" ); @@ -75,7 +76,8 @@ impl Filter { "outcome":outcome,"side":row.get::<_,String>(3)?, "price_micros":row.get::<_,i64>(4)?*10000,"original_size":quantity, "size_matched":quantity-remaining,"open_size":if status=="live"{remaining}else{0}, - "status":status,"expiration":row.get::<_,Option>(8)?}), + "status":status,"expiration":row.get::<_,Option>(8)?, + "amount_cents":row.get::<_,Option>(9)?,"spent_cents":row.get::<_,Option>(10)?}), ); last_id = Some(id); } diff --git a/crates/exchange/src/assets.rs b/crates/exchange/src/assets.rs index fe69889..78ddfa7 100644 --- a/crates/exchange/src/assets.rs +++ b/crates/exchange/src/assets.rs @@ -40,6 +40,7 @@ pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> { | "history" | "open_orders" | "trades" + | "market_buy" | "cancel_market_orders" ) ) { diff --git a/crates/exchange/src/book.rs b/crates/exchange/src/book.rs index 7d0349e..3ed58da 100644 --- a/crates/exchange/src/book.rs +++ b/crates/exchange/src/book.rs @@ -102,7 +102,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result tif != TimeInForce::Fak || !fills.is_empty(), "FAK has no matching liquidity" ); - settle(tx, &market, &outcome, fills, Some(seq))?; + settle(tx, &market, &outcome, fills, Some(Taker::Limit(seq)))?; } let (remaining, mut status): (i64, String) = tx.query_row( "SELECT remaining,status FROM orders WHERE seq=?", @@ -116,6 +116,88 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result Ok(json!({"order":seq,"filled":qty-remaining,"status":status})) } +pub(crate) struct BudgetBuy { + pub market: String, + pub outcome: String, + pub account: String, + pub amount_cents: i64, + pub max_price: i64, + pub tif: TimeInForce, +} + +pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> Result { + let BudgetBuy { + market, + outcome, + account, + amount_cents, + max_price, + tif, + } = order; + identifier(&account)?; + amount(amount_cents)?; + phase(tx, &market, &["continuous"])?; + ensure!( + matches!(outcome.as_str(), "YES" | "NO") && (0..=100).contains(&max_price), + "invalid outcome or price" + ); + ensure!( + matches!(tif, TimeInForce::Fak | TimeInForce::Fok), + "market buy requires FAK or FOK" + ); + ledger::cash(tx, &account, -amount_cents)?; + tx.execute( + "INSERT INTO orders(account,market,outcome,side,price,quantity,remaining,status) + VALUES(?,?,?,'buy',?,0,0,'live')", + params![account, market, outcome, max_price], + )?; + let seq = tx.last_insert_rowid(); + let fills = books + .get(&market, &outcome) + .map(|b| b.match_budget_buy(seq, max_price, amount_cents)) + .unwrap_or_default(); + ensure!(!fills.is_empty(), "no affordable liquidity"); + let quantity: i64 = fills.iter().map(|f| f.quantity).sum(); + let spent: i64 = fills.iter().map(|f| f.price * f.quantity).sum(); + let unspent = amount_cents - spent; + ensure!( + tif != TimeInForce::Fok || unspent == 0, + "FOK cannot fill the entire cash amount" + ); + tx.execute( + "UPDATE orders SET quantity=?1,remaining=?1 WHERE seq=?2", + params![quantity, seq], + )?; + tx.execute( + "INSERT INTO budget_buys(order_seq,amount_cents,spent_cents) VALUES(?,?,?)", + params![seq, amount_cents, spent], + )?; + settle(tx, &market, &outcome, fills, Some(Taker::Budget(seq)))?; + ledger::cash(tx, &account, unspent)?; + let status = if unspent == 0 { + "filled" + } else { + tx.execute("UPDATE orders SET status='cancelled' WHERE seq=?", [seq])?; + "cancelled" + }; + Ok( + json!({"order":seq,"status":status,"filled":quantity,"amount_cents":amount_cents,"spent_cents":spent,"unspent_cents":unspent}), + ) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum Taker { + Limit(i64), + Budget(i64), +} +impl Taker { + fn seq(self) -> i64 { + match self { + Self::Limit(seq) | Self::Budget(seq) => seq, + } + } +} + struct ExecutedLeg { seq: i64, outcome: String, @@ -129,6 +211,7 @@ fn book_leg( view: &str, fill: &Fill, seq: i64, + taker: Option, ) -> Result { let (account, outcome, side, limit): (String, String, String, i64) = tx.query_row( "SELECT account,outcome,side,price FROM orders @@ -143,7 +226,9 @@ fn book_leg( }; if side == "buy" { ensure!(price <= limit, "buy limit exceeded"); - ledger::cash(tx, &account, (limit - price) * fill.quantity)?; + if taker != Some(Taker::Budget(seq)) { + ledger::cash(tx, &account, (limit - price) * fill.quantity)?; + } ledger::position(tx, &account, market, &outcome, fill.quantity)?; } else { ensure!(price >= limit, "sell limit exceeded"); @@ -162,11 +247,11 @@ pub(crate) fn settle( market: &str, outcome: &str, fills: Vec, - taker: Option, + taker: Option, ) -> Result<()> { for f in fills { - let first = book_leg(tx, market, outcome, &f, f.bid)?; - let second = book_leg(tx, market, outcome, &f, f.ask)?; + let first = book_leg(tx, market, outcome, &f, f.bid, taker)?; + let second = book_leg(tx, market, outcome, &f, f.ask, taker)?; let execution: i64 = if first.outcome == second.outcome { let (buy, sell) = if first.side == "buy" { (first, second) @@ -212,7 +297,7 @@ pub(crate) fn settle( }; tx.execute( "INSERT INTO execution_context(execution,taker_order) VALUES(?,?)", - params![execution, taker], + params![execution, taker.map(Taker::seq)], )?; 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])?; diff --git a/crates/exchange/src/command.rs b/crates/exchange/src/command.rs index f329238..ef87fd4 100644 --- a/crates/exchange/src/command.rs +++ b/crates/exchange/src/command.rs @@ -46,6 +46,15 @@ pub(crate) enum Command { #[serde(default)] post_only: bool, }, + #[serde(rename = "market_buy")] + MarketBuy { + market: String, + outcome: String, + account: String, + amount_cents: i64, + max_price: i64, + tif: Option, + }, Cancel { account: String, order: i64, diff --git a/crates/exchange/src/market.rs b/crates/exchange/src/market.rs index 11584c8..633c2c2 100644 --- a/crates/exchange/src/market.rs +++ b/crates/exchange/src/market.rs @@ -138,6 +138,25 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result post_only, }, ), + Command::MarketBuy { + market, + outcome, + account, + amount_cents, + max_price, + tif, + } => book::market_buy( + tx, + books, + book::BudgetBuy { + market, + outcome, + account, + amount_cents, + max_price, + tif: tif.unwrap_or(crate::command::TimeInForce::Fak), + }, + ), Command::Cancel { order, account } => { identifier(&account)?; let qty = book::release(tx, order, &account, book::CancelReason::Cancelled)?; diff --git a/crates/exchange/src/schema.sql b/crates/exchange/src/schema.sql index 02b69f6..8a0b485 100644 --- a/crates/exchange/src/schema.sql +++ b/crates/exchange/src/schema.sql @@ -155,3 +155,9 @@ CREATE VIEW IF NOT EXISTS twap_result AS FROM twap_markets t LEFT JOIN twap_reports a ON a.stream=t.stream AND a.observed_at=t.start_at LEFT JOIN twap_reports b ON b.stream=t.stream AND b.observed_at=t.end_at; + +CREATE TABLE IF NOT EXISTS budget_buys ( + order_seq INTEGER PRIMARY KEY REFERENCES orders, + amount_cents INTEGER NOT NULL CHECK(amount_cents>0), + spent_cents INTEGER NOT NULL CHECK(spent_cents BETWEEN 0 AND amount_cents) +); diff --git a/crates/exchange/tests/market.rs b/crates/exchange/tests/market.rs index a837ece..b7b59f2 100644 --- a/crates/exchange/tests/market.rs +++ b/crates/exchange/tests/market.rs @@ -1089,3 +1089,57 @@ fn market_and_asset_cancels_are_scoped_to_the_original_side() { .unwrap(); assert_eq!(all, json!({"canceled":[other],"not_canceled":{}})); } + +#[test] +fn cash_buy_reconciles_direct_and_complementary_depth_with_an_exact_budget() { + let dir = tempdir().unwrap(); + let path = dir.path().join("budget.db"); + let mut e = Exchange::open(&path).unwrap(); + setup(&mut e); + e.execute(json!({"op":"fund","id":"c","account":"buyer","cents":170})) + .unwrap(); + e.execute(json!({"op":"open","id":"start","market":"e"})) + .unwrap(); + e.execute(order("ask", "alice", "sell", 35, 2)).unwrap(); + let mut no = order("other-side", "alice", "buy", 55, 3); + no["outcome"] = json!("NO"); + e.execute(no).unwrap(); + let request = json!({"op":"market_buy","id":"budget","asset_id":"eb:YES:e","account":"buyer", + "amount_cents":170,"max_price":50}); + let before = state(&mut e); + for (field, value) in [ + ("tif", json!("FOK")), + ("amount_cents", json!(171)), + ("max_price", json!(34)), + ] { + let mut invalid = request.clone(); + invalid[field] = value; + assert!(e.execute(invalid).is_err()); + assert_eq!(state(&mut e), before); + } + let receipt = e.execute(request.clone()).unwrap(); + assert_eq!(receipt["spent_cents"], 160); + assert_eq!(receipt["unspent_cents"], 10); + assert_eq!(receipt["filled"], 4); + assert_eq!(receipt["status"], "cancelled"); + drop(e); + let mut e = Exchange::open(path).unwrap(); + assert_eq!(e.execute(request).unwrap(), receipt); + let s = state(&mut e); + assert_eq!(s["accounts"][2]["cash"], 10); + assert_eq!(s["paired_fills"][0]["kind"], "mint"); + assert_eq!(s["markets"][0]["collateral"], 1200); + let lookup = e + .execute(json!({"op":"open_orders","account":"buyer","order":receipt["order"]})) + .unwrap(); + assert_eq!(lookup["orders"][0]["spent_cents"], 160); + assert_eq!(lookup["orders"][0]["open_size"], 0); + let fok = e + .execute( + json!({"op":"market_buy","id":"exact","market":"e","outcome":"YES", + "account":"bob","amount_cents":45,"max_price":45,"tif":"FOK"}), + ) + .unwrap(); + assert_eq!(fok["spent_cents"], 45); + assert_eq!(fok["status"], "filled"); +} diff --git a/crates/matching/README.md b/crates/matching/README.md index 351cff3..6b992c9 100644 --- a/crates/matching/README.md +++ b/crates/matching/README.md @@ -23,6 +23,9 @@ sequenceDiagram alt 连续交易 B->>M: match_incoming,传入一条新订单 M->>M: 从对手方最优价起遍历,同价按原序号分配 + else 盘中按金额买入 + B->>M: match_budget_buy,传入买单序号、最高价、预算分数 + M->>M: 在同一卖盘上逐单扣减可用预算,末档取可负担的整份 else 集合竞价 B->>M: opening,在本簿现有两侧计算统一成交价 end diff --git a/crates/matching/src/lib.rs b/crates/matching/src/lib.rs index da5042d..598ab78 100644 --- a/crates/matching/src/lib.rs +++ b/crates/matching/src/lib.rs @@ -37,6 +37,36 @@ impl OrderBook { } } + /// Buy whole shares at maker prices, walking the same FIFO ask tree as a limit buy. + pub fn match_budget_buy(&self, seq: i64, limit: i64, budget: i64) -> Vec { + let mut cash = budget; + let mut capacity = i64::MAX; + let mut fills = Vec::new(); + for ask in self.asks.values() { + if cash <= 0 || ask.price > limit || capacity == 0 { + break; + } + let affordable = if ask.price == 0 { + capacity + } else { + cash / ask.price + }; + let quantity = ask.remaining.min(affordable).min(capacity); + if quantity <= 0 { + break; + } + fills.push(Fill { + bid: seq, + ask: ask.seq, + price: ask.price, + quantity, + }); + cash -= ask.price * quantity; + capacity -= quantity; + } + fills + } + pub fn opening(&self) -> Vec { let (Some(bid), Some(ask)) = (self.bids.values().next(), self.asks.values().next()) else { return Vec::new(); diff --git a/docs/prediction-parity.md b/docs/prediction-parity.md index f4adff8..e62bec2 100644 --- a/docs/prediction-parity.md +++ b/docs/prediction-parity.md @@ -6,7 +6,7 @@ |---|---|---| | 事件、市场和结果 | 体育事件下有多个二元合约、规则、结果标签与稳定本地资产 ID | 场所资产映射、非体育事件、多结果组合和版本映射 | | 报价与走势 | 本地成交曲线、连续交易展示价、分档盘口 | 细分报价单位、外场快照和实际历史样本 | -| 委托与成交 | 单簿价格时间优先、GTC、GTD、IOC、FAK、FOK、连续交易 post-only、互补买卖单与批量撤单 | 按金额买入及场所延迟和失败回报 | +| 委托与成交 | 单簿价格时间优先、GTC、GTD、IOC、FAK、FOK、连续交易 post-only、互补买卖单、批量撤单与整份按金额买入 | 小数份额、金额精度及场所延迟和失败回报 | | 持仓与抵押 | 模拟资产拆分、成套合并、裁决后按账户主动赎回 | 链上赎回回执、费用与多结果转换 | | 裁决与交割 | 人工、两轮乐观裁决或双端点 TWAP 比较,保存证据并兑付 | 保证金及奖励、真实 UMA 仲裁、Chainlink 签名与现场报价、链上交割状态 | | 客户端 | CLI 查询规则、价格曲线、报价、账户挂单、逐笔成交、单笔终态与持仓状态 | 账户认证与会话可见范围、非交易活动、成本与盈亏及断线回补 | @@ -102,3 +102,9 @@ Polymarket 的 CTF 市场使用结果 token ID,Protocol V2 市场使用结果 `{"op":"cancel_orders","id":"batch-1","account":"alice","orders":[12,7,12,19]}` 接受 1 至 3000 个原始订单号,忽略重复项。假设 12 号仍有余量、7 号已全部成交、19 号不属于 Alice,回执为 `{"canceled":[12],"not_canceled":{"7":"order is filled","19":"order not found"}}`。买单只退还限价乘以未成交份数的已预留资金;卖单只返还未卖出的份额。新请求键会重新评估订单,重试原请求键和原内容会重放第一次的结果。 `cancel_market_orders` 必须指定 market 或 asset_id。仅提供 market 会撤销该账户在市场两侧的活跃订单,指定资产则只选择该结果的原始委托。例如撤掉原始 YES 卖单后,同价位由 NO 买单映射的流动性仍然存在。`{"op":"cancel_all","id":"all-1","account":"alice"}` 覆盖 Alice 在所有市场的活跃单。匹配不到挂单时返回空列表;账户名称是模拟 CLI 参数,外场认证范围与错误文本仍待实测。单笔 cancel 保留原有回执。[官方撤单范围与回执](https://docs.polymarket.com/trading/manage-orders.md) + +## 按金额买入 + +`{"op":"market_buy","id":"cash-buy-1","asset_id":"eb:YES:e","account":"buyer","amount_cents":170,"max_price":50,"tif":"FAK"}` 在连续交易阶段锁定 170 分预算。若最优卖单为 35 分两份,下一档为 NO 买单映射出的 45 分三份,则成交四份,实付 160 分,退回 10 分。订单可查到原始金额和实付金额;精确查询中的 original_size 是本地换算后的成交份数。操作接受现有 market / outcome 寻址,max_price 为每份最高可接受分价。FAK 为本地默认值;剩余预算即时撤销,有余款的回执 status 为 cancelled,filled 保留实际成交份数。 + +FOK 要求整笔金额成交,无法用完预算时交易回滚。超过最高价、没有可负担份额、账户可用现金不足以预留全部预算时也拒绝。买方按预算预留,遇较优成交价时只产生一次未花金额退款。当前撮合单位为整数份和分,外场支持小数份额及签名金额舍入;费用和实际外场零碎余量行为仍待对照。测试入口为 cash_buy_reconciles_direct_and_complementary_depth_with_an_exact_budget。[Polymarket 市价单与金额口径](https://docs.polymarket.com/trading/place-orders.md)