NaxosDataNaxosData

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.

Python SDK (10-Line Integration)pip install naxosdata
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.

Authentication Header Format
# 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"
Response Telemetry Headers

All REST responses include institutional telemetry headers enabling your algorithms to track latency, rate limit budgets, and historical row consumption in real time:

Header NameTypeDescription
X-Naxos-Latency-MsintegerServer processing round-trip execution duration in milliseconds.
X-RateLimit-LimitintegerMaximum allowed requests per rolling 60-second window for your tier.
X-RateLimit-RemainingintegerRemaining requests available before the current 60-second window resets.
X-Quota-Rows-UsedintegerCumulative historical L2 rows consumed in the current calendar month.
X-Quota-Rows-LimitintegerTotal 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 NameArrow TypeDescriptionCanonical Example
exchange_ts_msINT64Matching engine UTC timestamp at tick arrival in milliseconds.1730000000300
ingest_ts_msINT64Ingress wire timestamp at collector gateway in milliseconds.1730000000302
venueVARCHARPOLYMARKET | KALSHI | LIMITLESS | PREDICTIT | DRIFT_BET | SMARKETS."POLYMARKET"
market_idVARCHARNative venue contract identifier."poly-fed-nov-2026"
pair_idVARCHARCross-venue canonical clustering identifier for matched contracts."PAIR_FED_NOV26_25BPS"
seq_numINT64Monotonically increasing sequence number emitted by the venue feed.884129402
best_bidFLOAT64Top resting bid price in canonical USD [0.0001–0.9999].0.635
best_askFLOAT64Top resting ask price in canonical USD [0.0001–0.9999].0.640
spread_bpsFLOAT64Top-of-book bid-ask spread expressed in basis points.78.4
obi_top5FLOAT64Top-5 Level 2 orderbook volume imbalance ratio [-1.0 to +1.0].0.124
bidsSTRUCT[]Standardized 20-level resting bids [price: FLOAT32, size: FLOAT64, total: FLOAT64].[price: 0.635, size: 32000]
asksSTRUCT[]Standardized 20-level resting asks [price: FLOAT32, size: FLOAT64, total: FLOAT64].[price: 0.640, size: 25000]
calculated_volume_24hFLOAT64Rolling 24-hour notional USD volume computed at tick time.4210500.0
vwap_1hFLOAT64Volume-weighted average execution price over trailing 60 minutes.0.6384
ORDER BOOK IMBALANCE (OBI) FORMULA

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:

