---
title: "Multi-Leg Execution"
description: "Atomic multi-leg order execution with fill policies. All-or-none, best-effort, and delta-neutral modes for complex trade structures."
icon: "code-branch"
---

<Warning>
  **Ultra Feature.** Requires an Ultra subscription. [Get started at api.mathematicalcompany.com](https://api.mathematicalcompany.com)
</Warning>

# Multi-Leg Execution

Spread trades, hedged positions, and arbitrage strategies require multiple orders that must succeed or fail together. Horizon's multi-leg module provides atomic execution with three fill policies, aggregate risk checks, and cross-exchange leg support. Type validation is in Rust; execution orchestration is in Python.

## Overview

<CardGroup cols={2}>
  <Card title="Fill Policies" icon="list-check">
    All-or-none, best-effort, and delta-neutral execution modes.
  </Card>
  <Card title="Aggregate Risk" icon="shield-halved">
    `hz.aggregate_leg_risk()` sums notional across all legs before submission.
  </Card>
  <Card title="Validation" icon="check-double">
    `hz.validate_legs()` checks legs for completeness before execution.
  </Card>
  <Card title="Cross-Exchange" icon="arrows-left-right">
    Each leg can target a different exchange.
  </Card>
</CardGroup>

---

## Core Types

### FillPolicy

| Policy | Behavior |
|--------|----------|
| `AllOrNone` | If any leg fails, cancel all previously submitted legs |
| `BestEffort` | Submit all legs, continue on individual failures |
| `DeltaNeutral` | If one side fails, cancel the paired leg |

### Leg

```python
import horizon as hz

leg = hz.Leg(
    market_id="will-btc-hit-100k",
    side="buy",
    size=100.0,
    price=0.55,
    exchange="polymarket",
)
```

| Field | Type | Description |
|-------|------|-------------|
| `market_id` | `str` | Target market |
| `side` | `str` | `"buy"` or `"sell"` |
| `size` | `float` | Order size |
| `price` | `float` | Limit price |
| `exchange` | `str` | Target exchange |

---

## Core Functions

### hz.validate_legs

Check legs for completeness (non-empty market_id, positive size).

```python
error = hz.validate_legs(legs)
if error:
    print(f"Invalid: {error}")
```

### hz.aggregate_leg_risk

Sum risk metrics across all legs.

```python
total_notional, max_single_leg, num_exchanges = hz.aggregate_leg_risk(legs)
print(f"Total notional: ${total_notional:.2f}")
print(f"Max single leg: ${max_single_leg:.2f}")
print(f"Exchanges: {num_exchanges}")
```

### hz.build_mock_result

Build a mock execution result for backtesting.

```python
result = hz.build_mock_result(legs, hz.FillPolicy.AllOrNone, True)
print(f"Success: {result.success}")
print(f"Filled: {result.total_filled}/{result.total_legs}")
```

---

## Pipeline Function

### hz.multi_leg

Execute multiple legs atomically each cycle.

```python
ml = hz.multi_leg(
    legs_config=[
        {"market_id": "btc_100k", "side": "buy", "size": 50, "price": 0.55, "exchange": "polymarket"},
        {"market_id": "TLT", "side": "sell", "size": 10, "price": 95.0, "exchange": "alpaca"},
    ],
    policy="all_or_none",
)
```

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `legs_config` | `list[dict]` | `None` | Leg configurations (or read from `ctx.params["legs"]`) |
| `policy` | `str` | `"best_effort"` | `all_or_none`, `best_effort`, or `delta_neutral` |

Returns each cycle:

```python
{
    "success": True,
    "legs": [
        {"index": 0, "market": "btc_100k", "status": "submitted", "order_id": "p1"},
        {"index": 1, "market": "TLT", "status": "submitted", "order_id": "p2"},
    ],
    "total_notional": 977.5,
    "policy": "all_or_none",
}
```

---

## Examples

### Hedged Entry

```python
import horizon as hz

hz.run(
    name="hedged_entry",
    exchange=[hz.Polymarket(), hz.Alpaca(paper=True)],
    feeds={
        "btc": hz.PolymarketBook("will-btc-hit-100k"),
        "tlt": hz.AlpacaFeed(symbols=["TLT"]),
    },
    pipeline=[
        hz.multi_leg(
            legs_config=[
                {"market_id": "will-btc-hit-100k", "side": "buy", "size": 100, "price": 0.55, "exchange": "polymarket"},
                {"market_id": "TLT", "side": "sell", "size": 5, "price": 95.0, "exchange": "alpaca"},
            ],
            policy="all_or_none",
        ),
    ],
)
```

### Dynamic Legs from Pipeline

```python
import horizon as hz

def compute_legs(ctx):
    if ctx.feed is None:
        return {"legs": []}
    return {
        "legs": [
            {"market_id": "btc_100k", "side": "buy", "size": 50, "price": ctx.feed.price},
            {"market_id": "btc_150k", "side": "sell", "size": 50, "price": ctx.feed.price * 0.5},
        ],
    }

hz.run(
    name="dynamic_legs",
    pipeline=[compute_legs, hz.multi_leg(policy="delta_neutral")],
)
```
