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
15 changed files with 69 additions and 256 deletions
+9 -15
View File
@@ -13,21 +13,6 @@ flowchart LR
stream -.->|执行命令| api
```
## 定时免手续费
JSONL `schedule_fee_holiday` 接受 `market`、可选 `starts_at_ms` 和必需的 `ends_at_ms`。公开费率和市场详情读取当前生效的配置,市场 WebSocket 成交帧保留实际撮合所用的费率。
```mermaid
sequenceDiagram
participant C as 客户端
participant H as 市场 HTTP
participant E as Exchange
C->>H: 查询市场详情或费率
H->>E: 读取当前生效的费率
E-->>H: 返回有效费率和交易参数
H-->>C: 返回报价所需参数
```
## 一次命令会话
```mermaid
@@ -105,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
@@ -112,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
+29 -1
View File
@@ -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 {
+9 -20
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 下单
@@ -476,25 +484,6 @@ sequenceDiagram
E-->>C: 顺序返回报价、价差、中点、时间和游标
```
## 市场费率与免手续费窗口
`list` 可通过 `fee_category` 选择当前公开费率表。显式 `taker_fee_rate_ppm` 优先,未设置两者的市场继续沿用零费率。操作员可用 `schedule_fee_holiday` 设定 UTC 毫秒区间 `[starts_at_ms, ends_at_ms)`,省略开始时间表示立即生效。结束后自动恢复配置费率。
```mermaid
sequenceDiagram
actor O as 操作员
participant E as Exchange
participant F as fees.rs
participant D as SQLite
O->>E: 上架市场并配置类别或费率
E->>F: 保存基础费率
O->>E: 安排免手续费窗口
E->>D: 保存生效与结束时间
E->>F: 下单时读取有效费率
F->>D: 查询 effective_market_fee_terms
E->>D: 记录撮合实际使用的费率和费用
```
## 赛事目录与成交量
```mermaid
+3 -21
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"
@@ -264,7 +264,7 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
"INSERT INTO budget_spend_micros VALUES(?,?)",
params![seq, spent],
)?;
let fee = settle_with_rate(tx, &market, &outcome, fills, Some(Taker::Budget(seq)), rate)?;
let fee = settle(tx, &market, &outcome, fills, Some(Taker::Budget(seq)))?;
ledger::cash_micros(tx, &account, gross_remainder - fee)?;
let status = if unspent_micros == 0 {
"filled"
@@ -362,17 +362,6 @@ pub(crate) fn settle(
} else {
0
};
settle_with_rate(tx, market, outcome, fills, taker, rate)
}
fn settle_with_rate(
tx: &Transaction,
market: &str,
outcome: &str,
fills: Vec<Fill>,
taker: Option<Taker>,
rate: i64,
) -> Result<i64> {
let mut fees = 0;
for f in fills {
let first = book_leg(tx, market, outcome, &f, f.bid, taker)?;
@@ -421,13 +410,6 @@ fn settle_with_rate(
params![execution, taker.map(Taker::seq)],
)?;
if let Some(taker) = taker {
// The stream trigger seeds the configured base rate. Save the
// coefficient actually used by this order before publishing.
tx.prepare_cached(
"UPDATE market_stream_events SET fee_ppm=?2
WHERE kind='trade' AND source=?1 AND fee_ppm<>?2",
)?
.execute(params![execution, rate])?;
let fee = crate::fees::lot_fee(rate, f.price * 100, f.quantity);
if fee > 0 {
tx.execute(
+1 -1
View File
@@ -4,7 +4,7 @@ SELECT w.yes_label, w.no_label, tick.step_micros, minimum.microshares,
FROM market_wire_metadata w
LEFT JOIN market_tick_sizes tick ON tick.market=w.market
LEFT JOIN market_minimum_sizes minimum ON minimum.market=w.market
JOIN effective_market_fee_terms fee ON fee.market=w.market
JOIN market_fee_terms fee ON fee.market=w.market
LEFT JOIN neg_risk_members member ON member.market=w.market
LEFT JOIN sports_markets sport ON sport.market=w.market
LEFT JOIN events event ON event.id=sport.event
-7
View File
@@ -29,7 +29,6 @@ pub(crate) enum Command {
question: Option<String>,
rules: String,
taker_fee_rate_ppm: Option<i64>,
fee_category: Option<crate::fees::Category>,
base_fees: Option<crate::fees::BaseFees>,
min_order_size: Option<String>,
tick_size: Option<String>,
@@ -141,12 +140,6 @@ pub(crate) enum Command {
CancelAll {
account: String,
},
#[serde(rename = "schedule_fee_holiday")]
ScheduleFeeHoliday {
market: String,
starts_at_ms: Option<i64>,
ends_at_ms: i64,
},
Open {
market: String,
},
+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(
+2 -151
View File
@@ -3,7 +3,6 @@ use anyhow::{ensure, Result};
use matching::Fill;
use rusqlite::{params, Connection, OptionalExtension, Transaction};
use serde::Deserialize;
use serde_json::{json, Value};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
@@ -26,78 +25,13 @@ impl BaseFees {
}
}
#[derive(Clone, Copy, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum Category {
#[serde(rename = "btc_5m_15m")]
Btc5m15m,
Crypto,
Sports,
Finance,
Tech,
Elections,
Politics,
Economics,
Culture,
Weather,
Mentions,
Geopolitics,
Combos,
General,
}
impl Category {
pub(crate) fn rate(self) -> i64 {
match self {
Self::Btc5m15m
| Self::Sports
| Self::Finance
| Self::Tech
| Self::Elections
| Self::Combos
| Self::General => 50_000,
Self::Crypto
| Self::Politics
| Self::Economics
| Self::Culture
| Self::Weather
| Self::Mentions => 10_000,
Self::Geopolitics => 0,
}
}
}
pub(crate) fn schedule_holiday(
tx: &Transaction,
market: &str,
starts_at: Option<i64>,
ends_at: i64,
) -> Result<Value> {
crate::validation::identifier(market)?;
let now: i64 = tx.query_row(
"SELECT CAST(unixepoch('subsec')*1000 AS INTEGER)",
[],
|r| r.get(0),
)?;
let start = starts_at.unwrap_or(now);
ensure!(
start >= now && ends_at > start,
"invalid fee holiday window"
);
tx.execute(
"INSERT INTO market_fee_holidays VALUES(?1,?2,?3)",
params![market, start, ends_at],
)?;
Ok(json!({"market":market,"starts_at_ms":start,"ends_at_ms":ends_at}))
}
impl Exchange {
pub fn base_fee_bps(&self, token: &str) -> Result<Option<i64>, MarketDataError> {
let (_, market) = assets::parse_id(token)
.map_err(|_| MarketDataError::Invalid("Invalid token id".into()))?;
let mut stmt = self
.db
.prepare_cached("SELECT taker_bps FROM effective_market_fee_terms WHERE market=?1")?;
.prepare_cached("SELECT taker_bps FROM market_fee_terms WHERE market=?1")?;
Ok(stmt
.query_row([market], |r| r.get::<_, Option<i64>>(0))
.optional()?
@@ -106,9 +40,7 @@ impl Exchange {
}
pub(crate) fn rate(db: &Connection, market: &str) -> Result<i64> {
Ok(db
.prepare_cached("SELECT rate_ppm FROM effective_market_fee_terms WHERE market=?1")?
.query_row([market], |r| r.get(0))?)
Ok(db.query_row("SELECT COALESCE(f.rate_ppm,0) FROM markets m LEFT JOIN market_fee_rates f ON f.market=m.id WHERE m.id=?", [market], |r|r.get(0))?)
}
// Price and rate both have six decimals. Round the fee only after the
@@ -204,85 +136,4 @@ mod tests {
assert_eq!(micros(rate, (100 - price) * 10000, size), expected);
}
}
#[test]
fn category_rate_and_holiday_share_public_and_execution_configuration() {
use crate::Exchange;
use serde_json::json;
let dir = tempfile::tempdir().unwrap();
let mut db = Exchange::open(dir.path().join("fee-schedule.sqlite")).unwrap();
for cmd in [
json!({"op":"list","id":"short-btc","market":"btc","rules":"btc","fee_category":"btc_5m_15m"}),
json!({"op":"list","id":"sports","market":"sport","rules":"result","fee_category":"sports","base_fees":{"maker_bps":0,"taker_bps":120}}),
json!({"op":"list","id":"crypto","market":"crypto","rules":"result","fee_category":"crypto"}),
json!({"op":"list","id":"explicit","market":"explicit","rules":"result","fee_category":"sports","taker_fee_rate_ppm":22000}),
json!({"op":"list","id":"geo","market":"geo","rules":"result","fee_category":"geopolitics"}),
json!({"op":"list","id":"legacy","market":"legacy","rules":"result"}),
] {
db.execute(cmd).unwrap();
}
for (market, rate) in [
("btc", 50000),
("sport", 50000),
("crypto", 10000),
("explicit", 22000),
("geo", 0),
("legacy", 0),
] {
assert_eq!(super::rate(&db.db, market).unwrap(), rate);
}
let token = crate::assets::id("sport", "YES");
assert_eq!(db.base_fee_bps(&token).unwrap(), Some(120));
let now: i64 = db
.db
.query_row(
"SELECT CAST(unixepoch('subsec')*1000 AS INTEGER)",
[],
|r| r.get(0),
)
.unwrap();
let command = json!({"op":"schedule_fee_holiday","id":"holiday","market":"sport","ends_at_ms":now+60000});
assert_eq!(
db.execute(command.clone()).unwrap(),
db.execute(command).unwrap()
);
assert_eq!(db.base_fee_bps(&token).unwrap(), Some(0));
assert_eq!(super::rate(&db.db, "sport").unwrap(), 0);
let data = db.clob_market_info("sport").unwrap().unwrap();
assert_eq!(data["tbf"], 0);
assert!(data.get("fd").is_none());
assert_eq!(super::rate(&db.db, "crypto").unwrap(), 10000);
for command in [
json!({"op":"fund","id":"maker","account":"maker","cents":15000}),
json!({"op":"fund","id":"taker","account":"taker","cents":6000}),
json!({"op":"split","id":"split","market":"sport","account":"maker","qty":100}),
json!({"op":"open","id":"open","market":"sport"}),
json!({"op":"order","id":"ask","market":"sport","outcome":"YES","account":"maker","side":"sell","price":50,"qty":100}),
] {
db.execute(command).unwrap();
}
let bought = db.execute(
json!({"op":"market_buy","id":"buy","market":"sport","outcome":"YES","account":"taker","amount_cents":5000,"max_price":50,"tif":"FOK"})
).unwrap();
assert_eq!(bought["status"], "filled");
assert_eq!(bought["unspent_cents"], 0);
let (saved_rate, fees): (i64, i64) = db
.db
.query_row(
"SELECT fee_ppm,(SELECT COUNT(*) FROM execution_fees)
FROM market_stream_events WHERE kind='trade' AND market='sport'",
[],
|row| Ok((row.get(0)?, row.get(1)?)),
)
.unwrap();
assert_eq!((saved_rate, fees), (0, 0));
db.db
.execute(
"UPDATE market_fee_holidays SET starts_at_ms=0,ends_at_ms=1 WHERE market='sport'",
[],
)
.unwrap();
assert_eq!(super::rate(&db.db, "sport").unwrap(), 50000);
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ LEFT JOIN augmented_outcomes a ON a.market=w.market
LEFT JOIN market_tick_sizes tick ON tick.market=w.market
LEFT JOIN market_minimum_sizes minimum ON minimum.market=w.market
LEFT JOIN neg_risk_members member ON member.market=w.market
JOIN effective_market_fee_terms fee ON fee.market=w.market
JOIN market_fee_terms fee ON fee.market=w.market
LEFT JOIN quote_events quotes ON quotes.seq=(SELECT MAX(seq) FROM quote_events WHERE market=w.market)
LEFT JOIN last_asset_trades yes_trade ON yes_trade.market=w.market AND yes_trade.outcome='YES'
LEFT JOIN last_asset_trades no_trade ON no_trade.market=w.market AND no_trade.outcome='NO'
+5
View File
@@ -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(
+1 -9
View File
@@ -63,11 +63,6 @@ pub(crate) fn apply(
previous_ms,
scheduled_at_ms,
} => crate::kickoff::reschedule(tx, &event, previous_ms, scheduled_at_ms),
Command::ScheduleFeeHoliday {
market,
starts_at_ms,
ends_at_ms,
} => crate::fees::schedule_holiday(tx, &market, starts_at_ms, ends_at_ms),
Command::List {
market,
slug,
@@ -76,7 +71,6 @@ pub(crate) fn apply(
listing,
resolution,
taker_fee_rate_ppm,
fee_category,
base_fees,
min_order_size,
tick_size,
@@ -93,9 +87,7 @@ pub(crate) fn apply(
if let Some(size) = min_order_size {
crate::minimum_size::MinimumSize::configure(tx, &market, &size)?;
}
if let Some(rate) =
taker_fee_rate_ppm.or_else(|| fee_category.map(crate::fees::Category::rate))
{
if let Some(rate) = taker_fee_rate_ppm {
crate::fees::configure(tx, &market, rate)?;
}
if let Some(base) = base_fees {
-20
View File
@@ -254,26 +254,6 @@ CREATE VIEW IF NOT EXISTS market_fee_terms AS
SELECT m.id AS market, COALESCE(f.rate_ppm,0) AS rate_ppm, COALESCE(b.maker_bps,0) AS maker_bps,
COALESCE(b.taker_bps,CASE WHEN COALESCE(f.rate_ppm,0)%100=0 THEN COALESCE(f.rate_ppm,0)/100 END) AS taker_bps
FROM markets m LEFT JOIN market_fee_rates f ON f.market=m.id LEFT JOIN market_base_fees b ON b.market=m.id;
CREATE TABLE IF NOT EXISTS market_fee_holidays (
market TEXT NOT NULL REFERENCES markets(id),
starts_at_ms INTEGER NOT NULL CHECK(starts_at_ms>=0),
ends_at_ms INTEGER NOT NULL CHECK(ends_at_ms>starts_at_ms),
PRIMARY KEY(market,starts_at_ms)
) WITHOUT ROWID;
CREATE VIEW IF NOT EXISTS effective_market_fee_terms AS
SELECT base.market,
CASE WHEN holiday.market IS NOT NULL THEN 0 ELSE base.rate_ppm END AS rate_ppm,
CASE WHEN holiday.market IS NOT NULL THEN 0 ELSE base.maker_bps END AS maker_bps,
CASE WHEN holiday.market IS NOT NULL THEN 0 ELSE base.taker_bps END AS taker_bps
FROM market_fee_terms base
LEFT JOIN market_fee_holidays holiday
ON holiday.market=base.market AND holiday.starts_at_ms=(
SELECT h.starts_at_ms FROM market_fee_holidays h
WHERE h.market=base.market AND h.starts_at_ms<=unixepoch('subsec')*1000
AND h.ends_at_ms>unixepoch('subsec')*1000
ORDER BY h.starts_at_ms DESC LIMIT 1
);
CREATE TABLE IF NOT EXISTS cash_remainders (
account TEXT PRIMARY KEY REFERENCES accounts(id), micros INTEGER NOT NULL CHECK(micros BETWEEN 0 AND 9999)
);
+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");
+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)
## 结果资产与订单路由
@@ -135,12 +135,6 @@ FOK 要求整笔金额成交,无法用完预算时交易回滚。超过最高
官方文档描述页面隐藏未命名项,并提示只交易已命名项、避免直接交易「其他」。本地在订单写入时也拦截未命名项,显式「其他」维持可见并标记角色。输入获胜者名称按去除首尾空白后的精确文本匹配;操作员负责按公告统一姓名和别名。全组一次提交裁决、命名证据格式及订单拒绝位置均为本地实现。真实场所的公告传递时序、错误码和预留位链上标识尚待实测。
### 分类费率与免手续费窗口
`list` 可给定 `fee_category` 选择公开费率表。短周期 BTC(`btc_5m_15m`)、体育、金融、科技、选举、组合和通用类别使用 0.05。普通加密、普通政治、经济、文化、天气和 Mentions 使用 0.01,地缘政治使用 0。显式 `taker_fee_rate_ppm` 优先,未配置的旧市场继续以原费率运行。[官方费率表](https://docs.polymarket.com/trading/fees)
`schedule_fee_holiday` 可配置立即或未来生效的半开 UTC 时间窗口。在窗口内撮合、预算估算和公开费率读取同一有效配置,结束后自动恢复。单笔预算买单使用固定费率完成预算和入账。成交帧保存执行时的费率,旧记录不回填。生产如何选择需要收费的旧市场、识别类别与安排活动时间仍待外场比对。
## 账户活动明细
`{"op":"activity","account":"alice","types":["TRADE","SPLIT","MERGE","REDEEM","CONVERSION"],"limit":20}` 查询该账户已执行的普通市场活动。官方示例买入 25 份、每份 0.49 美元,金额为 12.25 美元。本地对应 `shares=25`、`price_micros=490000`、`cash_delta_cents=-1225`。卖出、合并和兑现按实际收到的分数记正值。成交金额按成交价计算,挂单预留或释放的余额不单独算成交。互补订单成交仍归 TRADE。转换显示组 ID、每个输入的份额数和释放的现金。赎回的 shares 是核销的两侧份额之和,输方也可产生实付为零的活动。[官方钱包活动示例](https://docs.polymarket.com/trading/wallet-activity.md) · [Data API v2 类型与游标规范](https://data-api.polymarket.com/v2/openapi.json)