MATHEMATICAL RECIPROCAL FORMULA:
Canonical_YES_Ask_Price = 1.00 - Raw_NO_Bid_Price
Canonical_YES_Ask_Size = Raw_NO_Bid_Size
RAW KALSHI FEED (BEFORE)
{
  "ticker": "KXFED-26NOV-T25",
  "yes_dollars": [[61.8, 34000]],
  "no_dollars":  [[37.8, 28000]],
  "ts": 1730000000210
}
NAXOSDATA NORMALIZED USD (AFTER)
{
  "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:

VenueUnderlying TechSettlement OracleTaker Fee FormulaGas / Flat Overhead
PolymarketPolygon POS (ERC-1155)UMA Optimistic Oracle v20 bps (0.0% CLOB taker fee)~$0.008/tx (Polygon gas)
KalshiCFTC Regulated DCMOfficial Gov / BLS / FedWireceil(0.07 × C × P × (1 - P) × 100) / 100$0.00 (No gas)
LimitlessBase L2 (EVM)Pyth Price Feeds / Multi-sig10 bps (0.10% on notional)~$0.004/tx (Base gas)
PredictItVictoria University (CFTC)Rules Committee Verification10% on net profit: 0.10 × C × (1 - P)5% withdrawal fee
Drift BETSolana DEX OrderbookPyth / Switchboard Oracles5 bps (0.05% on notional)~$0.001/tx (Solana micro-gas)
SmarketsUKGC / MGA Betting CLOBOfficial Sports / Election Results2.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:

Resolution & Oracle Comparator
Open Tool

Forensically audit oracle settlement disparities between Polymarket (UMA Optimistic Oracle v2 token votes) and Kalshi (CFTC-regulated official government releases).

Timezone Trap: Polymarket closes UTC 23:59:59 vs Kalshi EST 23:59:59 (4–5 hr unhedged window).
Recount Clause: Kalshi settles on certified tabulations; UMA may resolve immediately on AP media call.
Double-Loss Risk: Both legs settle to $0.00 if legal definitions diverge.
Arbitrage Breakeven & Quadratic Fee Solver
Open Tool

Calculates Kalshi's nonlinear variance curve 0.07 × C × P × (1 - P) and solves for the counterpart NO execution price threshold.

Peak Variance Fee: $0.0175/contract at P = 0.50 (quadratic apex).
Breakeven Solver: Computes counterpart max ask for +0.0%, +1.5%, and +3.0% net ROI.
Net Spread: Gross spread minus Polymarket gas and Kalshi variance fee.

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:

100-Point Fungibility Scoring Model
1. Oracle Match (40 pts)

Alignment of primary settlement authorities (UMA vs CFTC/BLS vs Pyth).

2. Expiration Alignment (30 pts)

Delta between contract resolution cutoff timestamps in minutes.

3. Cutoff & Void Terms (30 pts)

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:

Partitioning Structure
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-*.parquet

Use 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.

TradeRecord Schema — PyArrowPOLYMARKET · KALSHI
Field NameArrow TypeDescriptionExample
exchange_ts_msINT64Trade execution UTC timestamp (milliseconds).1730000000450
venueVARCHARPOLYMARKET or KALSHI."POLYMARKET"
market_idVARCHARNative venue contract identifier."poly-fed-nov-2026"
trade_idVARCHARUnique on-chain trade identifier or UUID."0x0c71ae7..."
priceFLOAT64Execution price in canonical USD [0.0001–0.9999].0.610
sizeFLOAT64Number of contracts / USD notional filled.16.39
sideVARCHARBUY or SELL — taker aggressor direction."BUY"
taker_sideVARCHARYES or NO — contract leg swept by taker."YES"
trader_walletVARCHAROn-chain trader wallet address (Polymarket only)."0x45d9212..."
trader_nameVARCHARResolved pseudonym if available."Alonmax"
transaction_hashVARCHARPolygon/Ethereum on-chain tx hash (Polymarket only)."0xfbaa12..."
is_block_tradeBOOLTrue if confirmed negotiated block trade.false
DuckDB Querying Example
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.

CommentRecord Schema — PyArrowPOLYMARKET NLP
Field NameArrow TypeDescriptionExample
created_at_msINT64Comment post timestamp UTC (milliseconds).1730000100000
venueVARCHARAlways POLYMARKET for this stream."POLYMARKET"
market_idVARCHARPolymarket event/market slug."poly-fed-nov-2026"
comment_idVARCHARUnique numeric comment identifier."3305081"
user_addressVARCHARPolymarket wallet address of commenter."0xc22d0f7..."
user_nameVARCHARResolved display name if set."Trader007"
textVARCHARFull raw comment text."Fed will hold 100%"
reaction_countINT32Total emoji reaction count at scrape time.12
reply_countINT32Number of child reply comments.3
sentiment_scoreFLOAT32Polarity score [-1.0 bearish → +1.0 bullish].0.72
SENTIMENT ALPHA SIGNAL CONSTRUCTION

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.

GET/v1/markets

Query the unified prediction market catalog across all six venues. Filter by venue, category, or lifecycle status.

QUERY PARAMETERS
venue: ALL | POLYMARKET | KALSHI | LIMITLESS | PREDICTIT | DRIFT_BET | SMARKETS
status: ACTIVE | RESOLVED | HALTED
category: Macro | Politics | Crypto | Economics
search: Full-text search string
GET/v1/orderbooks/{venue}/{market_id}/snapshot

Retrieve 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.

SAMPLE RESPONSE
{
  "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
}
GET/v1/orderbooks/{venue}/{market_id}/history

Retrieve historical OHLCV bars, calculated rolling volume, VWAP series, and top-of-book spread timeseries.

GET/v1/pairs

Synchronized cross-venue canonical pair matrix. Compares counterpart markets, computes rule fungibility scores (0–100), and calculates exact net-of-fee arbitrage ROI.

SAMPLE RESPONSE
{
  "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
  }]
}
POST/v1/backtest

Simulate multi-level depth depletion, asymmetric wire latency, and exact taker fee deductions on historical order book ticks.

REQUEST BODY
{
  "bankroll": 5000,
  "latency_ms": 35,
  "min_spread_cents": 1.5,
  "pair_id": "PAIR_FED_NOV26_25BPS"
}
GET/v1/health

