diff --git a/crates/cli/README.md b/crates/cli/README.md index f02bc88..a98c10d 100644 --- a/crates/cli/README.md +++ b/crates/cli/README.md @@ -1,6 +1,6 @@ # cli -可信操作员的 JSON 行命令入口。启动参数指定数据库文件,程序复用同一个 Exchange 连接。标准输入的每一行对应标准输出的一条 JSON 回执。输入结束时进程退出。输入线程和交易线程之间使用有界队列,交易线程每五秒检查到期任务,空闲时仍可撤掉断线客户端的挂单。 +可信操作员的 JSON 行命令入口。启动参数指定数据库文件,程序复用同一个 Exchange 连接。标准输入的每一行对应标准输出的一条 JSON 回执。输入结束时进程退出。输入线程和交易线程之间使用有界队列,交易线程按最近一笔 GTD 的有效截止时间唤醒,最长每五秒检查一次其他到期任务。 ## 文件依赖 @@ -24,8 +24,10 @@ sequenceDiagram U->>C: 启动并指定数据库路径 C->>E: 打开数据库 C->>S: 传入连接和输入输出流 - opt 输入空闲达到定时检查时刻 + S->>E: 查询最近一笔待到期 GTD 剩余时间 + opt 达到 GTD 截止点或五秒检查周期 S->>E: maintain 检查到期注册、释放余单并同步盘口 + S->>E: 重新计算下次唤醒时间 end loop 输入一行 U->>S: JSON 命令 diff --git a/crates/cli/src/stream.rs b/crates/cli/src/stream.rs index a28900a..41b055a 100644 --- a/crates/cli/src/stream.rs +++ b/crates/cli/src/stream.rs @@ -25,11 +25,21 @@ pub(crate) fn serve( } }); let interval = Duration::from_secs(5); - let mut next = Instant::now() + interval; + // New GTDs live at least two minutes, so rechecking within five seconds + // also catches orders added by another process before their cutoff. + let next_check = |exchange: &Exchange| -> Result { + let start = Instant::now(); + let wait = exchange + .next_gtd_expiry()? + .unwrap_or(interval) + .min(interval); + Ok(start + wait) + }; + let mut next = next_check(engine)?; loop { if Instant::now() >= next { engine.maintain()?; - next = Instant::now() + interval; + next = next_check(engine)?; } let line = match reader.recv_timeout(next.saturating_duration_since(Instant::now())) { Ok(line) => line?, diff --git a/crates/exchange/src/lib.rs b/crates/exchange/src/lib.rs index b17f213..413debd 100644 --- a/crates/exchange/src/lib.rs +++ b/crates/exchange/src/lib.rs @@ -161,6 +161,20 @@ impl Exchange { Ok(()) } + /// Time until the next pending GTD stops trading, measured on the database clock. + pub fn next_gtd_expiry(&self) -> Result> { + let (first, now): (Option, i64) = self.db.query_row( + "SELECT MIN(expiration), CAST(unixepoch('subsec')*1000 AS INTEGER) + FROM order_deadlines WHERE pending=1", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + )?; + Ok(first.map(|stated| { + let cutoff = stated.saturating_sub(60).saturating_mul(1000); + Duration::from_millis(cutoff.saturating_sub(now).max(0) as u64) + })) + } + /// Read requested outcome books in one consistent database and resident-book snapshot. pub fn public_books(&mut self, tokens: &[String]) -> Result> { let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?; diff --git a/crates/exchange/tests/market.rs b/crates/exchange/tests/market.rs index fdade39..40c22bf 100644 --- a/crates/exchange/tests/market.rs +++ b/crates/exchange/tests/market.rs @@ -686,6 +686,7 @@ fn gtd_expiry_survives_rejection_and_recovery() { let now: i64 = db .query_row("SELECT unixepoch()", [], |r| r.get(0)) .unwrap(); + assert_eq!(e.next_gtd_expiry().unwrap(), None); let mut ask = order("dated", "alice", "sell", 60, 5); ask["tif"] = json!("GTD"); assert!(e.execute(ask.clone()).is_err()); @@ -704,9 +705,14 @@ fn gtd_expiry_survives_rejection_and_recovery() { [ask_id], ) .unwrap(); + assert_eq!( + e.next_gtd_expiry().unwrap(), + Some(std::time::Duration::ZERO) + ); let mut sweep = order("sweep", "bob", "buy", 65, 1); sweep["tif"] = json!("FOK"); assert!(e.execute(sweep).is_err()); + assert!(e.next_gtd_expiry().unwrap().unwrap() > std::time::Duration::ZERO); assert_eq!(e.execute(ask).unwrap(), receipt); let lookup = e .execute(json!({"op":"open_orders","account":"alice","order":ask_id})) @@ -734,6 +740,7 @@ fn gtd_expiry_survives_rejection_and_recovery() { ) .unwrap(); let mut e = Exchange::open(&path).unwrap(); + assert_eq!(e.next_gtd_expiry().unwrap(), None); let s = state(&mut e); assert_eq!(s["accounts"][1]["cash"], 1880); assert_eq!(s["orders"][1]["status"], "expired"); diff --git a/docs/prediction-parity.md b/docs/prediction-parity.md index 46db82a..0f777a0 100644 --- a/docs/prediction-parity.md +++ b/docs/prediction-parity.md @@ -63,7 +63,7 @@ Polymarket 的查询使用认证身份,部分凭证有会话级可见范围。 ## 限时挂单 -连续交易的 order 支持 `"tif":"GTD"` 及整数秒 `expiration`,也可与 `"post_only":true` 合用。省略 tif 且提供正的到期时间时,本地采用 GTD。若数据库时钟为 T,申报 T+179 会拒绝;申报 T+180 时,有效截止点是 T+120,达到该秒就释放剩余预留。使用原请求键重试仍返回原受理回执,可通过 open_orders 指定订单号查看当前状态和申报时间。已有数据库的历史委托沿用其原有行为。[官方限价委托说明](https://docs.polymarket.com/trading/place-orders.md) +连续交易的 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 拒单、幂等重试和重启时解冻。