How to Build Your Own Uniswap V3 Market Maker Bot - A Beginner's Guide
Hey there, crypto enthusiasts! Ever wondered how to keep your token's liquidity in check on Uniswap? Well, you're in luck! Today, we're going to walk through creating a nifty little market maker bot that'll do the heavy lifting for you. Buckle up, because we're about to dive into the world of automated trading on Uniswap v3!
What's the Big Deal?
First things first – why would you want a market maker bot? Simple! It helps manage liquidity for your token pair, keeping things balanced and reducing volatility. Plus, it can be a great tool for DAOs, traders, or anyone looking to automate their trading strategy.
The Bot's Game Plan
Our bot's job is pretty straightforward:
- Set a target exchange rate between two assets in a pool.
- Check the current price regularly.
- Buy tokens when the price dips below our target.
- Sell tokens when the price climbs above our target.
Easy peasy, right? Let's break it down further.
Setting the Stage: Important Variables
Before we jump into the bot's functions, let's set up some crucial variables. These will form the backbone of our bot:
const ethers = require('ethers');
require("dotenv").config();
// Addresses and contract details
const wethAddress = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2'; // mainnet weth
const routerAddress = '0xE592427A0AEce92De3Edee1F18E0157C05861564'; // Uniswap Router
const quoterAddress = '0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6'; // Uniswap Quoter
const tokenAddress = '0x6982508145454ce325ddbe47a25d4ec3d2311933'; // PEPE TOKEN
// Trading parameters
const fee = 3000; // Uniswap pool fee in basis points (500, 3000, or 10000)
const buyAmount = ethers.parseUnits('0.001', 'ether');
const targetPrice = BigInt(35); // Target exchange rate
const targetAmountOut = buyAmount * targetPrice;
const sellAmount = buyAmount / targetPrice;
const tradeFrequency = 3600 * 1000; // Check price every hour (in milliseconds)
// Provider and wallet setup
const provider = new ethers.JsonRpcProvider(`https://your-rpc-url`);
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY);
const account = wallet.connect(provider);
These variables set up everything from the token addresses we're working with to our trading parameters and network connection.
Building Blocks: The Key Functions
1. Checking the Price
First up, we need a way to check the current price. Here's where our checkPrice function comes in:
const checkPrice = async () => {
const amountOut = await quoter.quoteExactInputSingle(wethAddress, tokenAddress, fee, buyAmount, 0);
console.log(`Current Exchange Rate: ${amountOut.toString()}`);
console.log(`Target Exchange Rate: ${targetAmountOut.toString()}`);
if (amountOut < targetAmountOut) buyTokens();
if (amountOut > targetAmountOut) sellTokens();
}
This function will use the Uniswap Quoter contract to get the latest price and compare it to our targetPrice.
2. Buying Tokens
When the price is low, it's shopping time! Our buyTokens function handles this:
const buyTokens = async () => {
console.log('Buying Tokens')
const deadline = Math.floor(Date.now() / 1000) + 600;
const tx = await router.exactInputSingle([wethAddress, tokenAddress, fee, wallet.address, deadline, buyAmount, 0, 0], {value: buyAmount});
await tx.wait();
console.log(tx.hash);
}
This function will use the buyAmount we defined earlier to purchase tokens when the price is below our target.
3. Selling Tokens
When prices are high, it's time to cash in. The sellTokens function takes care of that:
const sellTokens = async () => {
console.log('Selling Tokens')
const allowance = await token.allowance(wallet.address, routerAddress);
console.log(`Current allowance: ${allowance}`);
if (allowance < sellAmount) {
console.log('Approving Spend (bulk approve in production)');
const atx = await token.approve(routerAddress, sellAmount);
await atx.wait();
}
const deadline = Math.floor(Date.now() / 1000) + 600;
const tx = await router.exactInputSingle([tokenAddress, wethAddress, fee, wallet.address, deadline, sellAmount, 0, 0]);
await tx.wait();
console.log(tx.hash);
}
This function will sell the amount of tokens defined by sellAmount when we're above our target price.
4. Putting It All Together
Now, to keep this bot running 24/7, we use our main function:
checkPrice();
setInterval(() => {
checkPrice();
}, tradeFrequency);
This function uses setInterval to check the price at regular intervals (defined by tradeFrequency). It's like having a tireless trader working round the clock!
Customization is Key
Remember, this bot is just a starting point. You can easily adjust the targetPrice, buyAmount, sellAmount, and tradeFrequency to fit your specific strategy. You might even want to make targetPrice dynamic, following a moving average or other market indicators.
A Word of Caution
Before you unleash your bot on the crypto world, keep a few things in mind:
- This isn't meant for high-frequency trading or arbitrage.
- Always double-check code before running it or sending funds.
- Make sure you have enough ETH in your wallet to cover gas fees.
- Remember to keep your PRIVATE_KEY secure. Never share them or commit them to public repositories.
Wrapping Up
And there you have it – your very own Uniswap market maker bot! With these building blocks and a bit of JavaScript magic, you can automate your trading strategy and keep your token's liquidity in check.
Remember, the crypto world is always evolving, so keep learning and adapting. Happy trading, and may your tokens always stay liquid!