Expose aggregated binary order book depth per outcome

This commit is contained in:
2026-12-03 03:53:29 +08:00
parent 47d49cb8c9
commit 646cf193bb
6 changed files with 100 additions and 14 deletions
+5 -1
View File
@@ -65,7 +65,7 @@ sequenceDiagram
flowchart LR
cmd["src/command.rs"] -->|可选上架条款| cat["src/catalog.rs"]
market["src/market.rs"] -->|同事务保存| cat
api["src/lib.rs"] -->|目录和历史价查询| cat
api["src/lib.rs"] -->|目录、价格与深度查询| cat
cat -->|校验事件标识| valid["src/validation.rs"]
```
@@ -81,6 +81,10 @@ sequenceDiagram
U->>E: history 指定市场、结果和时间窗
E->>D: 按时间与成交序号索引分页查询
E-->>U: 返回成交时间、价格、数量
U->>E: book 指定市场和结果
E->>D: 读取该市场快照,将同结果订单和互补订单按价汇总剩余量
D-->>E: 买档降序,卖档升序
E-->>U: 返回阶段与两侧深度
```
## 最终裁决与模拟资产兑付
+36 -11
View File
@@ -141,6 +141,10 @@ impl Listing {
#[derive(Deserialize)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum Query {
Book {
market: String,
outcome: String,
},
Quote {
market: String,
outcome: String,
@@ -161,19 +165,31 @@ pub(crate) enum Query {
impl Query {
pub fn read(self, db: &Connection) -> Result<Value> {
match self {
Self::Book { market, outcome } => {
let phase = market_phase(db, &market, &outcome)?;
let mut stmt = db.prepare(
"SELECT side,price,SUM(remaining) FROM visible_orders WHERE market=?1 AND outcome=?2
GROUP BY side,price ORDER BY side, CASE side WHEN 'buy' THEN -price ELSE price END",
)?;
let mut rows = stmt.query(params![market, outcome])?;
let mut bids = Vec::new();
let mut asks = Vec::new();
while let Some(row) = rows.next()? {
let side: String = row.get(0)?;
let price: i64 = row.get(1)?;
let size: i64 = row.get(2)?;
let levels = if side == "buy" { &mut bids } else { &mut asks };
levels.push(json!({"price_micros":price*10000,"size":size}));
}
Ok(json!({"market":market,"outcome":outcome,"phase":phase,"bids":bids,"asks":asks}))
}
Self::Quote { market, outcome } => {
ensure!(matches!(outcome.as_str(), "YES" | "NO"), "invalid outcome");
let phase: String =
db.query_row("SELECT phase FROM markets WHERE id=?", [&market], |r| {
r.get(0)
})?;
let phase = market_phase(db, &market, &outcome)?;
let (bid, ask): (Option<i64>, Option<i64>) = db.query_row(
"SELECT MAX(CASE WHEN side='buy' AND outcome=?1 THEN price
WHEN side='sell' AND outcome<>?1 THEN 100-price END),
MIN(CASE WHEN side='sell' AND outcome=?1 THEN price
WHEN side='buy' AND outcome<>?1 THEN 100-price END)
FROM orders WHERE market=?2 AND status='live'",
params![outcome, market],
"SELECT MAX(CASE WHEN side='buy' THEN price END),
MIN(CASE WHEN side='sell' THEN price END)
FROM visible_orders WHERE market=?1 AND outcome=?2",
params![market, outcome],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
// Fills also cover databases created before timestamped history was introduced.
@@ -257,3 +273,12 @@ impl Query {
}
}
}
fn market_phase(db: &Connection, market: &str, outcome: &str) -> Result<String> {
ensure!(matches!(outcome, "YES" | "NO"), "invalid outcome");
Ok(
db.query_row("SELECT phase FROM markets WHERE id=?", [market], |r| {
r.get(0)
})?,
)
}
+1 -1
View File
@@ -32,7 +32,7 @@ impl Exchange {
pub fn execute(&mut self, payload: Value) -> Result<Value> {
if matches!(
payload["op"].as_str(),
Some("catalog" | "history" | "quote")
Some("catalog" | "history" | "quote" | "book")
) {
let query: catalog::Query = serde_json::from_value(payload)?;
let tx = self.db.transaction()?;
+8
View File
@@ -73,3 +73,11 @@ CREATE VIEW IF NOT EXISTS outcome_trade_prices AS
SELECT fill,market,outcome,at_ms,price_micros,quantity FROM trade_prices
UNION ALL SELECT seq,market,'YES',at_ms,yes_price*10000,quantity FROM paired_fills
UNION ALL SELECT seq,market,'NO',at_ms,(100-yes_price)*10000,quantity FROM paired_fills;
-- Each live binary order contributes once to each outcome's depth.
CREATE VIEW IF NOT EXISTS visible_orders AS
SELECT market,outcome,side,price,remaining FROM orders WHERE status='live'
UNION ALL
SELECT market,CASE outcome WHEN 'YES' THEN 'NO' ELSE 'YES' END,
CASE side WHEN 'buy' THEN 'sell' ELSE 'buy' END,100-price,remaining
FROM orders WHERE status='live';
+43
View File
@@ -493,3 +493,46 @@ fn direct_and_complementary_liquidity_share_price_time_priority() {
assert_eq!(s["fills"][1]["seq"], 3);
assert_eq!(s["fills"][1]["quantity"], 1);
}
#[test]
fn book_groups_direct_and_complementary_remaining_size() {
let dir = tempdir().unwrap();
let path = dir.path().join("depth.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let yes = json!({"op":"book","market":"e","outcome":"YES"});
let no = json!({"op":"book","market":"e","outcome":"NO"});
assert_eq!(e.execute(yes.clone()).unwrap()["asks"], json!([]));
e.execute(json!({"op":"open","id":"open","market":"e"}))
.unwrap();
e.execute(order("direct", "alice", "sell", 60, 3)).unwrap();
let mut mirrored = order("mirrored", "bob", "buy", 40, 4);
mirrored["outcome"] = json!("NO");
let seq = e.execute(mirrored).unwrap()["order"].clone();
e.execute(order("dearer", "alice", "sell", 65, 1)).unwrap();
let levels = e.execute(yes.clone()).unwrap();
assert_eq!(
levels["asks"],
json!([{"price_micros":600000,"size":7},{"price_micros":650000,"size":1}])
);
assert_eq!(levels["bids"], json!([]));
let inverse = e.execute(no.clone()).unwrap();
assert_eq!(
inverse["bids"],
json!([{"price_micros":400000,"size":7},{"price_micros":350000,"size":1}])
);
e.execute(order("partial", "bob", "buy", 60, 2)).unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(e.execute(yes.clone()).unwrap()["asks"][0]["size"], 5);
e.execute(json!({"op":"cancel","id":"withdraw","account":"bob","order":seq}))
.unwrap();
assert_eq!(e.execute(yes).unwrap()["asks"][0]["size"], 1);
assert_eq!(e.execute(no).unwrap()["bids"][0]["size"], 1);
assert!(e
.execute(json!({"op":"book","market":"missing","outcome":"YES"}))
.is_err());
assert!(e
.execute(json!({"op":"book","market":"e","outcome":"other"}))
.is_err());
}