Compare commits

..

4 Commits

14 changed files with 164 additions and 393 deletions
+11 -15
View File
@@ -90,6 +90,7 @@ sequenceDiagram
flowchart LR
main["main.rs"] --> http["market_http.rs"]
http --> api["exchange::Exchange::public_books"]
http --> clock["exchange::Exchange::server_time"]
```
```mermaid
@@ -97,12 +98,20 @@ sequenceDiagram
participant C as SDK
participant H as market_http
participant E as Exchange
opt 需要计算 GTD 截止时间
C->>H: GET /time
H->>E: server_time
E-->>H: Unix 秒
H-->>C: JSON 整数
end
C->>H: GET /book?token_id=... 或 POST /books
H->>E: 提交本次请求的资产 ID
E-->>H: 一个数据库快照中的盘口列表
H-->>C: 单盘 JSON 对象或批量 JSON 数组
```
`GET /time` 返回一个 JSON 整数,单位为 Unix 秒。客户端可用它估算本机与交易服务的时钟差,再填写 GTD 的 `expiration`。这是读取时钟的端点,无需账户或资产 ID。
同一个 HTTP 监听器提供 `GET /v2/prices-history`。客户端按资产查询历史,接续页可以只发同一资产和上一页的游标。[请求样例](../../docs/examples/clob-http.http)
```mermaid
@@ -183,6 +192,8 @@ sequenceDiagram
路径参数使用百分号编码。即使查询从 NO 开始,primary_token_id 仍对应 YES。可重放请求见[行情 HTTP 示例](../../docs/examples/clob-http.http)。
已裁决资产的公开盘口、买卖报价、中点和价差单查返回 404,批查跳过该资产。
### 查询盘口价差与中点
```mermaid
@@ -225,21 +236,6 @@ sequenceDiagram
H-->>C: history 数组,每点包含 t 和 p
```
### 批量读取 CLOB 历史曲线
`POST /batch-prices-history` 的请求体使用 markets、start_ts、end_ts、interval 和 fidelity。markets 中填结果资产 ID,去重后最多 20 个。绝对时间窗使用整数 Unix 秒。回执的 history 对象以资产 ID 为键,缺少观测的资产省略。
```mermaid
sequenceDiagram
participant C as 图表客户端
participant H as market_http.rs
participant E as prices_history/legacy.rs
C->>H: POST /batch-prices-history,选择多个结果资产
H->>E: 校验请求体后提交批量查询
E->>E: 从同一 SQLite 快照与时钟采样各条曲线
E-->>C: history 对象,每个资产一条非空曲线
```
### 发布后的裁决说明
```mermaid
+47 -33
View File
@@ -144,9 +144,9 @@ fn book_prices(engine: &Mutex<Exchange>, rows: Vec<WirePrice>, single: bool) ->
Ok(value)
}
fn json_body<T: serde::de::DeserializeOwned>(
fn batch_params<T: serde::de::DeserializeOwned>(
req: &mut Request,
) -> std::result::Result<T, (u16, &'static str)> {
) -> std::result::Result<Vec<T>, (u16, &'static str)> {
if req.body_length().is_some_and(|n| n as u64 > MAX_BODY) {
return Err((413, "Request body too large"));
}
@@ -387,25 +387,6 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
}
}
(&Method::Get, "/market-clarifications") => clarifications(engine, params),
(&Method::Post, "/batch-prices-history") => {
match json_body::<exchange::BatchClobHistoryQuery>(&mut req) {
Ok(query) => {
let result = engine
.lock()
.map_err(|_| HistoryError::Unavailable)
.and_then(|exchange| exchange.batch_clob_price_history(query));
match result {
Ok(history) => Ok(history),
Err(HistoryError::Invalid(message)) => {
return send(req, 400, json!({"error":message}), None)
}
Err(HistoryError::Unavailable) => Err((500, "Internal server error")),
}
}
Err((400, _)) => Err((400, "invalid request body")),
Err(error) => Err(error),
}
}
(&Method::Get, "/prices-history") => {
let result = serde_urlencoded::from_str::<exchange::ClobHistoryQuery>(params)
.map_err(|_| HistoryError::Invalid("invalid query parameters".into()))
@@ -423,11 +404,19 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
Err(HistoryError::Unavailable) => Err((500, "Internal server error")),
}
}
(&Method::Get, "/time") => engine
.lock()
.map_err(|_| (500, "Internal server error"))
.and_then(|db| {
db.server_time()
.map(|seconds| json!(seconds))
.map_err(|_| (500, "Internal server error"))
}),
(&Method::Get, "/price") => serde_urlencoded::from_str::<WirePrice>(params)
.map_err(|_| (400, "Invalid token id"))
.and_then(|p| book_prices(engine, vec![p], true)),
(&Method::Post, "/prices") => {
json_body::<Vec<WirePrice>>(&mut req).and_then(|rows| book_prices(engine, rows, false))
batch_params::<WirePrice>(&mut req).and_then(|rows| book_prices(engine, rows, false))
}
(&Method::Get, "/prices") => Err((400, "Invalid payload")),
(&Method::Get, "/spread" | "/midpoint") => {
@@ -446,7 +435,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
} else {
QuoteField::Midpoint
};
json_body::<Vec<BookParam>>(&mut req).and_then(|p| {
batch_params::<BookParam>(&mut req).and_then(|p| {
quote_response(
engine,
p.into_iter().map(|b| b.token_id).collect(),
@@ -460,14 +449,14 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
.map_err(|_| (400, "Invalid token id"))
.and_then(|p| query(engine, vec![p], true)),
(&Method::Post, "/books") => {
json_body::<Vec<BookParam>>(&mut req).and_then(|p| query(engine, p, false))
batch_params::<BookParam>(&mut req).and_then(|p| query(engine, p, false))
}
(&Method::Get, "/last-trade-price") => serde_urlencoded::from_str::<BookParam>(params)
.map_err(|_| (400, "Invalid token id"))
.and_then(|p| last_prices(engine, vec![p.token_id], true)),
(&Method::Get, "/last-trades-prices") => Err((400, "Invalid payload")),
(&Method::Post, "/last-trades-prices") => {
json_body::<Vec<BookParam>>(&mut req).and_then(|p| {
batch_params::<BookParam>(&mut req).and_then(|p| {
last_prices(
engine,
p.into_iter().map(|item| item.token_id).collect(),
@@ -485,6 +474,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
| "/midpoint"
| "/spread"
| "/book"
| "/time"
| "/last-trade-price"
| "/prices-history"
| "/markets"
@@ -499,7 +489,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
allow = Some("GET");
Err((405, "Method not allowed"))
}
(_, "/books" | "/spreads" | "/batch-prices-history") => {
(_, "/books" | "/spreads") => {
allow = Some("POST");
Err((405, "Method not allowed"))
}
@@ -600,7 +590,11 @@ pub(crate) fn serve(engine: Exchange, listener: TcpListener) -> Result<()> {
#[cfg(test)]
mod tests {
use super::*;
use std::{io::Write, net::TcpStream, time::Duration};
use std::{
io::Write,
net::TcpStream,
time::{Duration, SystemTime, UNIX_EPOCH},
};
#[test]
fn socket_serves_single_and_batch_books_and_rejects_invalid_requests() {
@@ -636,6 +630,9 @@ mod tests {
let lookup_info = json!({"mbf":0,"tbf":30,"fd":{"r":0.05,"e":1,"to":true},"gst":null,"nr":false,"rfqe":false,"ibce":false,"oas":0,"mos":0.01,"mts":0.0025,
"t":[{"o":"YES","t":"eb:YES:map+2/1"},{"o":"NO","t":"eb:NO:map+2/1"}]});
for command in [
json!({"op":"list","id":"resolved-list","market":"resolved-test","rules":"resolved fixture"}),
json!({"op":"close","id":"resolved-close","market":"resolved-test"}),
json!({"op":"finalize","id":"resolved-final","market":"resolved-test","winner":"YES"}),
json!({"op":"fund","id":"v-fund","account":"unpriced-owner","cents":100}),
json!({"op":"list","id":"v-list","market":"unpriced","rules":"valuation fixture"}),
json!({"op":"split","id":"v-split","account":"unpriced-owner","market":"unpriced","qty":1}),
@@ -760,12 +757,6 @@ mod tests {
("GET","/prices-history?market=eb:YES:s&interval=1w&fidelity=4",String::new(),400,Some(json!({"error":"invalid filters: minimum 'fidelity' for '1w' range is 5"}))),
("GET","/prices-history?market=eb:YES:s&startTs=100&endTs=1296101",String::new(),400,Some(json!({"error":"invalid filters: 'startTs' and 'endTs' interval is too long"}))),
("POST","/prices-history","{}".into(),405,None),
("POST","/batch-prices-history",json!({"markets":["eb:YES:missing","123"],"start_ts":100,"end_ts":200}).to_string(),200,Some(json!({"history":{}}))),
("POST","/batch-prices-history",json!({"markets":vec!["123";21],"interval":"1h"}).to_string(),200,Some(json!({"history":{}}))),
("POST","/batch-prices-history",json!({"markets":(0..21).map(|i|i.to_string()).collect::<Vec<_>>(),"interval":"1h"}).to_string(),400,Some(json!({"error":"invalid filters: 'markets' exceeds maximum of 20"}))),
("POST","/batch-prices-history",json!({"markets":[],"interval":"1h"}).to_string(),400,Some(json!({"error":"invalid filters: 'markets' is mandatory and must not be empty"}))),
("POST","/batch-prices-history",json!({"markets":["123"],"start_ts":1.5,"end_ts":200}).to_string(),400,Some(json!({"error":"invalid request body"}))),
("GET","/batch-prices-history",String::new(),405,None),
("GET","/price?token_id=eb:YES:mid-example&side=BUY",String::new(),200,Some(json!({"price":"0.08"}))),
("GET","/price?token_id=eb:YES:mid-example&side=SELL",String::new(),200,Some(json!({"price":"0.09"}))),
("GET","/price?token_id=eb:YES:one&side=SELL",String::new(),200,Some(json!({"price":"1"}))),
@@ -780,6 +771,14 @@ mod tests {
("POST","/prices",json!([{"token_id":"eb:YES:s"}]).to_string(),200,Some(json!({"eb:YES:s":{"SELL":"0.41"}}))),
("POST","/prices",json!(vec![json!({"token_id":"eb:YES:s","side":"BUY"}); MAX_BOOKS+1]).to_string(),400,None),
("DELETE","/prices",String::new(),405,None),
("GET","/book?token_id=eb:YES:resolved-test",String::new(),404,Some(json!({"error":MISSING}))),
("GET","/price?token_id=eb:YES:resolved-test&side=BUY",String::new(),404,Some(json!({"error":MISSING}))),
("GET","/midpoint?token_id=eb:NO:resolved-test",String::new(),404,Some(json!({"error":MISSING}))),
("GET","/spread?token_id=eb:NO:resolved-test",String::new(),404,Some(json!({"error":MISSING}))),
("POST","/books",json!([{"token_id":"eb:YES:resolved-test"},{"token_id":yes}]).to_string(),200,Some(json!([expected_yes.clone()]))),
("POST","/prices",json!([{"token_id":"eb:YES:resolved-test","side":"BUY"},{"token_id":"eb:YES:s","side":"BUY"}]).to_string(),200,Some(json!({"eb:YES:s":{"BUY":"0.39"}}))),
("POST","/midpoints",json!([{"token_id":"eb:YES:resolved-test"},{"token_id":"eb:YES:s"}]).to_string(),200,Some(json!({"eb:YES:s":"0.4"}))),
("POST","/spreads",json!([{"token_id":"eb:YES:resolved-test"}]).to_string(),200,Some(json!({}))),
("GET","/midpoint?token_id=eb:YES:mid-example",String::new(),200,Some(json!({"mid":"0.085"}))),
("POST","/midpoints",json!([{"token_id":"eb:YES:mid-example"},{"token_id":"eb:NO:mid-example"}]).to_string(),200,Some(sample)),
("GET","/midpoint?token_id=eb:YES:s",String::new(),200,Some(json!({"mid":"0.4"}))),
@@ -877,6 +876,8 @@ mod tests {
("POST","/v2/prices-history",String::new(),405,None),
("GET", "/books", String::new(), 405, None),
("POST", "/order", "{}".into(), 404, None),
("GET", "/time", String::new(), 200, None),
("POST", "/time", String::new(), 405, None),
];
let count = cases.len();
let worker = thread::spawn(move || {
@@ -890,6 +891,10 @@ mod tests {
}
});
for (method, path, body, status, expected) in cases {
let before = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let mut socket = TcpStream::connect(port).unwrap();
socket
.set_read_timeout(Some(Duration::from_secs(5)))
@@ -911,6 +916,15 @@ mod tests {
let actual: Value = serde_json::from_str(body).unwrap();
if let Some(expected) = expected {
assert_eq!(actual, expected);
} else if path == "/time" && status == 200 {
let after = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
assert!((before..=after).contains(&actual.as_u64().unwrap()));
} else if path == "/time" {
assert!(headers.to_ascii_lowercase().contains("allow: get"));
assert!(actual["error"].is_string());
} else if status == 200 {
assert_eq!(actual.as_array().unwrap().len(), MAX_BOOKS);
} else {
+10 -4
View File
@@ -34,6 +34,8 @@ flowchart LR
expiry -->|清理到期注册| beat
beat -->|释放订单尚未成交的预留| book
api -->|启动和请求时检查到期时间| expiry["src/expiry.rs"]
api -->|读取服务端 Unix 秒| expiry
book -->|使用同一时钟校验 GTD| expiry
expiry -->|释放订单剩余预留| book["src/book.rs"]
api -->|初始化数据库| schema["src/schema.sql"]
api -->|校验请求键| valid["src/validation.rs"]
@@ -231,6 +233,12 @@ sequenceDiagram
participant E as Exchange
participant D as SQLite
participant B as 常驻盘口
opt HTTP 客户端校时
C->>E: server_time
E->>D: 读取与 GTD 共用的 Unix 秒
D-->>E: 服务器时间
E-->>C: Unix 秒整数
end
C->>E: 提交 GTD,含 Unix 秒时间戳
E->>D: 校验申报时间并原子记录委托与期限
C->>E: 到达有效截止点后查询或提交新单
@@ -243,7 +251,7 @@ sequenceDiagram
E-->>C: 返回查询结果或新单回执
```
没有请求时,模拟 CLI 会等待输入。下一次查询、交易或进程重启会先结清已到期的余单。成交、手动撤单和停盘会同步移除相应的待到期项。
模拟 CLI 在等待输入时会按最近的截止点唤醒。盘口查询、交易或进程重启也会先结清已到期余单。单纯读时钟不会触发清理。成交、手动撤单和停盘会同步移除相应的待到期项。
## 用结果资产 ID 下单
@@ -1107,7 +1115,7 @@ sequenceDiagram
E->>D: 先处理到期订单,再从同一快照读取各市场最新 quote_events
D-->>E: 返回 YES 的买一和卖一
E->>E: 换算结果方向,缺买盘取 0、缺卖盘取 1,计算价差或中点
E-->>C: 按结果资产索引,未上市资产无条目
E-->>C: 按结果资产索引,跳过未上市和已裁决资产
```
HTTP 盘口查询由 public_book_prices 读取 quote_events,先清理到期任务,再在同一快照中读取各市场。BUY 取买一,SELL 取卖一。下单面板的 JSONL 命令继续查询最优对手价。
@@ -1150,8 +1158,6 @@ sequenceDiagram
E-->>C: t 为 Unix 秒,p 为十进制数
```
单资产与批量 CLOB 查询都通过 `prices_history/legacy.rs` 选择时间窗,复用 `legacy.sql`。同一批次只取一次数据库时钟,所有资产在同一个读事务内采样。封盘曲线沿用单查的截止时间,空曲线从批量响应中省略。
### 裁决规则的补充公告
```mermaid
+2 -2
View File
@@ -1,6 +1,6 @@
use crate::{command::TimeInForce, resident::Books};
use crate::{
ledger,
expiry, ledger,
validation::{amount, identifier, phase},
};
use anyhow::{ensure, Result};
@@ -109,7 +109,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
TimeInForce::Gtd => {
let expiration =
expiration.ok_or_else(|| anyhow::anyhow!("GTD requires expiration"))?;
let now: i64 = tx.query_row("SELECT unixepoch()", [], |r| r.get(0))?;
let now = expiry::unix_seconds(tx)?;
ensure!(
expiration >= now + 180,
"GTD expiration must be at least 180 seconds ahead"
+6 -4
View File
@@ -45,7 +45,7 @@ impl Snapshot {
fn build(tx: &Transaction, books: &Books, token: &str) -> Result<Snapshot> {
let (outcome, market) = assets::parse_id(token)?;
find(tx, books, token, outcome, market)?
find(tx, books, token, outcome, market, false)?
.context("No orderbook exists for the requested token id")
}
@@ -55,12 +55,14 @@ fn find(
token: &str,
outcome: &str,
market: &str,
public_only: bool,
) -> Result<Option<Snapshot>> {
let row: Option<(i64, bool)> = tx
.query_row(
"SELECT at_ms,EXISTS(SELECT 1 FROM neg_risk_members WHERE market=?1)
FROM book_snapshot_times WHERE market=?1",
[market],
FROM book_snapshot_times b JOIN markets m ON m.id=b.market
WHERE b.market=?1 AND (NOT ?2 OR m.phase<>'resolved')",
rusqlite::params![market, public_only],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
@@ -114,7 +116,7 @@ pub(crate) fn read_many(
let mut result = Vec::with_capacity(tokens.len());
for token in tokens {
if let Ok((outcome, market)) = assets::parse_id(token) {
if let Some(book) = find(tx, books, token, outcome, market)? {
if let Some(book) = find(tx, books, token, outcome, market, true)? {
result.push(serde_json::to_value(book)?);
}
}
+4
View File
@@ -2,6 +2,10 @@ use crate::book::{release, CancelReason};
use anyhow::Result;
use rusqlite::{Connection, Transaction, TransactionBehavior};
pub(crate) fn unix_seconds(db: &Connection) -> rusqlite::Result<i64> {
db.query_row("SELECT unixepoch()", [], |row| row.get(0))
}
/// Return a snapshot whose live book was current when the snapshot was acquired.
/// Expirations commit separately so a rejected command cannot revive an order.
pub(crate) fn transaction(
+6 -1
View File
@@ -55,7 +55,7 @@ pub use gamma_list::DirectoryResource;
pub use open_interest::InterestQuery;
pub use portfolio::http::ValueQuery;
pub use prices_history::http::HistoryQuery;
pub use prices_history::legacy::{BatchClobHistoryQuery, ClobHistoryQuery};
pub use prices_history::legacy::ClobHistoryQuery;
pub use public_trades::http::TradeQuery;
pub use quotes::{PriceQueryError, PriceRequest, PriceSide};
pub use resolution::http::ResolutionQuery;
@@ -168,6 +168,11 @@ impl Exchange {
Ok(())
}
/// Unix seconds on the same database clock used to validate GTD orders.
pub fn server_time(&self) -> Result<i64, MarketDataError> {
Ok(expiry::unix_seconds(&self.db)?)
}
/// Time until the next pending GTD stops trading, measured on the database clock.
pub fn next_gtd_expiry(&self) -> Result<Option<Duration>> {
let (first, now): (Option<i64>, i64) = self.db.query_row(
+48 -170
View File
@@ -1,8 +1,7 @@
use crate::{assets, inventory, Exchange, HistoryError};
use rusqlite::{params, Connection, Statement, TransactionBehavior};
use rusqlite::params;
use serde::Deserialize;
use serde_json::{json, Map, Value};
use std::collections::BTreeSet;
use serde_json::{json, Value};
#[derive(Deserialize)]
pub struct ClobHistoryQuery {
@@ -15,61 +14,36 @@ pub struct ClobHistoryQuery {
fidelity: Option<i64>,
}
#[derive(Deserialize)]
pub struct BatchClobHistoryQuery {
markets: Option<Vec<String>>,
start_ts: Option<i64>,
end_ts: Option<i64>,
interval: Option<String>,
fidelity: Option<i64>,
}
struct Window {
start: i64,
end: i64,
width: i64,
}
fn invalid(reason: &str) -> HistoryError {
HistoryError::Invalid(format!("invalid filters: {reason}"))
}
fn validate_absolute(reversed: bool, too_long: bool) -> Result<(), HistoryError> {
if reversed {
return Err(invalid(
"invalid time component, 'startTs' can't be older than 'endTs'",
));
}
if too_long {
return Err(invalid("'startTs' and 'endTs' interval is too long"));
}
Ok(())
}
impl Window {
fn new(
start: Option<i64>,
end: Option<i64>,
interval: Option<&str>,
fidelity: Option<i64>,
now: i64,
) -> Result<Self, HistoryError> {
let minutes = fidelity.unwrap_or(1).max(1);
impl ClobHistoryQuery {
fn window(&self, now: i64) -> Result<(i64, i64, i64), HistoryError> {
let invalid = |reason: &str| HistoryError::Invalid(format!("invalid filters: {reason}"));
for n in [self.start, self.end].into_iter().flatten() {
if !n.is_finite() || !(0.0..=f64::from(u32::MAX)).contains(&n) {
return Err(invalid("invalid timestamp"));
}
}
let start = self.start.unwrap_or(0.0);
let end = self.end.unwrap_or(0.0);
if end > 0.0 {
if start > end {
return Err(invalid(
"invalid time component, 'startTs' can't be older than 'endTs'",
));
}
if end - start > (15 * super::DAY) as f64 {
return Err(invalid("'startTs' and 'endTs' interval is too long"));
}
}
let minutes = self.fidelity.unwrap_or(1).max(1);
let width = minutes.min(i64::from(u32::MAX)) * 60_000;
if let Some(interval) = interval {
if let Some(interval) = self.interval.as_deref() {
let (span, minimum) = match interval {
"1h" => (3600, 1),
"6h" => (21600, 1),
"1d" => (super::DAY, 1),
"1w" => (7 * super::DAY, 5),
"1m" => (30 * super::DAY, 10),
"max" | "all" => {
return Ok(Self {
start: 0,
end: now,
width,
})
}
"max" | "all" => return Ok((0, now, width)),
_ => return Err(invalid(
"the 'interval' value is unknown. Known values: '1m', '1w', '1d', '6h', '1h'",
)),
@@ -79,82 +53,22 @@ impl Window {
"minimum 'fidelity' for '{interval}' range is {minimum}"
)));
}
return Ok(Self {
start: (now - span * 1000).max(0),
end: now,
width,
});
return Ok(((now - span * 1000).max(0), now, width));
}
if start.is_none() && end.is_none() {
if start == 0.0 && end == 0.0 {
return Err(invalid(
"the time component is mandatory, please use 'startTs' and 'endTs' or 'interval'",
));
}
Ok(Self {
start: start.unwrap_or(0),
end: end.unwrap_or(now),
width,
})
}
fn read(
&self,
stmt: &mut Statement<'_>,
market: &str,
outcome: &str,
now: i64,
) -> rusqlite::Result<Vec<Value>> {
stmt.query_map(
params![market, outcome, self.start, self.end, self.width, now],
|r| {
let timestamp: i64 = r.get(0)?;
let micros: i64 = r.get(1)?;
Ok(json!({"t":timestamp,"p":inventory::decimal(micros.into(), inventory::UNIT)}))
Ok((
boundary_ms(start, f64::ceil),
if end == 0.0 {
now
} else {
boundary_ms(end, f64::floor)
},
)?
.collect()
}
}
impl ClobHistoryQuery {
fn window(&self, now: i64) -> Result<Window, HistoryError> {
for n in [self.start, self.end].into_iter().flatten() {
if !n.is_finite() || !(0.0..=f64::from(u32::MAX)).contains(&n) {
return Err(invalid("invalid timestamp"));
}
}
let start = self.start.unwrap_or(0.0);
let end = self.end.unwrap_or(0.0);
if end > 0.0 {
validate_absolute(start > end, end - start > (15 * super::DAY) as f64)?;
}
Window::new(
(start != 0.0).then(|| boundary_ms(start, f64::ceil)),
(end != 0.0).then(|| boundary_ms(end, f64::floor)),
self.interval.as_deref(),
self.fidelity,
now,
)
}
}
impl BatchClobHistoryQuery {
fn window(&self, now: i64) -> Result<Window, HistoryError> {
let start = self.start_ts.unwrap_or(0);
let end = self.end_ts.unwrap_or(0);
if end > 0 {
validate_absolute(
start > end,
i128::from(end) - i128::from(start) > i128::from(15 * super::DAY),
)?;
}
Window::new(
(start != 0).then(|| start.saturating_mul(1000)),
(end != 0).then(|| end.saturating_mul(1000)),
self.interval.as_deref(),
self.fidelity,
now,
)
width,
))
}
}
@@ -170,64 +84,28 @@ fn boundary_ms(seconds: f64, round: fn(f64) -> f64) -> i64 {
}
}
fn snapshot_time(db: &Connection) -> rusqlite::Result<i64> {
db.query_row(
"SELECT CAST(unixepoch('subsec') * 1000 AS INTEGER)",
[],
|r| r.get(0),
)
}
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 tx = crate::expiry::transaction(&self.db, TransactionBehavior::Deferred)
let tx = crate::expiry::transaction(&self.db, rusqlite::TransactionBehavior::Deferred)
.map_err(|_| HistoryError::Unavailable)?;
let now = snapshot_time(&tx)?;
let window = query.window(now)?;
let now: i64 = tx.query_row(
"SELECT CAST(unixepoch('subsec') * 1000 AS INTEGER)",
[],
|r| r.get(0),
)?;
let (start, end, width) = query.window(now)?;
let points = {
let mut stmt = tx.prepare_cached(include_str!("legacy.sql"))?;
window.read(&mut stmt, market, outcome, now)?
let rows = stmt.query_map(params![market, outcome, start, end, width, now], |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}))
}
pub fn batch_clob_price_history(
&self,
query: BatchClobHistoryQuery,
) -> Result<Value, HistoryError> {
let tokens: BTreeSet<_> = query
.markets
.iter()
.flatten()
.filter(|token| !token.is_empty())
.collect();
if tokens.is_empty() {
return Err(invalid("'markets' is mandatory and must not be empty"));
}
if tokens.len() > 20 {
return Err(invalid("'markets' exceeds maximum of 20"));
}
let tx = crate::expiry::transaction(&self.db, TransactionBehavior::Deferred)
.map_err(|_| HistoryError::Unavailable)?;
let now = snapshot_time(&tx)?;
let window = query.window(now)?;
let mut history = Map::new();
{
let mut stmt = tx.prepare_cached(include_str!("legacy.sql"))?;
for token in tokens {
let Ok((outcome, market)) = assets::parse_id(token) else {
continue;
};
let points = window.read(&mut stmt, market, outcome, now)?;
if !points.is_empty() {
history.insert(token.to_string(), Value::Array(points));
}
}
}
tx.commit()?;
Ok(json!({"history":history}))
}
}
+10 -6
View File
@@ -200,7 +200,7 @@ impl PriceRequest {
// 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>>> {
quote_rows(db, requests)?
quote_rows(db, requests, false)?
.into_iter()
.zip(requests)
.map(|(quote, request)| {
@@ -220,7 +220,11 @@ fn price_rows(db: &Connection, requests: &[PriceRequest]) -> Result<Vec<Option<S
.collect()
}
fn quote_rows(db: &Connection, requests: &[PriceRequest]) -> Result<Vec<Option<Quote>>> {
fn quote_rows(
db: &Connection,
requests: &[PriceRequest],
public_only: bool,
) -> Result<Vec<Option<Quote>>> {
if !(1..=500).contains(&requests.len()) {
return Err(PriceQueryError::RequestCount.into());
}
@@ -234,11 +238,11 @@ fn quote_rows(db: &Connection, requests: &[PriceRequest]) -> Result<Vec<Option<Q
}
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
FROM json_each(?1) j LEFT JOIN markets m ON m.id=j.value AND (NOT ?2 OR m.phase<>'resolved')
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 rows = stmt.query(params![serde_json::to_string(&markets)?, public_only])?;
let mut quotes = Vec::with_capacity(requests.len());
while let Some(row) = rows.next()? {
let index: usize = row.get(5)?;
@@ -284,7 +288,7 @@ impl crate::Exchange {
pub fn public_book_prices(&self, requests: &[PriceRequest]) -> Result<Value> {
let tx = crate::expiry::transaction(&self.db, rusqlite::TransactionBehavior::Deferred)?;
let mut result = json!({});
for (request, quote) in requests.iter().zip(quote_rows(&tx, requests)?) {
for (request, quote) in requests.iter().zip(quote_rows(&tx, requests, true)?) {
if let Some(quote) = quote {
let (bid, ask) = quote.public_sides();
let ticks = match request.side {
@@ -333,7 +337,7 @@ impl crate::Exchange {
.map_err(|_| crate::MarketDataError::Unavailable)?;
let mut stmt = tx.prepare_cached(
"SELECT COALESCE(q.seq,0),q.yes_bid,q.yes_ask,q.at_ms,j.key FROM json_each(?1) j
JOIN markets m ON m.id=json_extract(j.value,'$[1]')
JOIN markets m ON m.id=json_extract(j.value,'$[1]') AND m.phase<>'resolved'
LEFT JOIN quote_events q ON q.seq=(SELECT MAX(seq) FROM quote_events WHERE market=m.id)"
)?;
let mut rows = stmt.query([input])?;
+1 -23
View File
@@ -683,9 +683,7 @@ fn gtd_expiry_survives_rejection_and_recovery() {
e.execute(json!({"op":"open","id":"start","market":"e"}))
.unwrap();
let db = rusqlite::Connection::open(&path).unwrap();
let now: i64 = db
.query_row("SELECT unixepoch()", [], |r| r.get(0))
.unwrap();
let now = e.server_time().unwrap();
assert_eq!(e.next_gtd_expiry().unwrap(), None);
let mut ask = order("dated", "alice", "sell", 60, 5);
ask["tif"] = json!("GTD");
@@ -1550,19 +1548,6 @@ fn legacy_history_samples_the_book_without_fills_and_appends_the_latest_mark() {
);
assert_eq!(points[3]["p"], 0.085);
assert!(points[3]["t"].as_i64().unwrap() > 240);
let batch = |e: &Exchange, start, end| {
e.batch_clob_price_history(serde_json::from_value(json!({
"markets":["eb:YES:mid-example","eb:NO:mid-example","123","eb:YES:missing","eb:YES:mid-example"],
"start_ts":start, "end_ts":end, "fidelity":1
})).unwrap()).unwrap()
};
let open = batch(&exchange, 120, 240);
let yes = open["history"]["eb:YES:mid-example"].as_array().unwrap();
let no = open["history"]["eb:NO:mid-example"].as_array().unwrap();
assert_eq!(&yes[..3], &points[..3]);
assert_eq!(yes[3]["t"], no[3]["t"]);
assert_eq!(no[3]["p"], 0.915);
assert_eq!(open["history"].as_object().unwrap().len(), 2);
exchange
.execute(json!({"op":"close","id":"close","market":"mid-example"}))
.unwrap();
@@ -1583,13 +1568,6 @@ fn legacy_history_samples_the_book_without_fills_and_appends_the_latest_mark() {
assert_eq!(read(&reopened, "NO", 180.001, 400.0), before_close);
assert!(read(&reopened, "YES", 273.0, 400.0).is_empty());
assert!(read(&reopened, "YES", 5.0, 5.0).is_empty());
assert_eq!(batch(&reopened, 273, 400), json!({"history":{}}));
let closed = batch(&reopened, 181, 400);
assert_eq!(closed["history"]["eb:NO:mid-example"], json!(before_close));
assert_eq!(
closed["history"]["eb:YES:mid-example"],
json!([{"t":240,"p":0.085}])
);
}
#[test]
+3
View File
@@ -90,3 +90,6 @@ GET http://127.0.0.1:9002/clob-markets/cup
### Load neg-risk.jsonl to query either token of a member of the election group.
GET http://127.0.0.1:9002/neg-risk?token_id=eb%3ANO%3Aa
### Exchange clock in Unix seconds, used to calculate GTD expiration.
GET http://127.0.0.1:9002/time
@@ -1,130 +0,0 @@
{
"mixed_window": {
"method": "POST",
"url": "https://clob.polymarket.com/batch-prices-history",
"request": {
"markets": [
"35090254409399344650860070211816464534198960801264823587796928404808383727584",
"715035038973852440637533813088906197843594055254726475255007478722039119872",
"35090254409399344650860070211816464534198960801264823587796928404808383727584",
"123"
],
"start_ts": 1796285515,
"end_ts": 1796285695
},
"date": "Sat, 05 Dec 2026 09:33:26 GMT",
"status": 200,
"body": {
"history": {
"35090254409399344650860070211816464534198960801264823587796928404808383727584": [
{
"t": 1796285540,
"p": 0.0375
},
{
"t": 1796285600,
"p": 0.0375
},
{
"t": 1796285654,
"p": 0.0375
},
{
"t": 1796463190,
"p": 0.0125
}
],
"715035038973852440637533813088906197843594055254726475255007478722039119872": [
{
"t": 1796285539,
"p": 0.5
},
{
"t": 1796285599,
"p": 0.5
},
{
"t": 1796285653,
"p": 0.5
}
]
}
}
},
"before_listing": {
"method": "POST",
"url": "https://clob.polymarket.com/batch-prices-history",
"request": {
"markets": [
"35090254409399344650860070211816464534198960801264823587796928404808383727584",
"715035038973852440637533813088906197843594055254726475255007478722039119872",
"123"
],
"start_ts": 100,
"end_ts": 250
},
"date": "Sat, 05 Dec 2026 09:33:26 GMT",
"status": 200,
"body": {
"history": {
"35090254409399344650860070211816464534198960801264823587796928404808383727584": [
{
"t": 1796463190,
"p": 0.0125
}
]
}
}
},
"distinct_over_limit": {
"method": "POST",
"url": "https://clob.polymarket.com/batch-prices-history",
"request": {
"markets": [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20"
],
"interval": "1h"
},
"date": "Sat, 05 Dec 2026 09:33:26 GMT",
"status": 400,
"body": {
"error": "invalid filters: 'markets' exceeds maximum of 20"
}
},
"fractional_time": {
"method": "POST",
"url": "https://clob.polymarket.com/batch-prices-history",
"request": {
"markets": [
"35090254409399344650860070211816464534198960801264823587796928404808383727584"
],
"start_ts": 1796285515.5,
"end_ts": 1796285695
},
"date": "Sat, 05 Dec 2026 09:33:26 GMT",
"status": 400,
"body": {
"error": "invalid request body"
}
}
}
+10
View File
@@ -0,0 +1,10 @@
{"markets":[
{"catalog":{"id":"7554899","slug":"cs2-bb3-lgc-2026-12-03-game1-round-total-30pt5","version":"v1","conditionId":"0xdf04a0495b0a16dbce386acdc16d9aed19784db9888be53d150354b83b7c18b1","closed":true,"closedTime":"2026-12-03 08:32:03.519799+00","acceptingOrders":false,"umaResolutionStatus":"resolved","outcomePrices":"[\"0\", \"1\"]","outcomes":"[\"Over\", \"Under\"]","positionIds":null,"clobTokenIds":"[\"73979342585906843441145134109923710004884703083095161594360108477170435492453\", \"78188826358032258311424545486331333398838521699262460256542567713692269401385\"]"},"book_responses":[{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:31 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:31 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/book?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:31 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=78188826358032258311424545486331333398838521699262460256542567713692269401385","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:32 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=78188826358032258311424545486331333398838521699262460256542567713692269401385","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:32 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/book?token_id=78188826358032258311424545486331333398838521699262460256542567713692269401385","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:32 GMT","body":{"error":"No orderbook exists for the requested token id"}}],"quotes":[{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:36:26 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:36:26 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/price?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453&side=BUY","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:36:26 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","side":"BUY"},{"token_id":"78188826358032258311424545486331333398838521699262460256542567713692269401385","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:26 GMT","body":[]},{"method":"POST","url":"https://clob.polymarket.com/midpoints","payload":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","side":"BUY"},{"token_id":"78188826358032258311424545486331333398838521699262460256542567713692269401385","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:26 GMT","body":{}},{"method":"POST","url":"https://clob.polymarket.com/spreads","payload":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","side":"BUY"},{"token_id":"78188826358032258311424545486331333398838521699262460256542567713692269401385","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:26 GMT","body":{}},{"method":"POST","url":"https://clob.polymarket.com/prices","payload":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","side":"BUY"},{"token_id":"78188826358032258311424545486331333398838521699262460256542567713692269401385","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:26 GMT","body":{}}]},
{"catalog":{"id":"7543472","slug":"setkameua-anat-illia-2026-12-03","version":"v2","conditionId":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","closed":true,"closedTime":"2026-12-03 08:31:00.370625+00","acceptingOrders":false,"umaResolutionStatus":null,"outcomePrices":"[\"1\", \"0\"]","outcomes":"[\"Nikolenko Anatolii\", \"Fokin Illia\"]","positionIds":["759916398134244316868652908232832573045153963965173623897622651599218278400","759916398134244316868652908232832573045153963965173623897622651599218278401"],"clobTokenIds":"[\"759916398134244316868652908232832573045153963965173623897622651599218278400\", \"759916398134244316868652908232832573045153963965173623897622651599218278401\"]"},"book_responses":[{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:32 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400","payload":null,"status":200,"date":"Thu, 03 Dec 2026 08:37:32 GMT","body":{"spread":"1"}},{"method":"GET","url":"https://clob.polymarket.com/book?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:32 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=759916398134244316868652908232832573045153963965173623897622651599218278401","payload":null,"status":200,"date":"Thu, 03 Dec 2026 08:37:32 GMT","body":{"mid":"0.5"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=759916398134244316868652908232832573045153963965173623897622651599218278401","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:33 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/book?token_id=759916398134244316868652908232832573045153963965173623897622651599218278401","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:32 GMT","body":{"error":"No orderbook exists for the requested token id"}}],"quotes":[{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:36:27 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400","payload":null,"status":200,"date":"Thu, 03 Dec 2026 08:36:27 GMT","body":{"spread":"1"}},{"method":"GET","url":"https://clob.polymarket.com/price?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400&side=BUY","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:36:27 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","side":"BUY"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:27 GMT","body":[]},{"method":"POST","url":"https://clob.polymarket.com/midpoints","payload":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","side":"BUY"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:27 GMT","body":{"759916398134244316868652908232832573045153963965173623897622651599218278401":"0.5"}},{"method":"POST","url":"https://clob.polymarket.com/spreads","payload":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","side":"BUY"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:27 GMT","body":{"759916398134244316868652908232832573045153963965173623897622651599218278400":"1"}},{"method":"POST","url":"https://clob.polymarket.com/prices","payload":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","side":"BUY"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:28 GMT","body":{}}]},
{"catalog":{"id":"7528433","slug":"sol-updown-15m-1796285700","version":"v2","conditionId":"0x0190f69570a8ebb0d5608f8f773ffc068b000000000000000000000000000000","closed":true,"closedTime":"2026-12-03 08:30:28.231292+00","acceptingOrders":false,"umaResolutionStatus":null,"outcomePrices":"[\"1\", \"0\"]","outcomes":"[\"Up\", \"Down\"]","positionIds":["708440684409184214698552699176045036593002385654320616860038876849074339840","708440684409184214698552699176045036593002385654320616860038876849074339841"],"clobTokenIds":"[\"708440684409184214698552699176045036593002385654320616860038876849074339840\", \"708440684409184214698552699176045036593002385654320616860038876849074339841\"]"},"book_responses":[{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=708440684409184214698552699176045036593002385654320616860038876849074339840","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:35 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=708440684409184214698552699176045036593002385654320616860038876849074339840","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:33 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/book?token_id=708440684409184214698552699176045036593002385654320616860038876849074339840","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:33 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=708440684409184214698552699176045036593002385654320616860038876849074339841","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:34 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=708440684409184214698552699176045036593002385654320616860038876849074339841","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:33 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/book?token_id=708440684409184214698552699176045036593002385654320616860038876849074339841","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:37:34 GMT","body":{"error":"No orderbook exists for the requested token id"}}],"quotes":[{"method":"GET","url":"https://clob.polymarket.com/midpoint?token_id=708440684409184214698552699176045036593002385654320616860038876849074339840","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:36:28 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/spread?token_id=708440684409184214698552699176045036593002385654320616860038876849074339840","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:36:28 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"GET","url":"https://clob.polymarket.com/price?token_id=708440684409184214698552699176045036593002385654320616860038876849074339840&side=BUY","payload":null,"status":404,"date":"Thu, 03 Dec 2026 08:36:28 GMT","body":{"error":"No orderbook exists for the requested token id"}},{"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"708440684409184214698552699176045036593002385654320616860038876849074339840","side":"BUY"},{"token_id":"708440684409184214698552699176045036593002385654320616860038876849074339841","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:28 GMT","body":[]},{"method":"POST","url":"https://clob.polymarket.com/midpoints","payload":[{"token_id":"708440684409184214698552699176045036593002385654320616860038876849074339840","side":"BUY"},{"token_id":"708440684409184214698552699176045036593002385654320616860038876849074339841","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:28 GMT","body":{}},{"method":"POST","url":"https://clob.polymarket.com/spreads","payload":[{"token_id":"708440684409184214698552699176045036593002385654320616860038876849074339840","side":"BUY"},{"token_id":"708440684409184214698552699176045036593002385654320616860038876849074339841","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:29 GMT","body":{}},{"method":"POST","url":"https://clob.polymarket.com/prices","payload":[{"token_id":"708440684409184214698552699176045036593002385654320616860038876849074339840","side":"BUY"},{"token_id":"708440684409184214698552699176045036593002385654320616860038876849074339841","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:29 GMT","body":{}}]}
],"mixed_batch":[
{"method":"POST","url":"https://clob.polymarket.com/books","payload":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","side":"BUY"},{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:29 GMT","body":[{"market":"0xa5f8a44504de30fa36fff2406b2b27b3d15476ed50448e4fc3ead4861d8a5e3e","asset_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","hash":"a4e1311a77002cac23f8be77c8e355df22551c4f"}]},
{"method":"POST","url":"https://clob.polymarket.com/midpoints","payload":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","side":"BUY"},{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:29 GMT","body":{"35090254409399344650860070211816464534198960801264823587796928404808383727584":"0.0375"}},
{"method":"POST","url":"https://clob.polymarket.com/spreads","payload":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","side":"BUY"},{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:29 GMT","body":{"35090254409399344650860070211816464534198960801264823587796928404808383727584":"0.001"}},
{"method":"POST","url":"https://clob.polymarket.com/prices","payload":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","side":"BUY"},{"token_id":"35090254409399344650860070211816464534198960801264823587796928404808383727584","side":"BUY"}],"status":200,"date":"Thu, 03 Dec 2026 08:36:29 GMT","body":{"35090254409399344650860070211816464534198960801264823587796928404808383727584":{"BUY":"0.037"}}}
]}
+6 -5
View File
@@ -65,7 +65,7 @@ Polymarket 的查询使用认证身份,部分凭证有会话级可见范围。
连续交易的 order 支持 `"tif":"GTD"` 及整数秒 `expiration`,也可与 `"post_only":true` 合用。省略 tif 且提供正的到期时间时,本地采用 GTD。若数据库时钟为 T,申报 T+179 会拒绝;申报 T+180 时,有效截止点是 T+120,达到该秒就释放剩余预留。使用原请求键重试仍返回原受理回执,可通过 open_orders 指定订单号查看当前状态和申报时间。JSONL 输入空闲时用数据库时钟计算距离最近一笔待到期 GTD 的毫秒数,到点唤醒并释放余单。进程重启时先清理已到期订单,再恢复盘口。操作系统调度或 SQLite 写锁会影响实际清理延迟。[官方限价委托说明](https://docs.polymarket.com/trading/place-orders.md)
模拟器以每次请求取得数据库快照的时间判断是否到期。无人请求时的独立定时通知、外场终态字符串及逐秒延迟仍待验证。回归用例 gtd_expiry_survives_rejection_and_recovery 覆盖部分成交后到期、FOK 拒单、幂等重试和重启时解冻。
通过 `GET /time` 可读取与 GTD 受理校验共用的 SQLite 时钟。成功响应是单个 Unix 秒整数。客户端若以服务器时间 `T` 计划有效挂单 600 秒,可填写 `T+660`;服务按实际受理时刻校验最短申报期限。读时钟本身不会更改挂单。回归用例 gtd_expiry_survives_rejection_and_recovery 从公开时钟取值,覆盖过早申报、部分成交后到期、FOK 拒单、幂等重试和重启时解冻。生产 `/time` 直连未取得可用响应,本轮依据官方接口定义。外场终态字符串及逐秒延迟仍待验证。[官方时钟接口](https://docs.polymarket.com/api-reference/data/get-server-time)
## 结果资产与订单路由
@@ -382,10 +382,6 @@ fidelity 以分钟为单位;省略或不大于零时按 1 分钟处理。相
官方 SDK 仓库有用户在同一已裁决资产上记录了两种结果:max 窗口按 60 分钟查询返回空,按 720 分钟查询有历史;后来该用户用显式起止时间取得更细数据。本地可返回已保存的全部历史。这项生产覆盖差异仍然存在。[原报告及后续复查](https://github.com/Polymarket/py-clob-client/issues/216)
#### CLOB 批量曲线
生产 `POST /batch-prices-history` 返回 history 映射。2026-12-05 样本中,重复资产合并,超过 20 个不同资产返回 400,未知资产省略。请求体的绝对时间使用 start_ts 和 end_ts,传小数得到 400。开放资产在历史窗口之外仍可附上最新点,封盘资产仅返回窗口截止前已有曲线。批量接口和单查复用本地采样 SQL,并在同一读事务内使用一个时钟。输入使用本地 Eventbook 资产 ID。生产采样抖动、保留期限及本地与外场资产映射仍需分别核对。[生产请求样本](examples/public-batch-clob-history.json) · [官方接口](https://docs.polymarket.com/api-reference/markets/get-batch-prices-history)
### 裁决规则补充公告与兑付权重
[本地样例](examples/clarifications.jsonl)先挂出 0.40 的 YES 买单。第一条说明保留挂单,第二条要求清盘,账户收回预留的 0.40。两条说明都按发布时间保留,初始规则仍可查看。模拟操作员可在盘前、连续交易或封盘待裁决期间发布公告。重复的请求 ID 返回原回执;之后新挂的订单不会因重放旧公告被撤。[官方规则澄清说明](https://docs.polymarket.com/concepts/resolution#clarifications)
@@ -470,3 +466,8 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场
用空数据库重放[原单状态样例](examples/order-status.jsonl)。卖方以 0.60 挂 5 份 post-only 卖单,买方按金额吃掉 2 份。卖方撤回余单后,按原订单号查询,累计成交仍为 2,可成交余量为 0,`order_type` 为 GTC。买方的原单类型为 FAK。按卖方订单号查询 `trades`,这笔执行的份额也是 2。重启和重发相同命令沿用原回执与受理时间。
`open_orders` 的列表和精确查询均返回 `created_at`(Unix 秒)、`order_type` 和本地扩展 `post_only`。升级已有数据库时,用已受理的命令回执和 GTD 截止记录恢复提交指令;没有原始时钟记录的受理时间为 null。缺少原始回执的历史行仍可查询,未知字段保留为 null。官方当前将累计成交和逐笔对账分别放在订单的 size_matched 和账户成交记录;其单笔订单 HTTP 接口需要账户认证。本地验证使用可信操作员的 JSONL 接口,订单号与账户是模拟环境的标识。生产私有接口尚未实测。[官方订单查询](https://docs.polymarket.com/trading/manage-orders)
### 已裁决市场的公开盘口
对电竞、乒乓球和 SOL 涨跌盘的六个已裁决结果单查 /book,全部返回 404。批量 /books 和 /prices 忽略已裁决资产,混合批次保留可用资产。中点和价差多数同样返回 404,但一个 V2 市场的两侧分别仍能读到价差 1 或中点 0.5。Eventbook 对已裁决结果统一省略四种公开行情,保留内部快照供交易状态和回放。封盘待裁决阶段、外场淘汰时延和例外是否由服务缓存触发仍待验证。[生产响应](examples/public-resolved-books.json)