Serve the CLOB price history protocol with minute-based fidelity

This commit is contained in:
2026-12-03 10:18:43 +08:00
parent 74749bfdb8
commit fe69e31929
10 changed files with 201 additions and 1 deletions
+23
View File
@@ -1111,3 +1111,26 @@ sequenceDiagram
D-->>Q: 返回买一与卖一
Q-->>H: 按资产和方向分组的可用价格
```
### CLOB 历史交易价格
```mermaid
flowchart LR
H["cli/market_http.rs"] --> L["prices_history/legacy.rs"]
L --> A["assets.rs"]
L --> Q["prices_history/legacy.sql"]
Q --> T["price_migration.sql 中的 outcome_trade_prices"]
Q --> S["schema.sql 中的 price_settlements"]
```
```mermaid
sequenceDiagram
participant C as HTTP
participant E as Exchange
participant D as SQLite
C->>E: clob_price_history
E->>D: 读事务中确认资产并取得当前时钟
E->>D: 按查询窗口和分钟粒度选每个桶内最后一个成交或兑付
D-->>E: 观测时间和定点价格
E-->>C: t 为 Unix 秒,p 为十进制数
```
+1
View File
@@ -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 prices_history::legacy::ClobHistoryQuery;
pub use quotes::{PriceQueryError, PriceRequest, PriceSide};
#[derive(Debug)]
+1
View File
@@ -1,4 +1,5 @@
pub(crate) mod http;
pub(crate) mod legacy;
use anyhow::{bail, ensure, Result};
use rusqlite::{params, Connection, Row};
use serde::{Deserialize, Serialize};
@@ -0,0 +1,89 @@
use crate::{assets, inventory, Exchange, HistoryError};
use rusqlite::params;
use serde::Deserialize;
use serde_json::{json, Value};
#[derive(Deserialize)]
pub struct ClobHistoryQuery {
market: String,
#[serde(rename = "startTs")]
start: Option<f64>,
#[serde(rename = "endTs")]
end: Option<f64>,
interval: Option<String>,
fidelity: Option<i64>,
}
impl ClobHistoryQuery {
fn bounds(&self, now: i64) -> Result<(i64, i64), HistoryError> {
let invalid = || HistoryError::Invalid("invalid price history window".into());
match (self.interval.as_deref(), self.start, self.end) {
(Some(interval), None, None) => {
let span = match interval {
"1h" => 3600,
"6h" => 6 * 3600,
"1d" => super::DAY,
"1w" => 7 * super::DAY,
"1m" => 30 * super::DAY,
"max" | "all" => return Ok((0, now)),
_ => return Err(invalid()),
};
Ok(((now - span * 1000).max(0), now))
}
(None, Some(start), Some(end))
if start.is_finite()
&& start >= 0.0
&& start < end
&& end <= f64::from(u32::MAX) =>
{
Ok((boundary_ms(start, f64::ceil), boundary_ms(end, f64::floor)))
}
_ => Err(invalid()),
}
}
}
// Multiplying a decimal timestamp such as 1.001 by 1000 can land below its
// exact millisecond. Preserve that point before rounding sub-ms boundaries.
fn boundary_ms(seconds: f64, round: fn(f64) -> f64) -> i64 {
let ms = seconds * 1000.0;
let nearest = ms.round() as i64;
if nearest as f64 / 1000.0 == seconds {
nearest
} else {
round(ms) as i64
}
}
impl Exchange {
pub fn clob_price_history(&self, query: ClobHistoryQuery) -> Result<Value, HistoryError> {
let (outcome, market) = assets::parse_id(&query.market)
.map_err(|_| HistoryError::Invalid("invalid market asset id".into()))?;
let width = query
.fidelity
.unwrap_or(1)
.checked_mul(60)
.filter(|n| *n > 0)
.ok_or_else(|| HistoryError::Invalid("invalid fidelity".into()))?;
let tx = self.db.unchecked_transaction()?;
let (listed, now): (bool, i64) = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1), CAST(unixepoch('subsec') * 1000 AS INTEGER)",
[market], |r| Ok((r.get(0)?, r.get(1)?))
)?;
if !listed {
return Err(HistoryError::Invalid("unknown market asset id".into()));
}
let (start, end) = query.bounds(now)?;
let points = {
let mut stmt = tx.prepare_cached(include_str!("legacy.sql"))?;
let rows = stmt.query_map(params![market, outcome, start, end, width], |r| {
let timestamp: i64 = r.get(0)?;
let micros: i64 = r.get(1)?;
Ok(json!({"t":timestamp,"p":inventory::decimal(micros.into(), inventory::UNIT)}))
})?;
rows.collect::<rusqlite::Result<Vec<_>>>()?
};
tx.commit()?;
Ok(json!({"history":points}))
}
}
@@ -0,0 +1,13 @@
-- Return the last observed price in each UTC fidelity window at its actual time.
WITH observations(ms, micros, sequence, payout) AS (
SELECT at_ms, price_micros, fill, 0 FROM outcome_trade_prices
WHERE market=?1 AND outcome=?2 AND at_ms BETWEEN ?3 AND ?4
UNION ALL
SELECT at_ms, CASE WHEN winner='VOID' THEN 500000 WHEN winner=?2 THEN 1000000 ELSE 0 END, id, 1
FROM price_settlements WHERE market=?1 AND at_ms BETWEEN ?3 AND ?4
), ranked AS (
SELECT ms, micros, ROW_NUMBER() OVER (
PARTITION BY ms/1000/?5 ORDER BY ms DESC, payout DESC, sequence DESC
) AS position FROM observations
)
SELECT ms/1000, micros FROM ranked WHERE position=1 ORDER BY ms
+23
View File
@@ -1532,6 +1532,25 @@ fn prices_history_keeps_the_terminal_tick_and_pins_pages_before_settlement() {
let wire = |engine: &Exchange, params: Value| {
engine.public_price_history(serde_json::from_value(params).unwrap())
};
let clob = |engine: &Exchange, start: f64, end: f64, minutes: i64| {
engine
.clob_price_history(
serde_json::from_value(json!({
"market":"eb:YES:e","startTs":start,"endTs":end,"fidelity":minutes
}))
.unwrap(),
)
.unwrap()
};
assert_eq!(
clob(&e, 120.0, 245.0, 1),
json!({"history":[{"t":149,"p":0.47},{"t":245,"p":0.55}]})
);
assert_eq!(clob(&e, 149.001, 244.999, 1), json!({"history":[]}));
assert_eq!(
clob(&e, 120.0, 245.0, 10),
json!({"history":[{"t":245,"p":0.55}]})
);
let first_wire = wire(
&e,
json!({"tokenId":"eb:YES:e","start":120,"end":290,"bucketSeconds":60,"limit":1}),
@@ -1563,6 +1582,10 @@ fn prices_history_keeps_the_terminal_tick_and_pins_pages_before_settlement() {
.unwrap();
drop(e);
let mut e = Exchange::open(&path).unwrap();
assert_eq!(
clob(&e, 120.0, 290.0, 1),
json!({"history":[{"t":149,"p":0.47},{"t":273,"p":0.5}]})
);
let second_wire = wire(
&e,
json!({"token_id":"eb:YES:e","start":120,"end":290,"cursor":saved,"limit":99}),