Compare commits

..

1 Commits

Author SHA1 Message Date
codex-bot f3be3c2c09 Expose the CLOB server clock used by GTD validation 2026-12-05 18:21:48 +08:00
13 changed files with 63 additions and 194 deletions
+9 -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
@@ -425,18 +434,3 @@ sequenceDiagram
E-->>H: true
H-->>C: 200,neg_risk 为真
```
### 钱包成交量
`GET /v2/user-volume?user=alice&start=1785542400&end=1785628800` 返回 `data.volume`(份数)、`data.volume_usdc` 和 `data.trade_count`。省略边界或填 0 表示该侧不限。
```mermaid
sequenceDiagram
participant C as 客户端
participant H as market_http.rs
participant E as Exchange
C->>H: GET /v2/user-volume
H->>E: 钱包、起止时间
E-->>H: UTC 整日成交汇总
H-->>C: data 对象
```
+29 -17
View File
@@ -335,13 +335,6 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
let (status, body) = data_page(path, params, engine);
return send(req, status, body, None);
}
if path == "/v2/user-volume" {
if req.method() != &Method::Get {
return send(req, 405, json!({"error":"Method not allowed"}), Some("GET"));
}
let (status, body) = data_page(path, params, engine);
return send(req, status, body, None);
}
let route = path.strip_prefix('/').unwrap_or(path);
let (name, segment) = route
.split_once('/')
@@ -411,6 +404,14 @@ 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)),
@@ -473,6 +474,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
| "/midpoint"
| "/spread"
| "/book"
| "/time"
| "/last-trade-price"
| "/prices-history"
| "/markets"
@@ -522,7 +524,6 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
let page = match path {
"/v2/oi" => read_page(params, engine, Exchange::public_open_interest),
"/v2/value" => read_page(params, engine, Exchange::public_portfolio_value),
"/v2/user-volume" => read_page(params, engine, Exchange::public_user_volume),
"/v2/trades" => read_page(params, engine, Exchange::public_trade_feed),
"/v2/resolutions" => read_page(params, engine, Exchange::public_resolutions),
_ => read_page(params, engine, Exchange::public_price_history),
@@ -541,10 +542,6 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
503,
json!({"code":"unavailable","error":"portfolio valuation unavailable","retryable":true}),
),
Err(HistoryError::Unavailable) if path == "/v2/user-volume" => (
503,
json!({"code":"unavailable","error":"user volume unavailable","retryable":true}),
),
Err(HistoryError::Unavailable) if path == "/v2/resolutions" => (
500,
json!({"code":"internal","error":"resolution state unavailable","retryable":true}),
@@ -593,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() {
@@ -715,10 +716,6 @@ mod tests {
("GET","/v2/value?user=a&condition=",String::new(),400,None),
("GET","/v2/value?user=0x4d97dcd97ec945f40cf65f87097ace5ea0476045",String::new(),400,None),
("POST","/v2/value",String::new(),405,None),
("GET","/v2/user-volume?user=unknown",String::new(),200,Some(json!({"data":{"volume":0,"volume_usdc":0,"trade_count":0}}))),
("GET","/v2/user-volume?user=0x4d97dcd97ec945f40cf65f87097ace5ea0476045",String::new(),400,None),
("GET","/v2/user-volume",String::new(),400,None),
("POST","/v2/user-volume",String::new(),405,None),
("GET","/v2/trades?user=unknown&conditionId=unknown&takerOnly=false",String::new(),200,Some(empty_trades)),
("GET","/v2/trades?offset=2",String::new(),400,None),
("GET","/v2/trades?cursor=invalid",String::new(),400,None),
@@ -879,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 || {
@@ -892,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)))
@@ -913,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 {
+9 -17
View File
@@ -2,19 +2,6 @@
维护一个 SQLite 模拟市场。每条写命令在同一事务内完成资金或份额预留、订单更新和幂等回执。成交明细由 matching 计算。只读 state 使用一个一致快照。
## 钱包成交量
```mermaid
sequenceDiagram
participant H as HTTP
participant E as portfolio/user_volume.rs
participant D as SQLite
H->>E: 钱包与 Unix 秒起止参数
E->>E: 校验钱包,把有效边界转换为 UTC 日
E->>D: 读取该钱包的买卖成交,汇总窗口内份数、成交额和笔数
E-->>H: 单个数据对象
```
## 文件依赖
箭头从使用方指向提供类型或功能的文件。虚线连到 workspace 内的另一个 crate。图中省略标准库及第三方 crate。
@@ -47,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"]
@@ -54,9 +43,6 @@ flowchart LR
api -->|事务内派发| market["src/market.rs"]
api -->|解析只读查询| queries["src/catalog.rs"]
queries -->|查询各盘及赛事成交量| volume["src/volume.rs"]
api -->|查询钱包成交量| user_volume["src/portfolio/user_volume.rs"]
user_volume -->|按 UTC 日期汇总钱包成交| user_volume_sql["src/portfolio/user_volume.sql"]
user_volume_sql -->|读取按账户拆开的成交| wallet_legs["src/price_migration.sql"]
volume -->|按市场汇总普通及互补成交| volumesql["src/volume.sql"]
volumesql -->|成交、时间及吃单方| schema
queries -->|市价预估| estimate["src/estimate.rs"]
@@ -247,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: 到达有效截止点后查询或提交新单
@@ -259,7 +251,7 @@ sequenceDiagram
E-->>C: 返回查询结果或新单回执
```
没有请求时,模拟 CLI 会等待输入。下一次查询、交易或进程重启会先结清已到期的余单。成交、手动撤单和停盘会同步移除相应的待到期项。
模拟 CLI 在等待输入时会按最近的截止点唤醒。盘口查询、交易或进程重启也会先结清已到期余单。单纯读时钟不会触发清理。成交、手动撤单和停盘会同步移除相应的待到期项。
## 用结果资产 ID 下单
+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"
+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(
+5 -1
View File
@@ -54,7 +54,6 @@ pub use gamma_directory::DirectoryKey;
pub use gamma_list::DirectoryResource;
pub use open_interest::InterestQuery;
pub use portfolio::http::ValueQuery;
pub use portfolio::UserVolumeQuery;
pub use prices_history::http::HistoryQuery;
pub use prices_history::legacy::ClobHistoryQuery;
pub use public_trades::http::TradeQuery;
@@ -169,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(
-3
View File
@@ -10,9 +10,6 @@ use rusqlite::{params, Connection};
use serde::Deserialize;
use serde_json::{json, Value};
mod user_volume;
pub use user_volume::UserVolumeQuery;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Filter {
@@ -1,49 +0,0 @@
use super::protocol::CONTRACTS;
use crate::{
inventory::decimal,
lots::PER_SHARE,
tick_size::PAR,
validation::{hex_id, identifier},
Exchange, MarketDataError,
};
use rusqlite::params;
use serde::Deserialize;
use serde_json::{json, Value};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UserVolumeQuery {
user: String,
start: Option<i64>,
end: Option<i64>,
}
impl Exchange {
pub fn public_user_volume(&self, query: UserVolumeQuery) -> Result<Value, MarketDataError> {
let user = &query.user;
identifier(user).map_err(|_| MarketDataError::Invalid("invalid user".into()))?;
if CONTRACTS.iter().any(|c| c.eq_ignore_ascii_case(user)) {
return Err(MarketDataError::Invalid(
"protocol contract is not a user".into(),
));
}
let start = query.start.filter(|&at| at != 0);
let end = query.end.filter(|&at| at != 0);
if matches!(start.zip(end), Some((start, end)) if start > end) {
return Ok(json!({"data":{"volume":0,"volume_usdc":0,"trade_count":0}}));
}
let day = |at: i64| at.div_euclid(86_400);
let (shares, notional, count): (i64, i64, i64) = self
.db
.prepare_cached(include_str!("user_volume.sql"))?
.query_row(
params![user, hex_id(user, 40), start.map(day), end.map(day)],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)?;
Ok(json!({"data":{
"volume":decimal(shares.into(), PER_SHARE),
"volume_usdc":decimal(notional.into(), PER_SHARE * PAR),
"trade_count":count
}}))
}
}
@@ -1,13 +0,0 @@
WITH owners AS (
SELECT ?1 AS id WHERE NOT ?2
UNION ALL
SELECT id FROM accounts WHERE ?2 AND id=?1 COLLATE NOCASE
), legs AS (
SELECT execution, quantity, price,
at_ms/86400000 - (at_ms%86400000<0) AS utc_day
FROM wallet_trade_legs
WHERE account IN (SELECT id FROM owners)
)
SELECT COALESCE(SUM(quantity),0), COALESCE(SUM(quantity*price),0), COUNT(DISTINCT execution)
FROM legs
WHERE (?3 IS NULL OR utc_day>=?3) AND (?4 IS NULL OR utc_day<=?4)
+1 -3
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");
-67
View File
@@ -1,67 +0,0 @@
use exchange::Exchange;
use serde_json::{json, Value};
fn volume(db: &Exchange, query: Value) -> Value {
db.public_user_volume(serde_json::from_value(query).unwrap())
.unwrap()["data"]
.clone()
}
#[test]
fn wallet_volume_counts_both_roles_and_rounds_bounds_to_utc_days() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("wallet-volume.sqlite");
let mut db = Exchange::open(&path).unwrap();
for line in include_str!("../../../docs/examples/valuation.jsonl")
.lines()
.take(7)
{
db.execute(serde_json::from_str(line).unwrap()).unwrap();
}
for cmd in [
json!({"op":"list","id":"list-pair","market":"pair","rules":"赛果"}),
json!({"op":"open","id":"open-pair","market":"pair"}),
json!({"op":"order","id":"buy-no","market":"pair","account":"alice","outcome":"NO","side":"buy","price":40,"qty":3}),
json!({"op":"order","id":"buy-yes","market":"pair","account":"bob","outcome":"YES","side":"buy","price":60,"qty":3}),
] {
db.execute(cmd).unwrap();
}
// Put the executions on opposite sides of UTC midnight.
let sqlite = rusqlite::Connection::open(&path).unwrap();
assert_eq!(
sqlite
.execute("UPDATE trade_prices SET at_ms=86399999", [])
.unwrap(),
1
);
assert_eq!(
sqlite
.execute("UPDATE paired_fills SET at_ms=86400000", [])
.unwrap(),
1
);
drop(sqlite);
let zero = json!({"volume":0,"volume_usdc":0,"trade_count":0});
assert_eq!(volume(&db, json!({"user":"unknown"})), zero);
assert_eq!(
volume(&db, json!({"user":"alice","start":86500,"end":86400})),
zero
);
assert_eq!(
volume(&db, json!({"user":"alice","start":1,"end":1})),
json!({"volume":2,"volume_usdc":1.2,"trade_count":1})
);
assert_eq!(
volume(&db, json!({"user":"alice","start":86500,"end":86500})),
json!({"volume":3,"volume_usdc":1.2,"trade_count":1})
);
assert_eq!(
volume(&db, json!({"user":"alice","start":0,"end":0})),
json!({"volume":5,"volume_usdc":2.4,"trade_count":2})
);
assert_eq!(
volume(&db, json!({"user":"bob"})),
json!({"volume":5,"volume_usdc":3,"trade_count":2})
);
}
+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 -7
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)
## 结果资产与订单路由
@@ -223,12 +223,6 @@ JSONL 下单面板的 `price` 接受 token_id 和方向,BUY 读取最低卖价
[可重放样例](examples/execution-prices.jsonl)开始时只有 YES 买单,买入 YES 的报价为 null。随后有人以 0.89 挂买 NO,YES 买入价变成 0.11,卖出价为 0.09。NO 买入价为 0.91,卖出价为 0.89。这四个报价均来自挂单,无需先发生交易。单侧没有对手时保留该键并返回 null。重复项合并,未知资产使整批失败。空批次拒绝,盘前返回待集合竞价的挂单报价。上述边界属于本地约定。本地 token_id 使用 Eventbook 的结果资产 ID,公开接口的生产响应、原生资产编号与无流动性时的处理仍待对照。
### 钱包成交量 Data API
官方 `GET /v2/user-volume` 按 UTC 整日统计钱包的买卖成交,返回份数、USDC 金额和成交笔数。起止参数以 Unix 秒表示,省略或填 0 关闭该侧边界。倒置窗口及无成交钱包返回零。[官方接口](https://docs.polymarket.com/api-reference/wallet/get-a-users-trading-volume)
在空数据库重放 [估值样例](examples/valuation.jsonl) 的前七条命令。Alice 和 Bob 分别查询 `/v2/user-volume`,均应得到 2 份、1.2 USDC 和 1 笔。互补成交使用各自的结果资产价格。金额为成交价乘份数,费用与抵押拆并不计。盘口关闭后历史成交仍可查询。本地按成交编号去重计笔数,无可信时间的旧成交只进入不限日期的汇总。独立的组合 RFQ 账本及生产端点的持续对账仍待接入。
## 精确抵押币现金余额
`balance` 返回账户可用现金、有效买单预留现金及二者之和,单位均为百万分之一模拟美元。拆分完整结果集所用的抵押和已买入的份额另由仓位账本记录。模拟 fund 可以用整数 micros 建立账户,也可以沿用 cents。入金回执和 activity 的 net_cash_delta_micros 可用于精确对账,原 funded 和 cash_delta_cents 字段保留整分部分。一个账户只接受首次 fund;相同请求可幂等重放。