Nethereum.Uniswap-V2-and-V3 icon indicating copy to clipboard operation
Nethereum.Uniswap-V2-and-V3 copied to clipboard

How to get current price of a pair

Open soltrac opened this issue 4 years ago • 2 comments

Hello,

I'm very new to uniswap sdk. I'm trying to figure out with this SDK. Given a contract with the pair, how can I know the current price?

Thanks

soltrac avatar Feb 25 '21 21:02 soltrac

https://uniswap.org/docs/v2/advanced-topics/pricing/ https://uniswap.org/docs/v2/smart-contracts/pair/

juanfranblanco avatar Feb 25 '21 23:02 juanfranblanco

Here is my code:

            int precision = 10000000;
            var getAmountsOutFunctionMessage = new GetAmountsOutFunction()
            {
                AmountIn = precision,
                Path = GetPath() // List<>{tokenAddress, ..., usdtAddress}
            };
            var getAmountsOutHandler = web3.Eth.GetContractQueryHandler<GetAmountsOutFunction>();
            var amounts = await getAmountsOutHandler
                .QueryAsync<List<BigInteger>>(
                routerAddress),
                getAmountsOutFunctionMessage);

            var ratio = BigDecimal.Pow(10, usdtDecimals - tokenDecimals);

            var priceUsd = amounts.Last() / ratio / precision;

Remember to get the decimal difference of the token to USDT, it's important

also the precision should be optimal, any smaller number will cause the query hang if the token price is too small.

excuse for bad design pattern, many of those variables can be reused. I generally just extract some key steps from my code.

lunarmoon26 avatar Oct 20 '21 14:10 lunarmoon26