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
+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