Compare Polymarket side prices between identified book snapshots

This commit is contained in:
2026-12-03 06:20:45 +08:00
parent 95d22e0369
commit 6795b8282c
6 changed files with 176 additions and 9 deletions
+1 -1
View File
@@ -16,7 +16,7 @@ fn decimal(value: &Value) -> Result<(&str, &str)> {
Ok((whole, frac))
}
fn price(value: &Value) -> Result<u64> {
pub(crate) fn price(value: &Value) -> Result<u64> {
let (whole, frac) = decimal(value)?;
let frac = frac.trim_end_matches('0');
ensure!(frac.len() <= 6, "price exceeds six decimal places");
+15 -2
View File
@@ -1,9 +1,16 @@
mod books;
mod price_check;
mod probes;
use anyhow::{ensure, Result};
use reqwest::blocking::Client;
use std::time::Duration;
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()
.connect_timeout(Duration::from_secs(5))
.timeout(Duration::from_secs(15))
@@ -11,11 +18,17 @@ fn main() -> Result<()> {
.build()?;
let mut ok = true;
for (name, result) in [
("polymarket", probes::polymarket(&client)),
("polymarket", probes::polymarket(&client, compare)),
("kalshi", probes::kalshi(&client)),
] {
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) => {
ok = false;
eprintln!("{name}: {e:#}");
+112
View File
@@ -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");
}
}
}
+18 -6
View File
@@ -1,4 +1,4 @@
use crate::books;
use crate::{books, price_check};
use anyhow::{anyhow, Context, Result};
use reqwest::{blocking::Client, Url};
use serde_json::{json, Value};
@@ -15,7 +15,7 @@ fn read(client: &Client, url: Url) -> Result<Value> {
.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(
client,
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() {
let url =
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)?;
snapshot["outcome_index"] = json!(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);
}
Ok(
json!({"venue":"polymarket","market":m["id"],"condition_id":m["conditionId"],"version":m["version"],"outcomes":outcomes}),
)
let mut result = json!({"venue":"polymarket","market":m["id"],"condition_id":m["conditionId"],
"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> {