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

sqrtp_low = price_to_sqrtp(4545)
sqrtp_cur = price_to_sqrtp(5000)
sqrtp_upp = price_to_sqrtp(5500)

def liquidity0(amount, pa, pb):
    if pa > pb: # pa is current price and pb is upper price in price range, so how it is 
                # possible that pa is greater than pb ??

        pa, pb = pb, pa # what does this line actually does?

    return (amount * (pa * pb) / q96) / (pb - pa) # as we make sqrt of prices, why here 
    # we used q96 again?

def liquidity1(amount, pa, pb):
    if pa > pb:
        pa, pb = pb, pa
    return amount * q96 / (pb - pa)

eth = 10**18
amount_eth = 1 * eth
amount_usdc = 5000 * eth

liq0 = liquidity0(amount_eth, sqrtp_cur, sqrtp_upp)
liq1 = liquidity1(amount_usdc, sqrtp_cur, sqrtp_low)
liq = int(min(liq0, liq1))  # Does substracting the liq1 from liq0 gives the liq? i mean
# how this works? 

> 1517882343751509868544

In this code i have few questions, the questions i asked in the code as comments.

1 Answer 1

0

How is it possible that pa is greater than pb?

This check is in place to handle potential input errors, if a user provide the upper price (pb) lower than the current price (pa) .

What does the line "pa, pb = pb, pa" do?

it just just swaps the values of pa and pb If pa is greater than pb, this line ensures that pa is assigned the value of pb and pb is assigned the value of pa.

As we make sqrt of prices, why do we use q96 again?

It is used to maintain precision in the calculations, when computing the liquidity, you need to use q96 again in the denominator to cancel out the scaling factor and keep the correct units.

Does subtracting liq1 from liq0 give the liq?

no, the line "liq = int(min(liq0, liq1))" calculates the liquidity (liq) as the minimum of the two calculated liquidity values, liq0 and liq1.

2
  • 1
    Thank u very much, but why do we need to calculate the liquidity as the minimum of the two calculated liquidity values?
    – Hacek
    Apr 8, 2023 at 16:13
  • it is just to ensure that the liquidity position remains within the specified price range. In this case, the price range is defined by the upper and lower price bounds (sqrtp_upp and sqrtp_low)
    – Saxtheowl
    Apr 8, 2023 at 18:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.