Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f3be3c2c09 |
@@ -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
|
||||
|
||||
@@ -404,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)),
|
||||
@@ -466,6 +474,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
| "/midpoint"
|
||||
| "/spread"
|
||||
| "/book"
|
||||
| "/time"
|
||||
| "/last-trade-price"
|
||||
| "/prices-history"
|
||||
| "/markets"
|
||||
@@ -581,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() {
|
||||
@@ -863,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 || {
|
||||
@@ -876,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)))
|
||||
@@ -897,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 {
|
||||
|
||||
@@ -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 下单
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
## 结果资产与订单路由
|
||||
|
||||
|
||||
Reference in New Issue
Block a user