Retain venue contract identity and report partial book observations
This commit is contained in:
@@ -73,6 +73,10 @@ fn main() -> Result<()> {
|
||||
match result {
|
||||
Ok(snapshot) => {
|
||||
println!("{snapshot}");
|
||||
if snapshot["orderbooks_complete"] != true {
|
||||
ok = false;
|
||||
eprintln!("{name}: catalog read succeeded, one or more order books failed");
|
||||
}
|
||||
if name == "polymarket" && compare && snapshot["price_check_passed"] != true {
|
||||
ok = false;
|
||||
eprintln!("polymarket: price comparison not confirmed for both outcomes");
|
||||
|
||||
@@ -28,6 +28,27 @@ pub(crate) fn polymarket(client: &Client, compare: bool) -> Result<Value> {
|
||||
.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,
|
||||
@@ -35,22 +56,14 @@ pub(crate) fn polymarket(client: &Client, compare: bool) -> Result<Value> {
|
||||
};
|
||||
let mut outcomes = Vec::new();
|
||||
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.clone()).context("Polymarket orderbook")?;
|
||||
let mut snapshot = books::poly_book(m, asset, &book)?;
|
||||
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]));
|
||||
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);
|
||||
}
|
||||
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
|
||||
@@ -67,14 +80,104 @@ pub(crate) fn kalshi(client: &Client) -> Result<Value> {
|
||||
Url::parse_with_params(root, &[("status", "open"), ("limit", "1")])?,
|
||||
)
|
||||
.context("Kalshi catalog")?;
|
||||
let ticker = markets["markets"]
|
||||
.get(0)
|
||||
.and_then(|m| m["ticker"].as_str())
|
||||
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"]);
|
||||
books::kalshi_book(ticker, &read(client, url).context("Kalshi 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());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user