use anyhow::{anyhow, ensure, Context, Result}; use reqwest::{blocking::Client, Url}; use serde_json::Value; fn read(client: &Client, url: Url) -> Result { client .get(url.clone()) .send() .with_context(|| format!("GET {url}"))? .error_for_status()? .json() .context("invalid JSON") } pub(crate) fn polymarket(client: &Client) -> Result { let markets = read( client, Url::parse("https://gamma-api.polymarket.com/markets?active=true&closed=false&limit=50")?, )?; let token = markets .as_array() .context("expected market array")? .iter() .filter(|m| m["enableOrderBook"] == true && m["acceptingOrders"] == true) .find_map(|m| { let ids = match &m["clobTokenIds"] { Value::String(raw) => serde_json::from_str(raw).ok()?, v => v.clone(), }; ids.get(0)?.as_str().map(str::to_owned) }) .context("no active CLOB token in sample")?; let url = Url::parse_with_params("https://clob.polymarket.com/book", &[("token_id", &token)])?; let book = read(client, url)?; ensure!( book["asset_id"].as_str() == Some(token.as_str()) && book["bids"].is_array() && book["asks"].is_array(), "invalid book or mismatched token" ); Ok(token) } pub(crate) fn kalshi(client: &Client) -> Result { let root = "https://external-api.kalshi.com/trade-api/v2/markets"; let markets = read( client, Url::parse_with_params(root, &[("status", "open"), ("limit", "1")])?, )?; let ticker = markets["markets"] .get(0) .and_then(|m| m["ticker"].as_str()) .context("no open market ticker")?; let mut url = Url::parse(root)?; url.path_segments_mut() .map_err(|_| anyhow!("invalid market URL"))? .extend([ticker, "orderbook"]); let book = read(client, url)?; let depth = &book["orderbook_fp"]; ensure!( depth["yes_dollars"].is_array() && depth["no_dollars"].is_array(), "invalid Kalshi depth" ); Ok(ticker.to_owned()) }