DEV Community

Market Masters
Market Masters

Posted on

Python Trading Bot Tutorial: Real-Time Crypto Prices and Alerts with Market Masters AI API

Python Trading Bot Tutorial: Real-Time Crypto Prices and Alerts with Market Masters AI API

Retail traders lose because they stare at screens. A bot that pulls live data and pings you on setups changes that.

This tutorial builds a Python bot using the Market Masters AI REST API. It fetches real-time prices for BTC/USDT on Binance, computes RSI, and alerts via Telegram when oversold.

Market Masters covers 2500+ cryptos, stocks, futures. Free tier gets basic screening. API starts free.

Prerequisites

  • Python 3.10+
  • pip install requests pandas ta-lib python-telegram-bot
  • Market Masters account (sign up, 30-day Premium trial no CC)
  • API key from dashboard
  • Telegram bot token ( @BotFather )

ta-lib needs system deps: apt install libta-lib0 libta-lib-dev or conda.

API Setup

import requests
import os

API_KEY = os.getenv('MARKET_MASTERS_API_KEY')
BASE_URL = 'https://api.marketmasters.ai/v1'

headers = {'Authorization': f'Bearer {API_KEY}'}
Enter fullscreen mode Exit fullscreen mode

Tradeoff: Bearer tokens simple but log carefully. Rotate keys monthly.

Fetch Real-Time Prices

Hit /prices/{exchange}/{symbol} for live ticks.

def get_price(exchange, symbol):
    url = f'{BASE_URL}/prices/{exchange}/{symbol}'
    resp = requests.get(url, headers=headers)
    if resp.status_code == 200:
        data = resp.json()
        return data['price'], data['timestamp']
    raise ValueError(f'API error: {resp.text}')

# Example
price, ts = get_price('binance', 'BTCUSDT')
print(f'BTC: ${price} at {ts}')
Enter fullscreen mode Exit fullscreen mode

Gotcha: Rate limit 60/min free tier. Batch symbols with /prices/multi.

Compute RSI

Use ta lib for 14-period RSI.

import pandas as pd
import talib

def get_ohlcv(exchange, symbol, interval='1m', limit=100):
    url = f'{BASE_URL}/klines/{exchange}/{symbol}?interval={interval}&limit={limit}'
    resp = requests.get(url, headers=headers)
    data = resp.json()['klines']
    df = pd.DataFrame(data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
    df = df.astype({'open': 'float', 'high': 'float', 'low': 'float', 'close': 'float'})
    return df

def rsi_alert(df):
    rsi = talib.RSI(df['close'].values, timeperiod=14)
    latest_rsi = rsi[-1]
    if latest_rsi < 30:
        return f'RSI oversold: {latest_rsi:.1f}'
    return None
Enter fullscreen mode Exit fullscreen mode

API returns OHLCV like Binance. Parse floats carefully; timestamps UTC.

Trading Logic

Simple: Poll every 60s, alert on RSI <30 or >70.

import time
from telegram import Bot

TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')
CHAT_ID = os.getenv('CHAT_ID')
bot = Bot(token=TELEGRAM_TOKEN)

def main():
    while True:
        try:
            df = get_ohlcv('binance', 'BTCUSDT')
            alert = rsi_alert(df)
            if alert:
                bot.send_message(chat_id=CHAT_ID, text=f'{alert} Price: ${df["close"].iloc[-1]:.2f}')
            time.sleep(60)
        except Exception as e:
            print(f'Error: {e}')
            time.sleep(60)

if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

Bugs: No position tracking. Add state file JSON. Handle disconnects with retries.

Run It

export MARKET_MASTERS_API_KEY=your_key
export TELEGRAM_TOKEN=your_bot_token
export CHAT_ID=your_chat_id
python bot.py
Enter fullscreen mode Exit fullscreen mode

Scales to portfolio: Loop symbols list.

React Dashboard (Bonus)

For UI, React app polls API, charts with Recharts.

// App.js
import { useEffect, useState } from 'react';
import { LineChart, Line } from 'recharts';

function App() {
  const [data, setData] = useState([]);
  useEffect(() => {
    const fetchData = async () => {
      const resp = await fetch('https://api.marketmasters.ai/v1/prices/binance/BTCUSDT', {
        headers: { Authorization: `Bearer ${process.env.REACT_APP_API_KEY}` }
      });
      // Update data...
    };
    const interval = setInterval(fetchData, 5000);
    return () => clearInterval(interval);
  }, []);

  return <LineChart data={data}><Line dataKey="price" /></LineChart>;
}
Enter fullscreen mode Exit fullscreen mode

npm create-react-app trading-dashboard. Proxy API calls server-side prod.

Tradeoffs

  • Polling vs WebSockets: API WebSockets Premium.
  • TA-Lib fast but C deps heavy; use pandas_ta pure Python.
  • Free tier limits: Upgrade for 1000s symbols.

Build your edge. Start free at Market Masters. Affiliate 20% recurring: link.

Code: GitHub repo (fork and star).

Top comments (0)