import requests import json url_v3 = "https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v3" pools_query_v3 = """ { pools(orderBy: txCount, orderDirection: desc) { txCount id sqrtPrice token0 { decimals symbol } token1 { decimals symbol } } } """ payload_v3_pools = json.dumps({ "query": pools_query_v3, }) headers_pools = {'Content-Type': 'application/json'} response_v3_pools = requests.request("POST", url_v3, headers=headers_pools, data=payload_v3_pools) print(response_v3_pools.json()) response_pools = response_v3_pools.json() data = response_pools['data'] pools = response_pools['data']['pools'] sorted_data = sorted(data.items(), key=lambda x:x[1]) The problem is that some pairs show the correct price but some don't. For example, when I look at the first pair (USDC/WETH), it displays the right price around 2,300.
i = 0 sqrt_price = int(pools[0]['sqrtPrice']) price = (sqrt_price / 2 **96) ** 2 decimals_diff = int(pools[i]['token1']['decimals']) - int(pools[i]['token0']['decimals']) # USDC has 6 decimals and WETH has . So, we have to adjust price by 10^18 / 10^6. Then we take the reciprocal of this # number, because we are interested in USDC/WETH price. adj_price = 1 / (price / 10 ** decimals_diff) print(adj_price) But when I look at the second pair ("WETH/USDT"), it displays 2.319e-21 which is obviously wrong.
i = 1 sqrt_price = int(pools[0]['sqrtPrice']) price = (sqrt_price / 2 **96) ** 2 decimals_diff = int(pools[i]['token1']['decimals']) - int(pools[i]['token0']['decimals']) # USDC has 6 decimals and WETH has . So, we have to adjust price by 10^18 / 10^6. Then we take the reciprocal of this # number, because we are interested in USDC/WETH price. adj_price = 1 / (price / 10 ** decimals_diff) print(adj_price) Any advice what I'm doing wrong and how to fix it? Also, is there a better way to get historical prices from Uniswap v3?