Build a Real-Time Trading Bot in Python: Fetch Prices and TA with Market Masters API
Market Masters AI gives developers access to institutional-grade data via REST API and WebSockets. This tutorial walks you through a Python bot that pulls live BTC prices, computes RSI for oversold/overbought signals, and logs trade alerts.
Target audience: Python devs new to trading APIs. No finance PhD required.
Why Market Masters?
- 2,500+ cryptos, S&P 500 stocks, futures, ETFs.
- Real-time screeners, 16 chart patterns, Elliott Waves.
- Free tier with API access.
Sign up: marketmasters.ai (no CC, 30-day Premium trial).
Setup
pip install requests websocket-client python-dotenv
Create .env:
MARKETMASTERS_API_KEY=your_key_here
Core Functions
Load env:
import os
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.getenv('MARKETMASTERS_API_KEY')
BASE_URL = 'https://api.marketmasters.ai/v1'
Fetch spot price:
import requests
def get_price(symbol):
url = f"{BASE_URL}/prices/{symbol}"
headers = {'Authorization': f'Bearer {API_KEY}'}
resp = requests.get(url)
resp.raise_for_status()
return resp.json()['data'][0]['price']
btc = get_price('BTCUSDT')
print(f"BTC/USDT: ${btc:.2f}")
Technical analysis (RSI example):
def get_rsi(symbol, period=14, timeframe='1h'):
url = f"{BASE_URL}/ta/{symbol}/rsi"
params = {'period': period, 'timeframe': timeframe}
headers = {'Authorization': f'Bearer {API_KEY}'}
resp = requests.get(url, params=params, headers=headers)
resp.raise_for_status()
return resp.json()['rsi'][-1]
rsi_val = get_rsi('BTCUSDT')
print(f"RSI (14, 1h): {rsi_val:.2f}")
WebSocket for Live Updates
import websocket
import json
def on_message(ws, msg):
data = json.loads(msg)
price = data['price']
rsi = get_rsi('BTCUSDT') # Refresh TA
signal = ""
if rsi < 30:
signal = "BUY (oversold)"
elif rsi > 70:
signal = "SELL (overbought)"
print(f"Price: ${price:.2f} | RSI: {rsi:.2f} | {signal}")
ws_url = f"wss://ws.marketmasters.ai/prices?symbol=BTCUSDT&token={API_KEY}"
ws = websocket.WebSocketApp(ws_url, on_message=on_message)
ws.run_forever()
Full Bot Script
Combine into trading_bot.py:
# [full code here - import all, main loop with error handling, Telegram alerts via Orion if premium]
import time
# ... (previous functions)
if __name__ == "__main__":
while True:
try:
price = get_price('BTCUSDT')
rsi = get_rsi('BTCUSDT')
if rsi < 30:
print("🚀 BUY ALERT")
# send_telegram_alert("BUY BTC")
elif rsi > 70:
print("🔴 SELL ALERT")
time.sleep(60) # Poll every minute
except Exception as e:
print(f"Error: {e}")
time.sleep(30)
Test and Deploy
Run: python trading_bot.py
Deploy on VPS with screen or systemd. Add portfolio tracking:
positions = {'BTC': 0.1} # Your holdings
pnl = sum(pos * get_price(k) for k,pos in positions.items())
Limitations and Improvements
- This is RSI-only. Stack with Market Masters' chart patterns API.
- Rate limits: Free tier 100/min.
- Risk: Backtest before live trading.
Get Started
Free API access today. Build smarter bots: marketmasters.ai/signup.
Affiliate: 20% recurring commissions.
Top comments (0)