# Horizon SDK - Autonomous Execution Roadmap

The grand vision: an LLM plugs in via MCP and autonomously operates a prediction market hedge fund. This roadmap tracks every system needed to get there.

**Status legend:** Not started / In Progress / Done

---

## Phase 1: Fund Infrastructure

The fund-level layer that sits above individual strategies and manages capital as a unified book.

### 1.1 Fund Portfolio Manager
- [x] Fund entity with NAV, cash balance, and position aggregation across all strategies
- [x] Capital allocation engine (equal-weight, risk-parity, performance-weighted, custom)
- [x] Fund-wide drawdown circuit breaker (cut all exposure at configurable threshold)
- [x] Cross-strategy correlation matrix (detect when two strategies are making the same bet)
- [ ] Rebalancing scheduler (time-based, drift-based, or event-triggered)
- [ ] Capital reservation system (reserve capital for pending approvals, upcoming opportunities)
- [x] Strategy-level P&L attribution (which strategy contributed what to fund returns)

### 1.2 Fund Accounting
- [x] Real-time NAV calculation (mark-to-market all positions across all strategies)
- [x] Daily NAV snapshots with persistence
- [x] Fee tracking: exchange fees, funding costs, slippage realized vs. estimated
- [ ] Benchmark engine (compare fund returns against naive strategies, market beta)
- [ ] Investor-grade reporting: period returns, risk-adjusted metrics, factor exposures
- [ ] Tax lot tracking (FIFO, LIFO, specific identification) for regulatory reporting
- [ ] Cash flow management (deposits, withdrawals, fee deductions)
- [ ] Multi-currency support (USD, USDC, ETH collateral)

### 1.3 Performance Analytics
- [ ] Rolling Sharpe, Sortino, Calmar at fund level (not just per-backtest)
- [ ] Drawdown watermark tracking with recovery time estimation
- [ ] Win rate, profit factor, and edge metrics aggregated across all strategies
- [ ] Performance persistence analysis (are returns sustainable or decaying?)
- [ ] Peer comparison framework (compare against other Horizon-deployed funds)

---

## Phase 2: Strategy Lifecycle

Programmatic control over strategy deployment, monitoring, scaling, and retirement.

### 2.1 Strategy Controller
- [x] Strategy registry with state machine (pending -> running -> paused -> stopped -> retired -> failed)
- [x] Programmatic deploy: launch a strategy as a background thread from API
- [x] Programmatic stop/pause/resume without killing the process
- [ ] Health monitoring: detect when a strategy is stuck, erroring, or stale
- [ ] Auto-restart on crash with exponential backoff
- [x] Graceful shutdown: cancel orders, snapshot state, free capital back to fund

### 2.2 Strategy Scaling
- [x] Dynamic capital allocation: increase/decrease capital based on performance
- [ ] Ramp-up schedule: new strategies start with small capital, scale up if profitable
- [x] Drawdown-based scaling: auto-reduce capital when a strategy is in drawdown
- [ ] Confidence-weighted sizing: scale capital by the LLM's conviction level
- [x] Maximum strategy count limit (prevent over-diversification)

### 2.3 Strategy Versioning & A/B Testing
- [ ] Strategy versioning: track parameter changes over time
- [ ] A/B testing framework: run two versions on the same market, compare results
- [ ] Shadow mode: run a strategy in paper mode alongside a live strategy
- [ ] Promotion workflow: shadow -> canary (small capital) -> full production
- [ ] Rollback: revert to previous strategy version if new one underperforms

### 2.4 Strategy Templates
- [ ] Pre-built strategy templates the LLM can parameterize and deploy
  - [ ] Directional (signal -> Kelly size -> submit)
  - [ ] Market making (fair value -> spread -> quote)
  - [ ] Arbitrage (detect -> size -> execute)
  - [ ] Copy trading (wallet signal -> filter -> mirror)
  - [ ] Event-driven (catalyst -> position -> manage)
