Converting a price to a tick that can be initialized1 is done using the following formula:
To convert a price to a tick that can be initialized:
- Turn the price into a sqrtPrice.2
To turn the price into a sqrtPrice, you will have to get the ratio value with an example of the pool ratio.3 This is done using 1 token of ETH (token1) and the price of the USDC (token0) desired for the chosen range.
- Select a price
1000 USDC for 1 ETHTickLow_USDC = 1000
-
Converting the price into the lowest decimal format:
USDC is token0 which has 6 decimals.TickLowFormatted = TickLow_USDC*10decimal token0
- Encode the sqrtPrice Ration
Take 1 ETH in wei (lowest decimal ie. 1018), and the USDC price formatted. Using them as the pool ratio reserves3
Token1ReserveRatio= 1000000000000000000
Token0ReserveRatio= 1000000000
Next, take the token 1 amount and divide by the token 0 amount, to get the sqrtPriceRatio.
sqrtPriceRatio = (Token1ReserveRatio/Token0ReserveRatio)
- Get the tick at the sqrtPrice:
tickForPrice = floor(log(sqrtPriceRatio, 1.0001))
- This will give you the tick for the price
207243
after taking the rounded-down floor value and removing decimals.
-
Adjust the tick to the tick spacing of the pool to get a valid initializable tick.
Take the tick for the chosen price divided by the tick spacing of the pool and the rounded-down floor value5 of the pool.
Next, multiply the floored value by the tick spacing.
closestLowTick = floor( tick / tickSpacing ) * tickSpacing
Note: For the closest high tick, you will take the ceiling of the
tick / tickSpacing
. This will give the closest tick range that includes the chosen price.
Footnotes:
- A tick that can be initialized must be evenly divisible by the tick spacing of the pool. Initialized ticks are used for liquidity positions. Learn more about this here: Uniswap v3 whitepaper section 6.1 paragraph 8, and image 6.8
- SqrtPrice is the current price of the pool. Check out the Math Primer for more.
- SqrtPriceRatio / pool ratio reserves. This is the ratio of tokens that would be in the pool. Imagine these two numbers as the initial liquidity deposit that sets the price of the pool. Check out the Math Primer Part 2 for more.
Updated