184 lines
7.1 KiB
Rust
184 lines
7.1 KiB
Rust
use crate::{books, price_check};
|
|
use anyhow::{anyhow, Context, Result};
|
|
use reqwest::{blocking::Client, Url};
|
|
use serde_json::{json, Value};
|
|
|
|
fn read(client: &Client, url: Url) -> Result<Value> {
|
|
let response = client
|
|
.get(url.clone())
|
|
.send()
|
|
.with_context(|| format!("GET {url}"))?;
|
|
response
|
|
.error_for_status()
|
|
.with_context(|| format!("HTTP {url}"))?
|
|
.json()
|
|
.with_context(|| format!("invalid JSON from {url}"))
|
|
}
|
|
|
|
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")?,
|
|
)
|
|
.context("Polymarket catalog")?;
|
|
let (m, assets) = markets
|
|
.as_array()
|
|
.context("expected market array")?
|
|
.iter()
|
|
.filter(|m| m["enableOrderBook"] == true && m["acceptingOrders"] == true)
|
|
.find_map(|m| books::poly_assets(m).ok().map(|assets| (m, assets)))
|
|
.context("no supported tradable binary market in sample")?;
|
|
polymarket_report(m, &assets, compare, |asset| {
|
|
let url =
|
|
Url::parse_with_params("https://clob.polymarket.com/book", &[("token_id", asset)])?;
|
|
let book = read(client, url.clone()).context("Polymarket orderbook")?;
|
|
let mut snapshot = books::poly_book(m, asset, &book)?;
|
|
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));
|
|
snapshot["price_check"] = price_check::report(&snapshot, buy, sell, after);
|
|
}
|
|
Ok(snapshot)
|
|
})
|
|
}
|
|
|
|
fn polymarket_report(
|
|
m: &Value,
|
|
assets: &[String; 2],
|
|
compare: bool,
|
|
mut observe: impl FnMut(&str) -> Result<Value>,
|
|
) -> Result<Value> {
|
|
let labels: Option<[String; 2]> = match &m["outcomes"] {
|
|
Value::String(raw) => Some(serde_json::from_str(raw).context("invalid outcome labels")?),
|
|
Value::Null => None,
|
|
labels => Some(serde_json::from_value(labels.clone()).context("invalid outcome labels")?),
|
|
};
|
|
let mut outcomes = Vec::new();
|
|
for (index, asset) in assets.iter().enumerate() {
|
|
let mut snapshot = observe(asset)
|
|
.unwrap_or_else(|err| json!({"asset_id":asset,"book_error":format!("{err:#}")}));
|
|
snapshot["outcome_index"] = json!(index);
|
|
snapshot["label"] = json!(labels.as_ref().map(|pair| &pair[index]));
|
|
outcomes.push(snapshot);
|
|
}
|
|
let mut result = json!({"venue":"polymarket","market":m["id"],"condition_id":m["conditionId"],
|
|
"orderbooks_complete":outcomes.iter().all(|s| s.get("book_error").is_none()),
|
|
"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> {
|
|
let root = "https://external-api.kalshi.com/trade-api/v2/markets";
|
|
let markets = read(
|
|
client,
|
|
Url::parse_with_params(root, &[("status", "open"), ("limit", "1")])?,
|
|
)
|
|
.context("Kalshi catalog")?;
|
|
let market = markets["markets"].get(0).context("no open market")?;
|
|
kalshi_report(root, market, |url| read(client, url))
|
|
}
|
|
|
|
fn kalshi_report(
|
|
root: &str,
|
|
market: &Value,
|
|
observe: impl FnOnce(Url) -> Result<Value>,
|
|
) -> Result<Value> {
|
|
let ticker = market["ticker"]
|
|
.as_str()
|
|
.filter(|s| !s.is_empty())
|
|
.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 mut snapshot = match observe(url).and_then(|data| books::kalshi_book(ticker, &data)) {
|
|
Ok(mut book) => {
|
|
book["orderbooks_complete"] = json!(true);
|
|
book
|
|
}
|
|
Err(err) => {
|
|
json!({"venue":"kalshi","ticker":ticker,"orderbooks_complete":false,"book_error":format!("{err:#}")})
|
|
}
|
|
};
|
|
snapshot["catalog"] = json!({"event_ticker":market["event_ticker"],"market_type":market["market_type"],
|
|
"status":market["status"],"mve_collection_ticker":market["mve_collection_ticker"],
|
|
"mve_selected_legs":market["mve_selected_legs"],"updated_time":market["updated_time"]});
|
|
Ok(snapshot)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn failed_first_polymarket_book_preserves_the_second_observation() {
|
|
let market: Value =
|
|
serde_json::from_str(include_str!("../fixtures/gamma-559651.json")).unwrap();
|
|
let assets = books::poly_assets(&market).unwrap();
|
|
let report = polymarket_report(&market, &assets, true, |id| {
|
|
if id == assets[0].as_str() {
|
|
anyhow::bail!("simulated timeout");
|
|
}
|
|
Ok(json!({"asset_id":id,"best_bid":null,"best_ask":null}))
|
|
})
|
|
.unwrap();
|
|
assert_eq!(report["market"], market["id"]);
|
|
assert_eq!(report["orderbooks_complete"], false);
|
|
assert_eq!(report["price_check_passed"], false);
|
|
let rows = report["outcomes"].as_array().unwrap();
|
|
assert_eq!(rows[0]["asset_id"].as_str(), Some(assets[0].as_str()));
|
|
assert_eq!(rows[0]["book_error"], "simulated timeout");
|
|
assert!(rows[0].get("best_bid").is_none());
|
|
assert_eq!(rows[1]["asset_id"].as_str(), Some(assets[1].as_str()));
|
|
assert_eq!(rows[1]["label"], "No");
|
|
assert_eq!(rows[1].get("best_bid"), Some(&Value::Null));
|
|
assert!(rows[1].get("book_error").is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn kalshi_combo_keeps_all_legs_on_failed_and_empty_books() {
|
|
let market: Value =
|
|
serde_json::from_str(include_str!("../fixtures/kalshi-combo.json")).unwrap();
|
|
let root = "https://external-api.kalshi.com/trade-api/v2/markets";
|
|
let failed = kalshi_report(root, &market, |url| {
|
|
assert_eq!(
|
|
url.path(),
|
|
format!(
|
|
"/trade-api/v2/markets/{}/orderbook",
|
|
market["ticker"].as_str().unwrap()
|
|
)
|
|
);
|
|
anyhow::bail!("simulated timeout");
|
|
})
|
|
.unwrap();
|
|
assert_eq!(failed["orderbooks_complete"], false);
|
|
assert!(failed.get("yes").is_none());
|
|
assert_eq!(failed["catalog"]["market_type"], "binary");
|
|
assert_eq!(
|
|
failed["catalog"]["mve_selected_legs"]
|
|
.as_array()
|
|
.unwrap()
|
|
.len(),
|
|
30
|
|
);
|
|
assert_eq!(
|
|
failed["catalog"]["mve_selected_legs"],
|
|
market["mve_selected_legs"]
|
|
);
|
|
let empty = kalshi_report(root, &market, |_| {
|
|
Ok(json!({"orderbook_fp":{"yes_dollars":[],"no_dollars":[]}}))
|
|
})
|
|
.unwrap();
|
|
assert_eq!(empty["orderbooks_complete"], true);
|
|
assert_eq!(empty["catalog"], failed["catalog"]);
|
|
assert_eq!(empty["yes"]["best_bid"], Value::Null);
|
|
assert!(empty.get("book_error").is_none());
|
|
}
|
|
}
|