Build a Real-Time Crypto Trading Bot in Python: Live Prices, RSI Signals, and CCXT Trades
Bitcoin drops 5% before your morning coffee hits. Manual trading misses those edges. This tutorial codes a Python bot that fetches live prices from exchanges, computes RSI for buy/sell signals, and executes paper trades via CCXT. Builders: get it running in 30 minutes, then hook Market Masters API for pro signals.
Targets: BTC/USDT on Binance. Extend to stocks or any CCXT exchange.
Setup
Install deps:
pip install ccxt pandas pandas_ta python-dotenv
Create .env:
BINANCE_API_KEY=your_key
BINANCE_SECRET=your_secret
Load in code:
import os
from dotenv import load_dotenv
load_dotenv()
exchange = ccxt.binance({
'apiKey': os.getenv('BINANCE_API_KEY'),
'secret': os.getenv('BINANCE_SECRET'),
'sandbox': True, # Paper trading
})
Gotcha: Sandbox needs separate API keys from Binance testnet. Real keys? Enable futures permissions.
Fetch Live Prices
OHLCV data, 1m candles:
import pandas as pd
import pandas_ta as ta
symbol = 'BTC/USDT'
timeframe = '1m'
limit = 100
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=limit)
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
df.set_index('timestamp', inplace=True)
Technical Analysis: RSI
RSI spots momentum. Below 30: buy. Above 70: sell.
df['rsi'] = ta.rsi(df['close'], length=14)
latest_rsi = df['rsi'].iloc[-1]
print(f"Latest RSI: {latest_rsi:.2f}")
Trading Strategy
Simple RSI crossover:
def get_signal(rsi):
if rsi < 30:
return 'buy'
elif rsi > 70:
return 'sell'
return 'hold'
signal = get_signal(latest_rsi)
Simulate position:
position = 0 # 0: flat, 1: long
if signal == 'buy' and position == 0:
amount = 0.001 # BTC
order = exchange.create_market_buy_order(symbol, amount)
position = 1
print(f"Bought {amount} BTC at {df['close'].iloc[-1]}")
elif signal == 'sell' and position == 1:
order = exchange.create_market_sell_order(symbol, amount)
position = 0
print(f"Sold at {df['close'].iloc[-1]}")
Live Loop
Run every minute:
import time
while True:
try:
ohlcv = exchange.fetch_ohlcv(symbol, timeframe)
df = pd.DataFrame(...) # As above
df['rsi'] = ta.rsi(df['close'])
signal = get_signal(df['rsi'].iloc[-1])
# Trade logic here
time.sleep(60)
except Exception as e:
print(f"Error: {e}")
time.sleep(60)
Backtest Quick Check
Test on history:
def backtest(df):
df['signal'] = df['rsi'].apply(get_signal)
df['returns'] = df['close'].pct_change()
df['strategy'] = df['signal'].shift(1) * df['returns']
cumulative = (1 + df['strategy']).cumprod().iloc[-1]
print(f"Strategy multiplier: {cumulative:.2f}x")
backtest(df)
Sample run (last 100 candles): Often beats buy-hold by catching reversals, but watch drawdowns.
Tradeoffs and Gotchas
- API Rate Limits: Binance: 1200 req/min. Use longer timeframes or websocket for prod.
- Slippage: Market orders slide in volatility. Use limits.
- Fees: 0.1% per side kills small trades.
- No TA-Lib? pandas_ta pure Python alternative.
- Leverage: Sandbox caps it. Real: start 1x.
- Risk: Paper first. Never risk >1-2% per trade.
Full code: [GitHub gist link – paste your repo].
Level Up
This bot scratches the surface. Market Masters AI gives real-time screeners across 2500+ cryptos/stocks, Orion AI for setups, chart patterns, and a REST API to plug in. Free tier: marketmasters.ai. Dev API docs live there too.
Build, test, trade smarter.
Code tested on Python 3.12, CCXT 4.3.x. Questions? Comments.
Top comments (0)