Technical Documentation
NaxosData API & SDK Reference
Institutional market data infrastructure for prediction markets. Standardized Level 2 order book normalization, cross-venue canonical matching, sub-millisecond streaming, quantitative settlement oracle auditing, and latency-modeled execution backtesting across all six supported prediction venues.
1. Quickstart
Get started with our institutional Python client library or native HTTP requests in less than two minutes. The SDK provides high-level bindings for normalized Level 2 order books, cross-venue arbitrage pairs, settlement oracle auditing, and local strategy execution.
import os
from naxosdata import NaxosClient, Venue
client = NaxosClient(api_key=os.getenv("NAXOS_API_KEY", "nx_inst_live"))
# 1. Fetch normalized Level 2 snapshot (20-level depth)
snap = client.get_orderbook_snapshot(venue=Venue.POLYMARKET, market_id="poly-fed-nov-2026")
print(f"Spread: {snap.spread_bps} bps | Best Bid: ${snap.best_bid:.3f} | Best Ask: ${snap.best_ask:.3f}")
# 2. Query cross-venue matched pairs filtered by volume & oracle alignment
pairs = client.get_pairs(min_fungibility=80, min_volume=10000.0)
for p in pairs[:3]:
print(f"[{p.pair_id}] {p.venue_long} -> {p.venue_short} | Net ROI: +{p.net_roi_pct:.2f}% | Score: {p.fungibility_score}/100")2. Authentication & Headers
Every request to the NaxosData REST API or real-time streaming endpoints must include an authenticated API key. Pass your key through either the standard HTTP Authorization: Bearer <key> header or the X-Naxos-API-Key header.
# Standard Bearer Token Authorization curl -X GET "https://api.naxosdata.com/v1/markets" \ -H "Authorization: Bearer nx_live_9f8a3c7e12b4a8d05c6e81a4b92d7f3e" \ -H "Accept: application/json" # Alternative API Key Header curl -X GET "https://api.naxosdata.com/v1/markets" \ -H "X-Naxos-API-Key: nx_live_9f8a3c7e12b4a8d05c6e81a4b92d7f3e"
All REST responses include institutional telemetry headers enabling your algorithms to track latency, rate limit budgets, and historical row consumption in real time:
| Header Name | Type | Description |
|---|---|---|
| X-Naxos-Latency-Ms | integer | Server processing round-trip execution duration in milliseconds. |
| X-RateLimit-Limit | integer | Maximum allowed requests per rolling 60-second window for your tier. |
| X-RateLimit-Remaining | integer | Remaining requests available before the current 60-second window resets. |
| X-Quota-Rows-Used | integer | Cumulative historical L2 rows consumed in the current calendar month. |
| X-Quota-Rows-Limit | integer | Total monthly row export allowance for your current subscription tier. |
3. Six-Venue Level 2 Orderbook Normalization Schema
Every prediction market exchange employs disparate data schemas: Polymarket represents binary contracts as ERC-1155 token balances on Polygon POS, Kalshi provides raw YES and NO bid rungs, Limitless utilizes Base smart contracts, PredictIt exposes integer cent shares, Drift BET operates on Solana DEX accounts, and Smarkets runs on a UKGC exchange CLOB. NaxosData normalizes all six exchanges into a canonical Level 2 book with 20 rungs of resting depth and uniform 0.0001–0.9999 probability pricing.
| Field Name | Arrow Type | Description | Canonical Example |
|---|---|---|---|
| exchange_ts_ms | INT64 | Matching engine UTC timestamp at tick arrival in milliseconds. | 1730000000300 |
| ingest_ts_ms | INT64 | Ingress wire timestamp at collector gateway in milliseconds. | 1730000000302 |
| venue | VARCHAR | POLYMARKET | KALSHI | LIMITLESS | PREDICTIT | DRIFT_BET | SMARKETS. | "POLYMARKET" |
| market_id | VARCHAR | Native venue contract identifier. | "poly-fed-nov-2026" |
| pair_id | VARCHAR | Cross-venue canonical clustering identifier for matched contracts. | "PAIR_FED_NOV26_25BPS" |
| seq_num | INT64 | Monotonically increasing sequence number emitted by the venue feed. | 884129402 |
| best_bid | FLOAT64 | Top resting bid price in canonical USD [0.0001–0.9999]. | 0.635 |
| best_ask | FLOAT64 | Top resting ask price in canonical USD [0.0001–0.9999]. | 0.640 |
| spread_bps | FLOAT64 | Top-of-book bid-ask spread expressed in basis points. | 78.4 |
| obi_top5 | FLOAT64 | Top-5 Level 2 orderbook volume imbalance ratio [-1.0 to +1.0]. | 0.124 |
| bids | STRUCT[] | Standardized 20-level resting bids [price: FLOAT32, size: FLOAT64, total: FLOAT64]. | [price: 0.635, size: 32000] |
| asks | STRUCT[] | Standardized 20-level resting asks [price: FLOAT32, size: FLOAT64, total: FLOAT64]. | [price: 0.640, size: 25000] |
| calculated_volume_24h | FLOAT64 | Rolling 24-hour notional USD volume computed at tick time. | 4210500.0 |
| vwap_1h | FLOAT64 | Volume-weighted average execution price over trailing 60 minutes. | 0.6384 |
OBI = (∑ Size_Bids[1..5] - ∑ Size_Asks[1..5]) / (∑ Size_Bids[1..5] + ∑ Size_Asks[1..5]). Positive values denote bid depth superiority, signaling upward short-term pressure; negative values denote ask depth superiority.
4. Kalshi Reciprocal Order Book Inversion
In Kalshi’s native protocol, market makers only place bids on YES or NO contracts. Buying a NO contract at 38¢ is mathematically equivalent to selling a YES contract at 62¢. Because raw Kalshi WebSocket feeds return two bid arrays (yes_dollars and no_dollars), NaxosData continuously computes the reciprocal ask ladder:
{
"ticker": "KXFED-26NOV-T25",
"yes_dollars": [[61.8, 34000]],
"no_dollars": [[37.8, 28000]],
"ts": 1730000000210
}{
"pair_id": "PAIR_FED_NOV26_25BPS",
"bids": [{"price": 0.618, "size": 34000}],
"asks": [{"price": 0.622, "size": 28000}],
"spread_bps": 64
}5. Six-Venue Fee Matrix & Settlement Specifications
Accurate cross-exchange arbitrage calculations require exact fee deduction curves for each exchange. NaxosData embeds precise exchange-specific mathematical fee functions across all six venues:
| Venue | Underlying Tech | Settlement Oracle | Taker Fee Formula | Gas / Flat Overhead |
|---|---|---|---|---|
| Polymarket | Polygon POS (ERC-1155) | UMA Optimistic Oracle v2 | 0 bps (0.0% CLOB taker fee) | ~$0.008/tx (Polygon gas) |
| Kalshi | CFTC Regulated DCM | Official Gov / BLS / FedWire | ceil(0.07 × C × P × (1 - P) × 100) / 100 | $0.00 (No gas) |
| Limitless | Base L2 (EVM) | Pyth Price Feeds / Multi-sig | 10 bps (0.10% on notional) | ~$0.004/tx (Base gas) |
| PredictIt | Victoria University (CFTC) | Rules Committee Verification | 10% on net profit: 0.10 × C × (1 - P) | 5% withdrawal fee |
| Drift BET | Solana DEX Orderbook | Pyth / Switchboard Oracles | 5 bps (0.05% on notional) | ~$0.001/tx (Solana micro-gas) |
| Smarkets | UKGC / MGA Betting CLOB | Official Sports / Election Results | 2.0% (200 bps) flat commission on net profit | $0.00 (No gas) |
6. Quantitative Tooling Suite & Mathematical Solvers
NaxosData ships two browser-based and programmatic quantitative utilities designed for prediction market arbitrage desks to prevent double-leg divergence wipeouts and eliminate fee leakage:
Forensically audit oracle settlement disparities between Polymarket (UMA Optimistic Oracle v2 token votes) and Kalshi (CFTC-regulated official government releases).
Calculates Kalshi's nonlinear variance curve 0.07 × C × P × (1 - P) and solves for the counterpart NO execution price threshold.
7. Matched Pairs Matrix & Multi-Venue Filtering
NaxosData cross-indexes contracts across all six exchanges using our semantic entity resolution pipeline. Every matched pair is assigned a canonical pair_id and scored across 3 risk vectors:
Alignment of primary settlement authorities (UMA vs CFTC/BLS vs Pyth).
Delta between contract resolution cutoff timestamps in minutes.
Handling of government shutdowns, statistical revisions, and recount disputes.
8. Parquet Historical Dataset Archives
Historical Level 2 order book ticks are written to disk as partitioned Apache Arrow Parquet datasets. Quants can stream or download complete microstructural archives for local backtesting:
data/archive/
├── orderbooks/
│ └── venue=POLYMARKET/
│ └── market_id=poly-fed-nov-2026/
│ └── date=2026-10-30/
│ └── orderbooks-1730290800.parquet # 20-level bids/asks, OBI, seq_num
├── trades/
│ ├── venue=POLYMARKET/date=2026-10-30/trades-*.parquet
│ └── venue=KALSHI/date=2026-10-30/trades-*.parquet
└── sentiment/
└── venue=POLYMARKET/date=2026-10-30/comments-*.parquetUse the only_recorded=true query parameter on the /v1/pairs endpoint to restrict queries strictly to matched contracts backed by verified local Parquet archives.
9. Executed Trades Tape — Polymarket & Kalshi
NaxosData continuously ingests the live public executed trades tape from Polymarket and Kalshi. Every on-chain or exchange-confirmed fill — including trader wallet address, transaction hash, execution price, contract size, and taker direction — is committed to Apache Parquet partitions at data/archive/trades/venue={VENUE}/date={YYYY-MM-DD}/trades-*.parquet.
| Field Name | Arrow Type | Description | Example |
|---|---|---|---|
| exchange_ts_ms | INT64 | Trade execution UTC timestamp (milliseconds). | 1730000000450 |
| venue | VARCHAR | POLYMARKET or KALSHI. | "POLYMARKET" |
| market_id | VARCHAR | Native venue contract identifier. | "poly-fed-nov-2026" |
| trade_id | VARCHAR | Unique on-chain trade identifier or UUID. | "0x0c71ae7..." |
| price | FLOAT64 | Execution price in canonical USD [0.0001–0.9999]. | 0.610 |
| size | FLOAT64 | Number of contracts / USD notional filled. | 16.39 |
| side | VARCHAR | BUY or SELL — taker aggressor direction. | "BUY" |
| taker_side | VARCHAR | YES or NO — contract leg swept by taker. | "YES" |
| trader_wallet | VARCHAR | On-chain trader wallet address (Polymarket only). | "0x45d9212..." |
| trader_name | VARCHAR | Resolved pseudonym if available. | "Alonmax" |
| transaction_hash | VARCHAR | Polygon/Ethereum on-chain tx hash (Polymarket only). | "0xfbaa12..." |
| is_block_trade | BOOL | True if confirmed negotiated block trade. | false |
import duckdb
# Query VWAP and order flow toxicity by trader wallet
df = duckdb.query("""
SELECT
venue,
market_id,
side,
COUNT(*) as total_fills,
ROUND(SUM(size * price) / SUM(size), 4) as vwap,
ROUND(SUM(size * price), 2) as volume_usd
FROM 'data/archive/trades/**/*.parquet'
WHERE date = CURRENT_DATE
GROUP BY venue, market_id, side
ORDER BY volume_usd DESC
LIMIT 20
""").df()
print(df)10. Polymarket Sentiment Comments Stream
Every public discussion comment submitted on Polymarket prediction contracts is scraped, deduplicated, and scored in real-time. This provides a continuous NLP sentiment signal aligned with the microstructural L2 order book timeline. Comments are archived at data/archive/sentiment/venue=POLYMARKET/date={YYYY-MM-DD}/comments-*.parquet with normalized compound polarity scores.
| Field Name | Arrow Type | Description | Example |
|---|---|---|---|
| created_at_ms | INT64 | Comment post timestamp UTC (milliseconds). | 1730000100000 |
| venue | VARCHAR | Always POLYMARKET for this stream. | "POLYMARKET" |
| market_id | VARCHAR | Polymarket event/market slug. | "poly-fed-nov-2026" |
| comment_id | VARCHAR | Unique numeric comment identifier. | "3305081" |
| user_address | VARCHAR | Polymarket wallet address of commenter. | "0xc22d0f7..." |
| user_name | VARCHAR | Resolved display name if set. | "Trader007" |
| text | VARCHAR | Full raw comment text. | "Fed will hold 100%" |
| reaction_count | INT32 | Total emoji reaction count at scrape time. | 12 |
| reply_count | INT32 | Number of child reply comments. | 3 |
| sentiment_score | FLOAT32 | Polarity score [-1.0 bearish → +1.0 bullish]. | 0.72 |
Aggregate sentiment_score by market, weighted by reaction_count, over a rolling 4-hour window. Cross-reference against L2 obi_top5 for signal confirmation. High-reaction bullish comment clusters correlated with L2 bid imbalance historically precede price moves of 3–8 bps.
11. REST Endpoints Reference
All endpoints accept JSON requests and return structured JSON responses. Pass authentication via Bearer token.
Query the unified prediction market catalog across all six venues. Filter by venue, category, or lifecycle status.
venue: ALL | POLYMARKET | KALSHI | LIMITLESS | PREDICTIT | DRIFT_BET | SMARKETSstatus: ACTIVE | RESOLVED | HALTEDcategory: Macro | Politics | Crypto | Economicssearch: Full-text search stringRetrieve a normalized 20-level Level 2 order book snapshot with bids, asks, mid-price, spread basis points, and order book imbalance (OBI). Pass optional timestamp_ms for point-in-time historical reconstruction.
{
"status": "success",
"venue": "POLYMARKET",
"market_id": "poly-fed-nov-2026",
"pair_id": "PAIR_FED_NOV26_25BPS",
"best_bid": 0.635,
"best_ask": 0.640,
"spread_bps": 78.4,
"bids": [{"price": 0.635, "size": 32000, "total": 32000, "notional": 20320}],
"asks": [{"price": 0.640, "size": 25000, "total": 25000, "notional": 16000}],
"wire_lag_ms": 14,
"seq_num": 884129402
}Retrieve historical OHLCV bars, calculated rolling volume, VWAP series, and top-of-book spread timeseries.
Synchronized cross-venue canonical pair matrix. Compares counterpart markets, computes rule fungibility scores (0–100), and calculates exact net-of-fee arbitrage ROI.
{
"status": "success",
"data": [{
"pair_id": "PAIR_FED_NOV26_25BPS",
"venue_long": "POLYMARKET",
"market_id_long": "poly-fed-nov-2026",
"venue_short": "KALSHI",
"market_id_short": "KXFED-26NOV-T25",
"fungibility_score": 98,
"net_roi_pct": 2.14,
"gross_edge_bps": 280,
"fee_deduction_bps": 66,
"is_live_recorded": true
}]
}Simulate multi-level depth depletion, asymmetric wire latency, and exact taker fee deductions on historical order book ticks.
{
"bankroll": 5000,
"latency_ms": 35,
"min_spread_cents": 1.5,
"pair_id": "PAIR_FED_NOV26_25BPS"
}System connectivity, continuous Parquet recorder heartbeat, wire latency metrics across all 6 prediction venues, partition totals, and real-time trades & sentiment row counters.
{
"status": "healthy",
"recorder_active": true,
"archive_stats": {
"total_markets": 452,
"total_pairs": 100,
"total_partitions": 359,
"total_orderbook_rows": 47218,
"total_trades_written": 71244,
"total_comments_written": 3,
"venues": ["POLYMARKET", "KALSHI", "LIMITLESS", "PREDICTIT", "DRIFT_BET", "SMARKETS"]
}
}Retrieve current API key usage telemetry, remaining 60-second rate limits, and historical row consumption against your subscription tier quota.
{
"status": "success",
"tier": { "name": "Institutional", "rate_limit_per_min": 1000, "monthly_row_quota": 100000000 },
"requests_this_minute": 14,
"rate_limit_remaining": 986,
"rows_used": 2450000
}Query executed public trade records with on-chain trader wallet addresses, transaction hashes, execution price, contract fill size, and taker aggressive side.
venue: POLYMARKET | KALSHImarket_id: Optional market IDlimit: Integer (1–500, default 25){
"status": "success",
"venue": "POLYMARKET",
"count": 25,
"data": [{
"exchange_ts_ms": 1730000000450,
"venue": "POLYMARKET",
"market_id": "poly-fed-nov-2026",
"trade_id": "0x0c71ae75d81b...",
"price": 0.610,
"size": 16.39,
"side": "BUY",
"taker_side": "YES",
"trader_wallet": "0x45d9212...",
"is_block_trade": false
}],
"archive_path": "data/archive/trades/venue=POLYMARKET/"
}Query real-time discussion comments stream scored with compound sentiment polarity [-1.0 bearish to +1.0 bullish], reply counts, and emoji reaction counts.
market_id: Polymarket event sluglimit: Integer (1–500, default 25){
"status": "success",
"venue": "POLYMARKET",
"count": 25,
"data": [{
"created_at_ms": 1730000100000,
"venue": "POLYMARKET",
"market_id": "poly-fed-nov-2026",
"comment_id": "3305081",
"user_name": "Trader007",
"text": "Fed will cut 25 bps for sure, core CPI numbers were in line",
"reaction_count": 14,
"sentiment_score": 0.72
}],
"archive_path": "data/archive/sentiment/venue=POLYMARKET/"
}Provision new labeled API keys, audit existing keys, or revoke compromised keys. Pass action: "create" | "revoke" in POST body.
{
"status": "success",
"tier": "institutional",
"keys": [
{ "id": "key-1", "name": "Primary Production Worker", "key": "nx_inst_...", "created": "2026-10-25" }
]
}Institutional authentication gateway. Create user accounts, generate session tokens, and synchronize multi-key permissions.
12. Real-Time WebSocket & SSE Stream
Connect to our real-time streaming endpoint to receive live Level 2 order book updates with monotonic sequence numbers, fluctuating resting depth, and synchronized counterpart books:
Emits an initial event: snapshot payload followed by continuous event: tick delta updates every 500ms with wire latency modeling.
event: snapshot
data: {"type":"snapshot","market_id":"poly-fed-nov-2026","best_bid":0.635,"best_ask":0.640,"seq_num":1000}
event: tick
data: {"type":"l2_delta","timestamp_ms":1730000000500,"best_bid":0.635,"best_ask":0.640,"seq_num":1003,"wire_lag_ms":14}13. Rate Limits & Subscription Tiers
API quotas and rate limits are enforced per API key using rolling 60-second sliding windows and monthly historical row consumption counters:
| Subscription Tier | Rate Limit | Historical Lookback | Monthly L2 Export Quota | Daily Max Requests |
|---|---|---|---|---|
| Hobbyist ($0/mo) | 60 req / min | 3-day lookback | 250,000 rows / mo | 10,000 req / day |
| Quant Pro ($30/mo) | 300 req / min | 90-day lookback | 10,000,000 rows / mo | 100,000 req / day |
| Institutional ($100/mo) | 1,000 req / min | Unlimited (All-time history) | 100,000,000 rows / mo | 1,000,000 req / day |
14. Error Codes & Handling
Standard HTTP status codes are accompanied by machine-readable error codes in the response body:
| HTTP Status | Error Code | Description & Action |
|---|---|---|
| 401 Unauthorized | UNAUTHORIZED | Missing or invalid API key. Pass a valid Bearer token in the Authorization header. |
| 403 Forbidden | LOOKBACK_EXCEEDED | Queried historical timestamp exceeds your subscription tier lookback limit. |
| 404 Not Found | NOT_FOUND | Specified venue or market ID does not exist in the active or historical catalog. |
| 429 Too Many Requests | RATE_LIMIT_EXCEEDED | Per-minute rate limit exceeded. Inspect Retry-After header for backoff seconds. |
| 429 Too Many Requests | QUOTA_EXCEEDED | Monthly historical row export quota depleted. Upgrade your tier to resume exports. |
| 500 Server Error | INTERNAL_ERROR | Internal ingestion connector timeout or unhandled server exception. |
15. Python Client SDK & Local CLI Tools
The open-source naxosdata library provides both programmatic Python bindings and terminal CLI commands for live ingestion and dataset auditing:
python main.py preflightValidates local API keys, network wire latency, and WebSocket socket connectivity across all six prediction venues.
python main.py record --venues ALLLaunches multi-threaded asynchronous L2 order book recorder and writes partitioned Apache Arrow Parquet archives.
python main.py inspect-archiveAudits local Parquet partitions, verifies schema consistency, and checks millisecond timestamp monotonicity.
python main.py scan-alertsScans live cross-venue order books for net-of-fee mispricings and dispatches instant webhook alerts to Telegram or Discord.
16. Event-Driven Backtesting Workflow
Dual-leg prediction market arbitrage requires simulating three microstructural realities that destroy naive paper returns:
Models empirical latency offsets: Polygon RPC commit (14.2ms) vs direct Kalshi API gateway (8.2ms).
Walks down resting depth rungs to calculate real execution fill price and slippage rather than naive top-of-book.
Models partial fill mismatches when Leg 1 completes but Leg 2 liquidity evaporates, factoring emergency unwind losses.
"""
Event-Driven Dual-Leg Prediction Market Arbitrage Backtester
Using NaxosData Synchronized L2 Feeds & Latency Modeling
"""
from dataclasses import dataclass
import math
from typing import List, Dict, Optional
from naxosdata import NaxosClient
@dataclass
class ExecutionResult:
timestamp_ms: int
pair_id: str
leg1_venue: str
leg1_filled: float
leg1_vwap: float
leg1_slippage_bps: int
leg2_venue: str
leg2_filled: float
leg2_vwap: float
leg2_slippage_bps: int
unhedged_shares: float
unwind_loss_usd: float
net_payout_usd: float
total_cost_usd: float
net_profit_usd: float
net_roi_pct: float
class EventDrivenArbBacktester:
def __init__(self, api_key: str, latency_map_ms: Dict[str, float] = None):
self.client = NaxosClient(api_key=api_key)
# Empirical wire latency model
self.latency_map_ms = latency_map_ms or {
"POLYMARKET": 14.2, # Polygon RPC commit & block inclusion
"KALSHI": 8.2, # Direct REST/WebSocket gateway
"LIMITLESS": 12.0, # Base L2 sequencer RPC
"PREDICTIT": 22.0, # Web API polling latency
"DRIFT_BET": 15.5, # Solana RPC slot commitment
"SMARKETS": 11.0, # Smarkets streaming gateway
}
def simulate_order_fill(self, asks: List[dict], target_shares: float):
"""Walks down resting L2 depth rungs to simulate fill size, VWAP, and slippage."""
remaining = target_shares
total_cost = 0.0
filled = 0.0
best_ask = asks[0]["price"] if asks else 0.0
for rung in asks:
available = rung["size"]
price = rung["price"]
fill_amount = min(remaining, available)
total_cost += fill_amount * price
filled += fill_amount
remaining -= fill_amount
if remaining <= 0:
break
vwap = (total_cost / filled) if filled > 0 else best_ask
slippage_bps = int(((vwap - best_ask) / best_ask) * 10000) if best_ask > 0 else 0
return filled, vwap, slippage_bps
def replay_arbitrage_window(self, pair_id: str, target_usd: float = 2500):
# 1. Fetch synchronized cross-venue comparison series from NaxosData
pair = self.client.pairs.comparison(pair_id=pair_id)
print(f"Loaded Pair: {pair_id} | Fungibility: {pair.fungibility_score}/100")
# 2. Iterate millisecond tick frames through historical window
ticks = self.client.orderbooks.timeseries(venue="POLYMARKET", market_id=pair.market_id_long, resolution="100ms")
results: List[ExecutionResult] = []
for tick in ticks:
# Reconstruct exact synchronized L2 depth at tick timestamp
snap_poly = self.client.orderbooks.snapshot(venue=pair.venue_long, market_id=pair.market_id_long, timestamp_ms=tick.timestamp_ms)
# Kalshi order book at timestamp + network latency offset
kalshi_ts = tick.timestamp_ms + int(self.latency_map_ms["KALSHI"])
snap_kalshi = self.client.orderbooks.snapshot(venue=pair.venue_short, market_id=pair.market_id_short, timestamp_ms=kalshi_ts)
# Leg 1: Sweep YES on Polymarket
target_shares = target_usd / (snap_poly.best_ask + (1 - snap_kalshi.best_bid))
leg1_filled, leg1_vwap, leg1_slip = self.simulate_order_fill(snap_poly.asks, target_shares)
# Leg 2: Sweep NO on Kalshi (reciprocal book: NO asks = 1 - YES bids)
kalshi_no_asks = [{"price": round(1 - b["price"], 3), "size": b["size"]} for b in snap_kalshi.bids]
leg2_filled, leg2_vwap, leg2_slip = self.simulate_order_fill(kalshi_no_asks, leg1_filled)
# Model Unhedged Leg Risk & Emergency Unwind
unhedged = abs(leg1_filled - leg2_filled)
unwind_loss = unhedged * 0.045 if unhedged > 0 else 0.0
# Compute Net-of-Fee Arbitrage P&L with exact Kalshi quadratic taker fee
kalshi_fee = math.ceil(0.07 * leg2_filled * leg2_vwap * (1.0 - leg2_vwap) * 100.0) / 100.0
total_cost = (leg1_filled * leg1_vwap) + (leg2_filled * leg2_vwap) + kalshi_fee + unwind_loss
guaranteed_payout = min(leg1_filled, leg2_filled) * 1.00
net_profit = guaranteed_payout - total_cost
net_roi = (net_profit / total_cost) * 100 if total_cost > 0 else 0
results.append(ExecutionResult(
timestamp_ms=tick.timestamp_ms,
pair_id=pair_id,
leg1_venue=snap_poly.venue,
leg1_filled=leg1_filled,
leg1_vwap=leg1_vwap,
leg1_slippage_bps=leg1_slip,
leg2_venue=snap_kalshi.venue,
leg2_filled=leg2_filled,
leg2_vwap=leg2_vwap,
leg2_slippage_bps=leg2_slip,
unhedged_shares=unhedged,
unwind_loss_usd=unwind_loss,
net_payout_usd=guaranteed_payout,
total_cost_usd=total_cost,
net_profit_usd=net_profit,
net_roi_pct=net_roi
))
return results
# Replay Fed Cut arbitrage window
sim = EventDrivenArbBacktester(api_key="nx_inst_live")
executions = sim.replay_arbitrage_window(pair_id="PAIR_FED_NOV26_25BPS", target_usd=2500)
profitable = [e for e in executions if e.net_profit_usd > 0]
print(f"Replay complete: {len(profitable)}/{len(executions)} arbitrage executions profitable net of fees & wire latency.")17. Interactive REST API Sandbox
Execute live queries directly against the local and production API endpoints with authenticated session telemetry: