Files
eventbook-exchange/crates/venue-probe/src/price_check.rs
T

113 lines
4.2 KiB
Rust

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 = crate::catalog::Market::parse(&gamma).unwrap().assets;
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");
}
}
}