System connectivity, continuous Parquet recorder heartbeat, wire latency metrics across all 6 prediction venues, partition totals, and real-time trades & sentiment row counters.

SAMPLE RESPONSE
{
  "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"]
  }
}
GET/v1/usage

Retrieve current API key usage telemetry, remaining 60-second rate limits, and historical row consumption against your subscription tier quota.

SAMPLE RESPONSE
{
  "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
}
GET/v1/tradesPOLYMARKET · KALSHI

Query executed public trade records with on-chain trader wallet addresses, transaction hashes, execution price, contract fill size, and taker aggressive side.

QUERY PARAMETERS
venue: POLYMARKET | KALSHI
market_id: Optional market ID
limit: Integer (1–500, default 25)
SAMPLE RESPONSE
{
  "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/"
}
GET/v1/sentimentPOLYMARKET NLP

Query real-time discussion comments stream scored with compound sentiment polarity [-1.0 bearish to +1.0 bullish], reply counts, and emoji reaction counts.

QUERY PARAMETERS
market_id: Polymarket event slug
limit: Integer (1–500, default 25)
SAMPLE RESPONSE
{
  "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/"
}
GET / POST/v1/keys

Provision new labeled API keys, audit existing keys, or revoke compromised keys. Pass action: "create" | "revoke" in POST body.

SAMPLE RESPONSE
{
  "status": "success",
  "tier": "institutional",
  "keys": [
    { "id": "key-1", "name": "Primary Production Worker", "key": "nx_inst_...", "created": "2026-10-25" }
  ]
}
POST/v1/auth/login · /v1/auth/register

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:

STREAMGET /v1/stream/orderbooks?market_id={id}&pair_id={pair_id}

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 TierRate LimitHistorical LookbackMonthly L2 Export QuotaDaily Max Requests
Hobbyist ($0/mo)60 req / min3-day lookback250,000 rows / mo10,000 req / day
Quant Pro ($30/mo)300 req / min90-day lookback10,000,000 rows / mo100,000 req / day
Institutional ($100/mo)1,000 req / minUnlimited (All-time history)100,000,000 rows / mo1,000,000 req / day

14. Error Codes & Handling

Standard HTTP status codes are accompanied by machine-readable error codes in the response body:

HTTP StatusError CodeDescription & Action
401 UnauthorizedUNAUTHORIZEDMissing or invalid API key. Pass a valid Bearer token in the Authorization header.
403 ForbiddenLOOKBACK_EXCEEDEDQueried historical timestamp exceeds your subscription tier lookback limit.
404 Not FoundNOT_FOUNDSpecified venue or market ID does not exist in the active or historical catalog.
429 Too Many RequestsRATE_LIMIT_EXCEEDEDPer-minute rate limit exceeded. Inspect Retry-After header for backoff seconds.
429 Too Many RequestsQUOTA_EXCEEDEDMonthly historical row export quota depleted. Upgrade your tier to resume exports.
500 Server ErrorINTERNAL_ERRORInternal 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:

Core CLI Commands
python main.py preflight

Validates local API keys, network wire latency, and WebSocket socket connectivity across all six prediction venues.

python main.py record --venues ALL

Launches multi-threaded asynchronous L2 order book recorder and writes partitioned Apache Arrow Parquet archives.

python main.py inspect-archive

Audits local Parquet partitions, verifies schema consistency, and checks millisecond timestamp monotonicity.

python main.py scan-alerts

Scans live cross-venue order books for net-of-fee mispricings and dispatches instant webhook alerts to Telegram or Discord.

16. Event-Driven Backtesting Workflow

Quant Engine Spec

Dual-leg prediction market arbitrage requires simulating three microstructural realities that destroy naive paper returns:

1. Asymmetric Wire Latency

Models empirical latency offsets: Polygon RPC commit (14.2ms) vs direct Kalshi API gateway (8.2ms).

2. Depth Sweep VWAP

Walks down resting depth rungs to calculate real execution fill price and slippage rather than naive top-of-book.

3. Unhedged Leg Risk

Models partial fill mismatches when Leg 1 completes but Leg 2 liquidity evaporates, factoring emergency unwind losses.

event_driven_arbitrage_backtester.py
"""
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

Live Query Runner

Execute live queries directly against the local and production API endpoints with authenticated session telemetry: