This has been a pain for me for a long time. You basically have to compare the liquidity of the different pairs and run the Uniswap formula for calculating the price.
Y * I / (X + I)
- I is your input amount of source tokens
- X is the balance of the pool
in the source token
- Y is the balance of the pool in the target token
In the end, the process we came up to get the price of all Uniswap pairs was the following.
- Find all token pairs by looking at all historical PairCreated
- Read the reserves from token0 and token1 from the pair
- Calculate the price of token0 and token1 in usd according to the uniswap formula.
This took us a lot of work to do, especially when you need it for multiple tokens and on multiple chains (maybe you want the same on pancake).
Anyway, we took our solution and we turned it into an API you can use if you want. It's the Moralis Deep Index API. You simply run
This will give you the exact same price you see on, for example, Etherscan. It currently supports ethereum, bsc and polygon. And it's free.
Disclaimer, I work at moralis and we developed this API.