DEV Community

Market Masters
Market Masters

Posted on

Build a Real-Time Crypto Trading Bot in Python with Market Masters API

Build a Real-Time Crypto Trading Bot in Python with Market Masters API

Real-time market data separates winning bots from the rest. In this tutorial, you will build a Python trading bot that fetches live crypto prices, runs simple technical analysis, and places simulated trades using the Market Masters developer API.

Prerequisites

  • Python 3.9+
  • A free Market Masters account (sign up at marketmasters.ai)
  • API key from your developer dashboard
  • Basic understanding of REST APIs and pandas

Step 1: Install Dependencies

pip install requests pandas ta python-dotenv
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure Your API Key

Create a .env file:

MARKETMASTERS_API_KEY=your_key_here
Enter fullscreen mode Exit fullscreen mode

Load it in Python:

import os
from dotenv import load_dotenv
load_dotenv()

API_KEY = os.getenv("MARKETMASTERS_API_KEY")
BASE_URL = "https://api.marketmasters.ai/v1"
Enter fullscreen mode Exit fullscreen mode

Step 3: Fetch Real-Time Prices

Use the market data endpoint to pull live prices for BTC and ETH:

import requests
import pandas as pd
from datetime import datetime

def get_real_time_price(symbol):
    url = f"{BASE_URL}/prices/realtime"
    headers = {"Authorization": f"Bearer {API_KEY}"}
    params = {"symbols": symbol, "exchange": "binance"}
    response = requests.get(url, headers=headers, params=params)
    return response.json()

btc_data = get_real_time_price("BTCUSDT")
print(btc_data)
Enter fullscreen mode Exit fullscreen mode

The response includes bid, ask, last price, and volume, updated every second.

Step 4: Add Technical Analysis

Calculate RSI and moving averages with the ta library:

import ta

def analyze_price(df):
    df["rsi"] = ta.momentum.RSIIndicator(df["close"]).rsi()
    df["sma_20"] = ta.trend.SMAIndicator(df["close"], window=20).sma_indicator()
    df["sma_50"] = ta.trend.SMAIndicator(df["close"], window=50).sma_indicator()
    return df

# Example dataframe from historical endpoint
df = pd.DataFrame(...)  # fetch OHLCV data
analyzed = analyze_price(df)
Enter fullscreen mode Exit fullscreen mode

Look for RSI below 30 (oversold) or above 70 (overbought) as signals.

Step 5: Build the Trading Bot Loop

Combine price fetching, analysis, and order placement in a simple loop:

import time

def place_order(symbol, side, quantity):
    url = f"{BASE_URL}/orders"
    headers = {"Authorization": f"Bearer {API_KEY}"}
    payload = {
        "symbol": symbol,
        "side": side,
        "type": "market",
        "quantity": quantity
    }
    response = requests.post(url, headers=headers, json=payload)
    return response.json()

while True:
    price = get_real_time_price("BTCUSDT")
    # Add your strategy logic here
    if analyzed["rsi"].iloc[-1] < 30:
        place_order("BTCUSDT", "buy", 0.001)
    time.sleep(60)  # check every minute
Enter fullscreen mode Exit fullscreen mode

This example runs paper trades. Switch to live mode only after thorough backtesting.

Step 6: Add React Dashboard (Optional)

For a frontend view, create a simple React app that polls the same API:

// In your React component
useEffect(() => {
  const fetchPrice = async () => {
    const res = await fetch("/api/prices/realtime?symbols=BTCUSDT");
    const data = await res.json();
    setPrice(data.last);
  };
  const interval = setInterval(fetchPrice, 1000);
  return () => clearInterval(interval);
}, []);
Enter fullscreen mode Exit fullscreen mode

Testing and Next Steps

  • Run the bot against Market Masters paper trading endpoint first.
  • Log every decision to a local SQLite database.
  • Add risk management: position sizing, stop losses, and max drawdown checks.

The Market Masters REST API also supports order flow, open interest, and liquidation data, so you can extend this bot into a full institutional-grade system.

CTA

Ready to ship your own trading bot? Grab your free API key at marketmasters.ai and start building today. Share your bot in the comments or fork the starter repo linked in the resources.

Top comments (0)