3

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.

James
  • 101
  • 2
  • 10

1 Answers1

5

so what you are doing is you are trying to get the wrong value.

the getamountsout doesn't give you you the price. you need to call the getpair from the pancakeswap factory address with your two tokens as parameters.(0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73) docs for the getpair function

then you get a contract address back from which you can call the getreserves function (docs for this contract) from which you get 3 values (_reserve0, _reserve1, _blockTimestampLast) where you divide the first by the second or the second by the first depending on which way you want the price

J. peters
  • 74
  • 4