Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c377947ea1 | |||
| 2d4e7012cd | |||
| 30e4a5cd17 | |||
| 74b7655723 | |||
| 5b244eb54f | |||
| 4bc9f8a326 | |||
| f8fbd68d19 | |||
| 2888563723 | |||
| 9d541c563b | |||
| e6a914b381 |
Generated
+2
@@ -117,7 +117,9 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"exchange",
|
||||
"httpdate",
|
||||
"percent-encoding",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_urlencoded",
|
||||
|
||||
@@ -12,3 +12,5 @@ tungstenite = "0.28"
|
||||
tiny_http = "0.12"
|
||||
serde_urlencoded = "0.7"
|
||||
percent-encoding = "2"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls", "json"] }
|
||||
httpdate = "1"
|
||||
|
||||
+36
-4
@@ -9,8 +9,11 @@
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main["src/main.rs"] -->|把标准输入输出交给 serve| stream["src/stream.rs"]
|
||||
main --> refresh["src/polymarket_refresh.rs"]
|
||||
main -.->|打开数据库| api["exchange crate"]
|
||||
stream -.->|执行命令| api
|
||||
refresh -.->|读取绑定并写入观测| api
|
||||
refresh -->|HTTPS GET| pm["Polymarket Data API"]
|
||||
```
|
||||
|
||||
## 一次命令会话
|
||||
@@ -183,6 +186,8 @@ sequenceDiagram
|
||||
|
||||
路径参数使用百分号编码。即使查询从 NO 开始,primary_token_id 仍对应 YES。可重放请求见[行情 HTTP 示例](../../docs/examples/clob-http.http)。
|
||||
|
||||
已裁决资产的公开盘口、买卖报价、中点和价差单查返回 404,批查跳过该资产。
|
||||
|
||||
### 查询盘口价差与中点
|
||||
|
||||
```mermaid
|
||||
@@ -221,7 +226,7 @@ sequenceDiagram
|
||||
participant E as prices_history/legacy.rs
|
||||
C->>H: GET /prices-history,market 与 interval 或 startTs、endTs
|
||||
H->>E: clob_price_history,fidelity 以分钟计
|
||||
E-->>H: 返回窗口内盘口中点样本,末尾追加最近可用点
|
||||
E-->>H: 返回窗口内盘口中点样本,未封盘时追加最近可用点
|
||||
H-->>C: history 数组,每点包含 t 和 p
|
||||
```
|
||||
|
||||
@@ -237,13 +242,13 @@ sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http
|
||||
participant E as Exchange
|
||||
C->>H: GET /market-clarifications?event_id=1&question_id=...
|
||||
H->>E: 按事件、市场、问题和可选交易哈希求交集,再排序和翻页
|
||||
C->>H: GET /market-clarifications?event_id=1&market_id=3
|
||||
H->>E: 按事件和市场目录 ID 筛选,再排序和翻页
|
||||
E-->>H: 规则说明、清盘标记和本地发布时间
|
||||
H-->>C: 已发布的公告数组
|
||||
```
|
||||
|
||||
event_id 取自本地 events 或 catalog 查询,market_id 取自 assets 查询。question_id 匹配市场登记的裁决问题,忽略字母大小写。三种 ID 均可重复,同类取并集,跨条件取交集。tx_hash 按已保存的发布交易哈希精确筛选。默认每页 50 条,limit 超过 100 时取 100,非正值恢复默认。offset 小于 0 时按 0 处理。order 支持逗号分隔的 Gamma 字段,例如 createdAt,id。默认按 ID 升序,未知排序字段返回 422。
|
||||
event_id 取自本地 events 或 catalog 查询,market_id 取自 assets 查询。两个参数均可重复,同类 ID 取并集,同时指定事件与市场时取交集。独立市场的公告也能通过 market_id 查询。默认按公告 ID 降序,每页 20 条;支持 order=id、ascending、offset 和 0 到 100 的 limit。当前查询对其他筛选参数返回 400。
|
||||
|
||||
### 从事件页进入订单簿
|
||||
|
||||
@@ -423,3 +428,30 @@ sequenceDiagram
|
||||
E-->>H: true
|
||||
H-->>C: 200,neg_risk 为真
|
||||
```
|
||||
|
||||
GET /v2/tokens 支持逗号分隔的资产 ID 或条件及事件 ID。两个选择器择一,回执按资产关联市场、事件和裁决结果。完整的 V2 Neg Risk 事件 ID 返回已登记成员的仓位对,62 位十六进制条件 ID 返回该条件的仓位对。
|
||||
|
||||
### 刷新已登记的 Polymarket 资产
|
||||
|
||||
`cli DATABASE --refresh-polymarket MARKET` 刷新指定本地市场。省略 `MARKET` 则按本地市场 ID 顺序刷新所有已登记的市场。每盘输出一行 JSON。任一盘失败时命令最终以非零状态退出,其他盘仍可提交。上游 HTTP `Date` 用作观测时间,旧观测保留已有目录状态。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor U as 操作员
|
||||
participant C as polymarket_refresh.rs
|
||||
participant E as Exchange
|
||||
participant P as Polymarket Data API
|
||||
U->>C: 指定数据库和可选市场 ID
|
||||
C->>E: 查询已登记的外场条件、资产和结果映射
|
||||
loop 每个市场
|
||||
C->>P: GET /v2/tokens?condition=...
|
||||
P-->>C: HTTP Date 和资产数组
|
||||
alt 所有已登记资产齐全
|
||||
C->>E: 提交 bind_polymarket_assets
|
||||
E-->>C: 单盘事务回执或校验错误
|
||||
else 请求或响应校验失败
|
||||
C->>C: 记录本盘错误
|
||||
end
|
||||
C-->>U: 输出本盘结果
|
||||
end
|
||||
```
|
||||
|
||||
+11
-1
@@ -1,5 +1,6 @@
|
||||
mod market_http;
|
||||
mod market_ws;
|
||||
mod polymarket_refresh;
|
||||
mod stream;
|
||||
mod subscriptions;
|
||||
|
||||
@@ -12,9 +13,18 @@ use std::{
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let mut args = env::args_os().skip(1);
|
||||
let usage = "usage: cli DATABASE [--market-ws HOST:PORT | --market-http HOST:PORT]";
|
||||
let usage = "usage: cli DATABASE [--market-ws HOST:PORT | --market-http HOST:PORT | --refresh-polymarket [MARKET]]";
|
||||
let path = args.next().context(usage)?;
|
||||
if let Some(mode) = args.next() {
|
||||
if mode == "--refresh-polymarket" {
|
||||
let market = args
|
||||
.next()
|
||||
.map(|s| s.into_string().map_err(|_| anyhow::anyhow!(usage)))
|
||||
.transpose()?;
|
||||
ensure!(args.next().is_none(), usage);
|
||||
let mut exchange = Exchange::open(path)?;
|
||||
return polymarket_refresh::run(&mut exchange, market.as_deref(), io::stdout().lock());
|
||||
}
|
||||
ensure!(mode == "--market-ws" || mode == "--market-http", usage);
|
||||
let addr: SocketAddr = args
|
||||
.next()
|
||||
|
||||
@@ -293,35 +293,48 @@ fn directory_lookup(engine: &Mutex<Exchange>, route: (&str, bool, &str), params:
|
||||
.ok_or((404, "Not found"))
|
||||
}
|
||||
|
||||
fn clarifications(engine: &Mutex<Exchange>, query: &str) -> (u16, Value) {
|
||||
let query = serde_urlencoded::from_str::<Vec<(String, String)>>(query)
|
||||
.map_err(|_| "invalid query")
|
||||
.and_then(|fields| exchange::ClarificationQuery::parse(&fields));
|
||||
let query = match query {
|
||||
Ok(query) => query,
|
||||
Err(error) => return (422, json!({"type":"validation error","error":error})),
|
||||
};
|
||||
fn clarifications(engine: &Mutex<Exchange>, query: &str) -> Reply {
|
||||
let invalid = (400, "Invalid clarification query");
|
||||
let fields: Vec<(String, String)> = serde_urlencoded::from_str(query).map_err(|_| invalid)?;
|
||||
let mut ids = Vec::new();
|
||||
let mut events = Vec::new();
|
||||
let mut limit = 20;
|
||||
let mut offset = 0;
|
||||
let mut ascending = false;
|
||||
for (key, value) in fields {
|
||||
match key.as_str() {
|
||||
"event_id" => events.push(value.parse().map_err(|_| invalid)?),
|
||||
"market_id" => ids.push(value.parse().map_err(|_| invalid)?),
|
||||
"limit" => limit = value.parse().map_err(|_| invalid)?,
|
||||
"offset" => offset = value.parse().map_err(|_| invalid)?,
|
||||
"ascending" => ascending = value.parse().map_err(|_| invalid)?,
|
||||
"order" if value == "id" => {}
|
||||
_ => return Err(invalid),
|
||||
}
|
||||
}
|
||||
let rows = engine
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|exchange| exchange.gamma_clarifications(&query).ok());
|
||||
match rows {
|
||||
Some(rows) => (200, Value::Array(rows)),
|
||||
None => (500, json!({"error":"Internal server error"})),
|
||||
}
|
||||
.map_err(|_| (500, "Internal server error"))?
|
||||
.filtered_market_clarifications(&ids, &events, limit, offset, ascending)
|
||||
.map_err(|e| match e {
|
||||
exchange::MarketDataError::Invalid(_) => invalid,
|
||||
exchange::MarketDataError::Unavailable => (500, "Internal server error"),
|
||||
})?;
|
||||
Ok(Value::Array(rows))
|
||||
}
|
||||
|
||||
fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
let (path, params) = req.url().split_once('?').unwrap_or((req.url(), ""));
|
||||
let mut allow = None;
|
||||
if req.method() == &Method::Get && path == "/market-clarifications" {
|
||||
let (status, body) = clarifications(engine, params);
|
||||
return send(req, status, body, None);
|
||||
}
|
||||
if req.method() == &Method::Get
|
||||
&& matches!(
|
||||
path,
|
||||
"/v2/prices-history" | "/v2/trades" | "/v2/resolutions" | "/v2/value" | "/v2/oi"
|
||||
"/v2/tokens"
|
||||
| "/v2/prices-history"
|
||||
| "/v2/trades"
|
||||
| "/v2/resolutions"
|
||||
| "/v2/value"
|
||||
| "/v2/oi"
|
||||
)
|
||||
{
|
||||
let (status, body) = data_page(path, params, engine);
|
||||
@@ -378,6 +391,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
Err(exchange::MarketDataError::Unavailable) => Err((500, "Directory unavailable")),
|
||||
}
|
||||
}
|
||||
(&Method::Get, "/market-clarifications") => clarifications(engine, params),
|
||||
(&Method::Get, "/prices-history") => {
|
||||
let result = serde_urlencoded::from_str::<exchange::ClobHistoryQuery>(params)
|
||||
.map_err(|_| HistoryError::Invalid("invalid query parameters".into()))
|
||||
@@ -464,6 +478,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
| "/market-clarifications"
|
||||
| "/v2/oi"
|
||||
| "/v2/value"
|
||||
| "/v2/tokens"
|
||||
| "/v2/trades"
|
||||
| "/v2/resolutions"
|
||||
| "/v2/prices-history",
|
||||
@@ -504,6 +519,7 @@ fn read_page<Q: serde::de::DeserializeOwned>(
|
||||
|
||||
fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value) {
|
||||
let page = match path {
|
||||
"/v2/tokens" => read_page(params, engine, Exchange::public_tokens),
|
||||
"/v2/oi" => read_page(params, engine, Exchange::public_open_interest),
|
||||
"/v2/value" => read_page(params, engine, Exchange::public_portfolio_value),
|
||||
"/v2/trades" => read_page(params, engine, Exchange::public_trade_feed),
|
||||
@@ -516,6 +532,10 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
|
||||
400,
|
||||
json!({"code":"invalid_request","error":message,"retryable":false}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/tokens" => (
|
||||
503,
|
||||
json!({"code":"unavailable","error":"token directory unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/oi" => (
|
||||
503,
|
||||
json!({"code":"unavailable","error":"open interest unavailable","retryable":true}),
|
||||
@@ -578,11 +598,8 @@ mod tests {
|
||||
fn socket_serves_single_and_batch_books_and_rejects_invalid_requests() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
let market = "map 2:胜者";
|
||||
let question = format!("0x{}", "ab".repeat(32));
|
||||
let transaction = format!("0x{}", "cd".repeat(32));
|
||||
db.execute(
|
||||
json!({"op":"list","id":"list","market":market,"rules":"simulated","tick_size":"0.01",
|
||||
"resolution":{"kind":"optimistic","eligible_at":0,"question_id":question}}),
|
||||
json!({"op":"list","id":"list","market":market,"rules":"simulated","tick_size":"0.01"}),
|
||||
)
|
||||
.unwrap();
|
||||
db.execute(json!({"op":"list","id":"path-market","market":"map+2/1","rules":"simulation","tick_size":"0.0025","base_fees":{"maker_bps":0,"taker_bps":30},"taker_fee_rate_ppm":50000})).unwrap();
|
||||
@@ -611,6 +628,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}),
|
||||
@@ -632,24 +652,15 @@ mod tests {
|
||||
let sample = json!({"eb:YES:mid-example":"0.085","eb:NO:mid-example":"0.915"});
|
||||
let pair = json!({"eb:YES:s":"0.4","eb:NO:s":"0.6","eb:YES:one":"0.6"});
|
||||
let price_batch = json!({"eb:YES:mid-example":{"BUY":"0.08","SELL":"0.09"},"eb:NO:mid-example":{"BUY":"0.91"},"eb:YES:one":{"BUY":"0.2"}});
|
||||
db.execute(json!({"op":"publish_clarification","id":"note","market":market,"content":"Map one includes overtime.","clear_book":false,"tx_hash":transaction})).unwrap();
|
||||
db.execute(json!({"op":"publish_clarification","id":"note","market":market,"content":"Map one includes overtime.","clear_book":false})).unwrap();
|
||||
let note = db
|
||||
.execute(json!({"op":"resolution","market":market}))
|
||||
.unwrap()["clarifications"]
|
||||
.clone();
|
||||
assert_eq!(note[0]["questionId"], question);
|
||||
assert_eq!(note[0]["txHash"], transaction);
|
||||
assert_eq!(note[0]["state"], "success");
|
||||
let note_id = note[0]["marketId"].as_i64().unwrap();
|
||||
let note_query = format!(
|
||||
"/market-clarifications?market_id=9999&market_id={note_id}&order=id&ascending=true"
|
||||
);
|
||||
let note_by_question = format!(
|
||||
"/market-clarifications?question_id=unknown&question_id=0x{}&tx_hash={transaction}&order=createdAt,id",
|
||||
question[2..].to_ascii_uppercase()
|
||||
);
|
||||
let note_wrong_hash =
|
||||
format!("/market-clarifications?question_id={question}&tx_hash=unknown");
|
||||
for command in include_str!("../../../docs/examples/topic.jsonl")
|
||||
.lines()
|
||||
.take(3)
|
||||
@@ -692,6 +703,10 @@ mod tests {
|
||||
assert_eq!(quoted["outcomePrices"], r#"["0.4","0.6"]"#);
|
||||
let empty_trades = json!({"data":[],"pagination":{"limit":100,"offset":0,"has_more":false,"next_cursor":null}});
|
||||
let cases = [
|
||||
("GET","/v2/tokens?token_ids=eb:NO:s,00123,eb:NO:s,eb:YES:s",String::new(),200,Some(db.public_tokens(serde_json::from_value(json!({"token_id":"eb:NO:s,123,eb:YES:s"})).unwrap()).unwrap())),
|
||||
("GET","/v2/tokens?condition=s&token_id=eb:YES:s",String::new(),400,None),
|
||||
("GET","/v2/tokens?token_id=00123,123",String::new(),200,Some(json!({"data":[]}))),
|
||||
("POST","/v2/tokens",String::new(),405,None),
|
||||
("GET","/v2/oi?conditionId=s,s",String::new(),200,Some(json!({"data":[{"condition_id":"s","value":0}]}))),
|
||||
("GET","/v2/oi?condition_id=0x0000000000000000000000000000000000000000000000000000000000000001",String::new(),200,Some(json!({"data":[]}))),
|
||||
("GET","/v2/oi?condition=bad-hash",String::new(),400,Some(json!({"code":"invalid_request","error":"invalid condition: bad-hash","retryable":false}))),
|
||||
@@ -730,14 +745,11 @@ mod tests {
|
||||
("GET","/events/999999",String::new(),404,None),
|
||||
("POST","/events/slug/test","{}".into(),405,None),
|
||||
("GET","/market-clarifications?event_id=1&event_id=2",String::new(),200,Some(json!([]))),
|
||||
("GET","/market-clarifications?event_id=0",String::new(),422,Some(json!({"type":"validation error","error":"error validating query argument \"event_id\": invalid integer value"}))),
|
||||
("GET","/market-clarifications?order=created_at",String::new(),422,Some(json!({"type":"validation error","error":"order fields are not valid"}))),
|
||||
("GET",note_by_question.as_str(),String::new(),200,Some(note.clone())),
|
||||
("GET",note_wrong_hash.as_str(),String::new(),200,Some(json!([]))),
|
||||
("GET",note_query.as_str(),String::new(),200,Some(note.clone())),
|
||||
("GET","/market-clarifications?limit=0",String::new(),200,Some(note.clone())),
|
||||
("GET","/market-clarifications?event_id=0",String::new(),400,None),
|
||||
("GET",note_query.as_str(),String::new(),200,Some(note)),
|
||||
("GET","/market-clarifications?limit=0",String::new(),200,Some(json!([]))),
|
||||
("GET","/market-clarifications?offset=1",String::new(),200,Some(json!([]))),
|
||||
("GET","/market-clarifications?limit=101",String::new(),200,Some(note)),
|
||||
("GET","/market-clarifications?limit=101",String::new(),400,None),
|
||||
("POST","/market-clarifications","{}".into(),405,None),
|
||||
("GET","/prices-history?market=eb:YES:missing&interval=1h&fidelity=10",String::new(),200,Some(json!({"history":[]}))),
|
||||
("GET","/prices-history?market=eb:NO:missing&startTs=1000&endTs=2000",String::new(),200,Some(json!({"history":[]}))),
|
||||
@@ -761,6 +773,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"}))),
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use exchange::{Exchange, PolymarketBinding};
|
||||
use reqwest::{blocking::Client, header, Url};
|
||||
use serde_json::{json, Value};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
io::{Read, Write},
|
||||
time::{Duration, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
const MAX_BODY_BYTES: u64 = 1_048_576;
|
||||
|
||||
fn fetch(client: &Client, binding: &PolymarketBinding) -> Result<(i64, Value)> {
|
||||
let url = Url::parse_with_params(
|
||||
"https://data-api.polymarket.com/v2/tokens",
|
||||
&[("condition", binding.condition.as_str())],
|
||||
)?;
|
||||
let response = client
|
||||
.get(url)
|
||||
.header(header::CACHE_CONTROL, "no-cache")
|
||||
.send()?;
|
||||
ensure!(
|
||||
response.status().is_success(),
|
||||
"directory returned HTTP {}",
|
||||
response.status()
|
||||
);
|
||||
let date = response
|
||||
.headers()
|
||||
.get(header::DATE)
|
||||
.context("missing Date")?
|
||||
.to_str()?;
|
||||
let observed_at = httpdate::parse_http_date(date)?.duration_since(UNIX_EPOCH)?;
|
||||
let observed_at = i64::try_from(observed_at.as_millis())?;
|
||||
let mut body = Vec::new();
|
||||
response.take(MAX_BODY_BYTES + 1).read_to_end(&mut body)?;
|
||||
ensure!(
|
||||
body.len() as u64 <= MAX_BODY_BYTES,
|
||||
"directory response too large"
|
||||
);
|
||||
Ok((observed_at, serde_json::from_slice(&body)?))
|
||||
}
|
||||
|
||||
fn command(binding: &PolymarketBinding, observed_at_ms: i64, body: Value) -> Result<Value> {
|
||||
let rows = body["data"].as_array().context("missing directory rows")?;
|
||||
let mut matched = BTreeMap::new();
|
||||
for row in rows {
|
||||
let token = row["token_id"]
|
||||
.as_str()
|
||||
.context("invalid token ID in response")?;
|
||||
if binding.token_ids.iter().any(|known| known == token) {
|
||||
ensure!(
|
||||
row["condition_id"] == binding.condition,
|
||||
"registered token changed condition"
|
||||
);
|
||||
ensure!(
|
||||
matched.insert(token, row).is_none(),
|
||||
"duplicate registered token"
|
||||
);
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
matched.len() == binding.token_ids.len(),
|
||||
"directory response omits a registered token"
|
||||
);
|
||||
let data: Vec<_> = matched.into_values().collect();
|
||||
Ok(json!({
|
||||
"id":format!("polymarket-observation:{}:{observed_at_ms}", binding.condition),
|
||||
"op":"bind_polymarket_assets","market":binding.market,
|
||||
"external_condition":binding.condition,"zero_outcome":binding.zero_outcome,
|
||||
"observed_at_ms":observed_at_ms,"data":data
|
||||
}))
|
||||
}
|
||||
|
||||
fn refresh(
|
||||
exchange: &mut Exchange,
|
||||
bindings: &[PolymarketBinding],
|
||||
mut fetch: impl FnMut(&PolymarketBinding) -> Result<(i64, Value)>,
|
||||
mut output: impl Write,
|
||||
) -> Result<()> {
|
||||
let mut failures = 0;
|
||||
for binding in bindings {
|
||||
let result = fetch(binding)
|
||||
.and_then(|(timestamp, body)| command(binding, timestamp, body))
|
||||
.and_then(|request| exchange.execute(request));
|
||||
let report = match result {
|
||||
Ok(receipt) => json!({"market":binding.market,"ok":true,"receipt":receipt}),
|
||||
Err(error) => {
|
||||
failures += 1;
|
||||
json!({"market":binding.market,"ok":false,"error":format!("{error:#}")})
|
||||
}
|
||||
};
|
||||
writeln!(output, "{report}")?;
|
||||
}
|
||||
ensure!(
|
||||
failures == 0,
|
||||
"{failures} Polymarket market(s) could not be refreshed"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn run(exchange: &mut Exchange, market: Option<&str>, output: impl Write) -> Result<()> {
|
||||
let bindings = exchange.polymarket_bindings(market)?;
|
||||
let client = Client::builder()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.timeout(Duration::from_secs(15))
|
||||
.user_agent("eventbook-readonly-refresh/0.1")
|
||||
.build()?;
|
||||
refresh(
|
||||
exchange,
|
||||
&bindings,
|
||||
|binding| fetch(&client, binding),
|
||||
output,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn refresh_survives_one_failed_market_and_retries_the_next_snapshot() {
|
||||
let fixture: Value = serde_json::from_str(include_str!(
|
||||
"../../../docs/examples/polymarket-asset-refresh.json"
|
||||
))
|
||||
.unwrap();
|
||||
let late = fixture["directory"]["observed_at_ms"].as_i64().unwrap();
|
||||
let resolved = fixture["directory"]["body"].clone();
|
||||
let mut e = Exchange::open(":memory:").unwrap();
|
||||
e.execute(json!({"op":"list","id":"list","market":"match","rules":"fixture"}))
|
||||
.unwrap();
|
||||
let bound_ids = resolved["data"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|row| row["token_id"].as_str().unwrap().to_owned())
|
||||
.collect();
|
||||
let good = PolymarketBinding {
|
||||
market: "match".into(),
|
||||
condition: resolved["data"][0]["condition_id"].as_str().unwrap().into(),
|
||||
zero_outcome: "NO".into(),
|
||||
token_ids: bound_ids,
|
||||
};
|
||||
let mut partial = resolved.clone();
|
||||
partial["data"].as_array_mut().unwrap().pop();
|
||||
assert!(command(&good, late, partial).is_err());
|
||||
let mut reordered = resolved.clone();
|
||||
reordered["data"].as_array_mut().unwrap().reverse();
|
||||
assert_eq!(
|
||||
command(&good, late, reordered).unwrap(),
|
||||
command(&good, late, resolved.clone()).unwrap()
|
||||
);
|
||||
let mut initial = command(&good, late - 1000, resolved.clone()).unwrap();
|
||||
initial.as_object_mut().unwrap().remove("observed_at_ms");
|
||||
e.execute(initial).unwrap();
|
||||
let mut out = Vec::new();
|
||||
let bad = PolymarketBinding {
|
||||
market: "unreachable".into(),
|
||||
condition: "unknown".into(),
|
||||
zero_outcome: "YES".into(),
|
||||
token_ids: vec![],
|
||||
};
|
||||
let bindings = [bad, good];
|
||||
assert!(refresh(
|
||||
&mut e,
|
||||
&bindings,
|
||||
|m| {
|
||||
ensure!(m.market != "unreachable", "simulated timeout");
|
||||
Ok((late, resolved.clone()))
|
||||
},
|
||||
&mut out
|
||||
)
|
||||
.is_err());
|
||||
let reports: Vec<Value> = std::str::from_utf8(&out)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.map(|line| serde_json::from_str(line).unwrap())
|
||||
.collect();
|
||||
assert_eq!(reports[0]["ok"], false);
|
||||
assert_eq!(reports[1]["ok"], true);
|
||||
refresh(
|
||||
&mut e,
|
||||
&bindings[1..],
|
||||
|_| Ok((late, resolved.clone())),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let recorded = e.polymarket_bindings(Some("match")).unwrap();
|
||||
assert_eq!(recorded[0].token_ids.len(), 4);
|
||||
let data = e
|
||||
.public_tokens(
|
||||
serde_json::from_value(json!({"condition":bindings[1].condition})).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(data["data"][0]["observed_at_ms"], late);
|
||||
}
|
||||
}
|
||||
@@ -1107,7 +1107,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 命令继续查询最优对手价。
|
||||
@@ -1133,7 +1133,7 @@ flowchart LR
|
||||
L --> A["assets.rs"]
|
||||
L --> Q["prices_history/legacy.sql"]
|
||||
Q --> T["quote_schema.sql 中的 quote_events"]
|
||||
Q --> O["prices_history/chart_schema.sql 中的采样起点和时间索引"]
|
||||
Q --> O["prices_history/chart_schema.sql 中的采样起点、封盘时间和时间索引"]
|
||||
API["lib.rs"] --> O
|
||||
Q --> S["schema.sql 中的 price_settlements"]
|
||||
```
|
||||
@@ -1145,7 +1145,7 @@ sequenceDiagram
|
||||
participant D as SQLite
|
||||
C->>E: clob_price_history
|
||||
E->>D: 清理到期委托并取得读快照与数据库时钟
|
||||
E->>D: 按 UTC 分钟网格重放各采样点当时的盘口,再读取最近可用点
|
||||
E->>D: 按 UTC 分钟网格重放盘口,封盘后只取窗口内的封盘前样本
|
||||
D-->>E: 观测时间和定点价格
|
||||
E-->>C: t 为 Unix 秒,p 为十进制数
|
||||
```
|
||||
@@ -1157,7 +1157,7 @@ flowchart LR
|
||||
C["command.rs"] --> M["market.rs"]
|
||||
M --> N["clarifications.rs"]
|
||||
N --> B["market.rs · clear_orders"] --> L["book.rs · release"]
|
||||
N --> S["schema.sql · market_clarifications / clarification_transactions / resolution_questions"]
|
||||
N --> S["schema.sql · market_clarifications"]
|
||||
R["resolution.rs"] --> N
|
||||
I["lib.rs · open"] --> D["event_directory_schema.sql"]
|
||||
A["catalog.rs · event / events / catalog"] --> D
|
||||
@@ -1171,14 +1171,14 @@ sequenceDiagram
|
||||
participant D as SQLite
|
||||
participant B as 常驻盘口
|
||||
O->>E: publish_clarification,携带请求 ID
|
||||
E->>D: 同一事务中保存原文、clear_book 和可选 tx_hash
|
||||
E->>D: 同一事务中保存原文和 clear_book
|
||||
opt 清盘
|
||||
E->>D: 撤销本市场所有存续委托,返还剩余现金或份额
|
||||
end
|
||||
E->>D: 保存回执并提交
|
||||
E->>B: 应用已提交的订单变更
|
||||
O->>E: 按事件目录 ID 查询公告
|
||||
E->>D: 关联事件目录、市场裁决问题和公告交易哈希,求交集后翻页
|
||||
E->>D: 匹配体育盘或主题盘口,取市场过滤交集后翻页
|
||||
D-->>E: 已筛选的公告
|
||||
E-->>O: 该页公告
|
||||
O->>E: resolution
|
||||
@@ -1434,3 +1434,30 @@ sequenceDiagram
|
||||
E-->>C: 返回本次两侧销毁量和实付金额
|
||||
end
|
||||
```
|
||||
|
||||
|
||||
### Data API 资产目录
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
http["cli/market_http.rs"] --> directory["token_directory.rs"]
|
||||
directory --> ids["assets.rs"]
|
||||
directory --> sql["token_directory.sql"]
|
||||
sql --> catalog["市场、事件目录和互斥组"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant H as HTTP
|
||||
participant E as public_tokens
|
||||
participant D as SQLite
|
||||
H->>E: 结果资产、市场条件或互斥组
|
||||
E->>E: 校验选择器、合并重复值
|
||||
E->>D: 同一快照读取目录、结果及裁决
|
||||
D-->>E: 结果标签、互补资产、事件及兑付
|
||||
E-->>H: 按请求顺序返回 data
|
||||
```
|
||||
|
||||
`bind_polymarket_assets` 将完整协议配对绑定到已创建的本地市场。操作员用 zero_outcome 声明外场结果索引 0 对应本地 YES 或 NO。绑定和请求回执在同一事务提交。数字资产、外场条件和已绑定的结构条件可通过 GET /v2/tokens 反查,响应附带 local_asset_id。完整的 V2 Neg Risk 事件 ID 展开该事件已绑定的仓位对,并按题目和结果位置排序。62 位十六进制结构条件只查询该题。旧 CTF 互斥组查询继续返回该组已绑定的两类资产。成交流程继续通过本地资产提交委托。
|
||||
|
||||
同一配对可携带 observed_at_ms 刷新外场状态。旧快照不会覆盖新状态,最终兑付冲突会回滚。
|
||||
|
||||
@@ -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)?);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ pub(crate) fn publish(
|
||||
market: &str,
|
||||
content: &str,
|
||||
clear_book: bool,
|
||||
tx_hash: Option<&str>,
|
||||
) -> Result<Value> {
|
||||
phase(tx, market, &["preopen", "continuous", "closed"])?;
|
||||
ensure!(!content.trim().is_empty(), "clarification text required");
|
||||
@@ -17,16 +16,6 @@ pub(crate) fn publish(
|
||||
params![market, content, clear_book],
|
||||
)?;
|
||||
let id = tx.last_insert_rowid();
|
||||
if let Some(hash) = tx_hash {
|
||||
ensure!(
|
||||
crate::validation::hex_id(hash, 64),
|
||||
"invalid clarification tx_hash"
|
||||
);
|
||||
tx.execute(
|
||||
"INSERT INTO clarification_transactions(clarification,tx_hash) VALUES(?1,?2)",
|
||||
params![id, hash],
|
||||
)?;
|
||||
}
|
||||
let canceled = if clear_book {
|
||||
market::clear_orders(tx, market)?
|
||||
} else {
|
||||
@@ -35,198 +24,46 @@ pub(crate) fn publish(
|
||||
Ok(json!({"id":id,"market":market,"clearBook":clear_book,"canceled_count":canceled}))
|
||||
}
|
||||
|
||||
pub struct ClarificationQuery {
|
||||
market_ids: Vec<i64>,
|
||||
event_ids: Vec<i64>,
|
||||
question_ids: Vec<String>,
|
||||
tx_hash: Option<String>,
|
||||
sort_columns: Vec<&'static str>,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
ascending: bool,
|
||||
}
|
||||
|
||||
impl ClarificationQuery {
|
||||
pub fn parse(fields: &[(String, String)]) -> Result<Self, &'static str> {
|
||||
let values = |key: &'static str| {
|
||||
fields
|
||||
.iter()
|
||||
.filter(move |(name, _)| name == key)
|
||||
.map(|(_, value)| value.as_str())
|
||||
};
|
||||
let integer = |key, default| {
|
||||
values(key).next().map_or(Ok(default), |value| {
|
||||
value.parse::<i64>().map_err(|_| "invalid integer")
|
||||
})
|
||||
};
|
||||
let ids = |key, invalid| {
|
||||
values(key)
|
||||
.map(|value| {
|
||||
let id = value.parse::<i64>().map_err(|_| "invalid integer")?;
|
||||
if id <= 0 {
|
||||
return Err(invalid);
|
||||
}
|
||||
Ok(id)
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
};
|
||||
let sort_columns = values("order")
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|key| !key.is_empty())
|
||||
.map(order_column)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let ascending = match values("ascending").next() {
|
||||
None | Some("1" | "t" | "T" | "true" | "TRUE" | "True") => true,
|
||||
Some("0" | "f" | "F" | "false" | "FALSE" | "False") => false,
|
||||
Some(_) => return Err("invalid boolean"),
|
||||
};
|
||||
let limit = integer("limit", 50)?;
|
||||
Ok(Self {
|
||||
market_ids: ids(
|
||||
"market_id",
|
||||
"error validating query argument \"market_id\": invalid integer value",
|
||||
)?,
|
||||
event_ids: ids(
|
||||
"event_id",
|
||||
"error validating query argument \"event_id\": invalid integer value",
|
||||
)?,
|
||||
question_ids: values("question_id")
|
||||
.filter(|id| !id.is_empty())
|
||||
.map(str::to_ascii_lowercase)
|
||||
.collect(),
|
||||
tx_hash: values("tx_hash")
|
||||
.next()
|
||||
.filter(|hash| !hash.is_empty())
|
||||
.map(str::to_owned),
|
||||
sort_columns,
|
||||
limit: if limit <= 0 { 50 } else { limit.min(100) },
|
||||
offset: integer("offset", 0)?.max(0),
|
||||
ascending,
|
||||
})
|
||||
}
|
||||
|
||||
fn by_id(
|
||||
market_ids: &[i64],
|
||||
event_ids: &[i64],
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
ascending: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
market_ids: market_ids.to_vec(),
|
||||
event_ids: event_ids.to_vec(),
|
||||
question_ids: Vec::new(),
|
||||
tx_hash: None,
|
||||
sort_columns: vec!["n.id"],
|
||||
limit,
|
||||
offset,
|
||||
ascending,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn order_column(key: &str) -> Result<&'static str, &'static str> {
|
||||
match key {
|
||||
"id" => Ok("n.id"),
|
||||
"marketId" => Ok("d.id"),
|
||||
"eventId" => Ok("e.id"),
|
||||
"questionId" => Ok("q.question_id"),
|
||||
"content" => Ok("n.content"),
|
||||
"clearBook" => Ok("n.clear_book"),
|
||||
"createdAt" => Ok("n.created_at"),
|
||||
"txHash" => Ok("x.tx_hash"),
|
||||
"state" | "notifyDiscord" | "showInFrontend" | "adapterAddress" | "negRiskRequestId"
|
||||
| "queuedAt" | "scheduledFor" | "txTimestamp" => Ok("NULL"),
|
||||
_ => Err("order fields are not valid"),
|
||||
}
|
||||
}
|
||||
|
||||
fn read(
|
||||
db: &Connection,
|
||||
market: Option<&str>,
|
||||
query: &ClarificationQuery,
|
||||
ids: &[i64],
|
||||
event_ids: &[i64],
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
ascending: bool,
|
||||
) -> rusqlite::Result<Vec<Value>> {
|
||||
let ids_json = json!(query.market_ids).to_string();
|
||||
let events_json = json!(query.event_ids).to_string();
|
||||
let questions_json = json!(query.question_ids).to_string();
|
||||
let (order, nulls) = if query.ascending {
|
||||
("ASC", "LAST")
|
||||
} else {
|
||||
("DESC", "FIRST")
|
||||
};
|
||||
let ordering = query
|
||||
.sort_columns
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(["n.id"])
|
||||
.map(|column| format!("{column} {order} NULLS {nulls}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let ids_json = json!(ids).to_string();
|
||||
let events_json = json!(event_ids).to_string();
|
||||
let order = if ascending { "ASC" } else { "DESC" };
|
||||
let sql = format!(
|
||||
"SELECT n.id,d.id,n.content,n.clear_book,n.created_at,e.id,q.question_id,x.tx_hash
|
||||
"SELECT n.id,d.id,n.content,n.clear_book,n.created_at
|
||||
FROM market_clarifications n JOIN market_directory_ids d ON d.market=n.market
|
||||
LEFT JOIN sports_markets s ON s.market=n.market
|
||||
LEFT JOIN topic_markets t ON t.market=n.market
|
||||
LEFT JOIN event_directory_ids e ON e.event=COALESCE(s.event,t.event)
|
||||
LEFT JOIN resolution_questions q ON q.market=n.market
|
||||
LEFT JOIN clarification_transactions x ON x.clarification=n.id
|
||||
WHERE (?1 IS NULL OR n.market=?1)
|
||||
AND (?2='[]' OR d.id IN (SELECT value FROM json_each(?2)))
|
||||
AND (?3='[]' OR e.id IN (SELECT value FROM json_each(?3)))
|
||||
AND (?4='[]' OR q.question_id IN (SELECT value FROM json_each(?4)))
|
||||
AND (?5 IS NULL OR x.tx_hash=?5)
|
||||
ORDER BY {ordering} LIMIT ?6 OFFSET ?7"
|
||||
ORDER BY n.id {order} LIMIT ?4 OFFSET ?5"
|
||||
);
|
||||
let mut stmt = db.prepare_cached(&sql)?;
|
||||
let rows = stmt.query_map(
|
||||
params![
|
||||
market,
|
||||
ids_json,
|
||||
events_json,
|
||||
questions_json,
|
||||
query.tx_hash,
|
||||
query.limit,
|
||||
query.offset
|
||||
],
|
||||
|r| {
|
||||
let mut row = json!({
|
||||
"id":r.get::<_,i64>(0)?, "marketId":r.get::<_,i64>(1)?,
|
||||
"content":r.get::<_,String>(2)?, "clearBook":r.get::<_,bool>(3)?,
|
||||
"createdAt":r.get::<_,String>(4)?, "showInFrontend":true, "state":"success",
|
||||
"notifyDiscord":false,
|
||||
"txTimestamp":null, "txHash":r.get::<_,Option<String>>(7)?
|
||||
});
|
||||
if let Some(event) = r.get::<_, Option<i64>>(5)? {
|
||||
row["eventId"] = json!(event);
|
||||
}
|
||||
if let Some(question) = r.get::<_, Option<String>>(6)? {
|
||||
row["questionId"] = json!(question);
|
||||
}
|
||||
Ok(row)
|
||||
},
|
||||
)?;
|
||||
let rows = stmt.query_map(params![market, ids_json, events_json, limit, offset], |r| {
|
||||
Ok(
|
||||
json!({"id":r.get::<_,i64>(0)?,"marketId":r.get::<_,i64>(1)?,
|
||||
"content":r.get::<_,String>(2)?,"clearBook":r.get::<_,bool>(3)?,
|
||||
"createdAt":r.get::<_,String>(4)?,"showInFrontend":true,
|
||||
"txTimestamp":null,"txHash":null}),
|
||||
)
|
||||
})?;
|
||||
rows.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn for_resolution(db: &Connection, market: &str) -> rusqlite::Result<Vec<Value>> {
|
||||
read(
|
||||
db,
|
||||
Some(market),
|
||||
&ClarificationQuery::by_id(&[], &[], -1, 0, true),
|
||||
)
|
||||
read(db, Some(market), &[], &[], -1, 0, true)
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn gamma_clarifications(
|
||||
&self,
|
||||
query: &ClarificationQuery,
|
||||
) -> Result<Vec<Value>, MarketDataError> {
|
||||
Ok(read(&self.db, None, query)?)
|
||||
}
|
||||
|
||||
pub fn market_clarifications(
|
||||
&self,
|
||||
ids: &[i64],
|
||||
@@ -250,12 +87,14 @@ impl Exchange {
|
||||
"invalid clarification filter".into(),
|
||||
));
|
||||
}
|
||||
self.gamma_clarifications(&ClarificationQuery::by_id(
|
||||
Ok(read(
|
||||
&self.db,
|
||||
None,
|
||||
ids,
|
||||
event_ids,
|
||||
i64::from(limit),
|
||||
offset,
|
||||
ascending,
|
||||
))
|
||||
)?)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ pub(crate) enum Command {
|
||||
micros: Option<i64>,
|
||||
},
|
||||
Event(crate::catalog::Event),
|
||||
#[serde(rename = "bind_polymarket_assets")]
|
||||
BindPolymarketAssets(crate::token_aliases::Bind),
|
||||
#[serde(rename = "reschedule_sports")]
|
||||
RescheduleSports {
|
||||
event: String,
|
||||
@@ -49,7 +51,6 @@ pub(crate) enum Command {
|
||||
market: String,
|
||||
content: String,
|
||||
clear_book: bool,
|
||||
tx_hash: Option<String>,
|
||||
},
|
||||
Clarify {
|
||||
market: String,
|
||||
|
||||
@@ -41,6 +41,8 @@ mod resident;
|
||||
mod resolution;
|
||||
mod tick_changes;
|
||||
mod tick_size;
|
||||
mod token_aliases;
|
||||
mod token_directory;
|
||||
use resident::Books;
|
||||
|
||||
use anyhow::{ensure, Context, Result};
|
||||
@@ -49,7 +51,6 @@ use serde_json::{json, Map, Value};
|
||||
use std::{path::Path, time::Duration};
|
||||
|
||||
pub use assets::parse_id as parse_asset_id;
|
||||
pub use clarifications::ClarificationQuery;
|
||||
pub use depth_feed::MarketPage;
|
||||
pub use gamma_directory::DirectoryKey;
|
||||
pub use gamma_list::DirectoryResource;
|
||||
@@ -60,6 +61,8 @@ pub use prices_history::legacy::ClobHistoryQuery;
|
||||
pub use public_trades::http::TradeQuery;
|
||||
pub use quotes::{PriceQueryError, PriceRequest, PriceSide};
|
||||
pub use resolution::http::ResolutionQuery;
|
||||
pub use token_aliases::PolymarketBinding;
|
||||
pub use token_directory::TokenDirectoryQuery;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum MarketDataError {
|
||||
@@ -122,7 +125,7 @@ impl Exchange {
|
||||
db.execute_batch(include_str!("quote_schema.sql"))?;
|
||||
}
|
||||
let history_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='trigger' AND name='chart_market_listed')",
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='trigger' AND name='chart_market_closed')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !history_ready {
|
||||
|
||||
@@ -16,6 +16,7 @@ pub(crate) fn apply(
|
||||
request_id: &str,
|
||||
) -> Result<Value> {
|
||||
match command {
|
||||
Command::BindPolymarketAssets(binding) => binding.register(tx),
|
||||
Command::Fund {
|
||||
account,
|
||||
cents,
|
||||
@@ -131,8 +132,7 @@ pub(crate) fn apply(
|
||||
market,
|
||||
content,
|
||||
clear_book,
|
||||
tx_hash,
|
||||
} => crate::clarifications::publish(tx, &market, &content, clear_book, tx_hash.as_deref()),
|
||||
} => crate::clarifications::publish(tx, &market, &content, clear_book),
|
||||
Command::Clarify {
|
||||
market,
|
||||
name,
|
||||
|
||||
@@ -12,4 +12,12 @@ END;
|
||||
INSERT OR IGNORE INTO chart_origins
|
||||
SELECT id,COALESCE((SELECT MIN(at_ms) FROM quote_events WHERE market=m.id),
|
||||
CAST(unixepoch('subsec')*1000 AS INTEGER)) FROM markets m;
|
||||
CREATE TABLE IF NOT EXISTS chart_closures (
|
||||
market TEXT PRIMARY KEY REFERENCES markets,
|
||||
at_ms INTEGER NOT NULL
|
||||
);
|
||||
CREATE TRIGGER IF NOT EXISTS chart_market_closed AFTER UPDATE OF phase ON markets
|
||||
WHEN NEW.phase='closed' AND OLD.phase<>'closed' BEGIN
|
||||
INSERT INTO chart_closures VALUES(NEW.id,CAST(unixepoch('subsec')*1000 AS INTEGER));
|
||||
END;
|
||||
COMMIT;
|
||||
|
||||
@@ -2,14 +2,16 @@
|
||||
-- The local sampler uses a UTC minute grid. The venue's collector has clock jitter.
|
||||
WITH RECURSIVE horizon AS (
|
||||
SELECT (SELECT at_ms FROM chart_origins WHERE market=?1) AS first_ms,
|
||||
(SELECT at_ms FROM price_settlements WHERE market=?1) AS resolved_ms,
|
||||
(SELECT winner FROM price_settlements WHERE market=?1) AS winner,
|
||||
(SELECT phase FROM markets WHERE id=?1) AS phase
|
||||
(SELECT at_ms FROM chart_closures WHERE market=?1) AS closed_ms,
|
||||
(SELECT phase IN ('closed','resolved') FROM markets WHERE id=?1) AS closed
|
||||
), bounds AS (
|
||||
SELECT first_ms, resolved_ms, winner,
|
||||
CASE WHEN phase='resolved' THEN COALESCE(resolved_ms,
|
||||
(SELECT MAX(at_ms) FROM quote_events WHERE market=?1))
|
||||
ELSE ?6/60000*60000 END AS last_ms
|
||||
SELECT first_ms, closed,
|
||||
CASE WHEN NOT closed THEN ?6/60000*60000
|
||||
WHEN closed_ms IS NOT NULL THEN closed_ms-1
|
||||
-- Old closed markets lack the close time. Use the last
|
||||
-- recorded nonempty quote and exclude the closing clear.
|
||||
ELSE (SELECT MAX(at_ms) FROM quote_events WHERE market=?1
|
||||
AND (yes_bid IS NOT NULL OR yes_ask IS NOT NULL)) END AS last_ms
|
||||
FROM horizon
|
||||
), grid(ms) AS (
|
||||
SELECT ((MAX(?3,first_ms)+?5-1)/?5)*?5 FROM bounds
|
||||
@@ -19,14 +21,12 @@ WITH RECURSIVE horizon AS (
|
||||
), points(ms,tail) AS (
|
||||
SELECT ms,0 FROM grid
|
||||
UNION ALL
|
||||
SELECT last_ms,1 FROM bounds WHERE resolved_ms IS NOT NULL OR first_ms<=last_ms
|
||||
SELECT last_ms,1 FROM bounds WHERE NOT closed AND first_ms<=last_ms
|
||||
)
|
||||
SELECT points.ms/1000,
|
||||
CASE WHEN points.ms=b.resolved_ms THEN
|
||||
CASE WHEN b.winner='VOID' THEN 500000 WHEN b.winner=?2 THEN 1000000 ELSE 0 END
|
||||
WHEN ?2='YES' THEN (COALESCE(q.yes_bid,0)+COALESCE(q.yes_ask,10000))*50
|
||||
CASE WHEN ?2='YES' THEN (COALESCE(q.yes_bid,0)+COALESCE(q.yes_ask,10000))*50
|
||||
ELSE 1000000-(COALESCE(q.yes_bid,0)+COALESCE(q.yes_ask,10000))*50 END
|
||||
FROM points CROSS JOIN bounds b
|
||||
FROM points
|
||||
LEFT JOIN quote_events q ON q.seq=(
|
||||
SELECT seq FROM quote_events WHERE market=?1 AND at_ms<=points.ms
|
||||
ORDER BY at_ms DESC,seq DESC LIMIT 1
|
||||
|
||||
@@ -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])?;
|
||||
|
||||
@@ -18,11 +18,6 @@ CREATE TABLE IF NOT EXISTS market_clarifications (
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS clarifications_by_market ON market_clarifications(market,id);
|
||||
CREATE TABLE IF NOT EXISTS clarification_transactions (
|
||||
clarification INTEGER PRIMARY KEY REFERENCES market_clarifications(id),
|
||||
tx_hash TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS clarifications_by_transaction ON clarification_transactions(tx_hash);
|
||||
CREATE TABLE IF NOT EXISTS positions (
|
||||
account TEXT REFERENCES accounts, market TEXT REFERENCES markets, outcome TEXT,
|
||||
quantity INTEGER NOT NULL CHECK(quantity >= 0), PRIMARY KEY(account,market,outcome)
|
||||
@@ -332,3 +327,29 @@ CREATE TABLE IF NOT EXISTS trade_cursor_key (
|
||||
);
|
||||
INSERT INTO trade_cursor_key(singleton,secret)
|
||||
SELECT 1,randomblob(32) WHERE NOT EXISTS(SELECT 1 FROM trade_cursor_key);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS polymarket_market_aliases (
|
||||
condition_id TEXT PRIMARY KEY,
|
||||
market TEXT NOT NULL UNIQUE REFERENCES markets(id),
|
||||
zero_outcome TEXT NOT NULL CHECK(zero_outcome IN ('YES','NO'))
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS polymarket_token_aliases (
|
||||
token_id TEXT PRIMARY KEY,
|
||||
condition_id TEXT NOT NULL REFERENCES polymarket_market_aliases(condition_id),
|
||||
module TEXT NOT NULL, structure TEXT, group_id TEXT, question INTEGER,
|
||||
slot INTEGER NOT NULL CHECK(slot IN (0,1)),
|
||||
observation TEXT NOT NULL CHECK(json_valid(observation)),
|
||||
UNIQUE(condition_id,module,slot)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS pm_alias_structures ON polymarket_token_aliases(structure);
|
||||
CREATE INDEX IF NOT EXISTS pm_alias_groups ON polymarket_token_aliases(group_id,question);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS pm_alias_structure_slots
|
||||
ON polymarket_token_aliases(structure,slot) WHERE structure IS NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS pm_alias_question_slots
|
||||
ON polymarket_token_aliases(group_id,question,module,slot) WHERE group_id IS NOT NULL;
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS polymarket_token_observation_times (
|
||||
token_id TEXT PRIMARY KEY REFERENCES polymarket_token_aliases(token_id),
|
||||
observed_at_ms INTEGER NOT NULL CHECK(observed_at_ms>0)
|
||||
);
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
use crate::{
|
||||
assets,
|
||||
token_directory::{condition_hex, decimal_token},
|
||||
validation::identifier,
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, OptionalExtension, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct Bind {
|
||||
market: String,
|
||||
external_condition: String,
|
||||
zero_outcome: String,
|
||||
observed_at_ms: Option<i64>,
|
||||
data: Vec<Value>,
|
||||
}
|
||||
|
||||
struct Row<'a> {
|
||||
token: &'a str,
|
||||
opposite: &'a str,
|
||||
module: &'a str,
|
||||
structure: Option<&'a str>,
|
||||
group: Option<&'a str>,
|
||||
slot: usize,
|
||||
question: Option<i64>,
|
||||
}
|
||||
|
||||
fn full_condition(id: &str) -> bool {
|
||||
id.len() == 66 && condition_hex(id).as_deref() == Some(id)
|
||||
}
|
||||
|
||||
fn position_id(raw: &str) -> [u8; 32] {
|
||||
// The decimal string has already been checked against uint256::MAX.
|
||||
let mut bytes = [0u8; 32];
|
||||
for digit in raw.bytes() {
|
||||
let mut carry = u16::from(digit - b'0');
|
||||
for byte in bytes.iter_mut().rev() {
|
||||
let next = u16::from(*byte) * 10 + carry;
|
||||
*byte = next as u8;
|
||||
carry = next >> 8;
|
||||
}
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
impl<'a> Row<'a> {
|
||||
fn read(row: &'a Value, condition: &str) -> Result<Self> {
|
||||
let token = row["token_id"].as_str().context("token_id is required")?;
|
||||
let opposite = row["opposite_token_id"]
|
||||
.as_str()
|
||||
.context("opposite_token_id is required")?;
|
||||
ensure!(
|
||||
decimal_token(token) == Some(token)
|
||||
&& decimal_token(opposite) == Some(opposite)
|
||||
&& token != opposite,
|
||||
"invalid external outcome identifiers"
|
||||
);
|
||||
ensure!(
|
||||
row["condition_id"] == condition,
|
||||
"external condition mismatch"
|
||||
);
|
||||
let module = row["module"].as_str().context("module is required")?;
|
||||
let slot = row["outcome_index"]
|
||||
.as_u64()
|
||||
.filter(|i| *i < 2)
|
||||
.context("invalid outcome index")? as usize;
|
||||
let structure = row["structural_condition_id"].as_str();
|
||||
let group = row["neg_risk_market_id"].as_str();
|
||||
let question = row["question_index"].as_i64();
|
||||
ensure!(
|
||||
group.is_some() == question.is_some()
|
||||
&& group.is_none_or(full_condition)
|
||||
&& question.is_none_or(|q| q >= 0),
|
||||
"invalid negative-risk question reference"
|
||||
);
|
||||
match module {
|
||||
"v1_ctf" => ensure!(
|
||||
row["structural_condition_id"].is_null(),
|
||||
"CTF has no structure ID"
|
||||
),
|
||||
"binary" | "neg_risk" => {
|
||||
ensure!(
|
||||
(module == "neg_risk") == group.is_some(),
|
||||
"V2 module mismatch"
|
||||
);
|
||||
let bytes = position_id(token);
|
||||
let other = position_id(opposite);
|
||||
let mut expected = String::from("0x");
|
||||
use std::fmt::Write;
|
||||
for byte in &bytes[..31] {
|
||||
write!(expected, "{byte:02x}")?;
|
||||
}
|
||||
expected.push_str("00");
|
||||
ensure!(
|
||||
structure == Some(expected.as_str())
|
||||
&& usize::from(bytes[31]) == slot
|
||||
&& bytes[..31] == other[..31]
|
||||
&& usize::from(other[31]) == 1 - slot,
|
||||
"V2 token does not encode the supplied condition and outcome"
|
||||
);
|
||||
}
|
||||
_ => anyhow::bail!("unsupported external token module"),
|
||||
}
|
||||
Ok(Self {
|
||||
token,
|
||||
opposite,
|
||||
module,
|
||||
structure,
|
||||
group,
|
||||
slot,
|
||||
question,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Bind {
|
||||
pub(crate) fn register(self, tx: &Transaction<'_>) -> Result<Value> {
|
||||
identifier(&self.market)?;
|
||||
ensure!(
|
||||
self.observed_at_ms.is_none_or(|ms| ms > 0),
|
||||
"invalid observation time"
|
||||
);
|
||||
ensure!(
|
||||
matches!(self.zero_outcome.as_str(), "YES" | "NO"),
|
||||
"zero_outcome must be YES or NO"
|
||||
);
|
||||
ensure!(
|
||||
full_condition(&self.external_condition),
|
||||
"expected a canonical external market condition"
|
||||
);
|
||||
ensure!(
|
||||
(2..=4).contains(&self.data.len()),
|
||||
"provide a complete outcome pair for each protocol"
|
||||
);
|
||||
let mut families = BTreeMap::new();
|
||||
for value in &self.data {
|
||||
let token = Row::read(value, &self.external_condition)?;
|
||||
let slot = token.slot;
|
||||
let pair = families.entry(token.module).or_insert_with(|| [None, None]);
|
||||
ensure!(
|
||||
pair[slot].replace(token).is_none(),
|
||||
"repeated protocol outcome"
|
||||
);
|
||||
}
|
||||
if self.observed_at_ms.is_some() {
|
||||
let mut states = BTreeMap::new();
|
||||
for value in &self.data {
|
||||
let row = Row::read(value, &self.external_condition)?;
|
||||
let state = SnapshotState::read(value)?;
|
||||
let pair = states.entry(row.module).or_insert_with(|| [None, None]);
|
||||
pair[row.slot] = Some(state);
|
||||
}
|
||||
for pair in states.values() {
|
||||
let [Some(a), Some(b)] = pair else {
|
||||
anyhow::bail!("incomplete protocol pair");
|
||||
};
|
||||
ensure!(
|
||||
a.closed == b.closed && a.resolved == b.resolved,
|
||||
"protocol pair has inconsistent lifecycle"
|
||||
);
|
||||
if let (Some(a), Some(b)) = (a.price, b.price) {
|
||||
ensure!((a + b - 1.0).abs() <= 1e-9, "final payouts must sum to one");
|
||||
}
|
||||
}
|
||||
}
|
||||
let v2_count = families.keys().filter(|m| **m != "v1_ctf").count();
|
||||
ensure!(v2_count <= 1, "multiple V2 protocols for the same market");
|
||||
let mut group_ref = None;
|
||||
for pair in families.values() {
|
||||
let [Some(a), Some(b)] = pair else {
|
||||
anyhow::bail!("incomplete protocol pair");
|
||||
};
|
||||
ensure!(
|
||||
a.opposite == b.token
|
||||
&& b.opposite == a.token
|
||||
&& a.structure == b.structure
|
||||
&& a.group == b.group
|
||||
&& a.question == b.question,
|
||||
"outcomes do not form one pair"
|
||||
);
|
||||
if let Some((group, question)) = group_ref {
|
||||
ensure!(
|
||||
(a.group, a.question) == (group, question),
|
||||
"protocols identify different questions"
|
||||
);
|
||||
}
|
||||
group_ref = Some((a.group, a.question));
|
||||
}
|
||||
let listed: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1)",
|
||||
[&self.market],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(listed, "unknown local market");
|
||||
tx.execute("INSERT INTO polymarket_market_aliases VALUES(?1,?2,?3) ON CONFLICT(condition_id) DO NOTHING",
|
||||
params![self.external_condition,self.market,self.zero_outcome])?;
|
||||
let bound: (String, String) = tx.query_row(
|
||||
"SELECT market,zero_outcome FROM polymarket_market_aliases WHERE condition_id=?1",
|
||||
[&self.external_condition],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)?;
|
||||
ensure!(
|
||||
bound == (self.market.clone(), self.zero_outcome.clone()),
|
||||
"market condition already bound with different identity"
|
||||
);
|
||||
let current_group: Option<(Option<String>, Option<i64>)> = tx.query_row(
|
||||
"SELECT group_id,question FROM polymarket_token_aliases WHERE condition_id=?1 LIMIT 1",
|
||||
[&self.external_condition], |row| Ok((row.get(0)?,row.get(1)?)),
|
||||
).optional()?;
|
||||
if let (Some((stored_group, stored_question)), Some((group, question))) =
|
||||
(current_group, group_ref)
|
||||
{
|
||||
ensure!(
|
||||
(stored_group.as_deref(), stored_question) == (group, question),
|
||||
"market already bound to a different question"
|
||||
);
|
||||
}
|
||||
for value in &self.data {
|
||||
let row = Row::read(value, &self.external_condition)?;
|
||||
// Only retain fields exposed by the external directory.
|
||||
let observation: serde_json::Map<_, _> = [
|
||||
"token_id",
|
||||
"condition_id",
|
||||
"structural_condition_id",
|
||||
"module",
|
||||
"outcome_index",
|
||||
"clob_index",
|
||||
"outcome",
|
||||
"opposite_token_id",
|
||||
"resolved",
|
||||
"final_price",
|
||||
"title",
|
||||
"market_slug",
|
||||
"closed",
|
||||
"neg_risk",
|
||||
"neg_risk_market_id",
|
||||
"question_index",
|
||||
"event_id",
|
||||
"event_slug",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|key| (key.to_owned(), value[key].clone()))
|
||||
.collect();
|
||||
let observation = Value::Object(observation);
|
||||
tx.execute(
|
||||
"INSERT INTO polymarket_token_aliases VALUES(?1,?2,?3,?4,?5,?6,?7,?8)
|
||||
ON CONFLICT(token_id) DO NOTHING",
|
||||
params![
|
||||
row.token,
|
||||
self.external_condition,
|
||||
row.module,
|
||||
row.structure,
|
||||
row.group,
|
||||
row.question,
|
||||
row.slot as i64,
|
||||
observation.to_string()
|
||||
],
|
||||
)?;
|
||||
let observed: Option<String> = tx
|
||||
.query_row(
|
||||
"SELECT observation FROM polymarket_token_aliases WHERE token_id=?1",
|
||||
[row.token],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
let prior: Value = serde_json::from_str(&observed.context("missing stored token")?)?;
|
||||
let prior_identity = Row::read(&prior, &self.external_condition)?;
|
||||
ensure!(
|
||||
prior_identity.module == row.module
|
||||
&& prior_identity.structure == row.structure
|
||||
&& prior_identity.slot == row.slot
|
||||
&& prior_identity.group == row.group
|
||||
&& prior_identity.question == row.question
|
||||
&& prior_identity.opposite == row.opposite,
|
||||
"token already bound with different identity"
|
||||
);
|
||||
if let Some(observed_at_ms) = self.observed_at_ms {
|
||||
refresh(tx, row.token, prior, &observation, observed_at_ms)?;
|
||||
}
|
||||
}
|
||||
Ok(
|
||||
json!({"market":self.market,"external_condition":self.external_condition,
|
||||
"zero_asset_id":assets::id(&self.market,&self.zero_outcome),"tokens":self.data.len()}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
struct SnapshotState {
|
||||
closed: bool,
|
||||
resolved: bool,
|
||||
price: Option<f64>,
|
||||
}
|
||||
|
||||
impl SnapshotState {
|
||||
fn read(data: &Value) -> Result<Self> {
|
||||
let closed = data["closed"]
|
||||
.as_bool()
|
||||
.context("closed must be a boolean")?;
|
||||
let resolved = data["resolved"]
|
||||
.as_bool()
|
||||
.context("resolved must be a boolean")?;
|
||||
let price = data["final_price"].as_f64();
|
||||
if resolved {
|
||||
ensure!(
|
||||
closed && price.is_some_and(|p| (0.0..=1.0).contains(&p)),
|
||||
"invalid final payout"
|
||||
);
|
||||
} else {
|
||||
ensure!(
|
||||
data["final_price"].is_null(),
|
||||
"unresolved asset has a final payout"
|
||||
);
|
||||
}
|
||||
Ok(Self {
|
||||
closed,
|
||||
resolved,
|
||||
price,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const LIVE_FIELDS: &[&str] = &["closed", "resolved", "final_price", "outcome"];
|
||||
|
||||
fn refresh(
|
||||
tx: &Transaction<'_>,
|
||||
token: &str,
|
||||
mut prior: Value,
|
||||
incoming: &Value,
|
||||
observed_at_ms: i64,
|
||||
) -> Result<()> {
|
||||
let last: Option<i64> = tx
|
||||
.query_row(
|
||||
"SELECT observed_at_ms FROM polymarket_token_observation_times WHERE token_id=?1",
|
||||
[token],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
if let Some(last) = last {
|
||||
if observed_at_ms < last {
|
||||
return Ok(());
|
||||
}
|
||||
if observed_at_ms == last {
|
||||
ensure!(
|
||||
LIVE_FIELDS.iter().all(|&key| prior[key] == incoming[key]),
|
||||
"conflicting observations at the same time"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if prior["resolved"] == true {
|
||||
ensure!(
|
||||
incoming["resolved"] == true
|
||||
&& prior["final_price"].as_f64() == incoming["final_price"].as_f64(),
|
||||
"observation contradicts a recorded final payout"
|
||||
);
|
||||
}
|
||||
for &key in LIVE_FIELDS {
|
||||
prior[key] = incoming[key].clone();
|
||||
}
|
||||
tx.execute(
|
||||
"UPDATE polymarket_token_aliases SET observation=?1 WHERE token_id=?2",
|
||||
params![prior.to_string(), token],
|
||||
)?;
|
||||
tx.execute(
|
||||
"INSERT INTO polymarket_token_observation_times VALUES(?1,?2)
|
||||
ON CONFLICT(token_id) DO UPDATE SET observed_at_ms=excluded.observed_at_ms",
|
||||
params![token, observed_at_ms],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An existing market mapping that can be refreshed from its upstream directory.
|
||||
pub struct PolymarketBinding {
|
||||
pub market: String,
|
||||
pub condition: String,
|
||||
pub zero_outcome: String,
|
||||
pub token_ids: Vec<String>,
|
||||
}
|
||||
|
||||
impl crate::Exchange {
|
||||
pub fn polymarket_bindings(&self, market: Option<&str>) -> Result<Vec<PolymarketBinding>> {
|
||||
let mut stmt = self.db.prepare_cached(
|
||||
"SELECT m.market,m.condition_id,m.zero_outcome,t.token_id
|
||||
FROM polymarket_market_aliases m JOIN polymarket_token_aliases t USING(condition_id)
|
||||
WHERE ?1 IS NULL OR m.market=?1
|
||||
ORDER BY m.market,t.token_id",
|
||||
)?;
|
||||
let mut rows = stmt.query([market])?;
|
||||
let mut bindings: Vec<PolymarketBinding> = Vec::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
let market: String = row.get(0)?;
|
||||
if let Some(last) = bindings.last_mut().filter(|last| last.market == market) {
|
||||
last.token_ids.push(row.get(3)?);
|
||||
} else {
|
||||
bindings.push(PolymarketBinding {
|
||||
market,
|
||||
condition: row.get(1)?,
|
||||
zero_outcome: row.get(2)?,
|
||||
token_ids: vec![row.get(3)?],
|
||||
});
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
market.is_none() || !bindings.is_empty(),
|
||||
"market has no Polymarket binding"
|
||||
);
|
||||
Ok(bindings)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
WITH selectors AS (
|
||||
SELECT key AS ordinal, json_extract(value,'$[0]') AS id,
|
||||
json_extract(value,'$[2]') AS kind
|
||||
FROM json_each(?1)
|
||||
), selector_ranges AS (
|
||||
-- The full Neg Risk event ID has a zero question index and outcome byte.
|
||||
-- Its 62-digit form still selects just the first condition.
|
||||
SELECT *,
|
||||
CASE WHEN kind='condition' AND length(id)=66
|
||||
AND substr(id,1,4)='0x02' AND substr(id,61)='000000'
|
||||
THEN substr(id,1,60)||'ffff00' END AS structural_event_end
|
||||
FROM selectors
|
||||
)
|
||||
SELECT s.ordinal,t.observation,m.market,
|
||||
CASE WHEN t.slot=0 THEN m.zero_outcome
|
||||
WHEN m.zero_outcome='YES' THEN 'NO' ELSE 'YES' END AS outcome,o.observed_at_ms
|
||||
FROM selector_ranges s
|
||||
JOIN polymarket_token_aliases t ON
|
||||
(s.kind='external_token' AND t.token_id=s.id)
|
||||
OR (s.kind='condition' AND
|
||||
(t.condition_id=s.id OR t.group_id=s.id OR t.structure=s.id OR t.structure=s.id||'00'
|
||||
OR (t.module='neg_risk' AND t.structure BETWEEN s.id AND s.structural_event_end)))
|
||||
JOIN polymarket_market_aliases m ON m.condition_id=t.condition_id
|
||||
LEFT JOIN polymarket_token_observation_times o ON o.token_id=t.token_id
|
||||
ORDER BY s.ordinal,t.question,t.condition_id,(t.module<>'v1_ctf'),t.slot
|
||||
@@ -0,0 +1,141 @@
|
||||
use crate::{assets, inventory::decimal, Exchange, MarketDataError};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashSet;
|
||||
|
||||
const MAX_TOKEN: &str =
|
||||
"115792089237316195423570985008687907853269984665640564039457584007913129639935";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TokenDirectoryQuery {
|
||||
#[serde(alias = "token_ids")]
|
||||
token_id: Option<String>,
|
||||
#[serde(alias = "condition_id", alias = "conditionId")]
|
||||
condition: Option<String>,
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> MarketDataError {
|
||||
MarketDataError::Invalid(message.into())
|
||||
}
|
||||
|
||||
pub(crate) fn condition_hex(value: &str) -> Option<String> {
|
||||
let hex = value
|
||||
.strip_prefix("0x")
|
||||
.or_else(|| value.strip_prefix("0X"))?;
|
||||
if !matches!(hex.len(), 62 | 64) || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
Some(format!("0x{}", hex.to_ascii_lowercase()))
|
||||
}
|
||||
|
||||
pub(crate) fn decimal_token(value: &str) -> Option<&str> {
|
||||
let digits = value.trim_start_matches('0');
|
||||
if value.is_empty()
|
||||
|| !value.bytes().all(|b| b.is_ascii_digit())
|
||||
|| digits.len() > MAX_TOKEN.len()
|
||||
|| (digits.len() == MAX_TOKEN.len() && digits > MAX_TOKEN)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(if digits.is_empty() { "0" } else { digits })
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_tokens(&self, query: TokenDirectoryQuery) -> Result<Value, MarketDataError> {
|
||||
let token = query.token_id.as_deref().filter(|s| !s.trim().is_empty());
|
||||
let condition = query.condition.as_deref().filter(|s| !s.trim().is_empty());
|
||||
let (raw, is_token, limit, selector) = match (token, condition) {
|
||||
(Some(raw), None) => (raw, true, 50, "token_id"),
|
||||
(None, Some(raw)) => (raw, false, 10, "condition"),
|
||||
_ => return Err(invalid("provide exactly one of 'token_id' or 'condition'")),
|
||||
};
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let mut seen = HashSet::new();
|
||||
let mut keys = Vec::new();
|
||||
for value in raw.split(',').map(str::trim) {
|
||||
let (key, outcome, kind) = if is_token {
|
||||
if let Ok((outcome, market)) = assets::parse_id(value) {
|
||||
(market.to_owned(), Some(outcome), "local_token")
|
||||
} else {
|
||||
let token = decimal_token(value)
|
||||
.ok_or_else(|| invalid(format!("invalid token id: {value}")))?;
|
||||
(token.to_owned(), None, "external_token")
|
||||
}
|
||||
} else if let Some(hex) = condition_hex(value) {
|
||||
(hex, None, "condition")
|
||||
} else {
|
||||
let listed: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1)
|
||||
OR EXISTS(SELECT 1 FROM neg_risk_groups WHERE id=?1)",
|
||||
[value],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
if !listed {
|
||||
return Err(invalid(format!("invalid condition id: {value}")));
|
||||
}
|
||||
(value.to_owned(), None, "condition")
|
||||
};
|
||||
if seen.insert((key.clone(), outcome)) {
|
||||
if seen.len() > limit {
|
||||
return Err(invalid(format!(
|
||||
"'{selector}' accepts at most {limit} distinct values"
|
||||
)));
|
||||
}
|
||||
keys.push((key, outcome, kind));
|
||||
}
|
||||
}
|
||||
let input = serde_json::to_string(&keys).map_err(|_| MarketDataError::Unavailable)?;
|
||||
let mut data = {
|
||||
let mut stmt = tx.prepare_cached(include_str!("token_directory.sql"))?;
|
||||
let rows = stmt.query_map([&input], |r| {
|
||||
let market: String = r.get(0)?;
|
||||
let phase: String = r.get(5)?;
|
||||
let winner: Option<String> = r.get(6)?;
|
||||
let index: i64 = r.get(7)?;
|
||||
let (outcome, other) = if index == 0 { ("YES", "NO") } else { ("NO", "YES") };
|
||||
let group: Option<String> = r.get(8)?;
|
||||
let price = winner.as_deref().filter(|_| phase=="resolved").map(|winner| {
|
||||
if winner == "VOID" { decimal(5,10) } else { decimal(i128::from(winner == outcome),1) }
|
||||
});
|
||||
Ok((r.get::<_, i64>(12)?, json!({
|
||||
"token_id":assets::id(&market,outcome),"condition_id":market,
|
||||
"structural_condition_id":null,"module":if group.is_some() { "local_neg_risk" } else { "local_binary" },
|
||||
"outcome_index":index,"clob_index":null,"outcome":r.get::<_,String>(if index==0 {3} else {4})?,
|
||||
"opposite_token_id":assets::id(&market,other),
|
||||
"resolved":phase=="resolved","closed":matches!(phase.as_str(),"closed"|"resolved"),
|
||||
"final_price":price,"title":r.get::<_,String>(1)?,"market_slug":r.get::<_,String>(2)?,
|
||||
"neg_risk":group.is_some(),"neg_risk_market_id":group,"question_index":r.get::<_,Option<i64>>(9)?,
|
||||
"event_id":r.get::<_,Option<i64>>(10)?,"event_slug":r.get::<_,Option<String>>(11)?
|
||||
})))
|
||||
})?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
};
|
||||
let externals = {
|
||||
let mut stmt = tx.prepare_cached(include_str!("token_aliases.sql"))?;
|
||||
let rows = stmt.query_map([&input], |r| {
|
||||
Ok((
|
||||
r.get::<_, i64>(0)?,
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, String>(2)?,
|
||||
r.get::<_, String>(3)?,
|
||||
r.get::<_, Option<i64>>(4)?,
|
||||
))
|
||||
})?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
};
|
||||
let external_ordinals: HashSet<_> = externals.iter().map(|r| r.0).collect();
|
||||
data.retain(|(ordinal, _)| !external_ordinals.contains(ordinal));
|
||||
for (ordinal, raw, market, outcome, observed_at_ms) in externals {
|
||||
let mut row: Value =
|
||||
serde_json::from_str(&raw).map_err(|_| MarketDataError::Unavailable)?;
|
||||
row["local_condition_id"] = json!(market);
|
||||
row["local_asset_id"] = json!(assets::id(&market, &outcome));
|
||||
row["observed_at_ms"] = json!(observed_at_ms);
|
||||
data.push((ordinal, row));
|
||||
}
|
||||
data.sort_by_key(|row| row.0);
|
||||
let data: Vec<_> = data.into_iter().map(|(_, row)| row).collect();
|
||||
tx.commit()?;
|
||||
Ok(json!({"data":data}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
WITH selectors AS (
|
||||
SELECT key AS ordinal, json_extract(value,'$[0]') AS market,
|
||||
json_extract(value,'$[1]') AS outcome, json_extract(value,'$[2]') AS kind
|
||||
FROM json_each(?1)
|
||||
), markets_selected AS (
|
||||
SELECT s.ordinal,m.id AS market,s.outcome
|
||||
FROM selectors s JOIN markets m ON m.id=s.market
|
||||
WHERE s.kind<>'external_token'
|
||||
UNION ALL
|
||||
SELECT s.ordinal,n.market,NULL
|
||||
FROM selectors s JOIN neg_risk_members n ON n.group_id=s.market
|
||||
WHERE s.kind='condition' AND s.outcome IS NULL AND NOT EXISTS (SELECT 1 FROM markets m WHERE m.id=s.market)
|
||||
), slots(outcome, outcome_index) AS (VALUES ('YES',0),('NO',1))
|
||||
SELECT m.id,w.question,w.slug,w.yes_label,w.no_label,m.phase,m.winner,s.outcome_index,
|
||||
n.group_id,n.ordinal,e.event_id,e.slug,x.ordinal
|
||||
FROM markets_selected x JOIN markets m ON m.id=x.market
|
||||
JOIN market_wire_metadata w ON w.market=x.market
|
||||
JOIN slots s ON x.outcome IS NULL OR s.outcome=x.outcome
|
||||
LEFT JOIN neg_risk_members n ON n.market=x.market
|
||||
LEFT JOIN listed_markets l ON l.market=x.market
|
||||
LEFT JOIN numbered_events e ON e.id=l.event
|
||||
ORDER BY x.ordinal,n.ordinal,m.id,s.outcome_index
|
||||
+202
-10
@@ -1553,21 +1553,23 @@ fn legacy_history_samples_the_book_without_fills_and_appends_the_latest_mark() {
|
||||
exchange
|
||||
.execute(json!({"op":"close","id":"close","market":"mid-example"}))
|
||||
.unwrap();
|
||||
db.execute("UPDATE chart_closures SET at_ms=273000", [])
|
||||
.unwrap();
|
||||
db.execute(
|
||||
"UPDATE quote_events SET at_ms=273000 WHERE yes_bid IS NULL AND yes_ask IS NULL",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
let before_close = vec![json!({"t":240,"p":0.915})];
|
||||
assert_eq!(read(&exchange, "NO", 180.001, 400.0), before_close);
|
||||
exchange
|
||||
.execute(json!({"op":"finalize","id":"verdict","market":"mid-example","winner":"NO"}))
|
||||
.unwrap();
|
||||
db.execute("UPDATE price_settlements SET at_ms=273000", [])
|
||||
.unwrap();
|
||||
drop(exchange);
|
||||
let reopened = Exchange::open(path).unwrap();
|
||||
assert_eq!(
|
||||
read(&reopened, "NO", 180.001, 240.0),
|
||||
vec![json!({"t":240,"p":0.915}), json!({"t":273,"p":1})]
|
||||
);
|
||||
assert_eq!(
|
||||
read(&reopened, "YES", 5.0, 5.0),
|
||||
vec![json!({"t":273,"p":0})]
|
||||
);
|
||||
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());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -4176,3 +4178,193 @@ fn order_submission_terms_survive_fills_cancel_retries_and_legacy_upgrade() {
|
||||
assert_eq!(e.execute(cmd.clone()).unwrap()["orders"][0], expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_token_directory_routes_results_and_expands_negative_risk_groups() {
|
||||
let mut exchange = Exchange::open(":memory:").unwrap();
|
||||
for line in include_str!("../../../docs/examples/neg-risk.jsonl")
|
||||
.lines()
|
||||
.take(5)
|
||||
{
|
||||
exchange
|
||||
.execute(serde_json::from_str(line).unwrap())
|
||||
.unwrap();
|
||||
}
|
||||
let read = |e: &Exchange, value| {
|
||||
e.public_tokens(serde_json::from_value(value).unwrap())
|
||||
.unwrap()["data"]
|
||||
.clone()
|
||||
};
|
||||
let group = read(&exchange, json!({"condition":"winner"}));
|
||||
assert_eq!(group.as_array().unwrap().len(), 6);
|
||||
assert_eq!(group[0]["condition_id"], "a");
|
||||
assert_eq!(group[0]["question_index"], 0);
|
||||
assert_eq!(group[1]["opposite_token_id"], group[0]["token_id"]);
|
||||
assert_eq!(group[4]["condition_id"], "other");
|
||||
assert!(group[0]["event_id"].is_number());
|
||||
let rows = read(
|
||||
&exchange,
|
||||
json!({"token_ids":"eb:NO:a,123,eb:YES:a,eb:NO:a"}),
|
||||
);
|
||||
assert_eq!(rows, json!([group[1], group[0]]));
|
||||
assert_eq!(rows[0]["final_price"], Value::Null);
|
||||
setup(&mut exchange);
|
||||
exchange
|
||||
.execute(json!({"op":"close","id":"close-e","market":"e"}))
|
||||
.unwrap();
|
||||
exchange
|
||||
.execute(json!({"op":"finalize","id":"void-e","market":"e","winner":"VOID"}))
|
||||
.unwrap();
|
||||
let voided = read(&exchange, json!({"conditionId":"e"}));
|
||||
assert_eq!(voided[0]["closed"], true);
|
||||
assert_eq!(voided[1]["resolved"], true);
|
||||
assert_eq!(voided[0]["final_price"], 0.5);
|
||||
assert_eq!(voided[1]["final_price"], 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polymarket_asset_bindings_preserve_protocols_and_explicit_outcome_direction() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("venue-ids.db");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
setup(&mut e);
|
||||
let fixture: Value = serde_json::from_str(include_str!(
|
||||
"../../../docs/examples/polymarket-asset-binding.json"
|
||||
))
|
||||
.unwrap();
|
||||
let mut command = json!({"op":"bind_polymarket_assets","id":"bind","market":"e","zero_outcome":"NO",
|
||||
"external_condition":fixture["external_condition"], "data":fixture["data"]});
|
||||
let receipt = e.execute(command.clone()).unwrap();
|
||||
assert_eq!(receipt["tokens"], 4);
|
||||
assert_eq!(e.execute(command.clone()).unwrap(), receipt);
|
||||
command["id"] = json!("flipped");
|
||||
command["zero_outcome"] = json!("YES");
|
||||
assert!(e.execute(command).is_err());
|
||||
drop(e);
|
||||
let e = Exchange::open(path).unwrap();
|
||||
let lookup = |query| {
|
||||
e.public_tokens(serde_json::from_value(query).unwrap())
|
||||
.unwrap()
|
||||
};
|
||||
let condition = lookup(json!({"condition":fixture["external_condition"]}));
|
||||
let rows = condition["data"].as_array().unwrap();
|
||||
assert_eq!(rows.len(), 4);
|
||||
assert_eq!(rows[0]["module"], "v1_ctf");
|
||||
assert_eq!(rows[2]["module"], "neg_risk");
|
||||
assert_eq!(rows[2]["local_asset_id"], "eb:NO:e");
|
||||
assert_eq!(rows[3]["local_asset_id"], "eb:YES:e");
|
||||
let structural = rows[2]["structural_condition_id"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
lookup(json!({"condition":&structural[..64]}))["data"],
|
||||
json!([rows[2], rows[3]])
|
||||
);
|
||||
let token = rows[3]["token_id"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
lookup(json!({"token_id":format!("00{token},00123,eb:NO:e")}))["data"][0],
|
||||
rows[3]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structural_event_expands_registered_position_pairs_and_compact_condition_selects_one() {
|
||||
let mut engine = Exchange::open(":memory:").unwrap();
|
||||
let fixture: Value = serde_json::from_str(include_str!(
|
||||
"../../../docs/examples/polymarket-token-event.json"
|
||||
))
|
||||
.unwrap();
|
||||
let rows = fixture["data"].as_array().unwrap();
|
||||
// Register in reverse order so lookup cannot rely on insertion order.
|
||||
for pair in rows.chunks_exact(4).rev() {
|
||||
let question = pair[0]["question_index"].as_i64().unwrap();
|
||||
let market = format!("match-winner-{question}");
|
||||
engine
|
||||
.execute(json!({"op":"list","id":format!("list-{question}"),
|
||||
"market":market,"rules":"Registered match winner"}))
|
||||
.unwrap();
|
||||
engine
|
||||
.execute(
|
||||
json!({"op":"bind_polymarket_assets","id":format!("bind-{question}"),
|
||||
"market":market,"zero_outcome":"YES","external_condition":pair[0]["condition_id"],
|
||||
"data":pair}),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let lookup = |condition: &str| {
|
||||
engine
|
||||
.public_tokens(serde_json::from_value(json!({"condition":condition})).unwrap())
|
||||
.unwrap()["data"]
|
||||
.clone()
|
||||
};
|
||||
let event = rows[2]["structural_condition_id"].as_str().unwrap();
|
||||
let expanded = lookup(event);
|
||||
let positions = expanded.as_array().unwrap();
|
||||
assert_eq!(positions.len(), 6);
|
||||
for (position, captured) in positions
|
||||
.iter()
|
||||
.zip(rows.iter().filter(|r| r["module"] == "neg_risk"))
|
||||
{
|
||||
assert_eq!(position["token_id"], captured["token_id"]);
|
||||
assert_eq!(position["question_index"], captured["question_index"]);
|
||||
}
|
||||
|
||||
let compact = &event[..64];
|
||||
assert_eq!(lookup(compact), json!([positions[0], positions[1]]));
|
||||
let question_two = rows[10]["structural_condition_id"].as_str().unwrap();
|
||||
assert_eq!(lookup(question_two), json!([positions[4], positions[5]]));
|
||||
let legacy_group = rows[0]["neg_risk_market_id"].as_str().unwrap();
|
||||
assert_eq!(lookup(legacy_group).as_array().unwrap().len(), 12);
|
||||
let legacy_condition = rows[0]["condition_id"].as_str().unwrap();
|
||||
assert_eq!(lookup(legacy_condition).as_array().unwrap().len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polymarket_observations_refresh_without_reverting_a_final_payout() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("refresh.db");
|
||||
let mut engine = Exchange::open(&path).unwrap();
|
||||
setup(&mut engine);
|
||||
let fixture: Value = serde_json::from_str(include_str!(
|
||||
"../../../docs/examples/polymarket-asset-refresh.json"
|
||||
))
|
||||
.unwrap();
|
||||
let resolved = fixture["directory"]["body"]["data"].clone();
|
||||
let mut open = resolved.clone();
|
||||
for item in open.as_array_mut().unwrap() {
|
||||
item["closed"] = json!(false);
|
||||
item["resolved"] = json!(false);
|
||||
item["final_price"] = Value::Null;
|
||||
}
|
||||
let late = fixture["directory"]["observed_at_ms"].as_i64().unwrap();
|
||||
let early = fixture["prior_book"]["observed_at_ms"].as_i64().unwrap();
|
||||
let condition = &resolved[0]["condition_id"];
|
||||
let obs = |id, stamp, rows: &Value| {
|
||||
json!({
|
||||
"op":"bind_polymarket_assets", "id":id,"market":"e","zero_outcome":"YES",
|
||||
"external_condition":condition,"observed_at_ms":stamp,"data":rows
|
||||
})
|
||||
};
|
||||
engine.execute(obs("before", early, &open)).unwrap();
|
||||
engine.execute(obs("final", late, &resolved)).unwrap();
|
||||
engine.execute(obs("old", early, &open)).unwrap();
|
||||
assert!(engine
|
||||
.execute(obs("same-time-conflict", late, &open))
|
||||
.is_err());
|
||||
assert!(engine
|
||||
.execute(obs("new-conflict", late + 1, &open))
|
||||
.is_err());
|
||||
drop(engine);
|
||||
let engine = Exchange::open(path).unwrap();
|
||||
let lookup = engine
|
||||
.public_tokens(serde_json::from_value(json!({"condition":condition})).unwrap())
|
||||
.unwrap();
|
||||
let rows = lookup["data"].as_array().unwrap();
|
||||
assert_eq!(rows.len(), 4);
|
||||
for row in rows {
|
||||
assert_eq!(row["resolved"], true);
|
||||
assert_eq!(row["observed_at_ms"], late);
|
||||
}
|
||||
let local = engine
|
||||
.public_tokens(serde_json::from_value(json!({"condition":"e"})).unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(local["data"][0]["resolved"], false);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
{
|
||||
"source": "https://data-api.polymarket.com/v2/tokens?condition=0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"date": "Fri, 04 Dec 2026 21:03:26 GMT",
|
||||
"external_condition": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"data": [
|
||||
{
|
||||
"token_id": "56766704504589537417119461476407464198158915644205212964421261364010493123785",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 0,
|
||||
"clob_index": 0,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "33748178601941852783056114873418965902944929138778460252404676407918318867810",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "33748178601941852783056114873418965902944929138778460252404676407918318867810",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 1,
|
||||
"clob_index": 1,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "56766704504589537417119461476407464198158915644205212964421261364010493123785",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179072",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000200",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 0,
|
||||
"clob_index": null,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179073",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179073",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000200",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 1,
|
||||
"clob_index": null,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179072",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
{
|
||||
"prior_book": {
|
||||
"url": "https://clob.polymarket.com/book?token_id=64069535502365350520464017439278800338614209934309608490621606944970108681676",
|
||||
"date": "Thu, 03 Dec 2026 07:55:53 GMT",
|
||||
"status": 200,
|
||||
"body": {
|
||||
"market": "0xe5febd2f236a15ef7c1cc70a481e081bb64223d3e67aa3870677cccd72530853",
|
||||
"asset_id": "64069535502365350520464017439278800338614209934309608490621606944970108681676",
|
||||
"timestamp": "1796284481649",
|
||||
"hash": "575e315a02461b9280427591ba1fe7e48b3b70ce",
|
||||
"bids": [],
|
||||
"asks": [],
|
||||
"min_order_size": "5",
|
||||
"tick_size": "0.01",
|
||||
"neg_risk": false,
|
||||
"last_trade_price": ""
|
||||
},
|
||||
"observed_at_ms": 1796284553000
|
||||
},
|
||||
"directory": {
|
||||
"url": "https://data-api.polymarket.com/v2/tokens?condition=0xe5febd2f236a15ef7c1cc70a481e081bb64223d3e67aa3870677cccd72530853",
|
||||
"status": 200,
|
||||
"date": "Fri, 04 Dec 2026 21:11:06 GMT",
|
||||
"body": {
|
||||
"data": [
|
||||
{
|
||||
"token_id": "64069535502365350520464017439278800338614209934309608490621606944970108681676",
|
||||
"condition_id": "0xe5febd2f236a15ef7c1cc70a481e081bb64223d3e67aa3870677cccd72530853",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 0,
|
||||
"clob_index": 0,
|
||||
"outcome": "Over",
|
||||
"opposite_token_id": "24637903833591077899504141654082654473942967248855682279041797174393952421575",
|
||||
"resolved": true,
|
||||
"final_price": 0.0,
|
||||
"title": "Map 1 Total Rounds: Over/Under 27.5",
|
||||
"market_slug": "cs2-bb3-lgc-2026-12-03-game1-round-total-27pt5",
|
||||
"closed": true,
|
||||
"neg_risk": false,
|
||||
"neg_risk_market_id": null,
|
||||
"question_index": null,
|
||||
"event_id": 1495714,
|
||||
"event_slug": "cs2-bb3-lgc-2026-12-03"
|
||||
},
|
||||
{
|
||||
"token_id": "24637903833591077899504141654082654473942967248855682279041797174393952421575",
|
||||
"condition_id": "0xe5febd2f236a15ef7c1cc70a481e081bb64223d3e67aa3870677cccd72530853",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 1,
|
||||
"clob_index": 1,
|
||||
"outcome": "Under",
|
||||
"opposite_token_id": "64069535502365350520464017439278800338614209934309608490621606944970108681676",
|
||||
"resolved": true,
|
||||
"final_price": 1.0,
|
||||
"title": "Map 1 Total Rounds: Over/Under 27.5",
|
||||
"market_slug": "cs2-bb3-lgc-2026-12-03-game1-round-total-27pt5",
|
||||
"closed": true,
|
||||
"neg_risk": false,
|
||||
"neg_risk_market_id": null,
|
||||
"question_index": null,
|
||||
"event_id": 1495714,
|
||||
"event_slug": "cs2-bb3-lgc-2026-12-03"
|
||||
},
|
||||
{
|
||||
"token_id": "774335495545660990871175894688282765790269993344601020630233166497523433472",
|
||||
"condition_id": "0xe5febd2f236a15ef7c1cc70a481e081bb64223d3e67aa3870677cccd72530853",
|
||||
"structural_condition_id": "0x01b64223d3e67aa3870677cccd72530853000000000000000000000000000000",
|
||||
"module": "binary",
|
||||
"outcome_index": 0,
|
||||
"clob_index": null,
|
||||
"outcome": "Over",
|
||||
"opposite_token_id": "774335495545660990871175894688282765790269993344601020630233166497523433473",
|
||||
"resolved": true,
|
||||
"final_price": 0.0,
|
||||
"title": "Map 1 Total Rounds: Over/Under 27.5",
|
||||
"market_slug": "cs2-bb3-lgc-2026-12-03-game1-round-total-27pt5",
|
||||
"closed": true,
|
||||
"neg_risk": false,
|
||||
"neg_risk_market_id": null,
|
||||
"question_index": null,
|
||||
"event_id": 1495714,
|
||||
"event_slug": "cs2-bb3-lgc-2026-12-03"
|
||||
},
|
||||
{
|
||||
"token_id": "774335495545660990871175894688282765790269993344601020630233166497523433473",
|
||||
"condition_id": "0xe5febd2f236a15ef7c1cc70a481e081bb64223d3e67aa3870677cccd72530853",
|
||||
"structural_condition_id": "0x01b64223d3e67aa3870677cccd72530853000000000000000000000000000000",
|
||||
"module": "binary",
|
||||
"outcome_index": 1,
|
||||
"clob_index": null,
|
||||
"outcome": "Under",
|
||||
"opposite_token_id": "774335495545660990871175894688282765790269993344601020630233166497523433472",
|
||||
"resolved": true,
|
||||
"final_price": 1.0,
|
||||
"title": "Map 1 Total Rounds: Over/Under 27.5",
|
||||
"market_slug": "cs2-bb3-lgc-2026-12-03-game1-round-total-27pt5",
|
||||
"closed": true,
|
||||
"neg_risk": false,
|
||||
"neg_risk_market_id": null,
|
||||
"question_index": null,
|
||||
"event_id": 1495714,
|
||||
"event_slug": "cs2-bb3-lgc-2026-12-03"
|
||||
}
|
||||
]
|
||||
},
|
||||
"observed_at_ms": 1796418666000
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
{
|
||||
"source_url": "https://data-api.polymarket.com/v2/tokens?condition=0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"captured_at": "Fri, 04 Dec 2026 21:03:58 GMT",
|
||||
"data": [
|
||||
{
|
||||
"token_id": "40384919342148672870770945432101495451968327778097401039020519003208568963549",
|
||||
"condition_id": "0x5364a90051fdd64d447207fe670842efab39bf873d37d88bbb77f7aa282a3577",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 0,
|
||||
"clob_index": 0,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "13408982299269116806894777758021694013482652654029730596500219066110331544576",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Toulouse FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-tou",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 0,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "13408982299269116806894777758021694013482652654029730596500219066110331544576",
|
||||
"condition_id": "0x5364a90051fdd64d447207fe670842efab39bf873d37d88bbb77f7aa282a3577",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 1,
|
||||
"clob_index": 1,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "40384919342148672870770945432101495451968327778097401039020519003208568963549",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Toulouse FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-tou",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 0,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458178560",
|
||||
"condition_id": "0x5364a90051fdd64d447207fe670842efab39bf873d37d88bbb77f7aa282a3577",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000000",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 0,
|
||||
"clob_index": null,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458178561",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Toulouse FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-tou",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 0,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458178561",
|
||||
"condition_id": "0x5364a90051fdd64d447207fe670842efab39bf873d37d88bbb77f7aa282a3577",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000000",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 1,
|
||||
"clob_index": null,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458178560",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Toulouse FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-tou",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 0,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "103333010293518730378106572744460037514611059173916399171749440880269466461468",
|
||||
"condition_id": "0x80c4b761829cd055b8bd990cbb04c9f0bad007aeaae6cc0ff39807cf3303d604",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 0,
|
||||
"clob_index": 0,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "98082619073142377808975564447235447133706299255372243296223031730369079572279",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Toulouse FC vs. Paris Saint-Germain FC end in a draw?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-draw",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 1,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "98082619073142377808975564447235447133706299255372243296223031730369079572279",
|
||||
"condition_id": "0x80c4b761829cd055b8bd990cbb04c9f0bad007aeaae6cc0ff39807cf3303d604",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 1,
|
||||
"clob_index": 1,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "103333010293518730378106572744460037514611059173916399171749440880269466461468",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Toulouse FC vs. Paris Saint-Germain FC end in a draw?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-draw",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 1,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458178816",
|
||||
"condition_id": "0x80c4b761829cd055b8bd990cbb04c9f0bad007aeaae6cc0ff39807cf3303d604",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000100",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 0,
|
||||
"clob_index": null,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458178817",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Toulouse FC vs. Paris Saint-Germain FC end in a draw?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-draw",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 1,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458178817",
|
||||
"condition_id": "0x80c4b761829cd055b8bd990cbb04c9f0bad007aeaae6cc0ff39807cf3303d604",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000100",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 1,
|
||||
"clob_index": null,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458178816",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Toulouse FC vs. Paris Saint-Germain FC end in a draw?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-draw",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 1,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "56766704504589537417119461476407464198158915644205212964421261364010493123785",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 0,
|
||||
"clob_index": 0,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "33748178601941852783056114873418965902944929138778460252404676407918318867810",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "33748178601941852783056114873418965902944929138778460252404676407918318867810",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 1,
|
||||
"clob_index": 1,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "56766704504589537417119461476407464198158915644205212964421261364010493123785",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179072",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000200",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 0,
|
||||
"clob_index": null,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179073",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179073",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000200",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 1,
|
||||
"clob_index": null,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179072",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,597 @@
|
||||
[
|
||||
{
|
||||
"catalog_url": "https://gamma-api.polymarket.com/markets?closed=true&limit=100&order=closedTime&ascending=false",
|
||||
"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\"]"
|
||||
},
|
||||
"sides": [
|
||||
{
|
||||
"asset": "73979342585906843441145134109923710004884703083095161594360108477170435492453",
|
||||
"around": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=73979342585906843441145134109923710004884703083095161594360108477170435492453&startTs=1796284923&endTs=1796288523&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:56 GMT",
|
||||
"body": {
|
||||
"history": [
|
||||
{
|
||||
"t": 1796285541,
|
||||
"p": 0.1
|
||||
},
|
||||
{
|
||||
"t": 1796285655,
|
||||
"p": 0.1
|
||||
},
|
||||
{
|
||||
"t": 1796285780,
|
||||
"p": 0.1
|
||||
},
|
||||
{
|
||||
"t": 1796285889,
|
||||
"p": 0.1
|
||||
},
|
||||
{
|
||||
"t": 1796286038,
|
||||
"p": 0.1
|
||||
},
|
||||
{
|
||||
"t": 1796286155,
|
||||
"p": 0.1
|
||||
},
|
||||
{
|
||||
"t": 1796286252,
|
||||
"p": 0.005
|
||||
},
|
||||
{
|
||||
"t": 1796286383,
|
||||
"p": 0.0005
|
||||
},
|
||||
{
|
||||
"t": 1796286495,
|
||||
"p": 0.0005
|
||||
},
|
||||
{
|
||||
"t": 1796286646,
|
||||
"p": 0.0005
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=73979342585906843441145134109923710004884703083095161594360108477170435492453&startTs=1796290323&endTs=1796290623&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:56 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
},
|
||||
"ancient": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=73979342585906843441145134109923710004884703083095161594360108477170435492453&startTs=120&endTs=245",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:56 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"asset": "78188826358032258311424545486331333398838521699262460256542567713692269401385",
|
||||
"around": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=78188826358032258311424545486331333398838521699262460256542567713692269401385&startTs=1796284923&endTs=1796288523&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:58 GMT",
|
||||
"body": {
|
||||
"history": [
|
||||
{
|
||||
"t": 1796285540,
|
||||
"p": 0.9
|
||||
},
|
||||
{
|
||||
"t": 1796285654,
|
||||
"p": 0.9
|
||||
},
|
||||
{
|
||||
"t": 1796285780,
|
||||
"p": 0.9
|
||||
},
|
||||
{
|
||||
"t": 1796285889,
|
||||
"p": 0.9
|
||||
},
|
||||
{
|
||||
"t": 1796286037,
|
||||
"p": 0.9
|
||||
},
|
||||
{
|
||||
"t": 1796286155,
|
||||
"p": 0.9
|
||||
},
|
||||
{
|
||||
"t": 1796286252,
|
||||
"p": 0.995
|
||||
},
|
||||
{
|
||||
"t": 1796286383,
|
||||
"p": 0.9995
|
||||
},
|
||||
{
|
||||
"t": 1796286495,
|
||||
"p": 0.9995
|
||||
},
|
||||
{
|
||||
"t": 1796286646,
|
||||
"p": 0.9995
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=78188826358032258311424545486331333398838521699262460256542567713692269401385&startTs=1796290323&endTs=1796290623&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:58 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
},
|
||||
"ancient": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=78188826358032258311424545486331333398838521699262460256542567713692269401385&startTs=120&endTs=245",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:58 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"catalog_url": "https://gamma-api.polymarket.com/markets?closed=true&limit=100&order=closedTime&ascending=false",
|
||||
"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\"]"
|
||||
},
|
||||
"sides": [
|
||||
{
|
||||
"asset": "759916398134244316868652908232832573045153963965173623897622651599218278400",
|
||||
"around": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=759916398134244316868652908232832573045153963965173623897622651599218278400&startTs=1796284860&endTs=1796288460&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:59 GMT",
|
||||
"body": {
|
||||
"history": [
|
||||
{
|
||||
"t": 1796284969,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285059,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285176,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285310,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285335,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285416,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285540,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285654,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285779,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796285889,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796286037,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796286154,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796286252,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796286382,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796286494,
|
||||
"p": 0.999
|
||||
},
|
||||
{
|
||||
"t": 1796286645,
|
||||
"p": 0.999
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=759916398134244316868652908232832573045153963965173623897622651599218278400&startTs=1796290260&endTs=1796290560&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:59 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
},
|
||||
"ancient": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=759916398134244316868652908232832573045153963965173623897622651599218278400&startTs=120&endTs=245",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:34:59 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"asset": "759916398134244316868652908232832573045153963965173623897622651599218278401",
|
||||
"around": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=759916398134244316868652908232832573045153963965173623897622651599218278401&startTs=1796284860&endTs=1796288460&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:00 GMT",
|
||||
"body": {
|
||||
"history": [
|
||||
{
|
||||
"t": 1796284969,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285059,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285176,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285310,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285335,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285416,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285540,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285654,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285779,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796285889,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796286037,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796286154,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796286252,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796286382,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796286494,
|
||||
"p": 0.001
|
||||
},
|
||||
{
|
||||
"t": 1796286645,
|
||||
"p": 0.001
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=759916398134244316868652908232832573045153963965173623897622651599218278401&startTs=1796290260&endTs=1796290560&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:00 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
},
|
||||
"ancient": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=759916398134244316868652908232832573045153963965173623897622651599218278401&startTs=120&endTs=245",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:01 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"catalog_url": "https://gamma-api.polymarket.com/markets?closed=true&limit=100&order=closedTime&ascending=false",
|
||||
"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\"]"
|
||||
},
|
||||
"sides": [
|
||||
{
|
||||
"asset": "708440684409184214698552699176045036593002385654320616860038876849074339840",
|
||||
"around": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=708440684409184214698552699176045036593002385654320616860038876849074339840&startTs=1796284828&endTs=1796288428&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:02 GMT",
|
||||
"body": {
|
||||
"history": [
|
||||
{
|
||||
"t": 1796284968,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285058,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285173,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285310,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285334,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285414,
|
||||
"p": 0.505
|
||||
},
|
||||
{
|
||||
"t": 1796285539,
|
||||
"p": 0.505
|
||||
},
|
||||
{
|
||||
"t": 1796285653,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285778,
|
||||
"p": 0.395
|
||||
},
|
||||
{
|
||||
"t": 1796285888,
|
||||
"p": 0.55
|
||||
},
|
||||
{
|
||||
"t": 1796286036,
|
||||
"p": 0.675
|
||||
},
|
||||
{
|
||||
"t": 1796286153,
|
||||
"p": 0.8
|
||||
},
|
||||
{
|
||||
"t": 1796286251,
|
||||
"p": 0.83
|
||||
},
|
||||
{
|
||||
"t": 1796286382,
|
||||
"p": 0.83
|
||||
},
|
||||
{
|
||||
"t": 1796286494,
|
||||
"p": 0.96
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=708440684409184214698552699176045036593002385654320616860038876849074339840&startTs=1796290228&endTs=1796290528&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:02 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
},
|
||||
"ancient": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=708440684409184214698552699176045036593002385654320616860038876849074339840&startTs=120&endTs=245",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:02 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"asset": "708440684409184214698552699176045036593002385654320616860038876849074339841",
|
||||
"around": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=708440684409184214698552699176045036593002385654320616860038876849074339841&startTs=1796284828&endTs=1796288428&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:03 GMT",
|
||||
"body": {
|
||||
"history": [
|
||||
{
|
||||
"t": 1796284969,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285059,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285176,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285310,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285335,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285416,
|
||||
"p": 0.495
|
||||
},
|
||||
{
|
||||
"t": 1796285540,
|
||||
"p": 0.495
|
||||
},
|
||||
{
|
||||
"t": 1796285654,
|
||||
"p": 0.5
|
||||
},
|
||||
{
|
||||
"t": 1796285779,
|
||||
"p": 0.605
|
||||
},
|
||||
{
|
||||
"t": 1796285888,
|
||||
"p": 0.455
|
||||
},
|
||||
{
|
||||
"t": 1796286036,
|
||||
"p": 0.335
|
||||
},
|
||||
{
|
||||
"t": 1796286154,
|
||||
"p": 0.205
|
||||
},
|
||||
{
|
||||
"t": 1796286252,
|
||||
"p": 0.17
|
||||
},
|
||||
{
|
||||
"t": 1796286382,
|
||||
"p": 0.175
|
||||
},
|
||||
{
|
||||
"t": 1796286494,
|
||||
"p": 0.08
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=708440684409184214698552699176045036593002385654320616860038876849074339841&startTs=1796290228&endTs=1796290528&fidelity=2",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:03 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
},
|
||||
"ancient": {
|
||||
"method": "GET",
|
||||
"url": "https://clob.polymarket.com/prices-history?market=708440684409184214698552699176045036593002385654320616860038876849074339841&startTs=120&endTs=245",
|
||||
"payload": null,
|
||||
"status": 200,
|
||||
"date": "Thu, 03 Dec 2026 08:35:04 GMT",
|
||||
"body": {
|
||||
"history": []
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -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"}}}
|
||||
]}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"one": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400","status":200,"date":"Fri, 04 Dec 2026 20:59:33 GMT","body":{"data":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":0,"clob_index":null,"outcome":"Nikolenko Anatolii","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","resolved":true,"final_price":1.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"}]}},
|
||||
"alias": {"url":"https://data-api.polymarket.com/v2/tokens?tokenId=759916398134244316868652908232832573045153963965173623897622651599218278400","status":400,"date":"Fri, 04 Dec 2026 20:59:33 GMT","body":{"error":"provide exactly one of 'token_id' or 'condition'","code":"invalid_request","retryable":false}},
|
||||
"pair": {"url":"https://data-api.polymarket.com/v2/tokens?condition=0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","status":200,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"data":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":0,"clob_index":null,"outcome":"Nikolenko Anatolii","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","resolved":true,"final_price":1.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":1,"clob_index":null,"outcome":"Fokin Illia","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","resolved":true,"final_price":0.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"}]}},
|
||||
"pair_alias": {"url":"https://data-api.polymarket.com/v2/tokens?conditionId=0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","status":200,"date":"Fri, 04 Dec 2026 20:59:33 GMT","body":{"data":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":0,"clob_index":null,"outcome":"Nikolenko Anatolii","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","resolved":true,"final_price":1.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":1,"clob_index":null,"outcome":"Fokin Illia","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","resolved":true,"final_price":0.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"}]}},
|
||||
"v1": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453","status":200,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"data":[{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","condition_id":"0xdf04a0495b0a16dbce386acdc16d9aed19784db9888be53d150354b83b7c18b1","structural_condition_id":null,"module":"v1_ctf","outcome_index":0,"clob_index":0,"outcome":"Over","opposite_token_id":"78188826358032258311424545486331333398838521699262460256542567713692269401385","resolved":true,"final_price":0.0,"title":"Map 1 Total Rounds: Over/Under 30.5","market_slug":"cs2-bb3-lgc-2026-12-03-game1-round-total-30pt5","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1495714,"event_slug":"cs2-bb3-lgc-2026-12-03"}]}},
|
||||
"multi": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=759916398134244316868652908232832573045153963965173623897622651599218278401%2C123%2C759916398134244316868652908232832573045153963965173623897622651599218278400%2C759916398134244316868652908232832573045153963965173623897622651599218278401","status":200,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"data":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":1,"clob_index":null,"outcome":"Fokin Illia","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","resolved":true,"final_price":0.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":0,"clob_index":null,"outcome":"Nikolenko Anatolii","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","resolved":true,"final_price":1.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"}]}},
|
||||
"both": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400&condition=0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","status":400,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"error":"provide exactly one of 'token_id' or 'condition'","code":"invalid_request","retryable":false}},
|
||||
"none": {"url":"https://data-api.polymarket.com/v2/tokens?","status":400,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"error":"provide exactly one of 'token_id' or 'condition'","code":"invalid_request","retryable":false}},
|
||||
"missing": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=123","status":200,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"data":[]}},
|
||||
"malformed": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=abc","status":400,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"error":"invalid token id: abc","code":"invalid_request","parameter":"token_id","retryable":false}},
|
||||
"bad_condition": {"url":"https://data-api.polymarket.com/v2/tokens?condition=invalid","status":400,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"error":"invalid condition id: invalid","code":"invalid_request","parameter":"condition","retryable":false}},
|
||||
"unknown_condition": {"url":"https://data-api.polymarket.com/v2/tokens?condition=0x0000000000000000000000000000000000000000000000000000000000000000","status":200,"date":"Fri, 04 Dec 2026 20:59:34 GMT","body":{"data":[]}},
|
||||
"multi_condition": {"url":"https://data-api.polymarket.com/v2/tokens?condition=0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000%2C0xdf04a0495b0a16dbce386acdc16d9aed19784db9888be53d150354b83b7c18b1","status":200,"date":"Fri, 04 Dec 2026 20:59:35 GMT","body":{"data":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":0,"clob_index":null,"outcome":"Nikolenko Anatolii","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","resolved":true,"final_price":1.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":1,"clob_index":null,"outcome":"Fokin Illia","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","resolved":true,"final_price":0.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"},{"token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","condition_id":"0xdf04a0495b0a16dbce386acdc16d9aed19784db9888be53d150354b83b7c18b1","structural_condition_id":null,"module":"v1_ctf","outcome_index":0,"clob_index":0,"outcome":"Over","opposite_token_id":"78188826358032258311424545486331333398838521699262460256542567713692269401385","resolved":true,"final_price":0.0,"title":"Map 1 Total Rounds: Over/Under 30.5","market_slug":"cs2-bb3-lgc-2026-12-03-game1-round-total-30pt5","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1495714,"event_slug":"cs2-bb3-lgc-2026-12-03"},{"token_id":"78188826358032258311424545486331333398838521699262460256542567713692269401385","condition_id":"0xdf04a0495b0a16dbce386acdc16d9aed19784db9888be53d150354b83b7c18b1","structural_condition_id":null,"module":"v1_ctf","outcome_index":1,"clob_index":1,"outcome":"Under","opposite_token_id":"73979342585906843441145134109923710004884703083095161594360108477170435492453","resolved":true,"final_price":1.0,"title":"Map 1 Total Rounds: Over/Under 30.5","market_slug":"cs2-bb3-lgc-2026-12-03-game1-round-total-30pt5","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1495714,"event_slug":"cs2-bb3-lgc-2026-12-03"}]}},
|
||||
"plural": {"url":"https://data-api.polymarket.com/v2/tokens?token_ids=759916398134244316868652908232832573045153963965173623897622651599218278400","status":200,"date":"Fri, 04 Dec 2026 21:00:05 GMT","body":{"data":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":0,"clob_index":null,"outcome":"Nikolenko Anatolii","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","resolved":true,"final_price":1.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"}]}},
|
||||
"zero_prefix": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=000759916398134244316868652908232832573045153963965173623897622651599218278400","status":200,"date":"Fri, 04 Dec 2026 21:00:05 GMT","body":{"data":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":0,"clob_index":null,"outcome":"Nikolenko Anatolii","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","resolved":true,"final_price":1.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"}]}},
|
||||
"empty_token": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=","status":400,"date":"Fri, 04 Dec 2026 21:00:05 GMT","body":{"error":"provide exactly one of 'token_id' or 'condition'","code":"invalid_request","retryable":false}},
|
||||
"huge": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999","status":400,"date":"Fri, 04 Dec 2026 21:00:05 GMT","body":{"error":"invalid token id: 999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999","code":"invalid_request","parameter":"token_id","retryable":false}},
|
||||
"short_condition": {"url":"https://data-api.polymarket.com/v2/tokens?condition=0x01ae18f1c798f53d0efe0903889e57483c0000000000000000000000000000","status":200,"date":"Fri, 04 Dec 2026 21:00:05 GMT","body":{"data":[{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":0,"clob_index":null,"outcome":"Nikolenko Anatolii","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","resolved":true,"final_price":1.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"},{"token_id":"759916398134244316868652908232832573045153963965173623897622651599218278401","condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","structural_condition_id":"0x01ae18f1c798f53d0efe0903889e57483c000000000000000000000000000000","module":"binary","outcome_index":1,"clob_index":null,"outcome":"Fokin Illia","opposite_token_id":"759916398134244316868652908232832573045153963965173623897622651599218278400","resolved":true,"final_price":0.0,"title":"Nikolenko Anatolii vs. Fokin Illia","market_slug":"setkameua-anat-illia-2026-12-03","closed":true,"neg_risk":false,"neg_risk_market_id":null,"question_index":null,"event_id":1496938,"event_slug":"setkameua-anat-illia-2026-12-03"}]}},
|
||||
"cap_tokens": {"url":"https://data-api.polymarket.com/v2/tokens?token_id=0%2C1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10%2C11%2C12%2C13%2C14%2C15%2C16%2C17%2C18%2C19%2C20%2C21%2C22%2C23%2C24%2C25%2C26%2C27%2C28%2C29%2C30%2C31%2C32%2C33%2C34%2C35%2C36%2C37%2C38%2C39%2C40%2C41%2C42%2C43%2C44%2C45%2C46%2C47%2C48%2C49%2C50","status":400,"date":"Fri, 04 Dec 2026 21:00:05 GMT","body":{"error":"'token_id' accepts at most 50 distinct values","code":"invalid_request","parameter":"token_id","retryable":false}}
|
||||
}
|
||||
@@ -376,7 +376,7 @@ Polymarket 的单资产最近成交接口规定,无成交时返回价格字符
|
||||
|
||||
旧版 CLOB 客户端用 market 指定结果资产。单侧盘口的生产曲线末点为 0.0005,同批中点为 0.0005、最近成交为 0.001。一个近端成交记录为空的资产也有连续的 0.5 历史点。取早于上市的绝对区间时,有历史的资产仍返回最近可用点;新资产在中点已经可查时也可能返回空曲线。[生产请求和对照样本](examples/public-clob-history.json) · [CLOB OpenAPI](https://docs.polymarket.com/api-reference/markets/get-prices-history)
|
||||
|
||||
本地用已经提交的盘口变更重建历史中点。到每个 UTC 采样边界,取该时刻之前(含该时刻)最近一次盘口;缺买侧用 0,缺卖侧用 1。没有挂单变化时延续上次观测。窗口之外也追加最近一分钟的可用点;若与窗口最后一点重合,可出现重复时间戳。模拟裁决后在裁决时刻以兑付值收尾。已裁决的旧盘若缺少裁决时间,只使用最后有时间记录的报价。升级旧库时从第一条可信报价开始,没有报价记录的资产从迁移时刻开始。生产采集存在秒级抖动,新盘首个采样的延迟、长期历史保留和裁决后取点尚未逐点验证。V2 的成交与兑付历史保留其独立数据源。
|
||||
本地用已经提交的盘口变更重建历史中点。到每个 UTC 采样边界,取该时刻之前(含该时刻)最近一次盘口;缺买侧用 0,缺卖侧用 1。没有挂单变化时延续上次观测。窗口之外也追加最近一分钟的可用点;若与窗口最后一点重合,可出现重复时间戳。封盘后,曲线只返回请求窗口内、封盘之前的采样点。电竞、乒乓球和 SOL 涨跌盘的六个生产结果均符合这一规则。电竞负侧、胜侧的末点分别为 0.0005 和 0.9995,目录最终兑付为 0 和 1。旧库没有封盘记录时,最多采样到最后一笔非空盘口记录。生产采样时钟有秒级偏移,新盘首个采样延迟和长期保留仍待核验。V2 曲线使用成交与兑付数据。[已裁决生产样本](examples/public-closed-chart-history.json)
|
||||
|
||||
fidelity 以分钟为单位;省略或不大于零时按 1 分钟处理。相对窗口 1w 至少需要 5 分钟、1m 至少需要 10 分钟。显式起止时间最多相隔 15 天,多一秒即拒绝。单给 startTs 时读到当前;两个时间相等时仍可返回末点。合法但未上市的本地资产返回空数组。[HTTP 样例](examples/clob-http.http)
|
||||
|
||||
@@ -386,9 +386,7 @@ fidelity 以分钟为单位;省略或不大于零时按 1 分钟处理。相
|
||||
|
||||
[本地样例](examples/clarifications.jsonl)先挂出 0.40 的 YES 买单。第一条说明保留挂单,第二条要求清盘,账户收回预留的 0.40。两条说明都按发布时间保留,初始规则仍可查看。模拟操作员可在盘前、连续交易或封盘待裁决期间发布公告。重复的请求 ID 返回原回执;之后新挂的订单不会因重放旧公告被撤。[官方规则澄清说明](https://docs.polymarket.com/concepts/resolution#clarifications)
|
||||
|
||||
`GET /market-clarifications` 支持按数字事件 ID、市场 ID、已登记的 UMA 问题 ID 及发布交易哈希查询。同类 ID 可重复,跨条件取交集。publish_clarification 可附带可信操作者提供的 tx_hash,和公告及清盘同事务写入。带事件或裁决问题的公告公开 eventId、questionId,本地已发布公告的 state 为 success。txTimestamp 暂无链上证据,保留 null。
|
||||
|
||||
2026-12-05 的 Gamma 生产样本中,无参数与 limit=0 均返回 50 条,limit=101 返回 100 条,offset=-1 等同于首屏。order=createdAt,id 接受逗号分隔的字段,order=created_at 返回 422。用公告 23029 的 questionId 查询命中同一公告,大写十六进制仍命中。其交易哈希精确筛选返回六条公告,大写哈希返回空数组。本地采用同样的查询口径。Gamma 未指定无排序参数时的稳定顺序,本地使用公告 ID 稳定翻页,默认升序;预约、排队和链上确认时间仍待接入。[官方公告列表](https://docs.polymarket.com/api-reference/markets/list-market-clarifications) · [生产查询样例](https://gamma-api.polymarket.com/market-clarifications?limit=2&order=id&ascending=true)
|
||||
`GET /market-clarifications` 支持按数字事件 ID、市场 ID 筛选、翻页和按公告 ID 排序。clearBook 表示发布时是否要求清盘。createdAt 是本地发布时间,txTimestamp 和 txHash 留空。官方另外支持按 UMA 问题 ID、交易哈希及其他排序字段查询,这些筛选项尚待实现。[官方公告列表](https://docs.polymarket.com/api-reference/markets/list-market-clarifications) · [官方返回示例](https://docs.polymarket.com/market-data/market-details#market-clarifications)
|
||||
|
||||
本地 resolution 查询在获胜结果确定后同时返回已持久化的 resolved_at_ms 和 payouts;旧市场缺少时间记录时返回 null。兑付权重顺序为 YES、NO:YES 胜为 [1,0],NO 胜为 [0,1],作废为 [1,1],分母为两项之和。挑战期内的提案不会生成兑付权重。链上区块、UMA 仲裁回执及生产 Data API 的状态枚举尚待对照。[Polymarket UMA 适配器](https://github.com/Polymarket/uma-ctf-adapter/blob/main/src/UmaCtfAdapter.sol) · [生产裁决状态接口](https://docs.polymarket.com/api-reference/markets/get-resolution-state)
|
||||
|
||||
@@ -468,3 +466,19 @@ 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)
|
||||
|
||||
### Data API 资产反查
|
||||
|
||||
GET /v2/tokens 接受 token_id / token_ids 或 condition / condition_id / conditionId,二选一。生产样本中,资产查询保持请求顺序并合并重复项,数字标识的前导零会被归一。合法的未知资产返回空数组。用本地市场 ID 返回 YES、NO 两侧,用本地互斥组 ID 按题目序号展开成员。已裁决市场可返回最终兑付值,VOID 有两项 0.5。回执保留稳定的本地 eb 标识并自描述本地模块。对照样本覆盖原生 V2、CTF 和短条件 ID。外场同一市场的多协议资产通过后文的绑定命令接入本地目录。[生产请求和响应](examples/public-token-directory.json) · [官方 OpenAPI](https://data-api.polymarket.com/v2/openapi.json)
|
||||
|
||||
### 本地登记 Polymarket 资产对照
|
||||
|
||||
可信 JSONL 命令 bind_polymarket_assets 接受本地市场、external_condition、zero_outcome 及官方 data 数组。每种协议必须提供互补一对。登记时核对 V2 编码、互斥组与题目归属,禁止冲突重绑。登记后用外场数字资产或条件查询 /v2/tokens 可得到原协议观察字段及 local_asset_id。旧 CTF 互斥组查询返回已登记的两类资产,完整 V2 Neg Risk 事件 ID 只展开已登记的结构仓位。以 62 位十六进制条件查询题目零时,仍只返回单个题目。外场状态与兑付值由观测快照提供。[三题生产样本](examples/polymarket-token-event.json) · [生产登记样本](examples/polymarket-asset-binding.json)
|
||||
|
||||
|
||||
对同一绑定重复提交带 observed_at_ms 的配对可刷新状态及结果标签。旧观测不会覆盖更新状态,同毫秒互相矛盾的快照和推翻最终兑付的请求会拒绝,整笔事务回滚。反查回执带观测时间。一个此前能公开读取盘口的电竞盘,后续 CTF 与 V2 目录均返回裁决输赢。回归使用它的真实裁决响应,并用同一资产生成开放快照来覆盖乱序。`cli DATABASE --refresh-polymarket [MARKET]` 可按需拉取已登记资产的完整快照。HTTP Date 表示响应时间,裁决数据的实际发布时间和传播时延仍待验证。[生产盘口及裁决快照](examples/polymarket-asset-refresh.json)
|
||||
|
||||
Reference in New Issue
Block a user