> ## Documentation Index
> Fetch the complete documentation index at: https://mathematicalcompany.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Horizon SDK

> Trading SDK. Rust core, Python interface. Prediction markets, equities, options, crypto.

# Horizon SDK

Horizon is a trading SDK. Rust core, Python interface. Build, backtest, and deploy strategies across **prediction markets** (Polymarket, Kalshi), **equities and options** (Alpaca, IBKR), **crypto** (Coinbase, Robinhood), and **paper** — all from a single `hz.run()` call.

<CardGroup cols={3}>
  <Card title="Rust Core" icon="gear">
    Risk pipeline, order management, position tracking, and exchange clients compiled to a native Python extension via PyO3.
  </Card>

  <Card title="Multi-Asset" icon="arrows-split-up-and-left">
    Prediction markets, equities, options, crypto. Trade across exchanges with cross-exchange netting and unified position tracking.
  </Card>

  <Card title="Pipeline Composition" icon="layer-group">
    Chain functions with automatic signature introspection. Insert or remove stages without changing downstream code.
  </Card>
</CardGroup>

## Key Features

* **Single entry point**: `hz.run()` handles engine creation, feed management, position sync, and the main loop
* **8-point risk pipeline**: kill switch, price/size validation, position limits, notional limits, drawdown checks, rate limiting, and dedup
* **Advanced orders**: stop-loss, take-profit, bracket orders with OCO linking, and order amendment
* **Execution algorithms**: TWAP, VWAP, and Iceberg for large order execution
* **Backtesting**: `hz.backtest()` replays historical data through the same pipeline as live trading, with full analytics
* **Kelly criterion**: Rust-native Kelly sizing functions for optimal position sizing
* **Automated market making**: Avellaneda-Stoikov model with inventory skew, competitive spread blending, and multi-level quoting
* **Signal combiner**: Weighted average, rank, and z-score combination of alpha signals with built-in extractors
* **Monte Carlo simulation**: Portfolio stress testing with correlated binary outcomes, VaR, CVaR, and full scenario distributions
* **Arbitrage executor**: Atomic cross-exchange arb execution with auto-rollback, pipeline scanner, and one-shot sweep
* **Equity/options discovery**: search stocks, pull options chains, compute Greeks, IV surfaces, and screen by fundamentals via the `equity` CLI group
* **`Side.Long`**: first-class side for equities and crypto alongside `Side.Yes`/`Side.No` for prediction markets
* **`Risk.equity()`**: classmethod with equity-appropriate defaults (no 0-1 price clamping, sensible position/notional limits)
* **Live feed system**: Binance WebSocket, Polymarket orderbook, Kalshi orderbook, Alpaca, IBKR, Chainlink on-chain oracles, and generic REST feeds
* **Multi-exchange support**: trade on multiple exchanges simultaneously with `exchanges=[...]`
* **Netting pairs**: offset correlated positions across exchanges for reduced notional exposure
* **Monitoring**: Prometheus metrics server, multi-channel alerts (Discord, Telegram, webhooks), and calibration tracking
* **SQLite persistence**: crash recovery via position snapshots and fill replay
* **TUI dashboard**: real-time monitoring with Textual (P\&L, positions, orders, risk, fills, feeds)
* **CLI**: run strategies with option overrides from the command line
* **Paper trading**: local simulated exchange with tick-based matching for strategy development

## How It Works

```python theme={null}
import horizon as hz

def fair_value(ctx: hz.Context) -> float:
    return ctx.feeds["btc"].price * 0.01

def quoter(ctx: hz.Context, fair: float) -> list[hz.Quote]:
    return hz.quotes(fair, spread=0.04, size=5)

hz.run(
    name="my_strategy",
    markets=["will-btc-hit-100k"],
    feeds={"btc": hz.BinanceWS("btcusdt")},
    pipeline=[fair_value, quoter],
    risk=hz.Risk(max_position=100, max_drawdown_pct=5),
)
```

Same structure works for equities:

```python theme={null}
import horizon as hz

def equity_signal(ctx: hz.Context) -> float:
    return ctx.feeds["aapl"].price

def equity_sizer(ctx: hz.Context, fair: float) -> list[hz.Quote]:
    return [hz.Quote(side=hz.Side.Long, price=fair, size=10)]

hz.run(
    name="aapl_buyer",
    markets=["AAPL"],
    exchanges=["alpaca"],
    feeds={"aapl": hz.AlpacaFeed("AAPL")},
    pipeline=[equity_signal, equity_sizer],
    risk=hz.Risk.equity(max_position=100, max_drawdown_pct=3),
)
```

## Backtest First, Deploy Live

Run the same pipeline on historical data before going live:

```python theme={null}
result = hz.backtest(
    markets=["will-btc-hit-100k"],
    data=[{"timestamp": i, "price": 0.50 + i * 0.0005} for i in range(500)],
    pipeline=[fair_value, quoter],
    risk=hz.Risk(max_position=100),
)
print(result.summary())
# Sharpe, max drawdown, win rate, profit factor, Brier score...
```

## Protect Positions

Add stop-loss and take-profit with a single call:

```python theme={null}
entry_id, sl_id, tp_id = engine.submit_bracket(
    request=OrderRequest(market_id="btc-100k", side=Side.Yes,
                         order_side=OrderSide.Buy, size=10, price=0.55),
    stop_trigger=0.45,
    take_profit_trigger=0.70,
)
# SL and TP are linked as OCO. When one triggers, the other is canceled
```

## Technology

| Layer       | Technology   | Purpose                                                |
| ----------- | ------------ | ------------------------------------------------------ |
| **Core**    | Rust + PyO3  | Risk, orders, positions, exchanges, feeds, asset types |
| **SDK**     | Python 3.10+ | Strategy composition, configuration, dashboard         |
| **Build**   | maturin      | Rust to Python native extension                        |
| **Async**   | tokio        | WebSocket feeds, HTTP exchange clients                 |
| **Storage** | SQLite (WAL) | Persistence, crash recovery, audit trail               |
