# Horizon SDK Roadmap

## Current State

- Rust core (PyO3): 3,572 lines
- Python SDK: 1,271 lines
- Tests: 1,920 lines (62 Rust + 143 Python, all passing)
- Live trading on Polymarket + Kalshi + Paper
- 8-point risk pipeline, multi-exchange routing, SQLite persistence, TUI dashboard

---

## Phase 1: Backtesting + Analytics (Foundation)

### 1.1 Backtesting Engine
- [ ] `hz.backtest()` entry point with same pipeline signature as `hz.run()`
- [ ] Historical data ingestion (CSV, JSON, Parquet)
- [ ] Event-driven replay through the Engine (reuse paper exchange matching)
- [ ] Configurable fill simulation (slippage models: fixed, proportional, square-root market impact)
- [ ] Latency simulation (configurable order-to-fill delay in ticks)
- [ ] Multi-market lifecycle (markets created/resolved on schedules during replay)
- [ ] Binary outcome settlement simulation (contracts settle at 0 or 1)
- [ ] Backtest-live parity (identical code path, just different data source)

### 1.2 Historical Data
- [ ] `HistoricalFeed` class: replay price/bid/ask/volume from file
- [ ] CSV loader (timestamp, price, bid, ask, volume columns)
- [ ] JSON loader (array of tick objects)
- [ ] Data validation (monotonic timestamps, price in [0,1] for prediction markets)
- [ ] Synthetic data generator for testing (`hz.generate_random_walk(...)`)

### 1.3 Performance Analytics
- [ ] `BacktestResult` object returned by `hz.backtest()`
- [ ] Return metrics: total return, CAGR, daily/monthly return distributions
- [ ] Risk-adjusted returns: Sharpe ratio, Sortino ratio, Calmar ratio
- [ ] Drawdown analysis: max drawdown, drawdown duration, underwater curve, recovery factor
- [ ] Trade-level analytics: win rate, profit factor, expectancy, avg win/loss ratio
- [ ] P&L attribution: by market, by exchange, by time period
- [ ] Execution quality: slippage vs limit price, fill rate
- [ ] Equity curve generation (list of (timestamp, equity) points)
- [ ] `result.summary()` pretty-printed report
- [ ] `result.to_csv(path)` export

### 1.4 Prediction Market Metrics
- [ ] Brier score tracking (calibration of probability estimates vs outcomes)
- [ ] Edge tracking (estimated probability vs market price at entry)
- [ ] Resolution P&L attribution (held-to-resolution vs exited-early)
- [ ] Category analytics (performance by market category)
- [ ] Time-to-resolution analysis (P&L as function of entry timing)

---

## Phase 2: Advanced Orders + Order Amendment

### 2.1 Order Amendment
- [ ] `engine.amend_order(order_id, new_price, new_size)` in Rust
- [ ] Exchange trait: `amend_order()` method
- [ ] Polymarket: cancel + resubmit (no native amend)
- [ ] Kalshi: cancel + resubmit (no native amend)
- [ ] Paper exchange: in-place modification
- [ ] Amendment tracking in OrderManager (amendment count, original vs current)

### 2.2 Stop-Loss / Take-Profit
- [ ] `StopOrder` type: trigger price + limit/market execution
- [ ] `TakeProfitOrder` type: trigger on unrealized P&L threshold
- [ ] `BracketOrder`: entry + stop-loss + take-profit as a group
- [ ] Engine-side monitoring loop (check triggers each cycle)
- [ ] OCO (One-Cancels-Other): when SL fills, cancel TP and vice versa

### 2.3 Execution Algorithms
- [ ] `ExecAlgo` base class in Python
- [ ] TWAP: slice large order into equal time intervals
- [ ] VWAP: slice based on historical volume profile
- [ ] Iceberg: show partial size, replenish on fill
- [ ] Engine integration: algo spawns child orders, tracks parent completion
- [ ] Paper exchange: simulate realistic fill rates for algo orders

### 2.4 Smart Order Routing
- [ ] Cross-exchange price comparison before submission
- [ ] Route to exchange with best bid/ask for the target side
- [ ] Fallback routing if primary exchange rejects
- [ ] Routing decision logging for audit

---

## Phase 3: Prediction Market Native Features (The Moat)

### 3.1 Kelly Criterion Sizing
- [ ] `hz.kelly(estimated_prob, market_price)` for binary contracts
- [ ] `hz.fractional_kelly(estimated_prob, market_price, fraction=0.5)`
- [ ] Multi-outcome Kelly optimization (3+ outcomes)
- [ ] Liquidity-adjusted Kelly (reduce size for thin books)
- [ ] Capital lock awareness (account for locked capital on Polymarket)
- [ ] Pipeline-integrated: `kelly_sizer` as a pipeline function

### 3.2 Probability Calibration
- [ ] `CalibrationTracker` class: log (estimated_prob, market_id, timestamp)
- [ ] Resolution callback: mark market as resolved YES/NO
- [ ] Brier score computation (overall and bucketed by probability range)
- [ ] Calibration curve generation (predicted vs actual frequency)
- [ ] De-biasing: suggest probability adjustments based on historical calibration
- [ ] SQLite storage: `calibration_log` table

### 3.3 Yes/No Parity Monitor
- [ ] Track YES + NO prices across all monitored markets
- [ ] Alert when |YES + NO - 1.0| > threshold
- [ ] Cross-platform comparison (same event on Polymarket vs Kalshi)
- [ ] Arbitrage window detection with size estimation
- [ ] `engine.parity_check(market_id)` method

