# Algorithm

## Price Stabilisation Algorithm

### Overview

The market maker implements statistical arbitrage by stabilising DEX pools to reference prices (CEX, Chainlink, etc). It calculates the precise swap amount that brings a "mispriced" pool to the reference price (without overshooting) capturing the spread while correcting market inefficiency. This leverages the high correlation (0.99+) between both DEX and reference prices.

### The Optimization Problem

It finds the exact swap quantity leaving the pool at precisely the reference price after execution.

Precision matters: overshooting creates a new mispricing, undershooting wastes gas on multiple trades.

We optimise for the pool's *spot price after swap*, not execution price.

Execution price is the trade average; spot price determines if the pool remains correctly priced.

### Binary Search Algorithm

Binary search efficiently finds optimal quantity by testing the midpoint between bounds and eliminating half the search space each iteration (6-12 iterations, under 50ms, with 0.01% precision). It's just simulation asking "what's the pool price after X tokens ?" thanks to Tycho.

Works for any AMM type, Uniswap V2/V3, Curve, Balancer (see Tycho integration).

**Files**: Core algorithm in `src/shd/opti/math.rs`, integrated at `src/shd/maker/impl.rs` for each tradable pool.

### Statistical Arbitrage&#x20;

This is stat arb, not pure arbitrage. It trades correlation, with inventory risk (that could be hedged on any exchange). When a pool shows $3,520 vs reference $3,500, we execute moving it to $3,500 and expect market forces to maintain that relationship.

**Key advantage**: single pool execution with precise sizing prevents overshooting

**Tradeoff**: Assumes correlation persistence and fast convergence (between pool and reference)

**Profit**: We capture the spread between our execution price and reference. Selling at $3,520 to move pool to $3,500 might execute at $3,510 average.

**Risks**: Convergence failure (opposite trade reverses pool price), inventory exposure, gas costs on low spreads.

**Mitigations**:

* `min_watch_spread_bps`: Only trade meaningful spreads (3-5 bps)
* `min_executable_spread_bps`: Profit must exceed gas (1-3 bps)
* `max_inventory_ratio`: Cap position size
* `min_reference_price_move_bps`: React to real dynamics (1 bps), save queries.

### Example

Pool at $3,520, reference $3,500 (57 bps spread). Binary search finds optimal: **0.6562 ETH** pushes pool precisely to $3,500, executing at $3,510 average for $6.56 profit. Using full 1.0 ETH inventory would overshoot to $3,485, creating opposite mispricing and worse execution.