- [ ] Template composition: combine templates (e.g., MM + directional overlay)
- [ ] Parameter schema: typed parameter definitions so the LLM knows what it can tune

---

## Phase 3: Market Intelligence

Systems that help the LLM decide which markets to trade, when, and at what size.

### 3.1 Market Fitness Scoring
- [x] Liquidity score: orderbook depth, spread, trade volume, time-to-fill estimate
- [x] Edge score: how mispriced is this market vs. the LLM's forecast?
- [x] Strategy fitness: which strategy types work on this market? (MM needs liquidity, directional needs edge)
- [ ] Risk score: correlation with existing portfolio, tail risk, event risk
- [x] Composite fitness score combining all dimensions
- [x] Market ranking: sort all available markets by fitness for a given strategy
- [x] Minimum liquidity threshold: auto-exclude markets below depth threshold

### 3.2 Market Resolution Settlement
- [x] Resolution detection: poll exchanges for resolved markets
- [x] Automatic P&L booking on resolution (position settles at 0 or 1)
- [ ] Capital recycling: freed capital automatically returns to fund pool
- [x] Resolution P&L attribution: track resolution profits separately from trading profits
- [ ] Post-resolution analysis: was our edge real? Update market-type models
- [ ] Near-resolution handling: auto-exit positions approaching resolution with high uncertainty
- [ ] Resolution calendar: track expected resolution dates for all active markets

### 3.3 Event Calendar Intelligence
- [ ] Catalyst database: track events that move markets (elections, FOMC, earnings, rulings)
- [ ] Time-to-catalyst scoring: prioritize markets with upcoming catalysts
- [ ] Pre-event positioning: increase exposure before catalysts, reduce after
- [ ] Cross-market catalyst mapping: one event affects multiple markets
- [ ] Historical catalyst impact analysis: how much did similar events move similar markets?

### 3.4 Market Universe Management
- [x] Active market universe: the set of markets the fund is tracking
- [x] Universe expansion: automatically discover and add promising markets
- [x] Universe contraction: remove markets that no longer meet criteria
- [x] Sector/theme grouping: group markets by topic (politics, crypto, sports, weather)
- [ ] Correlation clustering: identify groups of correlated markets

---

## Phase 4: Autonomous Decision Loop

The meta-loop that lets the LLM continuously research, deploy, and improve strategies.

### 4.1 Research Pipeline
- [x] Market scanning: periodic scan of all available markets for opportunities
- [ ] Signal aggregation: combine LLM forecasts, oracle signals, wallet signals, feeds
- [ ] Hypothesis generation: "market X is mispriced because Y"
- [ ] Evidence collection: gather supporting data for each hypothesis
- [x] Confidence scoring: how confident is the LLM in each hypothesis?

### 4.2 Automated Backtest-to-Deploy
- [ ] Hypothesis -> strategy parameter mapping
- [x] Automated backtesting with robustness checks (permutation, walk-forward)
- [x] Deploy decision criteria: minimum Sharpe, minimum trades, passing robustness tests
- [x] Automated deployment with ramp-up schedule
- [x] Paper-first policy: all new strategies start in paper mode

### 4.3 Memory & Learning
- [x] Strategy performance database: what was tried, what worked, what didn't
- [x] Market-type models: "political markets respond well to strategy X"
- [x] Regime-strategy mapping: "in high-vol regimes, use strategy Y"
- [x] Edge decay tracking: detect when an edge is fading before it's gone
- [x] Failure analysis: why did a strategy fail? (regime change, liquidity dry-up, model error)
- [x] Cross-session persistence: memory survives restarts

### 4.4 Continuous Improvement
- [ ] Parameter optimization: periodically re-optimize strategy parameters
- [ ] Strategy mutation: try small variations on successful strategies
- [ ] Dead strategy pruning: auto-retire strategies with no edge
- [ ] Portfolio rebalancing: shift capital from fading strategies to growing ones
- [ ] Meta-learning: learn which types of strategies the LLM is best at generating

