From 9b25fdc4247adc6deb3061c874cde33a684d55f1 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Thu, 3 Dec 2026 08:12:01 +0800 Subject: [PATCH] Expose paginated token price history through the public HTTP service --- Cargo.lock | 1 + crates/cli/README.md | 22 ++++ crates/cli/src/market_http.rs | 38 +++++- crates/exchange/Cargo.toml | 1 + crates/exchange/README.md | 25 ++++ crates/exchange/src/lib.rs | 1 + crates/exchange/src/prices_history.rs | 3 + crates/exchange/src/prices_history/http.rs | 142 +++++++++++++++++++++ crates/exchange/tests/market.rs | 49 +++++++ docs/examples/clob-http.http | 6 + docs/prediction-parity.md | 6 + 11 files changed, 292 insertions(+), 2 deletions(-) create mode 100644 crates/exchange/src/prices_history/http.rs diff --git a/Cargo.lock b/Cargo.lock index 5044bb2..63d0e89 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -139,6 +139,7 @@ name = "exchange" version = "0.1.0" dependencies = [ "anyhow", + "data-encoding", "matching", "rusqlite", "serde", diff --git a/crates/cli/README.md b/crates/cli/README.md index 0ba4b16..87e1a67 100644 --- a/crates/cli/README.md +++ b/crates/cli/README.md @@ -100,3 +100,25 @@ sequenceDiagram E-->>H: 一个数据库快照中的盘口列表 H-->>C: 单盘 JSON 对象或批量 JSON 数组 ``` + +同一个 HTTP 监听器提供 `GET /v2/prices-history`。客户端按资产查询历史,接续页可以只发同一资产和上一页的游标。[请求样例](../../docs/examples/clob-http.http) + +```mermaid +flowchart LR + main["main.rs"] --> http["market_http.rs"] + http --> history["exchange::HistoryQuery"] +``` + +```mermaid +sequenceDiagram + participant C as 图表客户端 + participant H as market_http + participant E as Exchange + C->>H: GET /v2/prices-history 含资产与窗口 + H->>E: 查询历史点与分页状态 + E-->>H: data 与 pagination + H-->>C: JSON 中的 next_cursor + C->>H: 同一 token_id 和 cursor + H->>E: 读取该窗口下一页 + E-->>C: 后续点及是否还有数据 +``` diff --git a/crates/cli/src/market_http.rs b/crates/cli/src/market_http.rs index 2ac0bd3..52b41ab 100644 --- a/crates/cli/src/market_http.rs +++ b/crates/cli/src/market_http.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use exchange::Exchange; +use exchange::{Exchange, HistoryError, HistoryQuery}; use serde::Deserialize; use serde_json::{json, Value}; use std::{io::Read, net::TcpListener, sync::Mutex, thread}; @@ -69,12 +69,16 @@ fn batch(req: &mut Request, engine: &Mutex) -> Reply { fn respond(mut req: Request, engine: &Mutex) -> std::io::Result<()> { let (path, params) = req.url().split_once('?').unwrap_or((req.url(), "")); let mut allow = None; + if req.method() == &Method::Get && path == "/v2/prices-history" { + let (status, body) = history(params, engine); + return send(req, status, body, None); + } let reply = match (req.method(), path) { (&Method::Get, "/book") => serde_urlencoded::from_str::(params) .map_err(|_| (400, "Invalid token id")) .and_then(|p| query(engine, vec![p], true)), (&Method::Post, "/books") => batch(&mut req, engine), - (_, "/book") => { + (_, "/book" | "/v2/prices-history") => { allow = Some("GET"); Err((405, "Method not allowed")) } @@ -88,6 +92,32 @@ fn respond(mut req: Request, engine: &Mutex) -> std::io::Result<()> { Ok(v) => (200, v), Err((status, msg)) => (status, json!({"error":msg})), }; + send(req, status, body, allow) +} + +fn history(params: &str, engine: &Mutex) -> (u16, Value) { + let page = serde_urlencoded::from_str::(params) + .map_err(|_| HistoryError::Invalid("invalid query parameters".to_owned())) + .and_then(|query| { + engine + .lock() + .map_err(|_| HistoryError::Unavailable)? + .public_price_history(query) + }); + match page { + Ok(data) => (200, data), + Err(HistoryError::Invalid(message)) => ( + 400, + json!({"code":"invalid_request","error":message,"retryable":false}), + ), + Err(HistoryError::Unavailable) => ( + 500, + json!({"code":"internal_error","error":"history unavailable","retryable":true}), + ), + } +} + +fn send(req: Request, status: u16, body: Value, allow: Option<&str>) -> std::io::Result<()> { let mut response = Response::from_data(body.to_string().into_bytes()) .with_status_code(status) .with_header(Header::from_bytes("Content-Type", "application/json").unwrap()); @@ -182,6 +212,10 @@ mod tests { 400, None, ), + ("GET", "/v2/prices-history?tokenId=eb%3AYES%3Amap+2%3A%E8%83%9C%E8%80%85&interval=1h&bucketSeconds=60", String::new(), 200, + Some(json!({"data":[],"pagination":{"has_more":false,"next_cursor":null,"offset":0,"limit":10000}}))), + ("GET","/v2/prices-history?token_id=7&interval=1h",String::new(),400,None), + ("POST","/v2/prices-history",String::new(),405,None), ("GET", "/books", String::new(), 405, None), ("POST", "/order", "{}".into(), 404, None), ]; diff --git a/crates/exchange/Cargo.toml b/crates/exchange/Cargo.toml index 89036cf..4a27388 100644 --- a/crates/exchange/Cargo.toml +++ b/crates/exchange/Cargo.toml @@ -9,6 +9,7 @@ anyhow.workspace = true serde.workspace = true serde_json = { workspace = true, features = ["arbitrary_precision"] } rusqlite.workspace = true +data-encoding = "2" sha1 = "0.10" [dev-dependencies] diff --git a/crates/exchange/README.md b/crates/exchange/README.md index d4f2d2e..9c60cb8 100644 --- a/crates/exchange/README.md +++ b/crates/exchange/README.md @@ -980,3 +980,28 @@ sequenceDiagram end E-->>H: 结束读事务并返回数组 ``` + +### 图表客户端读取历史 + +```mermaid +flowchart LR + http["cli/market_http.rs"] --> wire["prices_history/http.rs"] + wire --> ids["assets.rs"] + wire --> history["prices_history.rs"] + history --> sql["prices_history.sql"] +``` + +```mermaid +sequenceDiagram + participant H as HTTP 服务 + participant W as prices_history/http.rs + participant R as prices_history.rs + participant D as SQLite + H->>W: token_id、窗口或游标 + W->>W: 校验资产、恢复首次查询的窗口与页大小 + W->>R: 查询一页或 as_of 时点 + R->>D: 按窗口、成交与裁决序号上限读取 + D-->>R: 升序价格点及精度 + R-->>W: 数据与内部继续位置 + W-->>H: 公开点字段、偏移和 URL 安全的继续游标 +``` diff --git a/crates/exchange/src/lib.rs b/crates/exchange/src/lib.rs index 97d9191..542719f 100644 --- a/crates/exchange/src/lib.rs +++ b/crates/exchange/src/lib.rs @@ -45,6 +45,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::{HistoryError, HistoryQuery}; pub struct Exchange { db: Connection, diff --git a/crates/exchange/src/prices_history.rs b/crates/exchange/src/prices_history.rs index ffea719..4c134c5 100644 --- a/crates/exchange/src/prices_history.rs +++ b/crates/exchange/src/prices_history.rs @@ -1,3 +1,4 @@ +pub(crate) mod http; use anyhow::{bail, ensure, Result}; use rusqlite::{params, Connection, Row}; use serde::{Deserialize, Serialize}; @@ -124,6 +125,8 @@ impl Request { && self.interval.is_none() && self.bucket_seconds.is_none() && self.limit.is_none() + && cursor.fill_cap >= 0 + && cursor.settlement_cap >= 0 && cursor.market == self.market && cursor.outcome == self.outcome && cursor.start >= 0 diff --git a/crates/exchange/src/prices_history/http.rs b/crates/exchange/src/prices_history/http.rs new file mode 100644 index 0000000..f63cf42 --- /dev/null +++ b/crates/exchange/src/prices_history/http.rs @@ -0,0 +1,142 @@ +use super::{Cursor, Request}; +use crate::{assets, Exchange}; +use anyhow::{ensure, Context, Result}; +use data_encoding::BASE64URL_NOPAD; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +#[derive(Deserialize)] +pub struct HistoryQuery { + #[serde(alias = "tokenId")] + token_id: String, + start: Option, + end: Option, + interval: Option, + #[serde(alias = "bucketSeconds")] + bucket_seconds: Option, + #[serde(alias = "asOf")] + as_of: Option, + limit: Option, + cursor: Option, +} + +#[derive(Deserialize, Serialize)] +struct Continuation { + page: Cursor, + offset: u64, + // Clients may resend the original window with their cursor. + start: Option, + end: Option, + interval: Option, + bucket_seconds: Option, +} + +#[derive(Debug)] +pub enum HistoryError { + Invalid(String), + Unavailable, +} + +impl Exchange { + pub fn public_price_history(&self, query: HistoryQuery) -> Result { + let tx = self + .db + .unchecked_transaction() + .map_err(|_| HistoryError::Unavailable)?; + let response = query.read(&tx).map_err(|err| { + if err.downcast_ref::().is_some() { + HistoryError::Unavailable + } else { + HistoryError::Invalid(err.to_string()) + } + })?; + tx.commit().map_err(|_| HistoryError::Unavailable)?; + Ok(response) + } +} + +impl HistoryQuery { + fn read(mut self, db: &rusqlite::Connection) -> Result { + let (outcome, market) = assets::parse_id(&self.token_id)?; + let mut offset: u64 = 0; + let mut page_size = self.limit.unwrap_or(10000); + let mut request = Request { + market: market.to_owned(), + outcome: outcome.to_owned(), + start: self.start, + end: self.end, + interval: self.interval.clone(), + bucket_seconds: self.bucket_seconds, + as_of: self.as_of, + limit: self.limit, + cursor: None, + }; + if let Some(encoded) = self.cursor { + let unpack = || -> Option { + serde_json::from_slice(&BASE64URL_NOPAD.decode(encoded.as_bytes()).ok()?).ok() + }; + let prior = unpack().context("invalid cursor")?; + ensure!( + self.as_of.is_none() + && self.start.is_none_or(|n| Some(n) == prior.start) + && self.end.is_none_or(|n| Some(n) == prior.end) + && self + .interval + .as_ref() + .is_none_or(|s| Some(s) == prior.interval.as_ref()) + && self + .bucket_seconds + .is_none_or(|n| Some(n) == prior.bucket_seconds), + "window differs from cursor" + ); + offset = prior.offset; + page_size = prior.page.limit; + self.start = prior.start; + self.end = prior.end; + self.interval = prior.interval; + self.bucket_seconds = prior.bucket_seconds; + request.start = None; + request.end = None; + request.interval = None; + request.bucket_seconds = None; + request.limit = None; + request.cursor = Some(prior.page); + } else if page_size == 0 { + // A zero-sized first page cannot advance a cursor. Validate the window first. + request.limit = if self.as_of.is_some() { None } else { Some(1) }; + } else if self.as_of.is_some() { + ensure!(page_size <= 10000, "invalid limit"); + request.limit = None; + } + let mut result = request.read(db)?; + let data = result["data"] + .as_array_mut() + .context("invalid history page")?; + for point in data.iter_mut() { + if let Some(fields) = point.as_object_mut() { + fields.remove("source"); + } + } + if page_size == 0 { + data.clear(); + } + let count = data.len() as u64; + let next = &result["pagination"]["next_cursor"]; + let cursor = if next.is_null() || page_size == 0 { + None + } else { + let carry = Continuation { + page: serde_json::from_value(next.clone())?, + offset: offset.checked_add(count).context("invalid cursor offset")?, + start: self.start, + end: self.end, + interval: self.interval, + bucket_seconds: self.bucket_seconds, + }; + Some(BASE64URL_NOPAD.encode(&serde_json::to_vec(&carry)?)) + }; + Ok(json!({"data":result["data"].take(),"pagination":{ + "has_more":cursor.is_some(),"next_cursor":cursor,"limit":page_size,"offset":offset + }})) + } +} diff --git a/crates/exchange/tests/market.rs b/crates/exchange/tests/market.rs index 98ff9a5..0787d89 100644 --- a/crates/exchange/tests/market.rs +++ b/crates/exchange/tests/market.rs @@ -1529,6 +1529,26 @@ fn prices_history_keeps_the_terminal_tick_and_pins_pages_before_settlement() { point(245, 0.55, 0, "trade") ]) ); + let wire = |engine: &Exchange, params: Value| { + engine.public_price_history(serde_json::from_value(params).unwrap()) + }; + let first_wire = wire( + &e, + json!({"tokenId":"eb:YES:e","start":120,"end":290,"bucketSeconds":60,"limit":1}), + ) + .unwrap(); + assert_eq!( + first_wire["data"], + json!([{"timestamp":120,"price":0.47,"resolution_seconds":60}]) + ); + let saved = first_wire["pagination"]["next_cursor"].as_str().unwrap(); + assert!(wire(&e, json!({"token_id":"eb:NO:e","cursor":saved})).is_err()); + assert!(wire( + &e, + json!({"token_id":"eb:YES:e","start":121,"cursor":saved}) + ) + .is_err()); + assert!(wire(&e, json!({"token_id":"eb:YES:e","cursor":"broken!"})).is_err()); let mut first = query.clone(); first["limit"] = json!(1); let page = e.execute(first).unwrap(); @@ -1543,6 +1563,35 @@ fn prices_history_keeps_the_terminal_tick_and_pins_pages_before_settlement() { .unwrap(); drop(e); let mut e = Exchange::open(&path).unwrap(); + let second_wire = wire( + &e, + json!({"token_id":"eb:YES:e","start":120,"end":290,"cursor":saved,"limit":99}), + ) + .unwrap(); + assert_eq!(second_wire["pagination"]["limit"], 1); + assert_eq!(second_wire["pagination"]["offset"], 1); + assert_eq!( + second_wire["data"], + json!([{"timestamp":240,"price":0.55,"resolution_seconds":60}]) + ); + let final_wire = wire( + &e, + json!({"token_id":"eb:YES:e","cursor":second_wire["pagination"]["next_cursor"]}), + ) + .unwrap(); + assert_eq!( + final_wire["data"], + json!([{"timestamp":245,"price":0.55,"resolution_seconds":0}]) + ); + assert_eq!( + final_wire["pagination"], + json!({"limit":1,"offset":2,"has_more":false,"next_cursor":null}) + ); + let at_resolution = wire(&e, json!({"token_id":"eb:YES:e","asOf":273})).unwrap(); + assert_eq!( + at_resolution["data"], + json!([{"timestamp":273,"price":0.5,"resolution_seconds":0}]) + ); let mut seen = page["data"].as_array().unwrap().clone(); let mut cursor = page["pagination"]["next_cursor"].clone(); while !cursor.is_null() { diff --git a/docs/examples/clob-http.http b/docs/examples/clob-http.http index 657b1bd..1ef0636 100644 --- a/docs/examples/clob-http.http +++ b/docs/examples/clob-http.http @@ -9,3 +9,9 @@ Content-Type: application/json ### Unknown token GET http://127.0.0.1:9002/book?token_id=eb%3AYES%3Amissing + +### History for one outcome in the last hour +GET http://127.0.0.1:9002/v2/prices-history?token_id=eb%3AYES%3Ademo&interval=1h&bucket_seconds=60&limit=1 + +### Replace the cursor placeholder with pagination.next_cursor from the previous response +GET http://127.0.0.1:9002/v2/prices-history?token_id=eb%3AYES%3Ademo&cursor={{next_cursor}} diff --git a/docs/prediction-parity.md b/docs/prediction-parity.md index be0c9e5..1612148 100644 --- a/docs/prediction-parity.md +++ b/docs/prediction-parity.md @@ -327,3 +327,9 @@ order、market_sell 和卖出 estimate 可用 size_micros 输入数量,也可 本地批量上限 500 项、请求体上限 1 MiB。请求内按同一个读事务取数,同步常驻盘口一次。返回值保持请求顺序与重复项,略过未知标的,空数组返回空数组。生产端混合有效与未知标的、重复标的和已终结市场的行为仍待实测。[可重放 HTTP 请求](examples/clob-http.http) 官方接口文档将批量请求体错误列为 HTTP 400,示例错误值为 `Invalid payload`。另有一处盘口排序差异待现场判定:文档将买单描述为降序、卖单为升序,即最优价在前。当前实现沿用固定版 SDK 遍历盘口时使用的最优价在末尾的顺序。顺序会影响盘口哈希,现场验收须选择双侧均有多个价位的同一份快照,同时核对首尾价和哈希。[单盘接口](https://docs.polymarket.com/api-reference/market-data/get-order-book) · [批量接口](https://docs.polymarket.com/api-reference/market-data/get-order-books-request-body) + +## HTTP 价格历史与可重放分页 + +`GET /v2/prices-history` 接受 token_id 或 tokenId,支持绝对窗口、相对 interval 及 as_of / asOf。桶宽使用 bucket_seconds 或 bucketSeconds。响应公开 timestamp、price、resolution_seconds 以及 pagination。客户端可在重启后用同一资产继续翻页;即使新成交或裁决已经写入,后续页仍使用首页的序号上限。续页可重发相同窗口,页大小沿用首页。本地 limit=0 返回空页;这一边界仍待现场比对。 + +目前点来自 Eventbook 成交与模拟兑付。数据库保存本地历史,尚未复现生产分层行情的实际覆盖范围、过期细粒度查询或链上兑付确认时点。官方文档把可用粒度与具体时间窗绑定,单凭响应形状无法验证价格曲线一致。[V2 价格历史](https://docs.polymarket.com/api-reference/markets/get-a-tokens-price-history) · [请求样例](examples/clob-http.http)