How to build a Uniswap bot in python
DeFi is all the rage these days in the crypto world and for good reason. Arguably the current king of DeFI platforms is Uniswap, with at the time of writing close to 2 million users.
Using Uniswap is super easy. Connect your MetaMask and you’re basically good to go to start trading. Uniswap conveniently also offers an API and SDK so you can build your own trading bot. So let’s get you started with setting one up in Python.
Prerequisites in Python
Obviously you need to have Python installed. The Uniswap SDK is actually designed for JavaScripts, but luckily other smart people have already made python libraries for Uniswap functions. You can find one here: https://pypi.org/project/uniswap-python/
Prerequisites on blockchain
When you interact with the Ethereum blockchain, upon which Uniswap is built, you need a wallet to pay for any transactions you want to make. One of the most straightforward ways is to create a MetaMask wallet and copy the address and private key into 2 variables. And of course put some ETH in the wallet as well to actually fund your transactions.
Do note that you can test your bot on the Ethereum test networks ropsten and rinkeby, with free ether from a faucet.
You also need access to a full Ethereum node. Theoretically you can set one up on your PC like in the old days, but Ethereum is currently a huge database and this will take up 100s of GB of hard disk space.
It’s much easier to use Infura. Create a free account and voila, you have access to Ethereum. Store the infura access link in a variable as well.
Step 1: Connect to uniswap
Remember the python uniswap library mentioned above?
from uniswap import Uniswapuniswap_wrapper = Uniswap(metamaskvar, privatekeyvar, infura_url, version=2)
- metamaskvar = your metamask wallet address
- privatekeyvar = the private key to your metamask wallet
- infura_url = the link to your infura access
- version=2 : we’re using uniswap v2.
Now we have a uniswap object that we can use to interact with the Uniswap contract.
Step 2: let’s get some useful info
Uniswap allows users to trade to and from ETH (well, actually wETH) and other coins or between other coins directly, though in the background intermediate steps with ETH are made. Which means that all price quotes are referenced in ETH. To make it easier to calculate back to fiat, we can get a price quote from the coinmarketcap api. You do need to get your own free API key on coinmarketcap as well.
import requests
from requests import Request, Session#Coinmarketcap call
coinurl = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'
coinparameters = {
'symbol':'ETH',
'convert':'USD'
}
coinheaders = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': 'YOUR API KEY HERE',
}session = Session()
session.headers.update(coinheaders)try:
response = session.get(coinurl, params=coinparameters).json()
data = response['data']
ethdata=data['ETH']
pricedata=ethdata['quote']
usdprice=pricedata['USD']
ethprice=usdprice['price']
except (ConnectionError, Timeout, TooManyRedirects) as e:
print(e)
So in the end, the variable ethprice give you the current ETH price in USD.
Do note that the Coinmarketcap endpoint used above gives a lot of great data to use in your bot later on: volume, price changes,…
Secondly, Ethereum gas fees are currently very high. Ethereum v2 should lower them, but for now they can have a severe impact on your yield when trading.
So, how to calculate your gas fee? Gas fee = Gas used x Gas price.
Gas used depends on the complexity of a transaction on Ethereum. Unfortunately, a Uniswap trade is a fairly complex action and can require up to 250000 gas.
Gas price can be requested from sites like ethgasstation.info Again, you’ll need to sign up for a key.
gaspriceurl='https://ethgasstation.info/api/ethgasAPI.json?api-key='+YOURAPIKEYgaslimit = 250000
TO_GWEI= 1 * 10 **10
gas = requests.get(gaspriceurl).json()['fast']
print('gas in GWEI = '+str(gas/10))gasprice = (gas / (TO_GWEI))*ethprice*gaslimit
print('Estimated max gas price (USD) = '+str(gasprice))
This will calculate the USD value of a uniswap fast transaction.
Step 3: start trading on Uniswap
First decide which tokens you want to trade in, because you will need to look up the contract addresses. You can look these up in Uniswap.
E.g. ETH and BAT (basic attention coin) on Mainnet
bat = "0x0D8775F648430679A709E98d2b0Cb6250d2887EF"
eth = "0x0000000000000000000000000000000000000000"
The following code will give you
- your ETH balance
- your bat balance
- How many bat one ETH will buy you on Uniswap.
ONE_ETH = 1 * 10 ** 18
AMOUNTETH = 1print('Eth balance in metamask = '+str(uniswap_wrapper.get_eth_balance()/ONE_ETH))
print('Bat balance in metamask = '+str(uniswap_wrapper.get_token_balance(bat)))
print('How many bat for 1 ETH = '+str(uniswap_wrapper.get_token_eth_output_price(bat,AMOUNTETH)))
print('Price of purchase (USD) = '+str(AMOUNTETH*ethprice))
At this moment, you know:
- the ETH price quote in USD
- the max gas fee
- how much a trade will buy you
The last step is to actually make the trade.
tx = uniswap_wrapper.make_trade_output(eth,bat, AMOUNTETH)
print(tx)
And that’s it!
Conclusion
Technically creating a bot that’s able to make trades on Uniswap is fairly straightforward and easy, thanks to the available libraries and API’s. Now comes the difficult part: implementing the trading strategy and alas, that one’s up to you, dear reader!