Compare Polymarket side prices between identified book snapshots
This commit is contained in:
@@ -9,6 +9,8 @@ cargo run --locked -p venue-probe
|
|||||||
```mermaid
|
```mermaid
|
||||||
flowchart LR
|
flowchart LR
|
||||||
main["src/main.rs"] -->|依次调用两个只读探针| impls["src/probes.rs"]
|
main["src/main.rs"] -->|依次调用两个只读探针| impls["src/probes.rs"]
|
||||||
|
impls -->|可选买卖报价对照| check["src/price_check.rs"]
|
||||||
|
check -->|精确价格与市场标识| books
|
||||||
impls -->|目录标识、盘口校验和最优价| books["src/books.rs"]
|
impls -->|目录标识、盘口校验和最优价| books["src/books.rs"]
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -24,6 +26,12 @@ sequenceDiagram
|
|||||||
P->>C: 按 CTF token ID 或 V2 position ID 查询
|
P->>C: 按 CTF token ID 或 V2 position ID 查询
|
||||||
C-->>P: condition、资产 ID、买卖盘
|
C-->>P: condition、资产 ID、买卖盘
|
||||||
P->>P: 检查返回标识并提取最优价格与数量
|
P->>P: 检查返回标识并提取最优价格与数量
|
||||||
|
opt --compare-prices
|
||||||
|
P->>C: 对同一资产分别查询 BUY 和 SELL
|
||||||
|
C-->>P: 返回报价或 HTTP 错误
|
||||||
|
P->>C: 再次读取该资产盘口
|
||||||
|
P->>P: 检查前后哈希、买一与卖一,再判断方向
|
||||||
|
end
|
||||||
end
|
end
|
||||||
P->>K: 查询开放市场
|
P->>K: 查询开放市场
|
||||||
K-->>P: 返回 ticker
|
K-->>P: 返回 ticker
|
||||||
@@ -37,3 +45,9 @@ sequenceDiagram
|
|||||||
复查中,工作站分别向 Gamma `/markets?active=true&closed=false&limit=5` 与 Kalshi 生产 `/markets?status=open&limit=5` 发起匿名 GET,连接超时设为 6 秒。两次均返回 curl 28、HTTP 000,未建立 TCP 连接。目录未返回任何资产,因此本次没有由目录驱动的生产盘口回执。两家场所的可达性仍未验证。
|
复查中,工作站分别向 Gamma `/markets?active=true&closed=false&limit=5` 与 Kalshi 生产 `/markets?status=open&limit=5` 发起匿名 GET,连接超时设为 6 秒。两次均返回 curl 28、HTTP 000,未建立 TCP 连接。目录未返回任何资产,因此本次没有由目录驱动的生产盘口回执。两家场所的可达性仍未验证。
|
||||||
|
|
||||||
官方文档把 V2 position ID 与 CTF token ID 都作为 CLOB 的交易标识,Gamma 原始字段分别为 positionIds 和 clobTokenIds。回归用例覆盖两种版本、错配、空盘和小数数量。Kalshi 示例中,NO 买价 0.5005 与数量 1.25 对应 YES 卖价 0.4995、卖量 1.25。协议与精度依据见 [Polymarket 订单簿接口](https://docs.polymarket.com/market-data/prices-order-books.md) 和 [Kalshi 订单簿结构](https://docs.kalshi.com/getting_started/orderbook_responses.md)。
|
官方文档把 V2 position ID 与 CTF token ID 都作为 CLOB 的交易标识,Gamma 原始字段分别为 positionIds 和 clobTokenIds。回归用例覆盖两种版本、错配、空盘和小数数量。Kalshi 示例中,NO 买价 0.5005 与数量 1.25 对应 YES 卖价 0.4995、卖量 1.25。协议与精度依据见 [Polymarket 订单簿接口](https://docs.polymarket.com/market-data/prices-order-books.md) 和 [Kalshi 订单簿结构](https://docs.kalshi.com/getting_started/orderbook_responses.md)。
|
||||||
|
|
||||||
|
## 核对生产买卖报价
|
||||||
|
|
||||||
|
`venue-probe --compare-prices` 在常规输出上增加每个结果的 price_check。它把报价响应、HTTP 状态、前后盘口和哈希放在同一条记录中。两侧都有报价且买一低于卖一,前后盘口哈希和两侧最优档相同,才判断价格方向。BUY 等于卖一、SELL 等于买一记为 matches_documentation,二者正好对调记为 reversed,其他数值组合记为 different_prices。盘口变化记为 book_changed,缺哈希、缺边、买卖同价或报价失败记为 inconclusive。两个结果都符合文档时 price_check_passed 才为 true;其余情况保留观测并以非零状态退出。HTTP 读取之间可能发生变化又恢复,因此单次一致记录只说明这次观测。[官方买卖报价](https://docs.polymarket.com/market-data/prices-order-books.md#best-market-price)
|
||||||
|
|
||||||
|
[市场 559651 的目录字段摘录](fixtures/gamma-559651.json)来自公开 Gamma JSON 的网页读取,记录自身的更新时间为 2026-12-02 21:08:08 UTC。该 v1 市场同时返回两套 ID,盘口请求使用 clobTokenIds。目录买一为 0.012、卖一为 0.013、最小价格步长为 0.001。测试以这些真实目录值构造模拟的 CLOB 响应;本次工作站直连 Gamma 超时,网页读取该资产的 CLOB book 和 price 也未取得响应。目录观测与模拟样例均不能确认线上 BUY 和 SELL 返回了什么。[Gamma 公开市场目录](https://gamma-api.polymarket.com/markets?limit=1)
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"id": "559651",
|
||||||
|
"version": "v1",
|
||||||
|
"updatedAt": "2026-12-02T21:08:08.650001Z",
|
||||||
|
"conditionId": "0xa467b14d51f01b957109d9cbb1d6c124fab2a089d52ed8f471d23c2812e743b7",
|
||||||
|
"outcomes": "[\"Yes\", \"No\"]",
|
||||||
|
"clobTokenIds": "[\"32338220190071351435772801779725302244575775216413325951443816017994629993401\", \"25659310674993675562345759665114759892400026242514633218387667107987341231962\"]",
|
||||||
|
"positionIds": ["895257453734540292493143124621755605615887197499956109032745153687078305792", "895257453734540292493143124621755605615887197499956109032745153687078305793"],
|
||||||
|
"enableOrderBook": true,
|
||||||
|
"acceptingOrders": true,
|
||||||
|
"bestBid": 0.012,
|
||||||
|
"bestAsk": 0.013,
|
||||||
|
"lastTradePrice": 0.012,
|
||||||
|
"orderPriceMinTickSize": 0.001,
|
||||||
|
"orderMinSize": 5
|
||||||
|
}
|
||||||
@@ -16,7 +16,7 @@ fn decimal(value: &Value) -> Result<(&str, &str)> {
|
|||||||
Ok((whole, frac))
|
Ok((whole, frac))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn price(value: &Value) -> Result<u64> {
|
pub(crate) fn price(value: &Value) -> Result<u64> {
|
||||||
let (whole, frac) = decimal(value)?;
|
let (whole, frac) = decimal(value)?;
|
||||||
let frac = frac.trim_end_matches('0');
|
let frac = frac.trim_end_matches('0');
|
||||||
ensure!(frac.len() <= 6, "price exceeds six decimal places");
|
ensure!(frac.len() <= 6, "price exceeds six decimal places");
|
||||||
|
|||||||
@@ -1,9 +1,16 @@
|
|||||||
mod books;
|
mod books;
|
||||||
|
mod price_check;
|
||||||
mod probes;
|
mod probes;
|
||||||
use anyhow::{ensure, Result};
|
use anyhow::{ensure, Result};
|
||||||
use reqwest::blocking::Client;
|
use reqwest::blocking::Client;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
fn main() -> Result<()> {
|
fn main() -> Result<()> {
|
||||||
|
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||||
|
let compare = match args.as_slice() {
|
||||||
|
[] => false,
|
||||||
|
[flag] if flag == "--compare-prices" => true,
|
||||||
|
_ => anyhow::bail!("usage: venue-probe [--compare-prices]"),
|
||||||
|
};
|
||||||
let client = Client::builder()
|
let client = Client::builder()
|
||||||
.connect_timeout(Duration::from_secs(5))
|
.connect_timeout(Duration::from_secs(5))
|
||||||
.timeout(Duration::from_secs(15))
|
.timeout(Duration::from_secs(15))
|
||||||
@@ -11,11 +18,17 @@ fn main() -> Result<()> {
|
|||||||
.build()?;
|
.build()?;
|
||||||
let mut ok = true;
|
let mut ok = true;
|
||||||
for (name, result) in [
|
for (name, result) in [
|
||||||
("polymarket", probes::polymarket(&client)),
|
("polymarket", probes::polymarket(&client, compare)),
|
||||||
("kalshi", probes::kalshi(&client)),
|
("kalshi", probes::kalshi(&client)),
|
||||||
] {
|
] {
|
||||||
match result {
|
match result {
|
||||||
Ok(snapshot) => println!("{snapshot}"),
|
Ok(snapshot) => {
|
||||||
|
println!("{snapshot}");
|
||||||
|
if name == "polymarket" && compare && snapshot["price_check_passed"] != true {
|
||||||
|
ok = false;
|
||||||
|
eprintln!("polymarket: price comparison not confirmed for both outcomes");
|
||||||
|
}
|
||||||
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
ok = false;
|
ok = false;
|
||||||
eprintln!("{name}: {e:#}");
|
eprintln!("{name}: {e:#}");
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
use crate::books;
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use reqwest::{blocking::Client, Url};
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
|
||||||
|
pub(crate) fn report(before: &Value, buy: Value, sell: Value, last: Result<Value>) -> Value {
|
||||||
|
let (after, error) = match last {
|
||||||
|
Ok(book) => (book, None),
|
||||||
|
Err(e) => (Value::Null, Some(format!("{e:#}"))),
|
||||||
|
};
|
||||||
|
json!({"status":classify(before,&after,&buy,&sell),
|
||||||
|
"BUY":buy,"SELL":sell,"book_after":after,"book_after_error":error})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn quote(client: &Client, asset: &str, side: &str) -> Value {
|
||||||
|
let read = || -> Result<Value> {
|
||||||
|
let url = Url::parse_with_params(
|
||||||
|
"https://clob.polymarket.com/price",
|
||||||
|
&[("token_id", asset), ("side", side)],
|
||||||
|
)?;
|
||||||
|
let response = client.get(url).send().context("quote request")?;
|
||||||
|
let status = response.status();
|
||||||
|
let mut result = json!({"http_status":status.as_u16()});
|
||||||
|
match response.json::<Value>() {
|
||||||
|
Ok(body) => {
|
||||||
|
if status.is_success() {
|
||||||
|
match books::price(&body["price"]) {
|
||||||
|
Ok(price) => result["price_micros"] = json!(price),
|
||||||
|
Err(e) => result["error"] = json!(e.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result["response"] = body;
|
||||||
|
}
|
||||||
|
Err(e) => result["error"] = json!(e.to_string()),
|
||||||
|
}
|
||||||
|
Ok(result)
|
||||||
|
};
|
||||||
|
read().unwrap_or_else(|e| json!({"error":format!("{e:#}")}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn classify(before: &Value, after: &Value, buy: &Value, sell: &Value) -> &'static str {
|
||||||
|
let Some(hash) = before["hash"].as_str().filter(|h| !h.is_empty()) else {
|
||||||
|
return "inconclusive";
|
||||||
|
};
|
||||||
|
if after.is_null() || after["hash"].as_str().filter(|h| !h.is_empty()).is_none() {
|
||||||
|
return "inconclusive";
|
||||||
|
}
|
||||||
|
if after["hash"] != hash
|
||||||
|
|| before["best_bid"] != after["best_bid"]
|
||||||
|
|| before["best_ask"] != after["best_ask"]
|
||||||
|
{
|
||||||
|
return "book_changed";
|
||||||
|
}
|
||||||
|
let (Some(bid), Some(ask), Some(buy), Some(sell)) = (
|
||||||
|
before["best_bid"]["price_micros"].as_u64(),
|
||||||
|
before["best_ask"]["price_micros"].as_u64(),
|
||||||
|
buy["price_micros"].as_u64(),
|
||||||
|
sell["price_micros"].as_u64(),
|
||||||
|
) else {
|
||||||
|
return "inconclusive";
|
||||||
|
};
|
||||||
|
if bid >= ask {
|
||||||
|
return "inconclusive";
|
||||||
|
}
|
||||||
|
if (buy, sell) == (ask, bid) {
|
||||||
|
"matches_documentation"
|
||||||
|
} else if (buy, sell) == (bid, ask) {
|
||||||
|
"reversed"
|
||||||
|
} else {
|
||||||
|
"different_prices"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stable_distinct_book_differentiates_the_two_price_conventions() {
|
||||||
|
let gamma: Value =
|
||||||
|
serde_json::from_str(include_str!("../fixtures/gamma-559651.json")).unwrap();
|
||||||
|
let tokens = books::poly_assets(&gamma).unwrap();
|
||||||
|
assert_ne!(tokens[0], gamma["positionIds"][0].as_str().unwrap());
|
||||||
|
let level = |p: &Value| json!({"price":p.to_string(),"size":"1"});
|
||||||
|
// Synthetic CLOB responses at the two prices observed on Gamma.
|
||||||
|
let raw = json!({"market":gamma["conditionId"],"asset_id":tokens[0],"hash":"synthetic",
|
||||||
|
"bids":[level(&gamma["bestBid"])],"asks":[level(&gamma["bestAsk"])]});
|
||||||
|
let before = books::poly_book(&gamma, &tokens[0], &raw).unwrap();
|
||||||
|
let bid = json!({"price_micros":12000});
|
||||||
|
let ask = json!({"price_micros":13000});
|
||||||
|
assert_eq!(
|
||||||
|
classify(&before, &before, &ask, &bid),
|
||||||
|
"matches_documentation"
|
||||||
|
);
|
||||||
|
assert_eq!(classify(&before, &before, &bid, &ask), "reversed");
|
||||||
|
assert_eq!(classify(&before, &before, &bid, &bid), "different_prices");
|
||||||
|
assert_eq!(
|
||||||
|
classify(&before, &before, &json!({"http_status":404}), &bid),
|
||||||
|
"inconclusive"
|
||||||
|
);
|
||||||
|
let mut after = before.clone();
|
||||||
|
after["hash"] = json!("changed");
|
||||||
|
assert_eq!(classify(&before, &after, &ask, &bid), "book_changed");
|
||||||
|
after["hash"] = Value::Null;
|
||||||
|
assert_eq!(classify(&before, &after, &ask, &bid), "inconclusive");
|
||||||
|
for edge in [Value::Null, before["best_bid"].clone()] {
|
||||||
|
let mut one = before.clone();
|
||||||
|
one["best_ask"] = edge;
|
||||||
|
assert_eq!(classify(&one, &one, &ask, &bid), "inconclusive");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::books;
|
use crate::{books, price_check};
|
||||||
use anyhow::{anyhow, Context, Result};
|
use anyhow::{anyhow, Context, Result};
|
||||||
use reqwest::{blocking::Client, Url};
|
use reqwest::{blocking::Client, Url};
|
||||||
use serde_json::{json, Value};
|
use serde_json::{json, Value};
|
||||||
@@ -15,7 +15,7 @@ fn read(client: &Client, url: Url) -> Result<Value> {
|
|||||||
.with_context(|| format!("invalid JSON from {url}"))
|
.with_context(|| format!("invalid JSON from {url}"))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn polymarket(client: &Client) -> Result<Value> {
|
pub(crate) fn polymarket(client: &Client, compare: bool) -> Result<Value> {
|
||||||
let markets = read(
|
let markets = read(
|
||||||
client,
|
client,
|
||||||
Url::parse("https://gamma-api.polymarket.com/markets?active=true&closed=false&limit=50")?,
|
Url::parse("https://gamma-api.polymarket.com/markets?active=true&closed=false&limit=50")?,
|
||||||
@@ -37,15 +37,27 @@ pub(crate) fn polymarket(client: &Client) -> Result<Value> {
|
|||||||
for (index, asset) in assets.iter().enumerate() {
|
for (index, asset) in assets.iter().enumerate() {
|
||||||
let url =
|
let url =
|
||||||
Url::parse_with_params("https://clob.polymarket.com/book", &[("token_id", asset)])?;
|
Url::parse_with_params("https://clob.polymarket.com/book", &[("token_id", asset)])?;
|
||||||
let book = read(client, url).context("Polymarket orderbook")?;
|
let book = read(client, url.clone()).context("Polymarket orderbook")?;
|
||||||
let mut snapshot = books::poly_book(m, asset, &book)?;
|
let mut snapshot = books::poly_book(m, asset, &book)?;
|
||||||
snapshot["outcome_index"] = json!(index);
|
snapshot["outcome_index"] = json!(index);
|
||||||
snapshot["label"] = json!(labels.as_ref().map(|pair| &pair[index]));
|
snapshot["label"] = json!(labels.as_ref().map(|pair| &pair[index]));
|
||||||
|
if compare {
|
||||||
|
let buy = price_check::quote(client, asset, "BUY");
|
||||||
|
let sell = price_check::quote(client, asset, "SELL");
|
||||||
|
let after = read(client, url).and_then(|book| books::poly_book(m, asset, &book));
|
||||||
|
let check = price_check::report(&snapshot, buy, sell, after);
|
||||||
|
snapshot["price_check"] = check;
|
||||||
|
}
|
||||||
outcomes.push(snapshot);
|
outcomes.push(snapshot);
|
||||||
}
|
}
|
||||||
Ok(
|
let mut result = json!({"venue":"polymarket","market":m["id"],"condition_id":m["conditionId"],
|
||||||
json!({"venue":"polymarket","market":m["id"],"condition_id":m["conditionId"],"version":m["version"],"outcomes":outcomes}),
|
"version":m["version"],"outcomes":outcomes});
|
||||||
)
|
if compare {
|
||||||
|
result["price_check_passed"] = json!(outcomes
|
||||||
|
.iter()
|
||||||
|
.all(|s| s["price_check"]["status"] == "matches_documentation"));
|
||||||
|
}
|
||||||
|
Ok(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn kalshi(client: &Client) -> Result<Value> {
|
pub(crate) fn kalshi(client: &Client) -> Result<Value> {
|
||||||
|
|||||||
Reference in New Issue
Block a user