From 6e1cfb4e22e871dd2e0cd966283eda95db1ed1b0 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Thu, 3 Dec 2026 15:02:41 +0800 Subject: [PATCH] Match public CLOB side prices and batch responses to observed books --- crates/cli/README.md | 8 +-- crates/cli/src/market_http.rs | 99 +++++++++++++++-------------------- crates/exchange/README.md | 4 +- crates/exchange/src/quotes.rs | 65 +++++++++++++++++------ docs/examples/clob-http.http | 4 +- docs/prediction-parity.md | 6 +-- 6 files changed, 101 insertions(+), 85 deletions(-) diff --git a/crates/cli/README.md b/crates/cli/README.md index a98c10d..a014de6 100644 --- a/crates/cli/README.md +++ b/crates/cli/README.md @@ -196,18 +196,18 @@ sequenceDiagram H-->>C: 单查用 spread 或 mid 字段,批查以资产 ID 为键 ``` -### 买入或卖出一个结果的报价 +### 查询盘口买一和卖一 ```mermaid sequenceDiagram participant C as 客户端 participant H as market_http.rs participant E as exchange/quotes.rs - C->>H: GET /price 或 GET、POST /prices + C->>H: GET /price 或 POST /prices H->>H: 校验资产与方向一一配对 - H->>E: 查询最优对手报价 + H->>E: 查询盘口同侧最优档 E-->>H: 单笔价格或按资产与方向分组的报价 - H-->>C: 单查返回价格字符串,批查返回 JSON 数字 + H-->>C: 单查和批查的价格均为字符串 ``` [可重放请求](../../docs/examples/clob-http.http)同时展示相同盘口下的买价、卖价与中点。 diff --git a/crates/cli/src/market_http.rs b/crates/cli/src/market_http.rs index c2da0a4..66cf9d4 100644 --- a/crates/cli/src/market_http.rs +++ b/crates/cli/src/market_http.rs @@ -108,54 +108,42 @@ impl WirePrice { } } -#[derive(Deserialize)] -struct PriceList { - token_ids: String, - sides: String, -} - -impl PriceList { - fn into_rows(self) -> std::result::Result, (u16, &'static str)> { - let tokens = self.token_ids.split(','); - let sides = self.sides.split(','); - let count = tokens.clone().count(); - if count > MAX_BOOKS || count != sides.clone().count() { - return Err((400, "Invalid payload")); - } - Ok(tokens - .zip(sides) - .map(|(token, side)| WirePrice { - token_id: token.to_owned(), - side: Some(side.to_owned()), - }) - .collect()) - } -} - -fn execution_prices(engine: &Mutex, rows: Vec, single: bool) -> Reply { +fn book_prices(engine: &Mutex, rows: Vec, single: bool) -> Reply { if rows.is_empty() || rows.len() > MAX_BOOKS { return Err((400, "Invalid payload")); } let requests = rows .into_iter() - .map(WirePrice::into_request) + .map(|mut row| { + if !single && row.side.is_none() { + row.side = Some("SELL".into()); + } + row.into_request() + }) .collect::, _>>()?; let exchange = engine.lock().map_err(|_| (500, "Internal server error"))?; - let value = if single { - exchange.execution_price(&requests[0]) - } else { - exchange.execution_prices(&requests) - } - .map_err( - |error| match error.downcast_ref::() { - Some(exchange::PriceQueryError::InvalidToken) if single => (400, "Invalid token id"), - Some(exchange::PriceQueryError::MissingBook) => (404, MISSING), - Some(_) => (400, "Invalid payload"), - None => (500, "Internal server error"), - }, - )?; - if single && value["price"].is_null() { - return Err((422, "No price available for requested side")); + let value = + exchange + .public_book_prices(&requests) + .map_err( + |error| match error.downcast_ref::() { + Some(exchange::PriceQueryError::InvalidToken) if single => { + (400, "Invalid token id") + } + Some(exchange::PriceQueryError::MissingBook) => (404, MISSING), + Some(_) => (400, "Invalid payload"), + None => (500, "Internal server error"), + }, + )?; + if single { + let sides = value[requests[0].token_id.as_str()] + .as_object() + .ok_or((404, MISSING))?; + let price = sides + .values() + .next() + .ok_or((500, "Internal server error"))?; + return Ok(json!({"price":price})); } Ok(value) } @@ -427,13 +415,11 @@ fn respond(mut req: Request, engine: &Mutex) -> std::io::Result<()> { } (&Method::Get, "/price") => serde_urlencoded::from_str::(params) .map_err(|_| (400, "Invalid token id")) - .and_then(|p| execution_prices(engine, vec![p], true)), - (&Method::Post, "/prices") => batch_params::(&mut req) - .and_then(|rows| execution_prices(engine, rows, false)), - (&Method::Get, "/prices") => serde_urlencoded::from_str::(params) - .map_err(|_| (400, "Invalid payload")) - .and_then(PriceList::into_rows) - .and_then(|rows| execution_prices(engine, rows, false)), + .and_then(|p| book_prices(engine, vec![p], true)), + (&Method::Post, "/prices") => { + batch_params::(&mut req).and_then(|rows| book_prices(engine, rows, false)) + } + (&Method::Get, "/prices") => Err((400, "Invalid payload")), (&Method::Get, "/spread" | "/midpoint") => { let field = if path == "/spread" { QuoteField::Spread @@ -677,8 +663,7 @@ mod tests { } let sample = json!({"eb:YES:mid-example":"0.085","eb:NO:mid-example":"0.915"}); let pair = json!({"eb:YES:s":"0.4","eb:NO:s":"0.6"}); - let price_batch = - json!({"eb:YES:mid-example":{"BUY":0.09,"SELL":0.08},"eb:NO:mid-example":{"BUY":0.92}}); + let price_batch = json!({"eb:YES:mid-example":{"BUY":"0.08","SELL":"0.09"},"eb:NO:mid-example":{"BUY":"0.91"},"eb:YES:one":{"BUY":"0.2"}}); db.execute(json!({"op":"publish_clarification","id":"note","market":market,"content":"Map one includes overtime.","clear_book":false})).unwrap(); let note = db .execute(json!({"op":"resolution","market":market})) @@ -780,18 +765,18 @@ mod tests { ("GET","/prices-history?market=eb:YES:s&interval=1d&fidelity=0",String::new(),400,None), ("GET","/prices-history?market=eb:YES:s&startTs=1&endTs=2&interval=max",String::new(),400,None), ("POST","/prices-history","{}".into(),405,None), - ("GET","/price?token_id=eb:YES:mid-example&side=BUY",String::new(),200,Some(json!({"price":"0.09"}))), - ("GET","/price?token_id=eb:YES:mid-example&side=SELL",String::new(),200,Some(json!({"price":"0.08"}))), - ("GET","/price?token_id=eb:YES:one&side=SELL",String::new(),200,Some(json!({"price":"0.20"}))), - ("GET","/price?token_id=eb:YES:one&side=BUY",String::new(),422,None), + ("GET","/price?token_id=eb:YES:mid-example&side=BUY",String::new(),200,Some(json!({"price":"0.08"}))), + ("GET","/price?token_id=eb:YES:mid-example&side=SELL",String::new(),200,Some(json!({"price":"0.09"}))), + ("GET","/price?token_id=eb:YES:one&side=SELL",String::new(),200,Some(json!({"price":"1"}))), + ("GET","/price?token_id=eb:YES:one&side=BUY",String::new(),200,Some(json!({"price":"0.2"}))), ("GET","/price?token_id=eb:YES:missing&side=BUY",String::new(),404,Some(json!({"error":MISSING}))), ("GET","/price?token_id=eb:YES:s&side=HOLD",String::new(),400,Some(json!({"error":"Invalid side"}))), ("GET","/price?token_id=broken&side=BUY",String::new(),400,Some(json!({"error":"Invalid token id"}))), - ("GET","/prices?token_ids=eb:YES:mid-example,eb:YES:mid-example,eb:NO:mid-example&sides=BUY,SELL,BUY",String::new(),200,Some(price_batch.clone())), + ("GET","/prices?token_ids=eb:YES:mid-example,eb:YES:mid-example,eb:NO:mid-example&sides=BUY,SELL,BUY",String::new(),400,Some(json!({"error":"Invalid payload"}))), ("POST","/prices",json!([{"token_id":"eb:YES:mid-example","side":"BUY"},{"token_id":"eb:NO:mid-example","side":"BUY"},{"token_id":"eb:YES:mid-example","side":"SELL"},{"token_id":"eb:YES:one","side":"BUY"},{"token_id":"eb:YES:mid-example","side":"BUY"}]).to_string(),200,Some(price_batch)), ("GET","/prices?token_ids=eb:YES:s,eb:NO:s&sides=BUY",String::new(),400,Some(json!({"error":"Invalid payload"}))), - ("POST","/prices",json!([{"token_id":"eb:YES:s","side":"BUY"},{"token_id":"eb:NO:missing","side":"SELL"}]).to_string(),404,Some(json!({"error":MISSING}))), - ("POST","/prices",json!([{"token_id":"eb:YES:s"}]).to_string(),400,Some(json!({"error":"Invalid side"}))), + ("POST","/prices",json!([{"token_id":"eb:YES:s","side":"BUY"},{"token_id":"eb:NO:missing","side":"SELL"}]).to_string(),200,Some(json!({"eb:YES:s":{"BUY":"0.39"}}))), + ("POST","/prices",json!([{"token_id":"eb:YES:s"}]).to_string(),200,Some(json!({"eb:YES:s":{"SELL":"0.41"}}))), ("POST","/prices",json!(vec![json!({"token_id":"eb:YES:s","side":"BUY"}); MAX_BOOKS+1]).to_string(),400,None), ("DELETE","/prices",String::new(),405,None), ("GET","/midpoint?token_id=eb:YES:mid-example",String::new(),200,Some(json!({"mid":"0.085"}))), diff --git a/crates/exchange/README.md b/crates/exchange/README.md index 489db95..8965cee 100644 --- a/crates/exchange/README.md +++ b/crates/exchange/README.md @@ -1110,7 +1110,7 @@ sequenceDiagram E-->>C: 按结果资产索引,未上市资产无条目 ``` -交易方向查询也读取 quote_events。execution_price 和 execution_prices 通过 quotes.rs 查询请求时的最优对手价。批量调用在一条 SQL 中读取所有请求的市场,YES 和 NO 分别换算后再按方向取价。 +HTTP 盘口查询由 public_book_prices 读取 quote_events,先清理到期任务,再在同一快照中读取各市场。BUY 取买一,SELL 取卖一。下单面板的 JSONL 命令继续查询最优对手价。 ```mermaid sequenceDiagram @@ -1118,7 +1118,7 @@ sequenceDiagram participant E as Exchange participant Q as quotes.rs participant D as SQLite - H->>E: execution_prices,传入资产和交易方向 + H->>E: public_book_prices,传入资产和盘口方向 E->>Q: 读取批量报价 Q->>D: 单条查询读取每个市场最近一次最优档 D-->>Q: 返回买一与卖一 diff --git a/crates/exchange/src/quotes.rs b/crates/exchange/src/quotes.rs index 6320de5..45367a5 100644 --- a/crates/exchange/src/quotes.rs +++ b/crates/exchange/src/quotes.rs @@ -193,6 +193,27 @@ impl PriceRequest { // Use the last committed top of book, even when only one side has liquidity. // All requested markets share the caller's read snapshot. fn price_rows(db: &Connection, requests: &[PriceRequest]) -> Result>> { + quote_rows(db, requests)? + .into_iter() + .zip(requests) + .map(|(quote, request)| { + let quote = quote.ok_or(PriceQueryError::MissingBook)?; + let price = match request.side { + PriceSide::Buy => quote.ask, + PriceSide::Sell => quote.bid, + }; + Ok(price.map(|p| { + let mut text = format!("{}.{:04}", p / 10000, p % 10000); + while text.len() > 4 && text.ends_with('0') { + text.pop(); + } + text + })) + }) + .collect() +} + +fn quote_rows(db: &Connection, requests: &[PriceRequest]) -> Result>> { if !(1..=500).contains(&requests.len()) { return Err(PriceQueryError::RequestCount.into()); } @@ -211,26 +232,17 @@ fn price_rows(db: &Connection, requests: &[PriceRequest]) -> Result>(4)?.is_none() { - return Err(PriceQueryError::MissingBook.into()); - } let index: usize = row.get(5)?; - let quote = Quote::read(row, outcomes[index])?; - let price = match requests[index].side { - PriceSide::Buy => quote.ask, - PriceSide::Sell => quote.bid, - }; - prices.push(price.map(|p| { - let mut text = format!("{}.{:04}", p / 10000, p % 10000); - while text.len() > 4 && text.ends_with('0') { - text.pop(); - } - text - })); + let exists = row.get::<_, Option>(4)?.is_some(); + quotes.push( + exists + .then(|| Quote::read(row, outcomes[index])) + .transpose()?, + ); } - Ok(prices) + Ok(quotes) } pub(crate) fn prices(db: &Connection, requests: &[PriceRequest]) -> Result { @@ -261,6 +273,25 @@ impl crate::Exchange { price_map(&self.db, requests, false) } + /// Public CLOB side prices refer to resting orders on the named side. + pub fn public_book_prices(&self, requests: &[PriceRequest]) -> Result { + let tx = crate::expiry::transaction(&self.db, rusqlite::TransactionBehavior::Deferred)?; + let mut result = json!({}); + for (request, quote) in requests.iter().zip(quote_rows(&tx, requests)?) { + if let Some(quote) = quote { + let ticks = match request.side { + PriceSide::Buy => quote.bid.unwrap_or(0), + PriceSide::Sell => quote.ask.unwrap_or(crate::tick_size::PAR), + }; + let text = format!("{}.{:04}", ticks / 10000, ticks % 10000); + result[request.token_id.as_str()][request.label()] = + json!(text.trim_end_matches('0').trim_end_matches('.')); + } + } + tx.commit()?; + Ok(result) + } + pub fn spreads( &self, tokens: &[String], diff --git a/docs/examples/clob-http.http b/docs/examples/clob-http.http index 4915148..766a3ad 100644 --- a/docs/examples/clob-http.http +++ b/docs/examples/clob-http.http @@ -61,10 +61,10 @@ Content-Type: application/json [{"token_id":"eb:YES:mid-example"},{"token_id":"eb:NO:mid-example"}] -### Read the best ask to buy YES in the midpoint.jsonl fixture ("0.09") +### Read the resting YES bid in the midpoint.jsonl fixture ("0.08") GET http://127.0.0.1:9002/price?token_id=eb%3AYES%3Amid-example&side=BUY -### Read BUY and SELL for the same outcome (0.09 and 0.08) +### Query-only batch GET returns 400 Invalid payload GET http://127.0.0.1:9002/prices?token_ids=eb%3AYES%3Amid-example%2Ceb%3AYES%3Amid-example&sides=BUY%2CSELL ### Include both outcomes with a JSON body diff --git a/docs/prediction-parity.md b/docs/prediction-parity.md index 0f777a0..7edaab6 100644 --- a/docs/prediction-parity.md +++ b/docs/prediction-parity.md @@ -219,7 +219,7 @@ list 接受十进制份额字符串,最多六位小数;book、assets 和事 ## 下单面板的单笔与批量买卖报价 -`price` 接受 token_id 和方向,BUY 读取最低卖价,SELL 读取最高买价。单笔响应的 price 为十进制字符串。`prices` 在 requests 中接受最多 500 对资产与方向,在同一读快照中返回按资产和方向索引的 JSON 数值,匹配官方 REST 文档的样例类型。客户端可以直接为多个结果填入买卖按钮。大单仍需通过 estimate 按深度估算成交金额。[官方单笔与批量报价](https://docs.polymarket.com/market-data/prices-order-books.md#best-market-price) +JSONL 下单面板的 `price` 接受 token_id 和方向,BUY 读取最低卖价,SELL 读取最高买价。单笔响应的 price 为十进制字符串。`prices` 在 requests 中接受最多 500 对资产与方向,在同一读快照中返回按资产和方向索引的 JSON 数值,客户端可以直接为多个结果填入买卖按钮。公开 HTTP 接口遵循下文实测的盘口方向。大单仍需通过 estimate 按深度估算成交金额。[官方单笔与批量报价](https://docs.polymarket.com/market-data/prices-order-books.md#best-market-price) [可重放样例](examples/execution-prices.jsonl)开始时只有 YES 买单,买入 YES 的报价为 null。随后有人以 0.89 挂买 NO,YES 买入价变成 0.11,卖出价为 0.09。NO 买入价为 0.91,卖出价为 0.89。这四个报价均来自挂单,无需先发生交易。单侧没有对手时保留该键并返回 null。重复项合并,未知资产使整批失败。空批次拒绝,盘前返回待集合竞价的挂单报价。上述边界属于本地约定。本地 token_id 使用 Eventbook 的结果资产 ID,公开接口的生产响应、原生资产编号与无流动性时的处理仍待对照。 @@ -366,9 +366,9 @@ Polymarket 的单资产最近成交接口规定,无成交时返回价格字符 ### HTTP 买卖报价的方向 -用[同一份本地盘口](examples/midpoint.jsonl)重放:YES 买一 0.08、卖一 0.09。单查 BUY 返回 {"price":"0.09"},单查 SELL 返回 {"price":"0.08"}。批量查询同一结果的两个方向会保留两个键,价格为 JSON 数字。GET 的 token_ids、sides 两列按位置配对,POST 接收含 token_id 和 side 的对象数组。[HTTP 请求](examples/clob-http.http) · [批量 GET 规范](https://docs.polymarket.com/api-reference/market-data/get-market-prices-query-parameters) · [批量 POST 规范](https://docs.polymarket.com/api-reference/market-data/get-market-prices-request-body) +用[同一份本地盘口](examples/midpoint.jsonl)重放:YES 买一 0.08、卖一 0.09。公开 HTTP 单查 BUY 返回 {"price":"0.08"},SELL 返回 {"price":"0.09"}。POST /prices 返回各方向的价格字符串;已上市资产缺买或卖侧时分别返回 "0" 或 "1"。单查未知资产为 404,批量会省略未知资产。只在批量请求中省略 side 时默认为 SELL。 -官方行情指南从交易者角度描述 BUY 取卖一,OpenAPI 的单查文字则把 BUY 对应到买一。本地沿用行情指南与既有交易命令的口径。官方 Rust SDK 的模拟回执可以确认单查字符串、批查数字,无法据此判定生产方向。已上市资产缺少所需一侧时,本地 HTTP 单查返回 422,批查省略该方向。请求中出现未上市资产时整批返回 404。上述边界和交易方向仍待稳定盘口实测。[行情指南](https://docs.polymarket.com/market-data/prices-order-books#best-market-price) · [单查规范](https://docs.polymarket.com/api-reference/market-data/get-market-price) · [官方 SDK 用例](https://github.com/Polymarket/rs-clob-client-v2/blob/main/tests/clob.rs#L139-L216) +2026-12-03 06:55 UTC,三个生产资产各自的前后盘口哈希一致。单查与批量分别得到双侧 0.039/0.04、仅卖侧 0/0.001 和仅买侧 0.999/1。文档中仅带 token_ids 和 sides 的 GET /prices 在采样中返回 400 Invalid payload。本地保留此查询结果,正常批量读取用 POST。两侧均空时的 0/1 由单侧规则推得,尚缺双空实测。生产样本保存在连接器分支的 crates/venue-probe/fixtures/live-side-prices.json。客户端准备实际买卖时,仍可用本地 JSONL 交易命令查询对手价或按数量预估成交。[HTTP 请求](examples/clob-http.http) · [单查规范](https://docs.polymarket.com/api-reference/market-data/get-market-price) · [批量 GET 规范](https://docs.polymarket.com/api-reference/market-data/get-market-prices-query-parameters) ### CLOB 历史价格曲线