I'm building a tool with web3 and python that needs to quickly and accurately get prices of tokens on Binance Smart Chain via PancakeSwap.
The tool gathers information about BSC tokens, price, liquidity etc so I can further analyse rugpulls.
In the following code it is supplied with a contract address and it needs to supply the current price per token in BNB. It however glitches alot and does not give me the correct price and I cannot figure out whats wrong. Code is below.
from web3 import Web3
web3 = Web3(Web3.WebsocketProvider('wss://speedy-nodes-nyc.moralis.io/b51e035eb24e1e81cc144788/bsc/mainnet/ws'))
tokenPriceABI = 'Token Price ABI'
def getTokenPrice(tokenAddress):
BNBTokenAddress = Web3.toChecksumAddress("0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c") # BNB
amountOut = None#
#tokenAddress = Web3.toChecksumAddress(tokenAddress)
tokenRouter = web3_sell.eth.contract(address=tokenAddress, abi=tokenPriceABI)
router = web3_sell.eth.contract(address=Web3.toChecksumAddress("0x10ed43c718714eb63d5aa57b78b54704e256024e"), abi=pancakeABI)
amountIn = web3_sell.toWei(1, 'ether')
amountOut = router.functions.getAmountsOut(amountIn, [tokenAddress, BNBTokenAddress]).call()
amountOut = web3_sell.fromWei(amountOut[1], 'ether')
return amountOut
tokenAddress = input("Enter token address: ")
tokenAddress = Web3.toChecksumAddress(tokenAddress)
priceInBnb = getTokenPrice(tokenAddress)
print(priceInBnb)
Is anyone able to help? Thanks.