From f90605bfc78815af7e3059ed56c234f6e4605183 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Thu, 3 Dec 2026 07:12:31 +0800 Subject: [PATCH] Encode market order amounts and enforce rounded buy protection --- crates/exchange/README.md | 33 ++++++ crates/exchange/src/assets.rs | 1 + crates/exchange/src/book.rs | 10 +- crates/exchange/src/catalog.rs | 2 + crates/exchange/src/command.rs | 3 +- crates/exchange/src/estimate.rs | 23 ++-- crates/exchange/src/lib.rs | 2 + crates/exchange/src/market.rs | 16 ++- crates/exchange/src/market_amounts.rs | 146 ++++++++++++++++++++++++++ crates/exchange/tests/market.rs | 54 ++++++++++ docs/examples/market-amounts.jsonl | 12 +++ docs/prediction-parity.md | 6 ++ 12 files changed, 290 insertions(+), 18 deletions(-) create mode 100644 crates/exchange/src/market_amounts.rs create mode 100644 docs/examples/market-amounts.jsonl diff --git a/crates/exchange/README.md b/crates/exchange/README.md index 023dbc6..c1bbd51 100644 --- a/crates/exchange/README.md +++ b/crates/exchange/README.md @@ -825,3 +825,36 @@ sequenceDiagram C->>E: 重启后读取盘口和成交曲线 E-->>C: 余单按原序号恢复,历史返回 price_micros=13000 ``` + +### 市价单的保护价与成交价 + +```mermaid +flowchart LR + lib["lib.rs / assets.rs"] --> catalog["catalog.rs / estimate.rs"] + lib --> market["command.rs / market.rs"] + market --> book["book.rs"] + catalog --> encode["market_amounts.rs"] + market --> encode + book --> encode + encode --> grid["tick_size.rs / lots.rs"] +``` + +```mermaid +sequenceDiagram + participant C as 客户端 + participant E as Exchange + participant A as 市价单金额编码 + participant B as 常驻盘口 + C->>E: 预览花 10 美元,最高价 0.52 + E->>A: 按该市场 0.01 步长计算两侧金额 + A-->>C: 经 Exchange 返回 10000000 / 19230700 + C->>E: 确认市价买入 + E->>A: 按当前步长重算并检查保护价 + alt 编码有效 + E->>B: 按 10 美元预算与 0.52 上限撮合 + B-->>E: 卖盘 20 份,价格 0.50 + E-->>C: 成交 20 份,实付 10 美元,附原委托金额 + else 取整后达到上限加 0.0001 + E-->>C: 拒绝请求,保留账户余额与挂单 + end +``` diff --git a/crates/exchange/src/assets.rs b/crates/exchange/src/assets.rs index 9830a5a..7781491 100644 --- a/crates/exchange/src/assets.rs +++ b/crates/exchange/src/assets.rs @@ -69,6 +69,7 @@ pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> { | "market_sell" | "estimate" | "limit_amounts" + | "market_amounts" | "tick_history" | "tick_size_change" | "market_buy" diff --git a/crates/exchange/src/book.rs b/crates/exchange/src/book.rs index 9ee0de9..23cb8a9 100644 --- a/crates/exchange/src/book.rs +++ b/crates/exchange/src/book.rs @@ -201,8 +201,11 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? { minimum.check_budget(amount_cents, max_price, rate)?; } - crate::tick_size::validate( - crate::tick_size::TickSize::load(tx, &market)?.as_ref(), + let tick = crate::tick_size::TickSize::load(tx, &market)?; + let amounts = crate::market_amounts::Amounts::for_order( + tick.as_ref(), + Side::Buy, + amount_cents, max_price, )?; ledger::cash(tx, &account, -amount_cents)?; @@ -248,6 +251,9 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R "cancelled" }; let mut receipt = json!({"order":seq,"status":status,"filled":crate::lots::display(quantity),"amount_cents":amount_cents,"spent_cents":crate::inventory::decimal(spent.into(),10000),"unspent_cents":crate::inventory::decimal(unspent_micros.into(),10000)}); + if let Some(amounts) = amounts { + receipt["order_amounts"] = amounts.json(); + } if fee > 0 || spent % 10000 != 0 { receipt["fee_micros"] = json!(fee); receipt["unspent_micros"] = json!(unspent_micros); diff --git a/crates/exchange/src/catalog.rs b/crates/exchange/src/catalog.rs index acce230..9788aeb 100644 --- a/crates/exchange/src/catalog.rs +++ b/crates/exchange/src/catalog.rs @@ -236,6 +236,7 @@ impl Listing { pub(crate) enum Query { Estimate(crate::estimate::Request), LimitAmounts(crate::tick_size::LimitAmounts), + MarketAmounts(crate::market_amounts::Request), TickHistory(crate::tick_changes::History), PricesHistory(crate::prices_history::Request), QuoteHistory(crate::quotes::Filter), @@ -307,6 +308,7 @@ impl Query { Self::QuoteHistory(request) => request.read(db), Self::PricesHistory(request) => request.read(db), Self::TickHistory(request) => request.read(db), + Self::MarketAmounts(request) => request.read(db), Self::LimitAmounts(request) => request.read(db), Self::Estimate(request) => request.read(db, books), Self::Resolution { market } => crate::resolution::read(db, &market), diff --git a/crates/exchange/src/command.rs b/crates/exchange/src/command.rs index 422fb55..0f38b42 100644 --- a/crates/exchange/src/command.rs +++ b/crates/exchange/src/command.rs @@ -98,7 +98,8 @@ pub(crate) enum Command { outcome: String, account: String, key_id: Option, - amount_cents: i64, + amount_cents: Option, + amount_micros: Option, max_price: Option, max_price_micros: Option, tif: Option, diff --git a/crates/exchange/src/estimate.rs b/crates/exchange/src/estimate.rs index adce60c..485dfac 100644 --- a/crates/exchange/src/estimate.rs +++ b/crates/exchange/src/estimate.rs @@ -1,10 +1,4 @@ -use crate::{ - assets, - book::gross_micros, - command::TimeInForce, - resident::Books, - validation::{amount, phase}, -}; +use crate::{assets, book::gross_micros, command::TimeInForce, resident::Books, validation::phase}; use anyhow::{ensure, Result}; use matching::{Order, Side}; use rusqlite::Transaction; @@ -17,7 +11,8 @@ pub(crate) enum Request { Buy { market: String, outcome: String, - amount_cents: i64, + amount_cents: Option, + amount_micros: Option, max_price: Option, max_price_micros: Option, tif: Option, @@ -40,6 +35,7 @@ impl Request { market, outcome, amount_cents, + amount_micros, max_price, max_price_micros, tif, @@ -47,7 +43,7 @@ impl Request { market, outcome, Side::Buy, - amount_cents, + crate::market_amounts::cash_cents(amount_cents, amount_micros)?, crate::tick_size::input(max_price, max_price_micros)?, tif, ), @@ -76,9 +72,6 @@ impl Request { edge }); let tif = tif.unwrap_or(TimeInForce::Fak); - if side == Side::Buy { - amount(requested)?; - } ensure!( matches!(tif, TimeInForce::Fak | TimeInForce::Fok), "estimate requires FAK or FOK" @@ -88,7 +81,8 @@ impl Request { && (0..=crate::tick_size::PAR).contains(&limit), "invalid outcome or price" ); - crate::tick_size::validate(tick.as_ref(), limit)?; + let amounts = + crate::market_amounts::Amounts::for_order(tick.as_ref(), side, requested, limit)?; phase(tx, &market, &["continuous"])?; let rate = crate::fees::rate(tx, &market)?; if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? { @@ -133,6 +127,9 @@ impl Request { "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)}); + if let Some(amounts) = amounts { + result["order_amounts"] = amounts.json(); + } match side { Side::Buy => { result["total_spent_micros"] = json!(gross + fee); diff --git a/crates/exchange/src/lib.rs b/crates/exchange/src/lib.rs index b5fb595..24e4721 100644 --- a/crates/exchange/src/lib.rs +++ b/crates/exchange/src/lib.rs @@ -21,6 +21,7 @@ mod kickoff; mod ledger; mod lots; mod market; +mod market_amounts; mod minimum_size; mod neg_risk; mod open_interest; @@ -112,6 +113,7 @@ impl Exchange { "assets" | "estimate" | "limit_amounts" + | "market_amounts" | "tick_history" | "catalog" | "events" diff --git a/crates/exchange/src/market.rs b/crates/exchange/src/market.rs index 5b7f113..cd3a028 100644 --- a/crates/exchange/src/market.rs +++ b/crates/exchange/src/market.rs @@ -179,6 +179,14 @@ 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 tick = crate::tick_size::TickSize::load(tx, &market)?; + let amounts = crate::market_amounts::Amounts::for_order( + tick.as_ref(), + matching::Side::Sell, + qty, + price, + )?; let result = book::submit( tx, books, @@ -188,7 +196,7 @@ pub(crate) fn apply( key_id, outcome, side: "sell".to_owned(), - price: crate::tick_size::required(min_price, min_price_micros)?, + price, qty, tif, expiration: None, @@ -196,6 +204,9 @@ pub(crate) fn apply( }, )?; let mut receipt = result.receipt(); + if let Some(amounts) = amounts { + receipt["order_amounts"] = amounts.json(); + } receipt["proceeds_cents"] = json!(crate::inventory::decimal(result.gross_micros.into(), 10000)); receipt["unsold_shares"] = json!(crate::lots::display(qty - result.filled)); @@ -210,6 +221,7 @@ pub(crate) fn apply( account, key_id, amount_cents, + amount_micros, max_price, max_price_micros, tif, @@ -221,7 +233,7 @@ pub(crate) fn apply( outcome, account, key_id, - amount_cents, + amount_cents: crate::market_amounts::cash_cents(amount_cents, amount_micros)?, max_price: crate::tick_size::required(max_price, max_price_micros)?, tif: tif.unwrap_or(crate::command::TimeInForce::Fak), }, diff --git a/crates/exchange/src/market_amounts.rs b/crates/exchange/src/market_amounts.rs new file mode 100644 index 0000000..a210be9 --- /dev/null +++ b/crates/exchange/src/market_amounts.rs @@ -0,0 +1,146 @@ +use crate::{assets, lots, minimum_size::MinimumSize, tick_size::TickSize}; +use anyhow::{ensure, Result}; +use matching::Side; +use rusqlite::Connection; +use serde::Deserialize; +use serde_json::{json, Value}; + +pub(crate) fn cash_cents(cents: Option, micros: Option) -> Result { + let cents = match (cents, micros) { + (Some(n), None) => n, + (None, Some(n)) if n > 0 => n / 10_000, + _ => anyhow::bail!("provide one positive amount_cents or amount_micros"), + }; + crate::validation::amount(cents)?; + Ok(cents) +} + +pub(crate) struct Amounts { + maker: i64, + taker: i64, +} + +impl Amounts { + pub fn for_order( + tick: Option<&TickSize>, + side: Side, + requested: i64, + price_units: i64, + ) -> Result> { + match tick { + Some(tick) => Self::encode( + tick, + side, + requested, + price_units * crate::tick_size::PRICE_MICROS, + ) + .map(Some), + None => { + crate::tick_size::validate(None, price_units)?; + Ok(None) + } + } + } + + // requested is in whole cents for BUY, 0.01-share lots for SELL. + fn encode(tick: &TickSize, side: Side, requested: i64, price: i64) -> Result { + tick.check(price)?; + let maker = requested + .checked_mul(10_000) + .ok_or_else(|| anyhow::anyhow!("order amount overflow"))?; + ensure!(maker > 0, "positive order amount required"); + let scale = 1_000_000_i128; + let taker = match side { + Side::Buy => { + let quantum = match tick.0 { + 100_000 => 1000, + 10_000 => 100, + 5_000 | 1_000 => 10, + 2_500 | 100 => 1, + _ => anyhow::bail!("unsupported market tick"), + }; + let cash = i128::from(maker) * scale; + let shares = cash / i128::from(price) / quantum * quantum; + ensure!( + cash < shares * i128::from(price + 100), + "rounded market buy exceeds price protection" + ); + shares + } + Side::Sell => i128::from(maker) * i128::from(price) / scale, + }; + Ok(Self { + maker, + taker: i64::try_from(taker)?, + }) + } + + pub fn json(&self) -> Value { + json!({"makerAmount": self.maker.to_string(), "takerAmount": self.taker.to_string()}) + } +} + +#[derive(Deserialize)] +#[serde(tag = "side", rename_all = "lowercase", deny_unknown_fields)] +pub(crate) enum Request { + Buy { + market: String, + outcome: String, + price_micros: i64, + amount_cents: Option, + amount_micros: Option, + }, + Sell { + market: String, + outcome: String, + price_micros: i64, + qty: Option, + size_micros: Option, + }, +} +impl Request { + pub fn read(self, db: &Connection) -> Result { + let (market, outcome, side, requested, price) = match self { + Self::Buy { + market, + outcome, + price_micros, + amount_cents, + amount_micros, + } => ( + market, + outcome, + Side::Buy, + cash_cents(amount_cents, amount_micros)?, + price_micros, + ), + Self::Sell { + market, + outcome, + price_micros, + qty, + size_micros, + } => ( + market, + outcome, + Side::Sell, + lots::amount(qty, size_micros)?, + price_micros, + ), + }; + ensure!(matches!(outcome.as_str(), "YES" | "NO"), "invalid outcome"); + let tick = TickSize::load(db, &market)? + .ok_or_else(|| anyhow::anyhow!("listed market with configured tick_size required"))?; + let amounts = Amounts::encode(&tick, side, requested, price)?; + if let Some(minimum) = MinimumSize::load(db, &market)? { + minimum.check_microshares(match side { + Side::Buy => amounts.taker, + Side::Sell => amounts.maker, + })?; + } + let mut result = amounts.json(); + result["asset_id"] = json!(assets::id(&market, &outcome)); + result["tick_size"] = json!(tick.text()); + Ok(result) + } +} diff --git a/crates/exchange/tests/market.rs b/crates/exchange/tests/market.rs index a1fd0a1..25e06a4 100644 --- a/crates/exchange/tests/market.rs +++ b/crates/exchange/tests/market.rs @@ -2632,3 +2632,57 @@ fn auction_uses_fine_grid_and_coarsening_releases_exact_bid_reserve() { assert_eq!(after["available_micros"], 974000); assert_eq!(after["reserved_micros"], 0); } + +#[test] +fn market_amounts_preview_and_execution_share_the_same_protection() { + let mut exchange = Exchange::open(":memory:").unwrap(); + let buy = json!({"makerAmount":"10000000","takerAmount":"19230700"}); + let sell = json!({"makerAmount":"5010000","takerAmount":"2404800"}); + for line in include_str!("../../../docs/examples/market-amounts.jsonl").lines() { + let cmd: Value = serde_json::from_str(line).unwrap(); + let result = exchange.execute(cmd.clone()).unwrap(); + match cmd["op"].as_str().unwrap() { + "market_amounts" => { + let expected = if cmd["side"] == "buy" { &buy } else { &sell }; + for key in ["makerAmount", "takerAmount"] { + assert_eq!(result[key], expected[key]); + } + } + "estimate" => { + assert_eq!(result["order_amounts"], buy); + assert_eq!(result["filled_shares"], 20); + } + "market_buy" => { + assert_eq!(result["order_amounts"], buy); + assert_eq!(result["filled"], 20); + assert_eq!(result["spent_cents"], 1000); + } + "market_sell" => { + assert_eq!(result["order_amounts"], sell); + assert_eq!(result["proceeds_cents"].to_string(), "250.5"); + } + _ => {} + } + } +} + +#[test] +fn unsafe_encoded_buy_is_rejected_by_preview_estimate_and_submission() { + let mut e = Exchange::open(":memory:").unwrap(); + e.execute(json!({"op":"list","id":"l","market":"tiny","rules":"r","tick_size":"0.1"})) + .unwrap(); + e.execute(json!({"op":"open","id":"o","market":"tiny"})) + .unwrap(); + let before = state(&mut e); + for request in [ + json!({"op":"market_amounts","side":"buy","price_micros":300000,"amount_cents":1}), + json!({"op":"estimate","side":"buy","max_price":30,"amount_cents":1}), + json!({"op":"market_buy","id":"b","account":"buyer","max_price":30,"amount_cents":1}), + ] { + let mut request = request; + request["asset_id"] = json!("eb:YES:tiny"); + assert!(format!("{:#}", e.execute(request).unwrap_err()) + .contains("rounded market buy exceeds price protection")); + } + assert_eq!(state(&mut e), before); +} diff --git a/docs/examples/market-amounts.jsonl b/docs/examples/market-amounts.jsonl new file mode 100644 index 0000000..400719e --- /dev/null +++ b/docs/examples/market-amounts.jsonl @@ -0,0 +1,12 @@ +{"op":"list","id":"list","market":"demo","rules":"Simulation","tick_size":"0.01","min_order_size":"5"} +{"op":"market_amounts","side":"buy","asset_id":"eb:YES:demo","price_micros":520000,"amount_micros":10009999} +{"op":"fund","id":"fund-maker","account":"maker","cents":3000} +{"op":"fund","id":"fund-taker","account":"taker","cents":2000} +{"op":"split","id":"split","account":"maker","market":"demo","qty":25} +{"op":"open","id":"open","market":"demo"} +{"op":"order","id":"ask","account":"maker","asset_id":"eb:YES:demo","side":"sell","price":50,"qty":20} +{"op":"estimate","side":"buy","asset_id":"eb:YES:demo","max_price":52,"amount_micros":10009999} +{"op":"market_buy","id":"take-ask","account":"taker","asset_id":"eb:YES:demo","max_price":52,"amount_micros":10009999} +{"op":"market_amounts","side":"sell","asset_id":"eb:YES:demo","price_micros":480000,"size_micros":5019999} +{"op":"order","id":"bid","account":"maker","asset_id":"eb:YES:demo","side":"buy","price":50,"qty":6} +{"op":"market_sell","id":"take-bid","account":"taker","asset_id":"eb:YES:demo","min_price":48,"size_micros":5019999} diff --git a/docs/prediction-parity.md b/docs/prediction-parity.md index acf8185..39c702e 100644 --- a/docs/prediction-parity.md +++ b/docs/prediction-parity.md @@ -273,3 +273,9 @@ order、market_sell 和卖出 estimate 可用 size_micros 输入数量,也可 [逐行样例](examples/fine-price-execution.jsonl)中,买单限价 0.014 美元,实际按在先卖价 0.013 成交 5.12 份,成交额为 66,560 微美元。接着用 1 美分预算最多再买 0.76 份,实付 9,880 微美元,退回 120 微美元。YES 和 NO 的互补价格相加为 1 美元。已有整分输入 price、min_price、max_price 继续可用,也可以分别传 price_micros、min_price_micros、max_price_micros,每组择一。缺少已配置步长的旧盘沿用整分钱格。本地样例只使用模拟资金。生产撮合回执、手续费和到账顺序仍需对照。[官方限价和保护价定义](https://docs.polymarket.com/trading/place-orders.md) 首次升级价格格式需要停止旧版写入进程。新版在一个 SQLite 写事务内迁移订单价格、历史成交、报价和最近成交缓存。已经以微美元保存的价格曲线及其时间戳保持原始记录。迁移完成后只使用新版重新打开该数据库。 + +## 市价委托金额 + +配置价格步长后,`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 份。这里复现公开委托金额公式,真实签名、生产成交粒度与资金到账仍待对照。