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

# Multi-Leg Execution

> Atomic multi-leg order execution with fill policies. All-or-none, best-effort, and delta-neutral modes for complex trade structures.

<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 theme={null}
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 theme={null}
error = hz.validate_legs(legs)
if error:
    print(f"Invalid: {error}")
```

### hz.aggregate\_leg\_risk

Sum risk metrics across all legs.

```python theme={null}
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 theme={null}
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 theme={null}
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 theme={null}
{
    "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 theme={null}
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 theme={null}
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")],
)
```