### 3.4 Cross-Platform Arbitrage Detection
- [ ] `ArbitrageScanner` class: compare prices across exchanges for same event
- [ ] Market matching heuristic (slug similarity, manual mapping)
- [ ] Net-of-fees arbitrage calculation (account for maker/taker fees per platform)
- [ ] Execution feasibility check (liquidity on both sides)
- [ ] Alert/webhook on arbitrage window open/close
- [ ] `hz.arb_scan(markets, exchanges)` convenience function

### 3.5 Market Lifecycle Management
- [ ] Settlement-aware order management (auto-cancel approaching resolution)
- [ ] Expiration-triggered exits (option to hold to settlement or exit before)
- [ ] Resolution oracle integration (UMA for Polymarket, Kalshi official)
- [ ] Auto-reconcile positions on settlement
- [ ] Capital freed notification on resolution

### 3.6 Market Discovery
- [ ] `hz.discover_markets(exchange, category, min_volume, ...)` search API
- [ ] Polymarket: Gamma API market search with filters
- [ ] Kalshi: market listing with filters
- [ ] Market metadata enrichment (description, resolution criteria, volume, spread)
- [ ] New market creation alerts (poll for new markets, notify via webhook)

---

## Phase 4: Market Data + Monitoring + Alerting

### 4.1 L2 Orderbook Feeds
- [ ] `OrderbookSnapshot` type: list of (price, size) levels for bid/ask
- [ ] Polymarket WebSocket orderbook (full depth, not just best bid/ask)
- [ ] Kalshi orderbook polling (full depth)
- [ ] Orderbook-derived metrics: spread, mid, imbalance, depth at N levels
- [ ] Feed into Context for strategy use

### 4.2 Cross-Platform Price Aggregation
- [ ] Unified price view across Polymarket + Kalshi for same events
- [ ] Configurable market mapping (manual or slug-based matching)
- [ ] Composite feed: weighted average, best bid/ask across venues
- [ ] Price divergence alerts

### 4.3 Historical Data Warehouse
- [ ] Tick data storage in SQLite (timestamp, source, price, bid, ask, volume)
- [ ] Configurable retention policy (keep N days, archive older)
- [ ] Query API: `engine.history(market_id, start, end)` returns DataFrame-like
- [ ] Export: CSV, JSON
- [ ] Feed recording mode: capture live feeds to file for later replay in backtest

### 4.4 Alerting System
- [ ] `AlertManager` class with configurable channels
- [ ] Webhook alerts (POST to URL with JSON payload)
- [ ] Telegram bot integration
- [ ] Discord webhook integration
- [ ] Alert types: fill notification, risk trigger, market resolution, feed stale, arb window
- [ ] Alert throttling (max N alerts per M minutes)
- [ ] `hz.run(..., alerts={...})` configuration

### 4.5 Prometheus Metrics
- [ ] `/metrics` HTTP endpoint (optional, start with `hz.run(..., metrics_port=9090)`)
- [ ] Counters: orders_submitted, orders_filled, orders_rejected, fills_total
- [ ] Gauges: open_orders, active_positions, total_pnl, unrealized_pnl
- [ ] Histograms: order_latency_ms, fill_slippage
- [ ] Per-exchange and per-market labels

### 4.6 Enhanced Dashboard
- [ ] P&L chart panel (equity curve over time, rendered in TUI)
- [ ] Orderbook depth visualization
- [ ] Feed health panel (latency, update frequency, staleness)
- [ ] Alert log panel
- [ ] Interactive controls: adjust parameters, pause/resume quoting
- [ ] Export snapshot to file

---

## Phase 5: Multi-Strategy + ML + Developer Experience

### 5.1 Multi-Strategy Management
- [ ] Strategy isolation: separate P&L, independent risk limits per strategy
- [ ] Shared Engine with per-strategy namespacing
- [ ] Capital allocation: fixed, proportional, or performance-weighted per strategy
- [ ] Cross-strategy correlation monitoring
- [ ] `hz.run_multi(strategies=[...])` entry point

### 5.2 AI/ML Integration
- [ ] `ProbabilityModel` protocol: any object with `.predict(context) -> float`
- [ ] Pipeline integration: model as first function in pipeline
- [ ] Calibration feedback loop: compare model predictions vs resolutions
- [ ] Feature engineering helpers (rolling stats, feed-derived features)
- [ ] ONNX model serving support (load .onnx model, run inference in Rust)
- [ ] LLM agent support: wrap LLM calls as probability estimators

### 5.3 News/Sentiment Feeds
- [ ] Twitter/X sentiment feed (via API or scraping proxy)
- [ ] News headline feed (RSS, webhook)
- [ ] Sentiment scoring (positive/negative/neutral with market relevance)
- [ ] Pipeline integration: sentiment as Context field

### 5.4 Developer Experience
- [ ] `hz init` CLI command: scaffold a new strategy project
- [ ] `hz sweep` CLI command: parameter grid search over backtest
- [ ] `hz replay` CLI command: replay recorded feed data
- [ ] Dry-run mode: execute against real orderbooks without submitting
- [ ] Hot reload: update pipeline params without restart (watch config file)
- [ ] Jupyter notebook integration: inline backtest results, charts
- [ ] Strategy templates: market maker, arb, mean reversion, news-driven

### 5.5 Compliance & Audit
- [ ] Decision journal: log estimated probability, edge, model inputs per trade
- [ ] Tax lot tracking: cost basis per contract for tax reporting
- [ ] Reconciliation reports: compare internal state vs exchange state
- [ ] Geo-fencing: check jurisdiction before trading (prediction market regulation varies)
- [ ] Full audit trail export (JSON/CSV of all orders, fills, risk events, state changes)
