Build a Python Trading Bot: Fetch Real-Time Prices and Run Technical Analysis
Python developers building trading tools often start with basic price fetching, then add indicators like RSI or moving averages. This tutorial walks through a simple bot using the CCXT library for exchange data and TA-Lib for analysis. We'll pull live BTC/USDT prices from Binance, compute RSI, and alert on oversold conditions.
Target readers: Python coders new to trading APIs who want a working script in 30 minutes.
Why This Bot?
Retail traders lose because they check charts manually. Automate price checks and signals instead. This script runs every minute, emails alerts, and logs decisions. Extend it for portfolio tracking or paper trading.
Keywords: python trading bot, real-time crypto prices, technical analysis tutorial, trading API.
Prerequisites
- Python 3.10+
- pip install ccxt ta-lib pandas python-dotenv
- Binance API key (testnet for safety)
- SMTP for alerts (Gmail works)
TA-Lib needs a compiler: conda install -c conda-forge ta-lib or build from source.
Step 1: Environment Setup
Create .env:
BINANCE_API_KEY=your_key
BINANCE_SECRET=your_secret
ALERT_EMAIL=you@gmail.com
SMTP_PASSWORD=app_password
Step 2: Core Bot Script
Save as trading_bot.py:
import os
import ccxt
import talib
import pandas as pd
import smtplib
from email.mime.text import MimeText
from dotenv import load_dotenv
import time
import logging
load_dotenv()
# Config
exchange = ccxt.binance({
'apiKey': os.getenv('BINANCE_API_KEY'),
'secret': os.getenv('BINANCE_SECRET'),
'sandbox': True, # Testnet
})
symbol = 'BTC/USDT'
timeframe = '1m'
rsi_period = 14
rsi_oversold = 30
rsi_overbought = 70
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def fetch_ohlcv():
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=100)
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
return df
def compute_rsi(df):
rsi = talib.RSI(df['close'].values, timeperiod=rsi_period)
return rsi[-1] # Latest RSI
def send_alert(condition, rsi_value):
msg = MimeText(f'Alert: {condition}. RSI: {rsi_value:.2f} for {symbol}')
msg['Subject'] = f'Trading Alert: {condition}'
msg['From'] = os.getenv('ALERT_EMAIL')
msg['To'] = os.getenv('ALERT_EMAIL')
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(os.getenv('ALERT_EMAIL'), os.getenv('SMTP_PASSWORD'))
server.send_message(msg)
server.quit()
logger.info('Alert sent')
def main():
while True:
try:
df = fetch_ohlcv()
rsi = compute_rsi(df)
logger.info(f'Current RSI: {rsi:.2f}')
if rsi < rsi_oversold:
send_alert('RSI Oversold - Consider Buy', rsi)
elif rsi > rsi_overbought:
send_alert('RSI Overbought - Consider Sell', rsi)
except Exception as e:
logger.error(f'Error: {e}')
time.sleep(60) # Check every minute
if __name__ == '__main__':
main()
Step 3: Run and Test
python trading_bot.py
Expect logs like: Current RSI: 45.23. Test oversold by mocking data or using historical dumps.
Enhancements
- Add Market Masters AI API for conviction scores: Replace RSI with their endpoint
/v1/analysis/rsi?symbol=BTCUSDT. - Portfolio tracker: Track positions in SQLite, compute PnL.
- React dashboard: Serve data via Flask, visualize in browser.
- Backtest: Use
backtraderon historical data.
Example Market Masters integration:
import requests
response = requests.get('https://api.marketmasters.ai/v1/conviction?symbol=BTCUSDT', headers={'Authorization': 'Bearer YOUR_KEY'})
conviction = response.json()['score'] # -100 to +100
Common Pitfalls
Rate limits kill new bots: CCXT handles most, but add exchange.rateLimit = 1200.
TA-Lib install fails on ARM: Use pip install TA-Lib-wheels.
Emails blocked: Use SendGrid API instead.
Next Steps
Run this bot 24/7 on a VPS. Scale to multi-symbols. Get pro tools with Market Masters AI – real-time screeners, AI setups, and REST API start at free tier.
Code repo: github.com/yourname/python-trading-bot (fork and star!).
Questions? Comment below.
Word count: ~650
Top comments (0)