# Liquidity Math

## Definition of liquidity

Liquidity positions on Haiko are defined by an amount of liquidity, `L`, and a price range, defined by lower and upper bounds $$p\_L$$ and $$p\_U$$.&#x20;

Here, liquidity is an abstract measure. Depending on whether the position is active (i.e. its relative position to current market price), its liquidity can be denominated either in `base` assets, `quote` assets, or a mix of the two. In particular:

1. If the position is **bounded around** the current price $$p\_L\le{p}<{p\_U}$$, liquidity will be denominated in a mix of `base` and `quote` assets.
   * Base = $$L\times{\frac{\sqrt{p}\sqrt{p\_U}}{\sqrt{p\_U}-\sqrt{p}}}$$
   * Quote = $$L\times(\sqrt{p}-\sqrt{p\_L})$$
2. If the position is **below** the current price, liquidity will be single-sided and denominated in `quote` assets only.
   * Quote = $$L\times(\sqrt{p\_U}-\sqrt{p\_L})$$
3. If the position is **above** the current price, liquidity will be single-sided and denominated in `base` assets only.
   * Base = $$L\times{\frac{\sqrt{p\_L}\sqrt{p\_U}}{\sqrt{p\_U}-\sqrt{p\_L}}}$$

The total amount of liquidity, `L`,  placed within a position is fixed irrespective of the specific point-in-time mix of base and quote assets. Positions must maintain the following constant function invariant:

$$(B+\frac{L}{\sqrt{p\_L}})\times(Q+{L}{\sqrt{p\_U}})=L^{2}$$

where$$B$$ and $$Q$$ are the quantities of base and quote assets.

More information can be found, along with underlying derivations for the above equations, in the Uniswap V3 [whitepaper](https://uniswap.org/whitepaper-v3.pdf).&#x20;

### Liquidity aggregation

Liquidity positions are aggregated horizontally by summing up the total amount of liquidity at a given price.&#x20;

In practice, this is done by tracking a set of initialised limits (i.e. price points at which liquidity positions start and end), and updating the aggregate **active** **liquidity balance** of the market whenever price moves in and out of these positions.&#x20;

Each limit tracks two values:

* `liquidity` (`u128`), which denotes the total absolute amount of liquidity starting or ending at that limit
* `liquidity_delta` (`i128`), which denotes the total amount of liquidity starting at that limit (if `+ve` or ending at the limit (if `-ve`), reading from ascending order of price.&#x20;

Together, they allow markets to track the instantaneous amount of active liquidity between limit intervals.&#x20;
