Pool Data & TVL
For advanced trading strategies, arbitrage bots, or data analysis, you often need to look past high-level quotes and examine the raw state of a liquidity pool.
uniswap-python provides granular methods to extract on-chain state for Uniswap V3 pools.
Fetching Pool Instances
To query pool data, you first need the Web3 Contract instance of the pool. The library fetches the pool address from the Uniswap V3 Factory contract and initializes the ABI.
from uniswap.fee import FeeTier
# Get the ETH/USDC 0.3% pool contract
pool = uniswap.get_pool_instance(ETH, USDC, fee=FeeTier.TIER_3000)
Reading Immutable Parameters
Immutable parameters are set when the pool is deployed and can never change. This includes the token addresses, fee tier, and tick spacing constraints.
immutables = uniswap.get_pool_immutables(pool)
print(immutables)
# Output:
# {
# "factory": "0x1F98431c8aD98523631AE4a59f267346ea31F984",
# "token0": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
# "token1": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
# "fee": 3000,
# "tickSpacing": 60,
# "maxLiquidityPerTick": 11505743598341114571880798222544994
# }
Reading Dynamic State
The dynamic state includes the current price, active liquidity, and current tick. This data changes with nearly every trade.
state = uniswap.get_pool_state(pool)
print(state)
# Output:
# {
# "liquidity": 1234567890987654321,
# "sqrtPriceX96": 19283746564738291029384756,
# "tick": 205600,
# "observationIndex": 150,
# "observationCardinality": 152,
# "observationCardinalityNext": 152,
# "feeProtocol": 0,
# "unlocked": True
# }
Decoding sqrtPriceX96
The current price in V3 is stored as a sqrtPriceX96, a complex Q64.96 fixed-point number. uniswap-python includes a utility to decode this into a human-readable float ratio.
from uniswap.util import decode_sqrt_ratioX96
ratio = decode_sqrt_ratioX96(state['sqrtPriceX96'])
print(f"Current Price Ratio: {ratio}")
Calculating Total Value Locked (TVL)
Calculating the true TVL of a V3 pool is notoriously difficult because liquidity is scattered across thousands of individual price ticks. Simply multiplying the total pool balance by the current price is inaccurate due to concentrated liquidity mechanics.
uniswap-python solves this by iterating through the on-chain tick bitmap, finding every initialized tick, and mathematically summing the liquidity nets.
Performance Warning: Fetching tick data sequentially would require thousands of RPC calls, taking minutes. To optimize this, the
get_tvl_in_poolmethod leverages theMulticall2smart contract to batch queries 100 at a time. Even so, this operation is intensive. Cache results where possible.
pool = uniswap.get_pool_instance(DAI, USDC, fee=FeeTier.TIER_3000)
# Calculate exact on-chain TVL (adjusted for token decimals)
tvl_token0, tvl_token1 = uniswap.get_tvl_in_pool(pool)
print(f"Total DAI locked: {tvl_token0}")
print(f"Total USDC locked: {tvl_token1}")