diff --git a/crates/exchange/README.md b/crates/exchange/README.md index 1eab902..1abad69 100644 --- a/crates/exchange/README.md +++ b/crates/exchange/README.md @@ -20,6 +20,9 @@ flowchart LR api -->|解析写命令| cmd["src/command.rs"] api -->|事务内派发| market["src/market.rs"] api -->|解析只读查询| queries["src/catalog.rs"] + queries -->|市价预估| estimate["src/estimate.rs"] + estimate -->|同步并读取常驻盘口| cache + estimate -->|成交金额| book queries -->|按账户或订单对账| trades["src/account_trades.rs"] trades -->|读取两类成交| legsql["src/account_trades.sql"] trades -->|返回结果资产| assets @@ -288,3 +291,21 @@ sequenceDiagram E-->>C: 返回成交份数、实付与未花金额 end ``` + +## 市价预估和卖出 + +```mermaid +sequenceDiagram + participant C as CLI + participant E as Exchange + participant D as SQLite + participant M as 常驻盘口 + C->>E: estimate 给出买入预算或卖出份数 + E->>D: 取得快照并读取已提交的盘口变化 + E->>M: 同步后按价格、时间顺序生成假设成交 + E-->>C: 最末档价格、均价、金额和未成交量 + C->>E: market_sell 指定最低成交价、数量和 FAK 或 FOK + E->>M: 在新写事务中重新选择对手盘 + E->>D: 结算成交,释放未卖出份额 + E-->>C: 返回实际成交与收入 +``` diff --git a/crates/exchange/src/assets.rs b/crates/exchange/src/assets.rs index 78ddfa7..689f5ab 100644 --- a/crates/exchange/src/assets.rs +++ b/crates/exchange/src/assets.rs @@ -40,6 +40,8 @@ pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> { | "history" | "open_orders" | "trades" + | "market_sell" + | "estimate" | "market_buy" | "cancel_market_orders" ) diff --git a/crates/exchange/src/book.rs b/crates/exchange/src/book.rs index 3ed58da..1583f4e 100644 --- a/crates/exchange/src/book.rs +++ b/crates/exchange/src/book.rs @@ -20,7 +20,23 @@ pub(crate) struct NewOrder { pub post_only: bool, } -pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result { +pub(crate) struct ShareExecution { + pub seq: i64, + pub filled: i64, + pub status: String, + pub gross_cents: i64, +} +impl ShareExecution { + pub fn receipt(&self) -> Value { + json!({"order":self.seq,"filled":self.filled,"status":self.status}) + } +} + +pub(crate) fn gross_cents(fills: &[Fill]) -> i64 { + fills.iter().map(|f| f.price * f.quantity).sum() +} + +pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result { let NewOrder { market, account, @@ -77,6 +93,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result params![seq, deadline], )?; } + let mut gross = 0; if stage == "continuous" { let incoming = Order { seq, @@ -102,6 +119,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result tif != TimeInForce::Fak || !fills.is_empty(), "FAK has no matching liquidity" ); + gross = gross_cents(&fills); settle(tx, &market, &outcome, fills, Some(Taker::Limit(seq)))?; } let (remaining, mut status): (i64, String) = tx.query_row( @@ -113,7 +131,12 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result release(tx, seq, &account, CancelReason::Cancelled)?; status = "cancelled".into(); } - Ok(json!({"order":seq,"filled":qty-remaining,"status":status})) + Ok(ShareExecution { + seq, + filled: qty - remaining, + status, + gross_cents: gross, + }) } pub(crate) struct BudgetBuy { @@ -158,7 +181,7 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R .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 spent = gross_cents(&fills); let unspent = amount_cents - spent; ensure!( tif != TimeInForce::Fok || unspent == 0, diff --git a/crates/exchange/src/catalog.rs b/crates/exchange/src/catalog.rs index 6235d82..842a1aa 100644 --- a/crates/exchange/src/catalog.rs +++ b/crates/exchange/src/catalog.rs @@ -141,6 +141,7 @@ impl Listing { #[derive(Deserialize)] #[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)] pub(crate) enum Query { + Estimate(crate::estimate::Request), Resolution { market: String, }, @@ -172,8 +173,9 @@ pub(crate) enum Query { }, } impl Query { - pub fn read(self, db: &Connection) -> Result { + pub fn read(self, db: &Transaction, books: &mut crate::resident::Books) -> Result { match self { + Self::Estimate(request) => request.read(db, books), Self::Resolution { market } => crate::resolution::read(db, &market), Self::Assets { market } => assets::market_assets(db, &market), Self::Positions(filter) => filter.read(db), diff --git a/crates/exchange/src/command.rs b/crates/exchange/src/command.rs index ef87fd4..e74d096 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_sell")] + MarketSell { + market: String, + account: String, + outcome: String, + qty: i64, + min_price: i64, + tif: Option, + }, #[serde(rename = "market_buy")] MarketBuy { market: String, diff --git a/crates/exchange/src/estimate.rs b/crates/exchange/src/estimate.rs new file mode 100644 index 0000000..483deee --- /dev/null +++ b/crates/exchange/src/estimate.rs @@ -0,0 +1,110 @@ +use crate::{ + assets, + book::gross_cents, + command::TimeInForce, + resident::Books, + validation::{amount, phase}, +}; +use anyhow::{ensure, Result}; +use matching::{Order, Side}; +use rusqlite::Transaction; +use serde::Deserialize; +use serde_json::{json, Value}; + +#[derive(Deserialize)] +#[serde(tag = "side", rename_all = "lowercase", deny_unknown_fields)] +pub(crate) enum Request { + Buy { + market: String, + outcome: String, + amount_cents: i64, + max_price: Option, + tif: Option, + }, + Sell { + market: String, + outcome: String, + qty: i64, + min_price: Option, + tif: Option, + }, +} + +impl Request { + pub(crate) fn read(self, tx: &Transaction, books: &mut Books) -> Result { + let (market, outcome, side, requested, limit, tif) = match self { + Self::Buy { + market, + outcome, + amount_cents, + max_price, + tif, + } => ( + market, + outcome, + Side::Buy, + amount_cents, + max_price.unwrap_or(100), + tif, + ), + Self::Sell { + market, + outcome, + qty, + min_price, + tif, + } => ( + market, + outcome, + Side::Sell, + qty, + min_price.unwrap_or(0), + tif, + ), + }; + let tif = tif.unwrap_or(TimeInForce::Fak); + amount(requested)?; + ensure!( + matches!(tif, TimeInForce::Fak | TimeInForce::Fok), + "estimate requires FAK or FOK" + ); + ensure!( + matches!(outcome.as_str(), "YES" | "NO") && (0..=100).contains(&limit), + "invalid outcome or price" + ); + phase(tx, &market, &["continuous"])?; + let changes = books.changes(tx)?; + books.apply(changes); + // The hypothetical incoming order follows all resting orders in time priority. + let fills = books + .get(&market, &outcome) + .map(|b| match side { + Side::Buy => b.match_budget_buy(i64::MAX, limit, requested), + Side::Sell => b.match_incoming(&Order { + seq: i64::MAX, + side, + price: limit, + remaining: requested, + }), + }) + .unwrap_or_default(); + let shares: i64 = fills.iter().map(|f| f.quantity).sum(); + let gross = gross_cents(&fills); + let remainder = requested + - match side { + Side::Buy => gross, + Side::Sell => shares, + }; + let mut result = json!({"asset_id":assets::id(&market,&outcome),"filled_shares":shares, + "gross_cents":gross,"best_fill_price":fills.first().map(|f|f.price), + "worst_fill_price":fills.last().map(|f|f.price), + "average_price_micros":(gross*10000).checked_div(shares), + "fully_fillable":remainder==0,"executable":shares>0 && (tif==TimeInForce::Fak || remainder==0)}); + let key = match side { + Side::Buy => "unspent_cents", + Side::Sell => "unsold_shares", + }; + result[key] = json!(remainder); + Ok(result) + } +} diff --git a/crates/exchange/src/lib.rs b/crates/exchange/src/lib.rs index 6298279..ae641f0 100644 --- a/crates/exchange/src/lib.rs +++ b/crates/exchange/src/lib.rs @@ -2,6 +2,7 @@ mod account_orders; mod account_trades; mod assets; mod catalog; +mod estimate; mod expiry; mod twap; mod validation; @@ -42,6 +43,7 @@ impl Exchange { payload["op"].as_str(), Some( "assets" + | "estimate" | "catalog" | "history" | "quote" @@ -56,7 +58,7 @@ impl Exchange { let mut request = payload; assets::resolve(&tx, &mut request)?; let query: catalog::Query = serde_json::from_value(request)?; - let value = query.read(&tx)?; + let value = query.read(&tx, &mut self.books)?; tx.commit()?; return Ok(value); } diff --git a/crates/exchange/src/market.rs b/crates/exchange/src/market.rs index 633c2c2..5a41cfd 100644 --- a/crates/exchange/src/market.rs +++ b/crates/exchange/src/market.rs @@ -137,7 +137,44 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result expiration, post_only, }, - ), + ) + .map(|result| result.receipt()), + Command::MarketSell { + market, + account, + outcome, + qty, + min_price, + tif, + } => { + let tif = tif.unwrap_or(crate::command::TimeInForce::Fak); + ensure!( + matches!( + tif, + crate::command::TimeInForce::Fak | crate::command::TimeInForce::Fok + ), + "market sell requires FAK or FOK" + ); + let result = book::submit( + tx, + books, + book::NewOrder { + market, + account, + outcome, + side: "sell".to_owned(), + price: min_price, + qty, + tif, + expiration: None, + post_only: false, + }, + )?; + let mut receipt = result.receipt(); + receipt["proceeds_cents"] = json!(result.gross_cents); + receipt["unsold_shares"] = json!(qty - result.filled); + Ok(receipt) + } Command::MarketBuy { market, outcome, diff --git a/crates/exchange/tests/market.rs b/crates/exchange/tests/market.rs index b7b59f2..7d40144 100644 --- a/crates/exchange/tests/market.rs +++ b/crates/exchange/tests/market.rs @@ -1143,3 +1143,62 @@ fn cash_buy_reconciles_direct_and_complementary_depth_with_an_exact_budget() { assert_eq!(fok["spent_cents"], 45); assert_eq!(fok["status"], "filled"); } + +#[test] +fn market_estimate_uses_latest_committed_depth_without_reserving_it() { + let dir = tempdir().unwrap(); + let path = dir.path().join("estimate.db"); + let mut client = Exchange::open(&path).unwrap(); + setup(&mut client); + let mut maker = Exchange::open(path).unwrap(); + maker + .execute(json!({"op":"open","id":"open","market":"e"})) + .unwrap(); + maker + .execute(json!({"op":"split","id":"bm","account":"bob","market":"e","qty":2})) + .unwrap(); + maker.execute(order("bid", "bob", "buy", 60, 2)).unwrap(); + let mut opposite = order("opposite", "bob", "sell", 45, 2); + opposite["outcome"] = json!("NO"); + let resting = maker.execute(opposite).unwrap()["order"].clone(); + let preview = + json!({"op":"estimate","asset_id":"eb:YES:e","side":"sell","qty":5,"min_price":50}); + let before = state(&mut client); + let quote = client.execute(preview.clone()).unwrap(); + assert_eq!(quote["filled_shares"], 4); + assert_eq!(quote["gross_cents"], 230); + assert_eq!(quote["worst_fill_price"], 55); + assert_eq!(quote["average_price_micros"], 575000); + assert_eq!(quote["unsold_shares"], 1); + assert_eq!(state(&mut client), before); + let mut all = preview.clone(); + all["tif"] = json!("FOK"); + assert_eq!(client.execute(all).unwrap()["executable"], false); + maker + .execute(json!({"op":"cancel","id":"withdraw","account":"bob","order":resting})) + .unwrap(); + let fresh = client.execute(preview).unwrap(); + let sale = json!({"op":"market_sell","id":"sale","asset_id":"eb:YES:e","account":"alice","qty":5,"min_price":50}); + let mut guarded = sale.clone(); + guarded["min_price"] = json!(61); + assert!(client.execute(guarded).is_err()); + let reply = client.execute(sale.clone()).unwrap(); + assert_eq!(client.execute(sale).unwrap(), reply); + assert_eq!(reply["filled"], fresh["filled_shares"]); + assert_eq!(reply["proceeds_cents"], fresh["gross_cents"]); + assert_eq!(reply["proceeds_cents"], 120); + assert_eq!(reply["unsold_shares"], 3); + let empty = client + .execute(json!({"op":"estimate","market":"e","outcome":"YES","side":"sell","qty":1})) + .unwrap(); + assert!(empty["worst_fill_price"].is_null()); + assert!(empty["average_price_micros"].is_null()); + assert_eq!(empty["executable"], false); + maker.execute(order("ask", "alice", "sell", 35, 2)).unwrap(); + let buy = client + .execute(json!({"op":"estimate","asset_id":"eb:YES:e","side":"buy","amount_cents":81})) + .unwrap(); + assert_eq!(buy["worst_fill_price"], 35); + assert_eq!(buy["gross_cents"], 70); + assert_eq!(buy["unspent_cents"], 11); +} diff --git a/docs/prediction-parity.md b/docs/prediction-parity.md index e62bec2..cf39c79 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 查询规则、价格曲线、报价、账户挂单、逐笔成交、单笔终态与持仓状态 | 账户认证与会话可见范围、非交易活动、成本与盈亏及断线回补 | @@ -108,3 +108,9 @@ Polymarket 的 CTF 市场使用结果 token ID,Protocol V2 市场使用结果 `{"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) + +## 市价保护价与预估 + +`{"op":"estimate","asset_id":"eb:YES:e","side":"sell","qty":5,"min_price":50}` 在一致快照中将原始委托与互补委托按价格、受理顺序合并。假设有人直接以 60 分买入两份 YES,另有两份 NO 以 45 分挂卖(可对应 55 分 YES 买价),五份卖出请求可成交四份,gross_cents 为 230,worst_fill_price 为 55 分,average_price_micros 为 575000,剩余一份。FAK 可执行,FOK 会因缺少一份而拒绝。executable 仅描述快照深度与时效约束;预估无需账户,实际卖出会校验卖方库存。买入预估用 amount_cents 和可选 max_price;卖出预估用 qty 和可选 min_price。未指定边界时使用本地全价格区间。金额为毛额,均价以百万分之一美元表示,向下取整。空盘返回零成交量和空价格。 + +`{"op":"market_sell","id":"sell-1","asset_id":"eb:YES:e","account":"alice","qty":5,"min_price":55,"tif":"FAK"}` 在新的写事务内撮合。用预估最末档作为最低价可限制成交价格,预估之后撤单仍会减少可卖数量。回执含 filled、proceeds_cents 与 unsold_shares。按金额买入对应地使用 market_buy 和最高价。模拟器按整数份额估算,仍待用外场小数份额与费用样本核对。[官方市价估算口径](https://docs.polymarket.com/trading/place-orders.md)