Uniswap Python Trading Bot Using RSI
A comprehensive guide to building a Uniswap trading bot with RSI strategy.
Highlights
- RSI-Based Trigger: Buy when RSI exceeds 80 and sell when it falls below 60.
- Integration with Uniswap: Detailed steps to connect with Uniswap smart contracts using Web3.
- Risk Management: Guidance on data fetching, transaction signing, and best practices for secure trading.
Overview
Algorithmic trading on decentralized platforms such as Uniswap requires a robust understanding of blockchain interactions, technical indicators, and secure transaction management. In this guide, we focus on building a Python-based trading bot that uses the Relative Strength Index (RSI) as a trigger—buying assets when the RSI is above 80 and selling when it drops below 60.
The RSI is a momentum oscillator that measures the speed and change of price movements. In our strategy, an RSI above 80 may be interpreted as an overbought condition implying potential reversals, which triggers a buy order. Conversely, an RSI below 60 signals a potential sell opportunity. While these levels might seem unconventional compared to traditional RSI thresholds, they have been adjusted per strategy requirements.
Below, we walk through setting up your environment to interact with the Ethereum blockchain, fetch historical price data, compute the RSI, and execute trades on Uniswap using Web3. It is important to note that trading on decentralized exchanges can be risky, and thorough testing and risk management strategies are essential before deploying any live trades.
Environment Setup and Prerequisites
Before starting, ensure that you have a working Python environment. The main Python libraries required include:
| Library | Description | Installation Command |
|---|---|---|
| web3 | Connects to the Ethereum blockchain via nodes like Infura. | pip install web3 |
| pandas | Handles data manipulation and analysis. | pip install pandas |
| pandas_ta | Calculates technical indicators including RSI. | pip install pandas_ta |
| ccxt | Provides connectivity to market data sources. | pip install ccxt |
| numpy | Performs numerical operations. | pip install numpy |
Additionally, you will need an Infura account or another Ethereum node provider to connect to the Ethereum mainnet. You should also keep your private key secure and use environment variables or a secure vault system to store sensitive information.
Connecting to Uniswap Using Web3
Step-by-Step Guide
Setting up the Web3 connection is the first step in interacting with the Ethereum blockchain. The following code snippet demonstrates how to initialize your Web3 provider:
# Import necessary libraries
from web3 import Web3
import json
# Connect to Ethereum via Infura
INFURA_URL = "https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID"
web3 = Web3(Web3.HTTPProvider(INFURA_URL))
# Check connection
if not web3.isConnected():
raise ConnectionError("Unable to connect to Ethereum network")
Replace YOUR_INFURA_PROJECT_ID with your actual Infura project ID. This code sets up the connection to Ethereum, which is necessary for creating and signing transactions interacting with Uniswap contracts.
Fetching Historical Price Data
Acquiring Data for RSI Calculation
Accurate historical price data is essential to calculate the RSI. In this example, we simulate data fetching. In a production environment, connect to an API like CoinGecko, CryptoCompare, or directly via The Graph for Uniswap data.
import numpy as np
import pandas as pd
def get_historical_prices(token_address, limit=100):
# This function simulates fetching historical close prices.
# Replace this with an actual API call to fetch real data.
np.random.seed(42)
prices = np.random.random(limit) * 100
return pd.DataFrame({'close': prices})
# Example usage:
historical_data = get_historical_prices("TOKEN_CONTRACT_ADDRESS")
print(historical_data.head())
In the sample above, we generate random prices for demo purposes. Ensure that you replace this stub with your chosen data source for accurate trading decisions.
Calculating RSI
Using Pandas TA for Technical Analysis
The Relative Strength Index (RSI) is computed using the pandas_ta library. By converting historical price data into a DataFrame, we can easily calculate the RSI.
import pandas_ta as ta
def calculate_rsi(data, period=14):
# Use pandas_ta to compute the RSI for the closing prices
data['RSI'] = ta.rsi(data['close'], length=period)
# Return the most recent RSI value
return data['RSI'].iloc[-1]
# Example usage:
rsi_value = calculate_rsi(historical_data)
print("Current RSI:", rsi_value)
The calculate_rsi function calculates the RSI based on a given period (by default 14). We then extract the latest RSI value, which is used as the trading trigger.
Implementing the Trading Logic
Buy and Sell Triggers
Our trading strategy is straightforward:
- Buy Order: Execute if RSI exceeds 80.
- Sell Order: Execute if RSI drops below 60.
This strategy might require tuning based on market conditions. When the RSI crosses these thresholds, we interact with Uniswap's smart contracts to execute trades.
The following Python snippet illustrates the trade execution logic integrated with the aforementioned components:
import time
# Set up critical constants (ensure these are securely stored)
TOKEN_ADDRESS = "YOUR_TOKEN_CONTRACT_ADDRESS"
UNISWAP_ROUTER_ADDRESS = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D" # Uniswap V2 Router example
ACCOUNT_ADDRESS = "YOUR_WALLET_ADDRESS"
PRIVATE_KEY = "YOUR_PRIVATE_KEY"
TRADE_AMOUNT = web3.toWei(0.1, 'ether') # Amount of ETH to use in each trade
# Dummy ABI for Uniswap router; replace with actual ABI JSON
UNISWAP_ROUTER_ABI = json.loads('[]') # Replace with the actual ABI
# Create a contract instance
uniswap_router = web3.eth.contract(address=UNISWAP_ROUTER_ADDRESS, abi=UNISWAP_ROUTER_ABI)
def execute_trade(action):
# This function simulates executing a trade on Uniswap.
# Implement your swap logic using Uniswap's functions.
txn_details = {
'from': ACCOUNT_ADDRESS,
'value': TRADE_AMOUNT,
'gas': 200000,
'gasPrice': web3.eth.gas_price,
'nonce': web3.eth.getTransactionCount(ACCOUNT_ADDRESS),
}
if action == "buy":
print(f"Buying tokens for {TRADE_AMOUNT} wei...")
# Example: Call swapExactETHForTokens from the router
# transaction = uniswap_router.functions.swapExactETHForTokens(...)
elif action == "sell":
print(f"Selling tokens for {TRADE_AMOUNT} tokens...")
# Example: Call swapExactTokensForETH from the router
# transaction = uniswap_router.functions.swapExactTokensForETH(...)
# Here, the transaction should be signed and sent:
# signed_txn = web3.eth.account.sign_transaction(transaction, PRIVATE_KEY)
# tx_hash = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
# print("Transaction hash:", tx_hash.hex())
def main_trading_loop():
while True:
# Fetch market data (update this with actual data fetching logic)
data = get_historical_prices(TOKEN_ADDRESS)
current_rsi = calculate_rsi(data)
print(f"Current RSI: {current_rsi}")
if current_rsi > 80:
print("RSI indicates overbought conditions. Triggering BUY order.")
execute_trade("buy")
elif current_rsi < 60:
print("RSI indicates oversold conditions. Triggering SELL order.")
execute_trade("sell")
else:
print("RSI is in the neutral zone, no trade executed.")
# Pause before the next iteration (adjust this interval as necessary)
time.sleep(300) # Check every 5 minutes
if __name__ == "__main__":
main_trading_loop()
The main_trading_loop function continuously monitors the RSI. Based on the defined thresholds, either a buy or sell order is simulated. Remember to properly implement the transaction signing and interaction with the actual Uniswap contract functions based on your specific requirements.
This code is a simplified model demonstrating the essential steps. Before going live with any automated trading system, consider thorough backtesting, proper risk management (including stop-loss and take-profit strategies), and error handling.
Risk Management & Security
Best Practices for a Trading Bot
Operating a trading bot on decentralized exchanges involves several risk management and security aspects:
- Secure Storage: Never hard-code sensitive values like private keys. Use environmental variables or secret management tools.
- Gas Fees and Slippage: Monitor Ethereum gas fees; set custom tolerances to manage slippage in volatile markets.
- Testing: Always run your bot on a testnet first and conduct backtesting on historical data.
- Error Handling: Implement robust error handling and logging to quickly diagnose and address issues.
- Regulatory Compliance: Understand and comply with local laws and financial regulations when deploying trading systems.
Additional safeguards such as periodic audits of your code and simulation of extreme market conditions are recommended to ensure system robustness.
Supporting Components
Additional Resources and Enhancements
Once your basic trading functionality is in place, consider integrating the following enhancements:
- Enhanced Data Sources: Switch from simulated data to reliable API data from sources like CoinGecko or The Graph.
- Multiple Indicators: Consider combining RSI with other technical indicators for more robust decision-making.
- Order Management: Implement advanced order management functions including stop-loss and take-profit strategies.
- Logging and Monitoring: Add comprehensive logging to trace orders, transactions, and errors which can help in debugging and performance optimization.
The table below outlines the major components of the bot and their respective functionalities:
| Component | Functionality | Key Considerations |
|---|---|---|
| Web3 Connection | Establishing connection with Ethereum network | Secure and reliable node provider (e.g., Infura) |
| Historical Data Fetching | Retrieving price data for analysis | Use of API for accurate market data |
| RSI Calculation | Computation of the Relative Strength Index | Proper period selection and data integrity |
| Trade Execution | Interaction with Uniswap smart contracts | Managing gas fees, nonce, and secure signing |
| Risk Management | Safeguarding capital and trade decision-making | Stop-loss, take-profit, and error handling policies |
By integrating these elements, the trading bot becomes much more resilient to sudden market fluctuations and able to adapt based on live data.
References
- Uniswap V3 Python Bot - GitHub
- Automated Trade Execution on Uniswap V3 in Python - Medium
- Python and RSI Trading Strategy - Quantified Strategies
- RSI Trading Bot - GitHub
- RSI Trading Strategy Applied - Predictive Hacks
- How to Swap Tokens on Uniswap Using Python - Web3 Ethereum DeFi
- Building a Trading Bot in Python - Investing Robots
- Uniswap Trading Bot - Bitsgap
- Getting Started with Uniswap Python - Uniswap Python
- Crypto API Documentation - Cryptowatch
Related Queries
Last updated March 1, 2025