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());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user