MrCoinSiX
MrCoinSiX

Reputation: 621

Uniswap v2/v3 - calculate pool liquidity

I'm working on a routine to find the most liquid pool across Uniswap v2 and v3. Therefore I like to compare the pool's liquidity, but I'm not sure how to do so on a Uniswap v3 pool. Some help would be highly appreciated.

Uniswap v2

Math.sqrt(reserve0, reserve1)

Uniswap v3

??? call liquidity() function of pool?

Upvotes: 3

Views: 6835

Answers (3)

MrCoinSiX
MrCoinSiX

Reputation: 621

I ended up by calling balanceOf() for token0 and token1 for Uniswap v3 pools. Not the best solution, but the only one I came up with.

Upvotes: 1

kfx
kfx

Reputation: 8537

Yes, reading the liquidity from on-chain data is one way, and this number will be comparable with what you have for v2, because in both versions liquidity "can be thought of as the amount that token1 reserves (either actual or virtual) changes for a given change in √P".

But liquidity is more tricky in Uniswap v3 because it's (1) concentrated and (2) not uniform.

For one, in v2 the liquidity of a pool and the liquidity of a position are conceptually the same, the L = sqrt(x*y) formula works for both.

In Uniswap v3, the liquidity of a position is still computed by L = sqrt(x*y), but x and y here are virtual assets. They correspond to the real assets in the positions via equations

x = (x_real + L/√p_a), and

y = (y_real + L*√p_b)

The liquidity of a position is uniform in the range [p_a, p_b], and zero for prices outside of this range.

The liquidity of a v3 pool is defined the sum of the liquidities of all active (in-range) positions in the pool. It's convenient to get it from the chain, rather than to compute it yourself!

However, a swap can cause the pool to enter other tick ranges, so that some positions get kicked out of the range during a swap. This will change the pool's liquidity and price impact during the swap. See the Algorithm 4 from the whitepaper. It means that for accurate results it's also needed to track the liquidities of the close-to-price but inactive tick ranges.

Upvotes: 3

vht981230
vht981230

Reputation: 4946

This is the formula I found in UniswapV3 documentation. It seems like for Uniswap V3, additional parameters of upper bound, current, lower bound prices are needed to calculate liquidity.

q96 = 2**96

def price_to_sqrtp(p):
    return int(math.sqrt(p) * q96)

sqrtp_low = price_to_sqrtp(price_lower_bound)
sqrtp_cur = price_to_sqrtp(price_current)
sqrtp_upp = price_to_sqrtp(price_upper_bound)

def liquidity0(amount, pa, pb):
    return (amount * (pa * pb) / q96) / abs(pb - pa)

def liquidity1(amount, pa, pb):
    return amount * q96 / abs(pb - pa)

liq0 = liquidity0(reserve0, sqrtp_cur, sqrtp_upp)
liq1 = liquidity1(reserve1, sqrtp_cur, sqrtp_low)
liquidity = int(min(liq0, liq1))

Upvotes: 1

Related Questions