Serve side-specific execution quotes over the public market HTTP API
This commit is contained in:
@@ -193,3 +193,19 @@ sequenceDiagram
|
||||
Q-->>H: 每个已上市资产的价差、中点或缺边状态
|
||||
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
|
||||
H->>H: 校验资产与方向一一配对
|
||||
H->>E: 查询最优对手报价
|
||||
E-->>H: 单笔价格或按资产与方向分组的报价
|
||||
H-->>C: 单查返回价格字符串,批查返回 JSON 数字
|
||||
```
|
||||
|
||||
[可重放请求](../../docs/examples/clob-http.http)同时展示相同盘口下的买价、卖价与中点。
|
||||
|
||||
+120
-20
@@ -15,14 +15,7 @@ struct BookParam {
|
||||
token_id: String,
|
||||
// The official SDK can include a side on a BookParams item. The book contains both.
|
||||
#[serde(rename = "side")]
|
||||
_side: Option<Side>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
enum Side {
|
||||
Buy,
|
||||
Sell,
|
||||
_side: Option<exchange::PriceSide>,
|
||||
}
|
||||
|
||||
type Reply = std::result::Result<Value, (u16, &'static str)>;
|
||||
@@ -95,7 +88,81 @@ fn quote_response(
|
||||
Ok(Value::Object(result))
|
||||
}
|
||||
|
||||
fn batch_params(req: &mut Request) -> std::result::Result<Vec<BookParam>, (u16, &'static str)> {
|
||||
#[derive(Deserialize)]
|
||||
struct WirePrice {
|
||||
token_id: String,
|
||||
side: Option<String>,
|
||||
}
|
||||
|
||||
impl WirePrice {
|
||||
fn into_request(self) -> std::result::Result<exchange::PriceRequest, (u16, &'static str)> {
|
||||
let side = match self.side.as_deref() {
|
||||
Some("BUY") => exchange::PriceSide::Buy,
|
||||
Some("SELL") => exchange::PriceSide::Sell,
|
||||
_ => return Err((400, "Invalid side")),
|
||||
};
|
||||
Ok(exchange::PriceRequest {
|
||||
token_id: self.token_id,
|
||||
side,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[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 {
|
||||
if rows.is_empty() || rows.len() > MAX_BOOKS {
|
||||
return Err((400, "Invalid payload"));
|
||||
}
|
||||
let requests = rows
|
||||
.into_iter()
|
||||
.map(WirePrice::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"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn batch_params<T: serde::de::DeserializeOwned>(
|
||||
req: &mut Request,
|
||||
) -> std::result::Result<Vec<T>, (u16, &'static str)> {
|
||||
if req.body_length().is_some_and(|n| n as u64 > MAX_BODY) {
|
||||
return Err((413, "Request body too large"));
|
||||
}
|
||||
@@ -215,6 +282,15 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
allow = Some("GET");
|
||||
Err((405, "Method not allowed"))
|
||||
}
|
||||
(&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)),
|
||||
(&Method::Get, "/spread" | "/midpoint") => {
|
||||
let field = if path == "/spread" {
|
||||
QuoteField::Spread
|
||||
@@ -231,7 +307,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
} else {
|
||||
QuoteField::Midpoint
|
||||
};
|
||||
batch_params(&mut req).and_then(|p| {
|
||||
batch_params::<BookParam>(&mut req).and_then(|p| {
|
||||
quote_response(
|
||||
engine,
|
||||
p.into_iter().map(|b| b.token_id).collect(),
|
||||
@@ -253,7 +329,9 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
(&Method::Get, "/book") => serde_urlencoded::from_str::<BookParam>(params)
|
||||
.map_err(|_| (400, "Invalid token id"))
|
||||
.and_then(|p| query(engine, vec![p], true)),
|
||||
(&Method::Post, "/books") => batch_params(&mut req).and_then(|p| query(engine, p, false)),
|
||||
(&Method::Post, "/books") => {
|
||||
batch_params::<BookParam>(&mut req).and_then(|p| query(engine, p, false))
|
||||
}
|
||||
(&Method::Get, "/last-trade-price") => serde_urlencoded::from_str::<BookParam>(params)
|
||||
.map_err(|_| (400, "Invalid token id"))
|
||||
.and_then(|p| last_prices(engine, vec![p.token_id], true)),
|
||||
@@ -266,18 +344,24 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
false,
|
||||
)
|
||||
}),
|
||||
(&Method::Post, "/last-trades-prices") => batch_params(&mut req).and_then(|p| {
|
||||
last_prices(
|
||||
engine,
|
||||
p.into_iter().map(|item| item.token_id).collect(),
|
||||
false,
|
||||
)
|
||||
}),
|
||||
(_, "/last-trades-prices" | "/midpoints") => {
|
||||
(&Method::Post, "/last-trades-prices") => {
|
||||
batch_params::<BookParam>(&mut req).and_then(|p| {
|
||||
last_prices(
|
||||
engine,
|
||||
p.into_iter().map(|item| item.token_id).collect(),
|
||||
false,
|
||||
)
|
||||
})
|
||||
}
|
||||
(_, "/prices" | "/last-trades-prices" | "/midpoints") => {
|
||||
allow = Some("GET, POST");
|
||||
Err((405, "Method not allowed"))
|
||||
}
|
||||
(_, "/midpoint" | "/spread" | "/book" | "/last-trade-price" | "/v2/prices-history") => {
|
||||
(
|
||||
_,
|
||||
"/price" | "/midpoint" | "/spread" | "/book" | "/last-trade-price"
|
||||
| "/v2/prices-history",
|
||||
) => {
|
||||
allow = Some("GET");
|
||||
Err((405, "Method not allowed"))
|
||||
}
|
||||
@@ -400,7 +484,23 @@ 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 cases = [
|
||||
("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: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())),
|
||||
("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!(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"}))),
|
||||
("POST","/midpoints",json!([{"token_id":"eb:YES:mid-example"},{"token_id":"eb:NO:mid-example"}]).to_string(),200,Some(sample)),
|
||||
("GET","/midpoint?token_id=eb:YES:s",String::new(),200,Some(json!({"mid":"0.4"}))),
|
||||
|
||||
@@ -1096,3 +1096,18 @@ sequenceDiagram
|
||||
E->>E: 按结果换算两侧,计算价差或精确到半个价格步长的中点
|
||||
E-->>C: 按结果资产索引,未上市资产无条目
|
||||
```
|
||||
|
||||
交易方向查询也读取 quote_events。execution_price 和 execution_prices 通过 quotes.rs 查询请求时的最优对手价。批量调用在一条 SQL 中读取所有请求的市场,YES 和 NO 分别换算后再按方向取价。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant H as HTTP 行情服务
|
||||
participant E as Exchange
|
||||
participant Q as quotes.rs
|
||||
participant D as SQLite
|
||||
H->>E: execution_prices,传入资产和交易方向
|
||||
E->>Q: 读取批量报价
|
||||
Q->>D: 单条查询读取每个市场最近一次最优档
|
||||
D-->>Q: 返回买一与卖一
|
||||
Q-->>H: 按资产和方向分组的可用价格
|
||||
```
|
||||
|
||||
@@ -48,6 +48,7 @@ use std::{path::Path, time::Duration};
|
||||
pub use assets::parse_id as parse_asset_id;
|
||||
pub use depth_feed::MarketPage;
|
||||
pub use prices_history::http::HistoryQuery;
|
||||
pub use quotes::{PriceQueryError, PriceRequest, PriceSide};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum MarketDataError {
|
||||
|
||||
@@ -136,23 +136,42 @@ impl Filter {
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
enum Side {
|
||||
pub enum PriceSide {
|
||||
Buy,
|
||||
Sell,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct PriceRequest {
|
||||
token_id: String,
|
||||
side: Side,
|
||||
pub struct PriceRequest {
|
||||
pub token_id: String,
|
||||
pub side: PriceSide,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum PriceQueryError {
|
||||
RequestCount,
|
||||
InvalidToken,
|
||||
MissingBook,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for PriceQueryError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str(match self {
|
||||
Self::RequestCount => "expected 1 to 500 price requests",
|
||||
Self::InvalidToken => "invalid Eventbook asset_id",
|
||||
Self::MissingBook => "unknown Eventbook asset_id",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for PriceQueryError {}
|
||||
|
||||
impl PriceRequest {
|
||||
fn label(&self) -> &'static str {
|
||||
match self.side {
|
||||
Side::Buy => "BUY",
|
||||
Side::Sell => "SELL",
|
||||
PriceSide::Buy => "BUY",
|
||||
PriceSide::Sell => "SELL",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,14 +184,14 @@ 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>>> {
|
||||
ensure!(
|
||||
(1..=500).contains(&requests.len()),
|
||||
"expected 1 to 500 price requests"
|
||||
);
|
||||
if !(1..=500).contains(&requests.len()) {
|
||||
return Err(PriceQueryError::RequestCount.into());
|
||||
}
|
||||
let mut markets = Vec::with_capacity(requests.len());
|
||||
let mut outcomes = Vec::with_capacity(requests.len());
|
||||
for request in requests {
|
||||
let (outcome, market) = assets::parse_id(&request.token_id)?;
|
||||
let (outcome, market) =
|
||||
assets::parse_id(&request.token_id).map_err(|_| PriceQueryError::InvalidToken)?;
|
||||
markets.push(market);
|
||||
outcomes.push(outcome);
|
||||
}
|
||||
@@ -185,15 +204,14 @@ fn price_rows(db: &Connection, requests: &[PriceRequest]) -> Result<Vec<Option<S
|
||||
let mut rows = stmt.query([serde_json::to_string(&markets)?])?;
|
||||
let mut prices = Vec::with_capacity(requests.len());
|
||||
while let Some(row) = rows.next()? {
|
||||
ensure!(
|
||||
row.get::<_, Option<String>>(4)?.is_some(),
|
||||
"unknown Eventbook asset_id"
|
||||
);
|
||||
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 {
|
||||
Side::Buy => quote.ask,
|
||||
Side::Sell => quote.bid,
|
||||
PriceSide::Buy => quote.ask,
|
||||
PriceSide::Sell => quote.bid,
|
||||
};
|
||||
prices.push(price.map(|p| {
|
||||
let mut text = format!("{}.{:04}", p / 10000, p % 10000);
|
||||
@@ -207,8 +225,15 @@ fn price_rows(db: &Connection, requests: &[PriceRequest]) -> Result<Vec<Option<S
|
||||
}
|
||||
|
||||
pub(crate) fn prices(db: &Connection, requests: &[PriceRequest]) -> Result<Value> {
|
||||
price_map(db, requests, true)
|
||||
}
|
||||
|
||||
fn price_map(db: &Connection, requests: &[PriceRequest], include_empty: bool) -> Result<Value> {
|
||||
let mut result = json!({});
|
||||
for (request, price) in requests.iter().zip(price_rows(db, requests)?) {
|
||||
if price.is_none() && !include_empty {
|
||||
continue;
|
||||
}
|
||||
let number = price
|
||||
.as_deref()
|
||||
.map(str::parse::<serde_json::Number>)
|
||||
@@ -219,6 +244,14 @@ pub(crate) fn prices(db: &Connection, requests: &[PriceRequest]) -> Result<Value
|
||||
}
|
||||
|
||||
impl crate::Exchange {
|
||||
pub fn execution_price(&self, request: &PriceRequest) -> Result<Value> {
|
||||
request.single(&self.db)
|
||||
}
|
||||
|
||||
pub fn execution_prices(&self, requests: &[PriceRequest]) -> Result<Value> {
|
||||
price_map(&self.db, requests, false)
|
||||
}
|
||||
|
||||
pub fn spreads(
|
||||
&self,
|
||||
tokens: &[String],
|
||||
|
||||
@@ -60,3 +60,15 @@ POST http://127.0.0.1:9002/midpoints
|
||||
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")
|
||||
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)
|
||||
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
|
||||
POST http://127.0.0.1:9002/prices
|
||||
Content-Type: application/json
|
||||
|
||||
[{"token_id":"eb:YES:mid-example","side":"BUY"},{"token_id":"eb:NO:mid-example","side":"BUY"}]
|
||||
|
||||
@@ -363,3 +363,9 @@ Polymarket 的单资产最近成交接口规定,无成交时返回价格字符
|
||||
加载[中点订单样例](examples/midpoint.jsonl)后,YES 的买一为 0.08,NO 买一 0.91 对应 YES 卖一 0.09。单查 YES 得到 {"mid":"0.085"},批查两边得到 0.085 和 0.915。结果保留半个报价步长。即使价差很宽,中点查询也始终取两边的算术平均。缺边处理与上文价差查询相同,仍待生产样本验证。[官方行情指南](https://docs.polymarket.com/market-data/prices-order-books#fetch-a-midpoint)
|
||||
|
||||
单查字段有两种公开描述。行情指南的原始 HTTP 样例和官方 Rust SDK 的模拟服务均使用 `mid`,OpenAPI 定义的是 `mid_price`。本地返回前者,批量 GET 和 POST 均返回以资产 ID 为键的十进制字符串。这里引用的是文档与 SDK 测试,尚未取得同一时刻的生产回执。[Rust SDK 测试](https://github.com/Polymarket/rs-clob-client-v2/blob/main/tests/clob.rs#L89-L135) · [单资产 OpenAPI](https://docs.polymarket.com/api-reference/data/get-midpoint-price) · [批量 GET](https://docs.polymarket.com/api-reference/market-data/get-midpoint-prices-query-parameters)
|
||||
|
||||
### 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)
|
||||
|
||||
官方行情指南从交易者角度描述 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)
|
||||
|
||||
Reference in New Issue
Block a user