Minimizing Slippage and Taming Impermanent Loss
Automated Market Makers (AMMs) have become the backbone of decentralized exchanges, but anyone providing liquidity across multiple pools faces a genuine optimization problem: how do you split your capital to keep trade execution efficient (low slippage) while limiting your exposure to impermanent loss (IL)? Today we’ll build a concrete, numerically solvable example of this problem in Python, visualize the trade-off, and interpret the results.
The Math Behind AMMs
Most AMMs (Uniswap v2 style) rely on the constant product invariant:
$$x \cdot y = k$$
where $x$ and $y$ are the reserves of the two tokens in the pool. When a trader swaps in an amount $\Delta x$, the resulting price impact — the slippage — for a pool with reserve $X$ can be approximated as:
$$\text{Slippage}(\Delta x) = \frac{\Delta x}{X + \Delta x}$$
The deeper the pool (larger $X$), the smaller the slippage for a given trade size. This is why liquidity depth matters so much.
Impermanent loss, on the other hand, measures the opportunity cost of providing liquidity versus simply holding the two assets, as a function of the price ratio change $r = P_1 / P_0$:
$$IL(r) = \frac{2\sqrt{r}}{1+r} - 1$$
This function is always negative (a loss) except at $r=1$, and it gets worse the more the price ratio drifts from 1 — i.e., the more volatile the pair.
Setting Up the Allocation Problem
Suppose we are a liquidity provider with total capital $C$ to split across $N$ pools, with weights $w_i$ ($\sum_i w_i = 1$). Each pool $i$ has base reserves $X_i$, expected trading volume $V_i$, a typical trade size $T_i$, and an annualized volatility $\sigma_i$ that drives its impermanent-loss risk $IL_i$.
We want to minimize a combined cost function: the market-wide slippage cost weighted by volume, plus a convex risk penalty for concentrating capital into volatile pools (risk that grows faster than linearly as we get less diversified, exactly like variance in classical portfolio theory):
$$J(\mathbf{w}) = \underbrace{\alpha \sum_{i=1}^{N} V_i \cdot \frac{T_i}{w_i C + X_i}}{\text{slippage cost}} ;+; \underbrace{\frac{\beta}{C} \sum{i=1}^{N} (w_i C)^2 \cdot IL_i}_{\text{concentration / IL risk}}$$
subject to:
$$\sum_{i=1}^{N} w_i = 1, \qquad 0 \le w_i \le w_{\max}$$
Here $\alpha$ and $\beta$ are risk-preference weights, and $w_{\max}$ is a diversification cap (a realistic constraint most treasuries and DAOs apply so no single pool absorbs the entire position). The slippage term decreases as we add liquidity to a pool (deeper pool → less slippage), while the quadratic IL term increases superlinearly the more we concentrate capital into a volatile pool — this convexity is what naturally produces a diversified interior solution instead of an “all-in on one pool” corner solution.
The Python Implementation
The full example below is self-contained and ready to paste into a single Google Colaboratory cell.
1 | import numpy as np |
Code Walkthrough
Sections 1–2 (pool data & IL model): We define four representative pools with different reserve depth, volume, typical trade size, and volatility. impermanent_loss() implements the closed-form IL formula directly, using each pool’s volatility as a proxy for how far the price ratio $r$ is likely to drift.
Section 3 (cost functions): slippage_cost() sums the volume-weighted price impact across all pools — this is the “cost paid by traders/the market” if liquidity is too thin. risk_cost() implements the quadratic IL exposure term. Squaring (w_i * C) is the key modeling choice: it makes the risk penalty grow faster than the capital allocated, so the optimizer is discouraged from dumping everything into a single high-yield-looking pool — exactly the same logic behind variance terms in Markowitz portfolio theory.
Section 4 (optimization): We use scipy.optimize.minimize with the SLSQP method, which handles both equality constraints (weights sum to 1) and bounds (per-pool caps) natively. Because this cost surface can have multiple local optima depending on the starting point, we run 30 random restarts (np.random.dirichlet generates random points on the simplex) and keep the best result — a simple but effective robustness technique for non-trivial constrained optimization.
Sections 5–7 (2D plots): These isolate each mechanic individually — how slippage cost falls as one pool gets deeper, and the textbook impermanent-loss curve with our actual pools plotted on it according to their volatility-implied price ratio.
Section 8 (3D plot — performance note): A naive implementation of this grid would use nested for loops over w0 and w1, recomputing the objective one point at a time — for an 80×80 grid that’s 6,400 Python-level function calls, which gets slow fast as resolution increases. Instead, the code above builds the entire grid with np.meshgrid and evaluates every cost term as a single vectorized NumPy expression across the whole array at once. This routinely runs in under a millisecond even for a fine grid, versus tens or hundreds of milliseconds for the loop version — a large difference if you want to push resolution higher or animate the surface interactively.
Reading the Results
The bar chart should show the optimizer pulling capital toward the deepest, highest-volume, lowest-volatility pool (BTC/USDC) up to its diversification cap, while trimming exposure to the thinnest, most volatile pool (MATIC/USDC) — exactly the intuition a liquidity manager would want confirmed quantitatively rather than by gut feel.
=== Optimal Liquidity Allocation === ETH/USDC weight=0.3038 allocation=$303,764 BTC/USDC weight=0.4383 allocation=$438,264 SOL/USDC weight=0.1496 allocation=$149,626 MATIC/USDC weight=0.1083 allocation=$108,347 Total cost J (optimized) = 366,973.4 Total cost J (equal-weight baseline) = 382,227.4 Improvement: 3.99%

The slippage curve demonstrates the core AMM mechanic directly: as more capital flows into a pool, the marginal slippage benefit shrinks — a classic diminishing-returns curve, which is exactly why the optimizer doesn’t push 100% of capital into the single deepest pool.
Vectorized grid evaluation time: 0.00255 s for 6,400 points

The impermanent loss curve is the standard AMM textbook shape — symmetric-ish around $r=1$ and worsening as the price ratio moves further from parity in either direction. Overlaying our four pools shows visually why MATIC/USDC and SOL/USDC carry meaningfully higher IL risk than the two blue-chip pairs.

The 3D surface is the most informative view: it shows the full cost landscape as you jointly vary the ETH/USDC and BTC/USDC allocations (with the remaining capital split proportionally between SOL/USDC and MATIC/USDC at their optimal ratio). The red marker sits at the computed optimum, at the bottom of a visible “valley” in the surface — this is a good sanity check that the SLSQP result is a genuine minimum and not an artifact of a bad local search, since the surrounding grid values are all higher.

Takeaways
This example distills a real DeFi liquidity-management decision into a tractable convex optimization problem: balance the market-facing benefit of deep liquidity (lower slippage) against the LP’s own risk of concentrating capital into volatile pairs (impermanent loss). The quadratic risk formulation and diversification cap are what turn an otherwise “winner-take-all” allocation into a realistic, diversified portfolio — the same principle that underlies classical mean-variance portfolio construction, just adapted to the mechanics of constant-product AMMs. From here, natural extensions include swapping in real on-chain reserve and volume data via a DEX subgraph, using historical price data to estimate $\sigma_i$ empirically rather than assuming it, or adding a fee-income term to turn this into a full risk-adjusted-return maximization problem.






























