I'm using web3 to get the token balances (quantity) for a number of BEP20 tokens (eg safemoon 0x8076c74c5e3f5852037f31ff0093eeb8c8add8d3)
What I'm trying to get now is the latest token price in bnb or usd so that I can then work out my current balance
The balance is displayed on bscscan (as below) and that is effectively what I'm trying to get to
How would we get the price data points from web3?
Best Answer
Web3 has no concept of token value, as the value is speculative and differs between different markets.
You can either get the price from a particular market - e.g. Uniswap/Pancakeswap - or get a price from a service that provides a weighted average from a selection of different markets.
I believe Etherscan/BscScan uses the latter approach - i.e. checks the token prices in different markets, then adjusts for the volume in those markets.
BscScan make the data available via their API below, though you'll need a Pro account to access it:
https://api.bscscan.com/api?module=token&action=tokeninfo&contractaddress=0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82&apikey=YourApiKeyToken
(See https://bscscan.com/apis#tokens)