Building a Sandwich Trading Bot with Python for Uniswap and MetaMask: A Step-by-Step Tutorial

·

Decentralized finance (DeFi) has revolutionized how traders interact with digital assets. Among the most powerful tools in a DeFi trader’s arsenal is the automated trading bot—specifically, the sandwich trading bot. This advanced strategy leverages price imbalances and transaction ordering on decentralized exchanges like Uniswap to generate profits. In this comprehensive guide, you’ll learn how to build a sandwich trading bot using Python, interact with MetaMask, and execute trades on Ethereum—all while maintaining security and efficiency.

Whether you're exploring algorithmic trading or diving into DeFi automation, this tutorial provides a practical foundation for developing bots that react to real-time market conditions.


Understanding Sandwich Trading

A sandwich trade involves placing buy and sell orders around a large pending transaction. The bot detects incoming trades, then places its own buy order just before (front-running), inflating the price slightly, and sells after the target transaction executes (back-running), profiting from the temporary price spike.

While controversial in ethical terms, sandwich strategies are technically feasible on open blockchains like Ethereum where transaction mempools are public. However, this tutorial focuses purely on the technical implementation of trade execution—not front-running mechanisms.

👉 Discover how smart contract interactions power automated trading strategies


Prerequisites for Development

Before diving into coding, ensure you meet these requirements:

With these foundations, you’re ready to set up your development environment.


Step 1: Setting Up Your Development Environment

Start by installing essential Python packages:

pip install web3 requests eth-account

These libraries enable:

Create a new .py file—this will house your sandwich bot logic.


Step 2: Connecting to Ethereum via Infura

To interact with the Ethereum blockchain, use an API provider like Infura. Create a free account and obtain your project ID.

from web3 import Web3
from web3.middleware import geth_poa_middleware

# Replace with your Infura Project ID
provider_url = 'https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID'
web3 = Web3(Web3.HTTPProvider(provider_url))
web3.middleware_onion.inject(geth_poa_middleware, layer=0)

if web3.is_connected():
    print("Connected to Ethereum")
else:
    print("Failed to connect")

Ensure connectivity before proceeding.


Step 3: Loading Your MetaMask Wallet

Use your MetaMask private key to sign transactions securely in code.

from eth_account import Account

wallet_private_key = 'YOUR_PRIVATE_KEY'  # Never expose this!
wallet = Account.from_key(wallet_private_key)
print(f"Wallet Address: {wallet.address}")

⚠️ Security Note: Store keys in environment variables or encrypted vaults—never hardcode them.

👉 Learn how secure wallet integration enhances trading automation


Step 4: Configuring Uniswap Contract Addresses

Use the official Uniswap V2 Router address:

router_address = '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D'

# Example tokens: WETH and USDC
token_in = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2'  # WETH
token_out = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'  # USDC

You’ll also need the Uniswap Router ABI (Application Binary Interface). Download it from Uniswap’s official GitHub or use a verified JSON file.


Step 5: Fetching Real-Time Token Prices

Use CoinGecko API to get live prices:

import requests

def get_token_price(token_address):
    url = f"https://api.coingecko.com/api/v3/simple/token_price/ethereum?contract_addresses={token_address}&vs_currencies=usd"
    try:
        response = requests.get(url).json()
        return response[token_address.lower()]['usd']
    except Exception as e:
        print(f"Error fetching price: {e}")
        return None

# Example usage
price = get_token_price(token_in)
print(f"Current WETH Price: ${price}")

This function retrieves USD values for any ERC-20 token.


Step 6: Executing Trades on Uniswap

Implement two core functions: approval and swap.

Approve Token Spending

def approve_token_spending(token_contract, spender_address, amount):
    nonce = web3.eth.getTransactionCount(wallet.address)
    txn = token_contract.functions.approve(
        spender_address,
        amount
    ).buildTransaction({
        'chainId': 1,
        'gas': 100000,
        'gasPrice': web3.toWei('5', 'gwei'),
        'nonce': nonce,
    })
    signed_txn = web3.eth.account.sign_transaction(txn, wallet.privateKey)
    tx_hash = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
    receipt = web3.eth.wait_for_transaction_receipt(tx_hash)
    return receipt.success

Execute Swap

def execute_swap(amount_in, token_in, token_out, min_amount_out):
    router_contract = web3.eth.contract(address=router_address, abi=UNISWAP_ROUTER_ABI)
    deadline = int(time.time()) + 10000

    swap_txn = router_contract.functions.swapExactTokensForTokens(
        amount_in,
        min_amount_out,
        [token_in, token_out],
        wallet.address,
        deadline
    ).buildTransaction({
        'from': wallet.address,
        'gas': 250000,
        'gasPrice': web3.toWei('10', 'gwei'),
        'nonce': web3.eth.getTransactionCount(wallet.address),
    })

    signed_swap = web3.eth.account.sign_transaction(swap_txn, wallet.privateKey)
    tx_hash = web3.eth.send_raw_transaction(signed_swap.rawTransaction)
    receipt = web3.eth.wait_for_transaction_receipt(tx_hash)
    return receipt.transactionHash.hex()

Step 7: Implementing the Sandwich Logic

Now combine everything into a loop that monitors prices and triggers trades:

import time

while True:
    current_price = get_token_price(token_in)
    buy_threshold = current_price * 0.95  # Buy if price drops 5%
    sell_threshold = current_price * 1.05  # Sell if price rises 5%

    if current_price <= buy_threshold:
        print("Executing buy...")
        execute_swap(web3.toWei(0.1, 'ether'), token_out, token_in, 0)
    elif current_price >= sell_threshold:
        print("Executing sell...")
        execute_swap(web3.toWei(0.1, 'ether'), token_in, token_out, 0)

    time.sleep(15)  # Check every 15 seconds

This simplified version uses threshold-based triggers instead of real-time mempool analysis.


Frequently Asked Questions (FAQ)

Q: Is sandwich trading legal?

A: While technically possible on public blockchains, sandwich attacks raise ethical concerns and may violate platform terms. This tutorial is for educational purposes only—use strategies responsibly.

Q: Can I run this bot on testnets?

A: Yes! Use Ropsten, Goerli, or Sepolia testnets with faucets for free ETH. Test all logic before deploying on mainnet.

Q: How do I protect my private keys?

A: Never store keys in plain text. Use environment variables (os.getenv('PRIVATE_KEY')) or hardware wallets via libraries like eth-keys.

Q: What are gas fees, and how do they affect my bot?

A: Gas fees are network costs for executing transactions. High volatility increases congestion—monitor gas prices using tools like Etherscan Gas Tracker.

Q: Can I integrate other DEXs?

A: Absolutely. SushiSwap and PancakeSwap have similar ABIs. Modify contract addresses and router logic accordingly.

Q: How do I improve execution speed?

A: Optimize API calls, use WebSocket providers (e.g., Alchemy), and consider MEV relays for faster inclusion.

👉 Explore high-performance trading environments powered by blockchain infrastructure


Final Thoughts

Building a sandwich trading bot with Python, Uniswap, and MetaMask offers deep insight into DeFi automation. From setting up Web3 connections to executing real trades, this guide walks you through every critical step.

Remember: automation brings power—but also responsibility. Always test thoroughly in sandbox environments, prioritize security, and stay compliant with evolving regulations.

Whether you're prototyping arbitrage strategies or learning smart contract interaction, this foundation empowers your journey into algorithmic crypto trading.


Core Keywords:
sandwich trading bot, Uniswap, MetaMask, Python, DeFi, automated trading, Ethereum, smart contract