---

## Phase 5: Risk & Budgeting

Fund-level risk management that goes beyond per-strategy limits.

### 5.1 Risk Budgeting
- [x] Total fund VaR budget with allocation to strategies
- [x] Dynamic reallocation: strategies that use less risk budget free it for others
- [ ] Correlation-aware budgeting: correlated strategies share risk budget
- [x] Marginal risk contribution: how much risk does adding strategy X add to the fund?
- [x] Risk budget alerts: warn when a strategy approaches its budget

### 5.2 Fund-Wide Risk Controls
- [x] Fund drawdown limits (daily, weekly, monthly, inception)
- [ ] Gross/net exposure limits
- [ ] Sector/theme concentration limits
- [ ] Exchange concentration limits (max % on any one exchange)
- [ ] Counterparty risk tracking
- [ ] Liquidity coverage ratio: ensure fund can liquidate within N hours

### 5.3 Stress Testing at Fund Level
- [x] Scenario stress tests across all strategies simultaneously
- [x] Correlation breakdown scenarios (all markets move together)
- [x] Exchange failure scenarios (what if Polymarket goes down?)
- [x] Liquidity crisis scenarios (all orderbooks thin out)
- [x] Black swan simulation: extreme tail events
- [ ] Automatic de-risking when stress metrics breach thresholds

---

## Phase 6: Execution Intelligence

Feedback loops that improve execution quality over time.

### 6.1 Execution Feedback Loop
- [x] Per-strategy fill rate tracking
- [x] Slippage analysis: estimated vs. realized
- [x] Adverse selection scoring: are we getting picked off?
- [x] Market impact measurement: did our orders move the price?
- [x] Execution cost attribution: fees, slippage, timing cost

### 6.2 Adaptive Execution
- [x] Auto-tune spread width based on adverse selection rate
- [x] Auto-tune order size based on fill rate
- [x] Smart execution routing: choose exchange/method based on historical performance
- [ ] Time-of-day patterns: adjust execution based on when liquidity is best
- [ ] Queue position optimization: adjust limit price placement

### 6.3 Cross-Exchange Execution
- [ ] Unified orderbook view across Polymarket, Kalshi, etc.
- [ ] Cross-exchange arbitrage execution with atomic-or-nothing semantics
- [x] Exchange health monitoring: detect degraded performance, route around it
- [x] Fee optimization: route to cheapest exchange when price is equal

---

## Phase 7: MCP & Agent Integration

Enhanced MCP tools and agent framework for autonomous operation.

### 7.1 New MCP Tools
- [x] `fund_status` - NAV, returns, risk metrics, capital available
- [x] `deploy_strategy` - launch a strategy with parameters
- [x] `stop_strategy` - gracefully stop a running strategy
- [x] `list_strategies` - running strategies with health and P&L
- [x] `allocate_capital` - move capital between strategies
- [ ] `scan_opportunities` - scan markets and return ranked opportunities
- [ ] `research_market` - deep analysis of a single market
- [ ] `backtest_hypothesis` - backtest a strategy idea and return results
- [x] `fund_report` - generate investor-grade report
- [x] `risk_dashboard` - current risk metrics, budget utilization, stress results

### 7.2 Agent Decision Framework
- [x] Decision logging: every autonomous decision recorded with reasoning
- [x] Confidence thresholds: minimum confidence required for each action type
- [x] Escalation rules: when to escalate to human (large trades, unusual markets, low confidence)
- [x] Rate limiting: max decisions per hour to prevent runaway loops
- [x] Dry-run mode: LLM proposes actions, human approves batch
- [x] Decision audit trail: full chain from observation -> reasoning -> action -> outcome

