Match public CLOB side prices and batch responses to observed books

This commit is contained in:
2026-12-03 15:02:41 +08:00
parent 4262b7adaa
commit 6e1cfb4e22
6 changed files with 101 additions and 85 deletions
+4 -4
View File
@@ -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)同时展示相同盘口下的买价、卖价与中点。
+42 -57
View File
@@ -108,54 +108,42 @@ impl WirePrice {
}
}
#[derive(Deserialize)]
struct PriceList {
token_ids: String,
sides: String,
}
impl PriceList {
fn into_rows(self) -> std::result::Result<Vec<WirePrice>, (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<Exchange>, rows: Vec<WirePrice>, single: bool) -> Reply {
fn book_prices(engine: &Mutex<Exchange>, rows: Vec<WirePrice>, 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::<std::result::Result<Vec<_>, _>>()?;
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::<exchange::PriceQueryError>() {
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::<exchange::PriceQueryError>() {
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<Exchange>) -> std::io::Result<()> {
}
(&Method::Get, "/price") => serde_urlencoded::from_str::<WirePrice>(params)
.map_err(|_| (400, "Invalid token id"))
.and_then(|p| execution_prices(engine, vec![p], true)),
(&Method::Post, "/prices") => batch_params::<WirePrice>(&mut req)
.and_then(|rows| execution_prices(engine, rows, false)),
(&Method::Get, "/prices") => serde_urlencoded::from_str::<PriceList>(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::<WirePrice>(&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"}))),
+2 -2
View File
@@ -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: 返回买一与卖一
+48 -17
View File
@@ -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<Vec<Option<String>>> {
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<Vec<Option<Quote>>> {
if !(1..=500).contains(&requests.len()) {
return Err(PriceQueryError::RequestCount.into());
}
@@ -211,26 +232,17 @@ fn price_rows(db: &Connection, requests: &[PriceRequest]) -> Result<Vec<Option<S
ORDER BY j.key",
)?;
let mut rows = stmt.query([serde_json::to_string(&markets)?])?;
let mut prices = Vec::with_capacity(requests.len());
let mut quotes = Vec::with_capacity(requests.len());
while let Some(row) = rows.next()? {
if row.get::<_, Option<String>>(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<String>>(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<Value> {
@@ -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<Value> {
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],