I was trying to get the price of various crypto coins using web3.py.
tokenAddres = '0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82' #Cake
tokenAddres = Web3.toChecksumAddress(tokenAddres)
bnbPrice = calcBNBPrice()
print(f'current BNB price: {bnbPrice}')
priceInBnb = calcSell(1, tokenAddres)
print(f'SHIT_TOKEN VALUE IN BNB : {priceInBnb} | Just convert it to USD ')
print(f'SHIT_TOKEN VALUE IN USD: {priceInBnb * bnbPrice}')
The calcsell function should be the one that return the value of the token in BNB
def calcSell(tokenToSell, tokenAddress):
BNBTokenAddress = Web3.toChecksumAddress("0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c") # BNB
amountOut = None
tokenRouter = web3.eth.contract(address=Web3.toChecksumAddress(tokenAddress), abi=tokenAbi)
tokenDecimals = tokenRouter.functions.decimals().call()
tokenToSell = setDecimals(tokenToSell, tokenDecimals) # Set token a correct number of 0s
router = web3.eth.contract(address=Web3.toChecksumAddress(pancakeSwapContract), abi=pancakeSwapAbi)
amountIn = web3.toWei(tokenToSell, 'ether')
amountOut = router.functions.getAmountsOut(amountIn, [tokenAddress, BNBTokenAddress]).call()
amountOut = web3.fromWei(amountOut[1], 'ether')
return amountOut
The value I get is:
SHIT_TOKEN VALUE IN BNB : 974136.205251839691973598 | Just convert it to USD
SHIT_TOKEN VALUE IN USD: 340708627.4489159379891912819
while the correct one is:
SHIT_TOKEN VALUE IN BNB : 0.048846069961106416 | Just convert it to USD
SHIT_TOKEN VALUE IN USD: 16.98585439310707
Any guess?
use this api https://docs.moralis.io/
you can easily get token price with WEB3API