> For the complete documentation index, see [llms.txt](https://docs.metric.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.metric.xyz/integrate/integrate-metric-liquidity/estimate-a-fill-from-depth.md).

# Estimate a fill from depth

Price an order from bid/ask depth, including the bin it ends in

The `depth` in [Retrieve pool bid and ask](https://docs.metric.xyz/reference/api/retrieve-current-bid-and-ask.md) and [Retrieve pool batch bid and ask](https://docs.metric.xyz/reference/api/retrieve-batch-bid-and-ask.md) lets you size an order yourself, without a request per amount. Each level is one bin, with the cumulative input and output to walk through its end; see [Depth levels](https://docs.metric.xyz/reference/api/retrieve-current-bid-and-ask.md#depth-levels) for the fields.

[Find best route](https://docs.metric.xyz/reference/api/find-best-route.md) runs this same calculation: it walks the depth, then prices the bin an order ends in as in [Exact fill inside a bin](#exact-fill-inside-a-bin). So for the same snapshot, the walk below with the exact fill returns what Find best route returns.

## Walking the depth

Pick the side from the direction: **bids** to sell token0, **asks** to buy token0. Then walk its levels in order, turning the cumulative columns into per-bin amounts:

```
// Exact input: X is what you pay. Returns what you receive.
remaining = X;  received = 0
prevIn = 0;  prevOut = 0
for level in side:
    if level.cumulativeInputVolume <= prevIn: continue   // adds no input: skip
    binIn  = level.cumulativeInputVolume - prevIn
    binOut = level.cumulativeVolume      - prevOut
    prevIn = level.cumulativeInputVolume;  prevOut = level.cumulativeVolume
    if binOut == 0: continue                              // nothing to receive here
    if remaining < binIn:                                 // the order ends in this bin
        return received + fillInside(level.price, binIn, binOut, remaining)
    received  += binOut
    remaining -= binIn
    if remaining == 0: return received
// out of levels: the order is larger than this side's depth
```

`fillInside` prices the part of the bin the order ends in. The simplest choice is the bin's proportional share, `floor(binOut × remaining / binIn)`; for the pool's own fill, use [Exact fill inside a bin](#exact-fill-inside-a-bin).

For **exact output** (`X` is what you receive), swap the roles: pay each whole bin's `binIn` while `remaining >= binOut`, and price the bin the order ends in with `payInside(level.price, binIn, binOut, remaining)`. Its proportional share is `ceil(binIn × remaining / binOut)`; the exact version is in [Exact fill inside a bin](#exact-fill-inside-a-bin).

Use BigInt throughout and multiply before dividing: the proportional products can exceed 2^128.

The average fill price is `received / X` (exact input) or `X / paid` (exact output), in raw units. The proportional share is a lower bound: the start of a bin fills better than its average (see [How the price moves inside a bin](#how-the-price-moves-inside-a-bin)), so it can understate an order that ends inside a bin by up to half of that bin's remaining width. That matters only on pools with wide bins. A small order in a 6.25% bin fills about 3% better; in a 0.01% bin, less than 0.005% better.

**Example:** selling 5 WETH (`X = 5000000000000000000`) into the bids of the [example response](https://docs.metric.xyz/reference/api/retrieve-current-bid-and-ask.md#response), a WETH/USDC pool (WETH has 18 decimals, USDC 6):

```json
"bids": [
  { "binIdx": -1, "price": "49937913286041055521250", "cumulativeVolume": "7430706558",  "cumulativeInputVolume": "2744786401520641763" },
  { "binIdx": -2, "price": "49932918995283375647711", "cumulativeVolume": "21731301391", "cumulativeInputVolume": "8027598362225637937" }
]
```

1. The first bin takes all `2744786401520641763` of its input and returns `7430706558` USDC.
2. The remaining `2255213598479358237` ends inside the second bin. That bin has `5282811960704996174` input and `14300594833` output, so its proportional share returns `floor(14300594833 × 2255213598479358237 / 5282811960704996174) = 6104872967`.
3. In total you receive `13535579525` (13,535.58 USDC), an average of 2,707.12 USDC per WETH. The [exact fill](#exact-fill-inside-a-bin) returns `13535754492`.

## How the price moves inside a bin

Depth is exact at bin boundaries. Inside a bin, the pool moves its price in a straight line with the output the bin pays, from the bin's opening price to its closing `price`. So the bin's average price, `binIn / binOut`, sits exactly halfway between the two, and an order that stops partway through pays only the bin's earlier, better prices.

`binIn` and `binOut` are the bin's full size: what crossing all of it costs and pays out. The input `r` or output `o` still to fill when the order reaches the bin is how far into it the order gets.

For example, take an ask bin that pays out 100 for 100, with a closing price of 1.1. Its average price is 1.0, so it opens at 0.9. Buying the first 50 costs 47.5, the average of 0.9 and 1.0 times 50, not the proportional 50.

Depth carries only the closing price, so the exact fill below first recovers the opening price from it, then prices the part of the bin the order takes along that line.

## Exact fill inside a bin

The proportional share stays valid as a lower bound. For what the pool fills inside the bin an order ends in, which is what [Find best route](https://docs.metric.xyz/reference/api/find-best-route.md) returns for the same snapshot, use the calculation below as `fillInside` and `payInside` in the walk. Every bin before it is crossed whole.

No estimate from depth can match the pool to the unit. Depth prices and amounts are rounded, and in the bin the pool's price currently sits in, depth leaves out the part already traded, which the pool's own sell-side solve uses. So this calculation gives up a small margin: for exact input it never returns more than the pool pays, and for exact output it never asks less than the pool charges.

It takes the bin's `binIn`, `binOut` and closing `price` from the walk, the input `r` still to fill (exact input) or the output `o` still to receive (exact output), and `dec0`/`dec1`, the `token0Decimals`/`token1Decimals` from [`/metadata`](https://docs.metric.xyz/reference/api/metadata.md). The products exceed 2^512, so use arbitrary-precision integers.

The whole calculation, as pseudo-code. Each step is explained below, with its formula.

```
// The bin's curvature: what all of binOut would cost at the closing price, minus binIn.
asks: closeIn = floor(binOut × price × 10^dec1 / (2^64 × 10^dec0))
bids: closeIn = floor(binOut × 2^64 × 10^dec0 / (price × 10^dec1))
E = closeIn − binIn
// E <= 0, E > binIn on asks, or E >= binIn on bids: use the proportional share.

// The bin's lowest price, which sizes the margin for the pool's price rounding.
low = asks: floor(price × (binIn − E) / (binIn + E));  bids: price
margin(a) = ceil(2 × a / low) + 1

// What the pool charges for output o of this bin.
askIn(o) = ceil(o × ((binIn − E) × binOut + E × o) / binOut²)
bidIn(o) = ceil(o × (binIn − E) × ((binIn + E) × binOut − E × o) / (binOut × ((binIn + E) × binOut − 2 × E × o)))

// Exact input, asks: solve (binIn − E)·x + E·x² = r with 64 fractional bits, root rounded up.
S   = 2^64 × (binIn − E)
out = floor(2^64 × 2 × r × binOut / (S + ceilSqrt(S² + 2^128 × 4 × E × r)))
// Exact input, bids: fill at the opening price, then correct once, as the pool does.
g   = min(floor(binOut × r / (binIn − E)), binOut)
out = bidIn(g) <= r ? g : floor(g × r / bidIn(g))
fillInside(r) = clamp(out − margin(out), floor(binOut × r / binIn), binOut)

// Exact output: askIn on asks, bidIn on bids.
payInside(o) = min(in(o) + margin(in(o)), ceil(binIn × o / binOut))
```

Below, $$I$$ is `binIn`, $$O$$ is `binOut`, $$p$$ is `price`, and $$d\_0$$, $$d\_1$$ are `dec0`, `dec1`. Every $$\lfloor\cdot\rfloor$$ and $$\lceil\cdot\rceil$$ is integer division rounded down or up, and $$\lceil\sqrt{\cdot},\rceil$$ is the integer square root rounded up.

**1. The bin's curvature.** $$\mathrm{closeIn}$$ is what the whole bin would cost if every unit were charged the closing price, and $$E$$ is how much more that is than what the bin really costs:

$$
\mathrm{closeIn} =
\begin{cases}
\left\lfloor \dfrac{O \cdot p \cdot 10^{d\_1}}{2^{64} \cdot 10^{d\_0}} \right\rfloor & \text{asks} \\\[2ex]
\left\lfloor \dfrac{O \cdot 2^{64} \cdot 10^{d\_0}}{p \cdot 10^{d\_1}} \right\rfloor & \text{bids}
\end{cases}
\qquad\qquad
E = \mathrm{closeIn} - I
$$

The `2^64` and decimals only convert the level's fixed-point `price` into raw token units. Per unit of output, the bin then costs $$(I + E)/O$$ at its close, $$I/O$$ on average and $$(I - E)/O$$ at its open: $$E$$ is how far the closing cost sits above the average, and the opening cost sits the same distance below it. When $$E = 0$$ the price is flat and the proportional share is exact. In the 100-for-100 bin above, $$\mathrm{closeIn} = 110$$ and $$E = 10$$.

If $$E \le 0$$, $$E > I$$ on asks, or $$E \ge I$$ on bids, the depth doesn't describe a straight-line bin, so use the proportional share instead.

**2. The safety margin.** The pool rounds each price inside a bin to a whole unit of its 64-bit fixed-point grid, so its result can differ from these formulas by a few units. The estimate gives those units up, so that it never returns more than the pool pays or asks less than it charges. A grid step matters most where the price is lowest, so the margin is sized at the bin's lowest price, $$p\_{\text{low}}$$: the opening price on asks, where the price rises through the bin, and the closing `price` on bids, where it falls:

$$
p\_{\text{low}} =
\begin{cases}
\left\lfloor \dfrac{p,(I - E)}{I + E} \right\rfloor & \text{asks} \\\[2ex]
p & \text{bids}
\end{cases}
\qquad\qquad
\mathrm{margin}(a) = \left\lceil \frac{2a}{p\_{\text{low}}} \right\rceil + 1
$$

$$a$$ is the result the margin applies to, the output for exact input or the input for exact output. The margin covers two grid steps of it, plus one unit for rounding the amount itself. At ordinary prices that's 2 units; it grows only on tokens priced at a tiny fraction of the other.

**3. What the pool charges** for output $$o$$ of this bin: $$o$$ times the average of the bin's opening cost and its cost at $$o$$, rounded up. On asks the cost per unit rises in a straight line. On bids the pool's price, output per input, falls in a straight line, so the cost per unit curves and the formula is longer:

$$
\mathrm{askIn}(o) = \left\lceil \frac{o,\big((I - E),O + E,o\big)}{O^2} \right\rceil
$$

$$
\mathrm{bidIn}(o) = \left\lceil \frac{o,(I - E),\big((I + E),O - E,o\big)}{O,\big((I + E),O - 2E,o\big)} \right\rceil
$$

Both are 0 at $$o = 0$$, $$I$$ for the whole bin and the proportional share when $$E = 0$$.

**4. Exact input.** Here the order fixes what you pay and the formula finds what you receive, which runs step 3 backwards. On **asks**, solve $$(I - E),x + E,x^2 = r$$ with 64 fractional bits, rounding the root up:

$$
S = 2^{64},(I - E)
\qquad\qquad
\mathrm{out} = \left\lfloor \frac{2^{65}, r, O}{S + \left\lceil \sqrt{S^2 + 2^{130}, E, r},\right\rceil} \right\rfloor
$$

On **bids**, fill at the opening price, then correct once, as the pool does:

$$
g = \min!\left( \left\lfloor \frac{O, r}{I - E} \right\rfloor,\ O \right)
\qquad\qquad
\mathrm{out} =
\begin{cases}
g & \text{if } \mathrm{bidIn}(g) \le r \\\[1ex]
\left\lfloor \dfrac{g, r}{\mathrm{bidIn}(g)} \right\rfloor & \text{otherwise}
\end{cases}
$$

Then take off the margin, and keep the result between the proportional share and the whole bin:

$$
\mathrm{fillInside}(r) = \min!\left( \max!\left( \mathrm{out} - \mathrm{margin}(\mathrm{out}),\ \left\lfloor \frac{O, r}{I} \right\rfloor \right),\ O \right)
$$

**5. Exact output.** Here the order fixes what you receive, so step 3 prices it directly. With $$\mathrm{in} = \mathrm{askIn}$$ on asks and $$\mathrm{bidIn}$$ on bids, add the margin, and never ask more than the proportional share:

$$
\mathrm{payInside}(o) = \min!\left( \mathrm{in}(o) + \mathrm{margin}\big(\mathrm{in}(o)\big),\ \left\lceil \frac{I, o}{O} \right\rceil \right)
$$

In the [WETH example](#walking-the-depth), the second bin gives `closeIn = 5283076140833714739`, so `E = 264180128718565` and $$p\_{\text{low}}$$ is the level's `price`. Then `g = 6105178272`, and `bidIn(g) = 2255261744665388318` is more than `r`, so `out = floor(g × r / bidIn(g)) = 6105047936`. The margin is `2`, so the bin returns `6105047934` instead of `6104872967`. In total you receive `13535754492` (13,535.75 USDC).

## Before you execute

Depth is a snapshot for estimation, and the pool moves with every trade and price update. Never execute an amount estimated from depth with zero slippage. For an exact amount, quote with `MetricOmmSwapQuoter` before executing.