### 7.3 Natural Language Interface
- [ ] "Deploy a market maker on the top 5 most liquid political markets"
- [ ] "Reduce exposure to crypto markets by 50%"
- [ ] "What's our biggest risk right now?"
- [ ] "Backtest momentum strategy on election markets from 2024"
- [ ] "Why did we lose money yesterday?"
- [ ] Strategy description -> pipeline function mapping

---

## Phase 8: Observability & Operations

Production operations for a fund that runs 24/7.

### 8.1 Monitoring Dashboard
- [ ] Fund-level dashboard: NAV chart, strategy status grid, risk heatmap
- [ ] Strategy drill-down: per-strategy P&L, positions, order flow
- [ ] Alert feed: surveillance alerts, risk breaches, strategy errors
- [ ] Market universe view: all tracked markets with fitness scores
- [ ] Execution quality panel: fill rates, slippage, costs

### 8.2 Alerting & Notifications
- [ ] Multi-channel alerts: Slack, Discord, Telegram, email, webhook
- [ ] Alert routing: different alerts to different channels/people
- [ ] Alert escalation: if not acknowledged in N minutes, escalate
- [ ] Alert suppression: avoid alert fatigue with dedup and cooldowns
- [ ] Daily/weekly summary digests

### 8.3 Operational Resilience
- [ ] Process supervision: auto-restart crashed strategies
- [ ] State checkpointing: resume from last checkpoint on restart
- [ ] Database backup: automated compliance DB backups
- [ ] Exchange connectivity monitoring with auto-reconnect
- [ ] Graceful degradation: if one exchange is down, continue on others
- [ ] Disaster recovery playbook: documented steps for major failures

---

## What's Already Done

These systems already exist in Horizon and support the autonomous vision:

- [x] MCP server (44 tools, 2 resources)
- [x] Market discovery (discover_markets, discover_events, top_markets)
- [x] LLM signal engine (llm_forecast, llm_scan, llm_signal)
- [x] Oracle forecasting (forecast_market, scan_edges)
- [x] Kelly sizing (kelly, fractional, liquidity-adjusted, multi-Kelly)
- [x] Market making (reservation_price, optimal_spread, HJB)
- [x] Arbitrage (8 types: parity, stat, latency, composite, event, MM, spread, implication)
- [x] Risk pipeline (8-point: kill switch, price/size, position, notional, drawdown, rate, dedup)
- [x] Compliance module (audit trail, surveillance, RBAC, approval, limits, kill switch, reports, retention)
- [x] Backtesting with replay and robustness testing
- [x] Walk-forward optimization and CPCV
- [x] Feeds (17 types: Binance, Polymarket, Kalshi, REST, Chainlink, ESPN, NWS, etc.)
- [x] Exchanges (Polymarket, Kalshi, Alpaca, Coinbase, Robinhood, IBKR, Paper)
- [x] Copy trading and wallet intelligence
- [x] Sentinel risk monitoring
- [x] Stealth execution (adaptive TWAP, iceberg, sniper)
- [x] Cloud deploy
- [x] Multi-strategy book (monitoring)
- [x] Position reconciliation
- [x] PnL attribution
- [x] Evolutionary optimizer
- [x] Regime detection (Markov HMM)
- [x] Alpha research tools (bars, labeling, fracdiff, HRP, meta-labeling)
- [x] Quantitative models (25+ Rust implementations)
- [x] Dashboard (Textual TUI)
- [x] CLI
- [x] Fund module (NAV engine, capital allocator, strategy controller, risk monitor, settlement, accounting, market scorer)
- [x] Autonomous execution (market universe, strategy memory, correlation monitor, VaR budgeting, fund stress testing, execution quality, adaptive tuning, smart routing, research pipeline, autopilot, decision framework, autonomous agent)
- [x] Fund MCP tools (17 tools: status, report, deploy, stop, pause, resume, list, scale, NAV history, risk dashboard, stress test, P&L attribution, memory query/record, correlation matrix, execution report)
