From 5d82be009148d426c2cdce45aee39da461bd3cdc Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Thu, 3 Dec 2026 07:18:25 +0800 Subject: [PATCH] Derive market order protection from visible opposing depth --- crates/exchange/README.md | 18 +++++++++ crates/exchange/src/book.rs | 14 ++++--- crates/exchange/src/estimate.rs | 54 +++++++++++++------------ crates/exchange/src/market.rs | 10 ++++- crates/exchange/src/resident.rs | 36 +++++++++++++++++ crates/exchange/tests/market.rs | 59 ++++++++++++++++++++++++++++ crates/matching/README.md | 4 ++ crates/matching/src/lib.rs | 18 +++++++++ docs/examples/depth-protection.jsonl | 13 ++++++ docs/prediction-parity.md | 8 ++++ 10 files changed, 201 insertions(+), 33 deletions(-) create mode 100644 docs/examples/depth-protection.jsonl diff --git a/crates/exchange/README.md b/crates/exchange/README.md index c1bbd51..303d97a 100644 --- a/crates/exchange/README.md +++ b/crates/exchange/README.md @@ -858,3 +858,21 @@ sequenceDiagram E-->>C: 拒绝请求,保留账户余额与挂单 end ``` + +### 市价单按盘口深度定价 + +```mermaid +sequenceDiagram + participant C as 客户端 + participant E as estimate.rs 或 market.rs 与 book.rs + participant R as resident.rs + participant B as matching 盘口 + C->>E: 买入 1.80 美元,省略最高价 + E->>R: 用本事务已同步的 YES 盘口计算保护价 + R->>B: 读取最优价起的卖盘档位 + B-->>R: 0.40 有 2 份,0.50 有 3 份 + R->>R: 累计金额,第二档覆盖 1.80 美元 + R-->>E: 保护价 0.50,包含互补 NO 买单形成的卖盘 + E->>B: 用预算和保护价计算可成交数量 + E-->>C: 估价返回预期成交,下单提交成功后返回实际成交 +``` diff --git a/crates/exchange/src/book.rs b/crates/exchange/src/book.rs index 23cb8a9..0f14fef 100644 --- a/crates/exchange/src/book.rs +++ b/crates/exchange/src/book.rs @@ -171,7 +171,7 @@ pub(crate) struct BudgetBuy { pub account: String, pub key_id: Option, pub amount_cents: i64, - pub max_price: i64, + pub max_price: Option, pub tif: TimeInForce, } @@ -188,15 +188,16 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R identifier(&account)?; amount(amount_cents)?; phase(tx, &market, &["continuous"])?; - ensure!( - matches!(outcome.as_str(), "YES" | "NO") - && (0..=crate::tick_size::PAR).contains(&max_price), - "invalid outcome or price" - ); + ensure!(matches!(outcome.as_str(), "YES" | "NO"), "invalid outcome"); ensure!( matches!(tif, TimeInForce::Fak | TimeInForce::Fok), "market buy requires FAK or FOK" ); + let max_price = books + .protection_price(&market, &outcome, Side::Buy, amount_cents, max_price, tif) + .ok_or_else(|| { + anyhow::anyhow!("insufficient opposing depth for market buy protection price") + })?; let rate = crate::fees::rate(tx, &market)?; if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? { minimum.check_budget(amount_cents, max_price, rate)?; @@ -254,6 +255,7 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R if let Some(amounts) = amounts { receipt["order_amounts"] = amounts.json(); } + receipt["protection_price_micros"] = json!(max_price * crate::tick_size::PRICE_MICROS); if fee > 0 || spent % 10000 != 0 { receipt["fee_micros"] = json!(fee); receipt["unspent_micros"] = json!(unspent_micros); diff --git a/crates/exchange/src/estimate.rs b/crates/exchange/src/estimate.rs index 485dfac..71c6269 100644 --- a/crates/exchange/src/estimate.rs +++ b/crates/exchange/src/estimate.rs @@ -65,34 +65,36 @@ impl Request { ), }; let tick = crate::tick_size::TickSize::load(tx, &market)?; - let edge = tick.as_ref().map_or(0, |t| i64::from(t.local_step().get())); - let limit = limit.unwrap_or(if side == Side::Buy { - crate::tick_size::PAR - edge - } else { - edge - }); let tif = tif.unwrap_or(TimeInForce::Fak); ensure!( matches!(tif, TimeInForce::Fak | TimeInForce::Fok), "estimate requires FAK or FOK" ); - ensure!( - matches!(outcome.as_str(), "YES" | "NO") - && (0..=crate::tick_size::PAR).contains(&limit), - "invalid outcome or price" - ); - let amounts = - crate::market_amounts::Amounts::for_order(tick.as_ref(), side, requested, limit)?; + ensure!(matches!(outcome.as_str(), "YES" | "NO"), "invalid outcome"); phase(tx, &market, &["continuous"])?; - let rate = crate::fees::rate(tx, &market)?; - if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? { - match side { - Side::Buy => minimum.check_budget(requested, limit, rate)?, - Side::Sell => minimum.check_microshares(requested * crate::lots::MICROS)?, - } - } let changes = books.changes(tx)?; books.apply(changes); + let protection = books.protection_price(&market, &outcome, side, requested, limit, tif); + let amounts = match protection { + Some(price) => { + crate::market_amounts::Amounts::for_order(tick.as_ref(), side, requested, price)? + } + None => None, + }; + let rate = crate::fees::rate(tx, &market)?; + if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? { + match (side, protection) { + (Side::Buy, Some(price)) => minimum.check_budget(requested, price, rate)?, + (Side::Sell, _) => minimum.check_microshares(requested * crate::lots::MICROS)?, + (Side::Buy, None) => {} + } + } + // A failed FOK estimate still reports how much depth was visible. + let limit = protection.unwrap_or(if side == Side::Buy { + crate::tick_size::PAR + } else { + 0 + }); // The hypothetical incoming order follows all resting orders in time priority. let mut fills = books .get(&market, &outcome) @@ -117,16 +119,18 @@ impl Request { } else { 0 }; - let fully_fillable = match side { - Side::Buy => remaining_cash == 0, - Side::Sell => requested == shares, - }; + let fully_fillable = protection.is_some() + && match side { + Side::Buy => remaining_cash == 0, + Side::Sell => requested == shares, + }; let mut result = json!({"asset_id":assets::id(&market,&outcome),"filled_shares":crate::lots::display(shares), "gross_cents":crate::inventory::decimal(gross.into(),10000),"best_fill_price":fills.first().map(|f|crate::inventory::decimal(f.price.into(),100)), "worst_fill_price":fills.last().map(|f|crate::inventory::decimal(f.price.into(),100)), "average_price_micros":(i128::from(gross)*100).checked_div(i128::from(shares)), "fee_micros":fee,"taker_fee_rate_ppm":rate, - "fully_fillable":fully_fillable,"executable":shares>0 && (tif==TimeInForce::Fak || fully_fillable)}); + "protection_price_micros":protection.map(|p|p * crate::tick_size::PRICE_MICROS), + "fully_fillable":fully_fillable,"executable":protection.is_some() && shares>0 && (tif==TimeInForce::Fak || fully_fillable)}); if let Some(amounts) = amounts { result["order_amounts"] = amounts.json(); } diff --git a/crates/exchange/src/market.rs b/crates/exchange/src/market.rs index cd3a028..d58ce9c 100644 --- a/crates/exchange/src/market.rs +++ b/crates/exchange/src/market.rs @@ -179,7 +179,12 @@ pub(crate) fn apply( "market sell requires FAK or FOK" ); let qty = crate::lots::amount(qty, size_micros)?; - let price = crate::tick_size::required(min_price, min_price_micros)?; + let limit = crate::tick_size::input(min_price, min_price_micros)?; + let price = books + .protection_price(&market, &outcome, matching::Side::Sell, qty, limit, tif) + .ok_or_else(|| { + anyhow::anyhow!("insufficient opposing depth for market sell protection price") + })?; let tick = crate::tick_size::TickSize::load(tx, &market)?; let amounts = crate::market_amounts::Amounts::for_order( tick.as_ref(), @@ -207,6 +212,7 @@ pub(crate) fn apply( if let Some(amounts) = amounts { receipt["order_amounts"] = amounts.json(); } + receipt["protection_price_micros"] = json!(price * crate::tick_size::PRICE_MICROS); receipt["proceeds_cents"] = json!(crate::inventory::decimal(result.gross_micros.into(), 10000)); receipt["unsold_shares"] = json!(crate::lots::display(qty - result.filled)); @@ -234,7 +240,7 @@ pub(crate) fn apply( account, key_id, amount_cents: crate::market_amounts::cash_cents(amount_cents, amount_micros)?, - max_price: crate::tick_size::required(max_price, max_price_micros)?, + max_price: crate::tick_size::input(max_price, max_price_micros)?, tif: tif.unwrap_or(crate::command::TimeInForce::Fak), }, ), diff --git a/crates/exchange/src/resident.rs b/crates/exchange/src/resident.rs index 85290f2..02da353 100644 --- a/crates/exchange/src/resident.rs +++ b/crates/exchange/src/resident.rs @@ -43,6 +43,42 @@ impl Books { self.markets.get(market)?.get(outcome) } + /// The cash input to an exchange command is in cents, the share input in lots. + pub fn protection_price( + &self, + market: &str, + outcome: &str, + side: Side, + requested: i64, + limit: Option, + tif: crate::command::TimeInForce, + ) -> Option { + limit.or_else(|| { + // The reference Python SDK sums one binary64 value per public + // price level, in dollars (BUY) or shares (SELL). Match its limit + // selection here; all execution and settlement use integer units. + let target = requested as f64 / 100.0; + let mut depth = 0.0; + let mut last = None; + for (price, lots) in self.get(market, outcome)?.opposing_levels(side) { + let shares = lots as f64 / crate::lots::PER_SHARE as f64; + depth += match side { + Side::Buy => shares * (price as f64 / crate::tick_size::PAR as f64), + Side::Sell => shares, + }; + last = Some(price); + if depth >= target { + return last; + } + } + if tif == crate::command::TimeInForce::Fak { + last + } else { + None + } + }) + } + pub fn recover(tx: &Transaction) -> Result { let mut books = Self::default(); let mut stmt = tx.prepare( diff --git a/crates/exchange/tests/market.rs b/crates/exchange/tests/market.rs index 25e06a4..85f8e49 100644 --- a/crates/exchange/tests/market.rs +++ b/crates/exchange/tests/market.rs @@ -2686,3 +2686,62 @@ fn unsafe_encoded_buy_is_rejected_by_preview_estimate_and_submission() { } assert_eq!(state(&mut e), before); } + +#[test] +fn derives_protection_from_current_depth_and_replays_the_original_receipt() { + let dir = tempdir().unwrap(); + let path = dir.path().join("book.db"); + let mut writer = Exchange::open(&path).unwrap(); + let mut client = Exchange::open(&path).unwrap(); + for line in include_str!("../../../docs/examples/depth-protection.jsonl").lines() { + let cmd: Value = serde_json::from_str(line).unwrap(); + match cmd["op"].as_str().unwrap() { + "estimate" => { + let result = client.execute(cmd.clone()).unwrap(); + assert_eq!(result["filled_shares"], 5); + if cmd["tif"] == "FOK" { + assert!(result["protection_price_micros"].is_null()); + assert_eq!(result["executable"], false); + let before = state(&mut client); + assert!(client.execute(json!({"op":"market_buy","id":"short","asset_id":"eb:YES:fixture","account":"taker","amount_cents":231,"tif":"FOK"})).is_err()); + assert_eq!(state(&mut client), before); + } else { + assert_eq!(result["protection_price_micros"], 500000); + assert_eq!(result["executable"], true); + } + } + "market_buy" => { + let r = client.execute(cmd.clone()).unwrap(); + assert_eq!(r["protection_price_micros"], 500000); + assert_eq!(r["filled"], 4); + assert_eq!(r["spent_cents"], 180); + drop(client); + client = Exchange::open(&path).unwrap(); + assert_eq!(client.execute(cmd).unwrap(), r); + } + "market_sell" => { + let r = client.execute(cmd).unwrap(); + assert_eq!(r["protection_price_micros"], 200000); + assert_eq!(r["proceeds_cents"], 80); + } + _ => { + writer.execute(cmd).unwrap(); + } + } + } +} + +#[test] +fn automatic_price_uses_sdk_level_precision_while_cash_execution_is_exact() { + let mut e = Exchange::open(":memory:").unwrap(); + setup(&mut e); + e.execute(json!({"op":"open","id":"open","market":"e"})) + .unwrap(); + for (id, price) in [("a10", 10), ("a70", 70), ("a90", 90)] { + e.execute(order(id, "alice", "sell", price, 1)).unwrap(); + } + let r = e.execute(json!({"op":"market_buy","id":"depth","market":"e","outcome":"YES","account":"bob","amount_cents":80,"tif":"FOK"})).unwrap(); + assert_eq!(r["protection_price_micros"], 900000); + assert_eq!(r["spent_cents"], 80); + assert_eq!(r["filled"], 2); +} diff --git a/crates/matching/README.md b/crates/matching/README.md index 6dee337..a78c02b 100644 --- a/crates/matching/README.md +++ b/crates/matching/README.md @@ -23,6 +23,10 @@ sequenceDiagram alt 连续交易 B->>M: match_incoming,传入一条新订单 M->>M: 从对手方最优价起遍历,同价按原序号分配 + else 未指定市价委托保护价 + B->>M: opposing_levels,传入买卖方向 + M->>M: 从最优对手价起,逐档汇总同价订单的剩余份额 + M-->>B: 逐档返回价格和总量,调用方按需停止读取 else 盘中按金额买入 B->>M: match_budget_buy,传入买单序号、最高价、以微美元计的总预算 M->>M: 在同一卖盘上逐单扣减可用预算,末档取预算可负担的最大整数单位数 diff --git a/crates/matching/src/lib.rs b/crates/matching/src/lib.rs index 4e98f63..5683cf1 100644 --- a/crates/matching/src/lib.rs +++ b/crates/matching/src/lib.rs @@ -42,6 +42,24 @@ impl OrderBook { } } + /// Visible opposing price levels, best first. Sum orders at one level + /// before exposing it so a client sees the same depth regardless of FIFO splits. + pub fn opposing_levels(&self, side: Side) -> impl Iterator + '_ { + let orders: Box + '_> = match side { + Side::Buy => Box::new(self.asks.values()), + Side::Sell => Box::new(self.bids.values()), + }; + let mut orders = orders.peekable(); + std::iter::from_fn(move || { + let first = orders.next()?; + let mut size = i128::from(first.remaining); + while let Some(order) = orders.next_if(|o| o.price == first.price) { + size += i128::from(order.remaining); + } + Some((first.price, size)) + }) + } + /// Buy integer lots at maker prices. Express the budget in price ticks /// multiplied by quantity lots, the same units as price * remaining. pub fn match_budget_buy(&self, seq: i64, limit: i64, budget: i64) -> Vec { diff --git a/docs/examples/depth-protection.jsonl b/docs/examples/depth-protection.jsonl new file mode 100644 index 0000000..83c21f6 --- /dev/null +++ b/docs/examples/depth-protection.jsonl @@ -0,0 +1,13 @@ +{"op":"list","id":"list","market":"fixture","rules":"Simulated result","tick_size":"0.01"} +{"op":"fund","id":"a","account":"maker","cents":2000} +{"op":"fund","id":"b","account":"taker","cents":1000} +{"op":"split","id":"mint","market":"fixture","account":"maker","qty":7} +{"op":"open","id":"start","market":"fixture"} +{"op":"order","id":"ordinary","asset_id":"eb:YES:fixture","account":"maker","side":"sell","price":40,"qty":2} +{"op":"order","id":"complement","asset_id":"eb:NO:fixture","account":"maker","side":"buy","price":50,"qty":3} +{"op":"estimate","asset_id":"eb:YES:fixture","side":"buy","amount_cents":231,"tif":"FOK"} +{"op":"estimate","asset_id":"eb:YES:fixture","side":"buy","amount_cents":231,"tif":"FAK"} +{"op":"market_buy","id":"take","asset_id":"eb:YES:fixture","account":"taker","amount_cents":180,"tif":"FOK"} +{"op":"order","id":"bid-low","asset_id":"eb:YES:fixture","account":"maker","side":"buy","price":20,"qty":2} +{"op":"order","id":"bid-high","asset_id":"eb:YES:fixture","account":"maker","side":"buy","price":30,"qty":2} +{"op":"market_sell","id":"sell","asset_id":"eb:YES:fixture","account":"taker","qty":3,"tif":"FOK"} diff --git a/docs/prediction-parity.md b/docs/prediction-parity.md index 39c702e..f45dc89 100644 --- a/docs/prediction-parity.md +++ b/docs/prediction-parity.md @@ -279,3 +279,11 @@ order、market_sell 和卖出 estimate 可用 size_micros 输入数量,也可 配置价格步长后,`market_amounts` 读出保护价对应的 `makerAmount` 与 `takerAmount`。买单用 `amount_cents` 或 `amount_micros` 指定预算,向下取整到美分。卖单用 `qty` 或 `size_micros` 指定份额,向下取整到 0.01 份。显式保护价必须落在市场网格上。买单编码的有效价格若达到用户上限加 0.0001,预览、估价和下单均拒绝。成交估价及真实模拟成交回执通过 `order_amounts` 给出相同口径。估价还考虑当时盘口、手续费和本地可成交单位。[官方市价单金额计算](https://docs.polymarket.com/trading/place-orders.md) [回放样例](examples/market-amounts.jsonl)先预览 10 美元预算在最高价 0.52 下的 19.2307 份编码,再按 0.50 卖盘买到 20 份。随后卖出 5.01 份,最低接受 0.48 美元,实际按 0.50 美元得到 2.505 美元。本地成交的最小数量单位仍是 0.01 份。这里复现公开委托金额公式,真实签名、生产成交粒度与资金到账仍待对照。 + +## 由对手盘口推导市价单保护价 + +省略最高买价或最低卖价时,使用当前交易品盘口的价格优先顺序。买单逐档累计金额,卖单逐档累计份额,首次达到请求量的一档给出保护价。FAK 在深度不足时取最远可见档。FOK 在深度不足时无法生成委托。空盘两种模式都无法自动定价。估价用 `protection_price_micros: null` 和 `executable: false` 表示无法定价,并返回可见的部分深度。显式保护价继续生效。[官方 Python CLOB v2 定价实现(固定版本)](https://github.com/Polymarket/py-clob-client-v2/blob/9c7c9e89cbbc11528daae90dc66ef65c9380cbdf/py_clob_client_v2/order_builder/builder.py#L307-L351) + +[本地回放样例](examples/depth-protection.jsonl)包含普通 YES 卖单和 NO 买单映射出的 YES 卖盘。定价使用费用前的订单簿深度,实际成交另行检查预算、费用和本地数量精度。保护价只对该次读取的盘口有效,提交请求时会重新读取。客户端可显式提交预览过的保护价。相同请求号的重试返回已保存的原始回执。 + +在固定版本的官方 Python 函数上实测,若依次有 0.10、0.70、0.90 美元各一份卖盘,0.80 美元预算会得到 0.90 美元保护价。原因是前两档的二进制浮点和略低于 0.80。本地在推导委托保护价时复现这一可观察结果,成交和扣款仍按整数计算,两份合计恰好 0.80 美元。样例未向生产环境发单。