Expose single and batch execution-side prices from one book snapshot
This commit is contained in:
@@ -10,6 +10,8 @@
|
||||
flowchart LR
|
||||
test["tests/market.rs"] -->|通过公开 API 驱动市场| api["src/lib.rs"]
|
||||
api -->|解析结果资产 ID| assets["src/assets.rs"]
|
||||
queries -->|解析单笔和批量报价| marks
|
||||
marks -->|拆解每个 token_id| assets
|
||||
queries -->|生成目录中的结果资产| assets
|
||||
acct -->|回传订单的资产 ID| assets
|
||||
portfolio -->|回传持仓的资产 ID| assets
|
||||
@@ -608,3 +610,20 @@ sequenceDiagram
|
||||
E-->>C: 回执或预估结果
|
||||
end
|
||||
```
|
||||
|
||||
## 下单面板的买卖报价
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant E as Exchange
|
||||
participant Q as quotes.rs
|
||||
participant D as SQLite
|
||||
C->>E: prices 请求多个 token_id 和 BUY 或 SELL
|
||||
E->>D: 清理到期单并取得读快照
|
||||
E->>Q: 校验每个资产与请求数量
|
||||
Q->>D: 一次查询各市场最近的已提交买一与卖一
|
||||
D-->>Q: YES 侧报价,缺边为 null
|
||||
Q->>Q: 反推出 NO 报价,按请求方向选择对手价
|
||||
Q-->>C: 按资产与方向返回价格,无对手报 null
|
||||
```
|
||||
|
||||
@@ -9,6 +9,16 @@ pub(crate) fn id(market: &str, outcome: &str) -> String {
|
||||
format!("eb:{outcome}:{market}")
|
||||
}
|
||||
|
||||
pub(crate) fn parse_id(asset: &str) -> Result<(&str, &str)> {
|
||||
let (outcome, market) = asset
|
||||
.strip_prefix("eb:")
|
||||
.and_then(|s| s.split_once(':'))
|
||||
.context("invalid Eventbook asset_id")?;
|
||||
ensure!(matches!(outcome, "YES" | "NO"), "invalid asset outcome");
|
||||
identifier(market)?;
|
||||
Ok((outcome, market))
|
||||
}
|
||||
|
||||
pub(crate) fn outcomes(market: &str, yes: &str, no: &str) -> Value {
|
||||
json!([
|
||||
{"outcome":"YES","label":yes,"asset_id":id(market,"YES")},
|
||||
@@ -66,13 +76,7 @@ pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> {
|
||||
let Some(asset) = fields.remove("asset_id") else {
|
||||
return Ok(());
|
||||
};
|
||||
let (outcome, market) = asset
|
||||
.as_str()
|
||||
.and_then(|s| s.strip_prefix("eb:"))
|
||||
.and_then(|s| s.split_once(':'))
|
||||
.context("invalid Eventbook asset_id")?;
|
||||
ensure!(matches!(outcome, "YES" | "NO"), "invalid asset outcome");
|
||||
identifier(market)?;
|
||||
let (outcome, market) = parse_id(asset.as_str().context("invalid Eventbook asset_id")?)?;
|
||||
for (field, value) in [("market", market), ("outcome", outcome)] {
|
||||
if let Some(existing) = fields.get(field) {
|
||||
ensure!(
|
||||
|
||||
@@ -237,6 +237,10 @@ pub(crate) enum Query {
|
||||
Estimate(crate::estimate::Request),
|
||||
PricesHistory(crate::prices_history::Request),
|
||||
QuoteHistory(crate::quotes::Filter),
|
||||
Price(crate::quotes::PriceRequest),
|
||||
Prices {
|
||||
requests: Vec<crate::quotes::PriceRequest>,
|
||||
},
|
||||
Volume {
|
||||
event: Option<String>,
|
||||
market: Option<String>,
|
||||
@@ -293,6 +297,8 @@ impl Query {
|
||||
.response(),
|
||||
)
|
||||
}
|
||||
Self::Price(request) => request.single(db),
|
||||
Self::Prices { requests } => crate::quotes::prices(db, &requests),
|
||||
Self::QuoteHistory(request) => request.read(db),
|
||||
Self::PricesHistory(request) => request.read(db),
|
||||
Self::Estimate(request) => request.read(db, books),
|
||||
|
||||
@@ -103,6 +103,8 @@ impl Exchange {
|
||||
| "history"
|
||||
| "prices_history"
|
||||
| "quote"
|
||||
| "price"
|
||||
| "prices"
|
||||
| "quote_history"
|
||||
| "volume"
|
||||
| "book"
|
||||
|
||||
@@ -122,3 +122,81 @@ impl Filter {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
enum Side {
|
||||
Buy,
|
||||
Sell,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct PriceRequest {
|
||||
token_id: String,
|
||||
side: Side,
|
||||
}
|
||||
|
||||
impl PriceRequest {
|
||||
fn label(&self) -> &'static str {
|
||||
match self.side {
|
||||
Side::Buy => "BUY",
|
||||
Side::Sell => "SELL",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn single(&self, db: &Connection) -> Result<Value> {
|
||||
let mut rows = price_rows(db, std::slice::from_ref(self))?;
|
||||
Ok(json!({"price": rows.pop().flatten()}))
|
||||
}
|
||||
}
|
||||
|
||||
// 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"
|
||||
);
|
||||
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)?;
|
||||
markets.push(market);
|
||||
outcomes.push(outcome);
|
||||
}
|
||||
let mut stmt = db.prepare_cached(
|
||||
"SELECT COALESCE(q.seq,0),q.yes_bid,q.yes_ask,q.at_ms,m.id,j.key
|
||||
FROM json_each(?1) j LEFT JOIN markets m ON m.id=j.value
|
||||
LEFT JOIN quote_events q ON q.seq=(SELECT MAX(seq) FROM quote_events WHERE market=m.id)
|
||||
ORDER BY j.key",
|
||||
)?;
|
||||
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"
|
||||
);
|
||||
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,
|
||||
};
|
||||
prices.push(price.map(|cents| format!("{}.{:02}", cents / 100, cents % 100)));
|
||||
}
|
||||
Ok(prices)
|
||||
}
|
||||
|
||||
pub(crate) fn prices(db: &Connection, requests: &[PriceRequest]) -> Result<Value> {
|
||||
let mut result = json!({});
|
||||
for (request, price) in requests.iter().zip(price_rows(db, requests)?) {
|
||||
let number = price
|
||||
.as_deref()
|
||||
.map(str::parse::<serde_json::Number>)
|
||||
.transpose()?;
|
||||
result[request.token_id.as_str()][request.label()] = json!(number);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -2065,3 +2065,55 @@ fn minimum_size_checks_submitted_orders_and_preserves_partial_fills() {
|
||||
.unwrap()["min_order_size"]
|
||||
.is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_and_batch_execution_prices_follow_opposing_liquidity() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("execution-prices.db");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
let mut batch = Value::Null;
|
||||
let mut single = Vec::new();
|
||||
for line in include_str!("../../../docs/examples/execution-prices.jsonl").lines() {
|
||||
let request: Value = serde_json::from_str(line).unwrap();
|
||||
let response = e.execute(request.clone()).unwrap();
|
||||
match request["op"].as_str().unwrap() {
|
||||
"price" => single.push(response["price"].clone()),
|
||||
"prices" => {
|
||||
for (asset, buy, sell) in [
|
||||
("eb:YES:cup:final", 0.11, 0.09),
|
||||
("eb:NO:cup:final", 0.91, 0.89),
|
||||
] {
|
||||
assert_eq!(response[asset]["BUY"].as_f64(), Some(buy));
|
||||
assert_eq!(response[asset]["SELL"].as_f64(), Some(sell));
|
||||
}
|
||||
batch = request;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert_eq!(single, vec![Value::Null, json!("0.11")]);
|
||||
let mut reader = Exchange::open(&path).unwrap();
|
||||
assert_eq!(
|
||||
reader.execute(batch.clone()).unwrap(),
|
||||
e.execute(batch.clone()).unwrap()
|
||||
);
|
||||
e.execute(json!({"op":"cancel_all","id":"cancel","account":"alice"}))
|
||||
.unwrap();
|
||||
let empty = reader.execute(batch.clone()).unwrap();
|
||||
assert_eq!(empty["eb:NO:cup:final"], json!({"BUY":null,"SELL":null}));
|
||||
let item = batch["requests"][0].clone();
|
||||
let limit = json!({"op":"prices","requests":vec![item.clone();500]});
|
||||
assert_eq!(
|
||||
reader.execute(limit).unwrap(),
|
||||
json!({"eb:YES:cup:final":{"BUY":null}})
|
||||
);
|
||||
for invalid in [
|
||||
json!({"op":"prices","requests":[]}),
|
||||
json!({"op":"prices","requests":vec![item.clone();501]}),
|
||||
json!({"op":"prices","requests":[item,{"token_id":"eb:YES:unknown","side":"BUY"}]}),
|
||||
json!({"op":"price","token_id":"eb:other:cup:final","side":"SELL"}),
|
||||
json!({"op":"price","token_id":"eb:YES:cup:final","side":"other"}),
|
||||
] {
|
||||
assert!(reader.execute(invalid).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{"op":"list","id":"m","market":"cup:final","rules":"Official final result"}
|
||||
{"op":"fund","id":"f","account":"alice","cents":2000}
|
||||
{"op":"open","id":"o","market":"cup:final"}
|
||||
{"op":"order","id":"y","market":"cup:final","account":"alice","side":"buy","outcome":"YES","price":9,"qty":2}
|
||||
{"op":"price","token_id":"eb:YES:cup:final","side":"BUY"}
|
||||
{"op":"order","id":"n","market":"cup:final","account":"alice","side":"buy","outcome":"NO","price":89,"qty":2}
|
||||
{"op":"prices","requests":[{"token_id":"eb:YES:cup:final","side":"BUY"},{"token_id":"eb:YES:cup:final","side":"SELL"},{"token_id":"eb:NO:cup:final","side":"BUY"},{"token_id":"eb:NO:cup:final","side":"SELL"}]}
|
||||
{"op":"price","token_id":"eb:YES:cup:final","side":"BUY"}
|
||||
@@ -216,3 +216,9 @@ FOK 要求整笔金额成交,无法用完预算时交易回滚。超过最高
|
||||
[可重放样例](examples/minimum-size.jsonl)上架时设置 min_order_size="5"。卖家挂 8 份,第一张 5 份买单成交后余下 3 份,仍可在盘口看到。第二张 FAK 买单给定预算 2.60 模拟美元、保护价 0.52,达到提交 5 份的门槛,可成交剩余 3 份。若改为 2.59 则在预留资金前拒绝。卖单和按份数发出的限价单检查提交份数;盘前、盘中、YES 与 NO 接受同一门槛。撤单、逐笔成交和存量余额沿用原有语义。
|
||||
|
||||
list 接受十进制份额字符串,最多六位小数;book、assets 和事件 catalog 返回去掉多余末尾零的字符串。没有配置的旧市场返回 null,继续适用原有数量与预算逻辑。本地只能交易整份,门槛 5.125 的最小可提交份数为 6。预算买单用保护价和这一起订份数计算最低预算,并计入该价位的一笔吃单费。例如保护价 0.50、费率 0.05 时,六份需要 3.075 模拟美元,分为单位的预算至少 3.08。这个含费门槛、部分成交余量与生产舍入方式仍待外场比对。
|
||||
|
||||
## 下单面板的单笔与批量买卖报价
|
||||
|
||||
`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)
|
||||
|
||||
[可重放样例](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,公开接口的生产响应、原生资产编号与无流动性时的处理仍待对照。
|
||||
|
||||
Reference in New Issue
Block a user