Build a Python Trading Bot: Real-Time Prices, Technical Analysis, and Alerts
Retail traders lose 70% of their capital in the first year. Most blame the market. The real issue: bad signals from stale data and weak analysis. You can fix that with a Python bot that pulls live prices, runs TA indicators, and alerts on setups.
This tutorial builds one from scratch. Uses free APIs (Binance for prices, TA-Lib for indicators). Add Market Masters API later for pro conviction scores. Runs in 100 lines. Deploy to VPS for 24/7.
Why Bother
Manual charting misses edges. Bots catch them: sub-minute checks, backtests, risk limits. I built mine after spotting 3x returns on BTC calls it flagged first.
Setup
pip install python-binance ta-lib pandas numpy requests python-telegram-bot
TA-Lib needs binaries: Ubuntu apt install ta-lib; Mac brew install ta-lib; Windows wheel from unofficial.
Get API keys:
- Binance: https://www.binance.com/en/my/settings/api-management (spot testnet first)
- Telegram: @botfather for token
Core: Fetch Prices
import requests
from binance.client import Client
import pandas as pd
import numpy as np
import talib
import telegram
API_KEY = 'your_binance_key'
API_SECRET = 'your_binance_secret'
TELEGRAM_TOKEN = 'your_bot_token'
CHAT_ID = 'your_chat_id'
client = Client(API_KEY, API_SECRET)
def get_klines(symbol='BTCUSDT', interval='1m', limit=100):
klines = client.get_klines(symbol=symbol, interval=interval, limit=limit)
df = pd.DataFrame(klines, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'number_of_trades', 'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore'])
df['close'] = pd.to_numeric(df['close'])
return df
Compute Indicators
RSI oversold under 30, overbought over 70. MACD crossovers signal momentum.
def compute_signals(df):
df['rsi'] = talib.RSI(df['close'], timeperiod=14)
df['macd'], df['macdsignal'], df['macdhist'] = talib.MACD(df['close'])
latest = df.iloc[-1]
prev = df.iloc[-2]
signals = []
if latest['rsi'] < 30 and prev['rsi'] >= 30:
signals.append('RSI Oversold')
if latest['rsi'] > 70 and prev['rsi'] <= 70:
signals.append('RSI Overbought')
if latest['macd'] > latest['macdsignal'] and prev['macd'] <= prev['macdsignal']:
signals.append('MACD Bull Cross')
return signals
Alert Logic
def send_alert(symbol, signals):
bot = telegram.Bot(token=TELEGRAM_TOKEN)
message = f"🚨 {symbol} Signals: {', '.join(signals)}"
bot.send_message(chat_id=CHAT_ID, text=message)
Main Loop
def main():
symbol = 'BTCUSDT'
while True:
df = get_klines(symbol)
signals = compute_signals(df)
if signals:
send_alert(symbol, signals)
time.sleep(60) # 1m checks
import time
from datetime import datetime
main()
Full script: [gist link placeholder]. Test on testnet.
Scale It
- Backtest: pandas resample, vectorized TA.
- Multi-symbol: loop symbols list.
- Market Masters: Swap Binance for their REST API (docs.marketmasters.ai). Get conviction (-100 to +100) from 15 indicators. Free tier: 5 alerts/day.
# Market Masters example
response = requests.get('https://api.marketmasters.ai/v1/conviction/BTCUSDT', headers={'Authorization': 'Bearer YOUR_KEY'})
conviction = response.json()['score']
if conviction > 80:
send_alert('BTCUSDT', ['High Conviction Buy'])
Gotchas
- Rate limits: Binance 1200/min. Sleep accordingly.
- TA-Lib install hell: Docker it.
- Slippage: Paper trade first ($10K sim capital).
- VPS: $5 DigitalOcean, screen/tmux.
Deploy: nohup python bot.py &. Logs to file.
Results
Mine flagged BTC bottom April 2025 (RSI 28 + MACD cross). 40% drawdown avoided.
Build yours. Start free at marketmasters.ai. API docs ready. Questions? Comments below.
Top comments (0)