Build a Crypto Trading Bot with MarketLens API

Tutorial March 13, 2026 18 min read NEW

Crypto markets never sleep. A trading bot can monitor prices 24/7, calculate signals, and alert you when it is time to act. In this tutorial, you will build a complete crypto monitoring bot in Python using the MarketLens API -- from fetching real-time prices to setting up automated webhook alerts.

The bot will monitor a watchlist of coins, calculate simple moving average (SMA) crossover signals, and send alerts via webhooks when conditions are met. The entire project uses standard Python libraries and can run on any server, Raspberry Pi, or cloud VM.

Start your Pro trial for crypto bots

50,000 calls/day, WebSocket streaming, 300+ coins. Use FOUNDER50 for 50% off after trial.

Start Pro Trial

What You Will Build

By the end of this tutorial, your crypto bot will:

  • Fetch real-time crypto prices for BTC, ETH, SOL, and any of 300+ supported coins
  • Monitor a custom watchlist with price change tracking
  • Calculate SMA crossover signals (golden cross / death cross) using historical data
  • Set automated price alerts with the MarketLens alerts API
  • Send webhook notifications when alert conditions are triggered
  • Run on a schedule for 24/7 monitoring

Get Your Free API Key

Get 500 free API calls/day. No credit card required.

Join 15,000+ developers. No spam.

Prerequisites

  • Python 3.10 or later
  • A free MarketLens API key (1,000 calls/day free, or Pro for 50,000/day)
  • Basic Python knowledge (functions, dicts, loops)

Install the dependencies:

bash
pip install requests pandas schedule

1Set Up the Bot Framework

Start by setting up the API connection and defining your crypto watchlist. Head to marketlens.dev/signup to get your free API key.

python
#!/usr/bin/env python3
"""Crypto Trading Bot powered by MarketLens API."""

import requests
import pandas as pd
import schedule
import time
from datetime import datetime

# === Configuration ===
API_KEY = "ml_your_api_key_here"   # Get yours at marketlens.dev/signup
BASE_URL = "https://marketlens.dev/api/v1"
HEADERS = {"X-API-Key": API_KEY}

# Coins to monitor
WATCHLIST = ["BTC", "ETH", "SOL", "AVAX", "MATIC", "LINK", "DOT", "ADA"]

# Optional: your webhook URL for alerts (Discord, Slack, etc.)
WEBHOOK_URL = "https://your-server.com/crypto-alerts"

2Fetch Real-Time Crypto Prices

The MarketLens /crypto/{symbol} endpoint returns real-time price data for any of 300+ supported coins. Each call returns price, 24h change, volume, and market cap.

python
def get_crypto_price(symbol: str) -> dict:
    """Fetch real-time crypto price from MarketLens."""
    url = f"{BASE_URL}/crypto/{symbol}"
    resp = requests.get(url, headers=HEADERS)
    resp.raise_for_status()
    return resp.json()["data"]

# Fetch Bitcoin price
btc = get_crypto_price("BTC")
print(f"BTC: ${btc['price']:,.2f} ({btc['change_pct_24h']}% 24h)")
# Output: BTC: $87,432.50 (+2.34% 24h)

# Fetch Ethereum price
eth = get_crypto_price("ETH")
print(f"ETH: ${eth['price']:,.2f} ({eth['change_pct_24h']}% 24h)")
# Output: ETH: $3,245.80 (+1.87% 24h)

3Build a Watchlist Monitor

Create a function that scans your entire watchlist and displays a clean summary with price, 24h change, and volume.

python
def scan_watchlist(coins: list) -> pd.DataFrame:
    """Scan all coins in the watchlist and return a summary."""
    rows = []
    for symbol in coins:
        try:
            data = get_crypto_price(symbol)
            rows.append({
                "Coin": symbol,
                "Price": f"${data['price']:,.2f}",
                "24h %": f"{data['change_pct_24h']:+.2f}%",
                "Volume": f"${data['volume_24h']:,.0f}",
                "Market Cap": f"${data['market_cap']:,.0f}",
            })
        except Exception as e:
            print(f"Error fetching {symbol}: {e}")

    df = pd.DataFrame(rows)
    return df

# Run the watchlist scan
df = scan_watchlist(WATCHLIST)
print(f"\n--- Crypto Watchlist | {datetime.now():%Y-%m-%d %H:%M} ---")
print(df.to_string(index=False))

Sample output:

output
--- Crypto Watchlist | 2026-03-13 14:30 ---
 Coin       Price   24h %        Volume       Market Cap
  BTC  $87,432.50  +2.34%  $28,450,000,000  $1,712,000,000,000
  ETH   $3,245.80  +1.87%  $12,340,000,000    $390,000,000,000
  SOL     $178.20  +4.12%   $3,210,000,000     $78,500,000,000
 AVAX      $42.50  -1.23%     $890,000,000     $16,200,000,000
MATIC       $1.15  +0.89%     $420,000,000      $4,800,000,000
 LINK      $18.75  +3.45%     $560,000,000     $11,300,000,000
  DOT       $8.90  -0.56%     $310,000,000      $5,600,000,000
  ADA       $0.65  +1.02%     $280,000,000     $22,800,000,000

4Calculate Trading Signals (SMA Crossover)

A simple but effective signal is the SMA crossover: when the short-term average crosses above the long-term average (golden cross), it signals a potential buy. When it crosses below (death cross), it signals caution. Use the MarketLens /crypto/{symbol}/history endpoint to get historical data.

python
def get_crypto_history(symbol: str, period: str = "3m") -> pd.DataFrame:
    """Fetch historical OHLCV data for a crypto coin."""
    url = f"{BASE_URL}/crypto/{symbol}/history"
    resp = requests.get(url, headers=HEADERS, params={"period": period})
    resp.raise_for_status()
    data = resp.json()["data"]["history"]
    df = pd.DataFrame(data)
    df["date"] = pd.to_datetime(df["date"])
    return df.sort_values("date")

def calculate_sma_signal(symbol: str,
                         short_window: int = 7,
                         long_window: int = 25) -> dict:
    """Calculate SMA crossover signal for a crypto coin.

    Returns:
        dict with signal ('BUY', 'SELL', 'HOLD'), short_sma, long_sma
    """
    df = get_crypto_history(symbol, "3m")

    # Calculate moving averages
    df["sma_short"] = df["close"].rolling(window=short_window).mean()
    df["sma_long"] = df["close"].rolling(window=long_window).mean()

    # Get the latest values
    latest = df.iloc[-1]
    prev = df.iloc[-2]

    short_sma = latest["sma_short"]
    long_sma = latest["sma_long"]

    # Detect crossover
    if prev["sma_short"] <= prev["sma_long"] and short_sma > long_sma:
        signal = "BUY"    # Golden cross
    elif prev["sma_short"] >= prev["sma_long"] and short_sma < long_sma:
        signal = "SELL"   # Death cross
    else:
        signal = "HOLD"

    return {
        "symbol": symbol,
        "signal": signal,
        "price": latest["close"],
        "sma_short": round(short_sma, 2),
        "sma_long": round(long_sma, 2),
    }

# Check signals for all watchlist coins
for coin in WATCHLIST:
    sig = calculate_sma_signal(coin)
    emoji = {"BUY": "[BUY]", "SELL": "[SELL]", "HOLD": "[HOLD]"}
    print(f"{emoji[sig['signal']]} {sig['symbol']}: ${sig['price']:,.2f} | SMA7: {sig['sma_short']} | SMA25: {sig['sma_long']}")

5Set Up Price Alerts

The MarketLens /alerts endpoint lets you create price alerts that fire when a coin crosses a target price. You can monitor alerts via polling or receive them instantly via webhooks.

python
def create_price_alert(symbol: str, target: float,
                          direction: str = "above",
                          webhook_url: str = None) -> dict:
    """Create a crypto price alert.

    Args:
        symbol: Coin symbol (e.g., 'BTC', 'ETH')
        target: Target price in USD
        direction: 'above' or 'below'
        webhook_url: URL to receive POST notification
    """
    payload = {
        "symbol": symbol,
        "target_price": target,
        "direction": direction,
        "asset_type": "crypto",
    }
    if webhook_url:
        payload["webhook_url"] = webhook_url

    resp = requests.post(
        f"{BASE_URL}/alerts",
        headers=HEADERS,
        json=payload,
    )
    resp.raise_for_status()
    return resp.json()

# Alert when BTC hits $100,000
create_price_alert("BTC", 100_000, "above", WEBHOOK_URL)
print("Alert set: BTC > $100,000")

# Alert when ETH drops below $3,000
create_price_alert("ETH", 3_000, "below", WEBHOOK_URL)
print("Alert set: ETH < $3,000")

# Alert when SOL hits $200
create_price_alert("SOL", 200, "above", WEBHOOK_URL)
print("Alert set: SOL > $200")

6Handle Webhook Notifications

When an alert triggers, MarketLens sends a POST request to your webhook URL. Here is a simple Flask server to receive and process alerts:

python
# webhook_server.py -- receives alert notifications
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route("/crypto-alerts", methods=["POST"])
def handle_alert():
    """Receive a crypto price alert from MarketLens."""
    data = request.json

    symbol = data["symbol"]
    price = data["current_price"]
    target = data["target_price"]
    direction = data["direction"]

    print(f"ALERT: {symbol} is now ${price:,.2f} ({direction} ${target:,.2f})")

    # You can add custom actions here:
    # - Send a Telegram/Discord message
    # - Log to a database
    # - Trigger a trade on an exchange

    return jsonify({"status": "received"}), 200

if __name__ == "__main__":
    app.run(port=5000)

The webhook payload includes symbol, current_price, target_price, direction, and triggered_at. You can forward these to Discord, Telegram, Slack, or any notification channel.

7Automate with a Scheduler

Crypto markets run 24/7, so your bot should too. Use the schedule library to run the watchlist scan and signal calculation at regular intervals.

python
def run_bot():
    """Main bot loop: scan watchlist + check signals."""
    print(f"\n{'='*50}")
    print(f"Bot scan at {datetime.now():%Y-%m-%d %H:%M:%S}")
    print(f"{'='*50}")

    # 1. Scan watchlist prices
    df = scan_watchlist(WATCHLIST)
    print(df.to_string(index=False))

    # 2. Check SMA signals
    print(f"\n--- Signals ---")
    for coin in WATCHLIST:
        try:
            sig = calculate_sma_signal(coin)
            if sig["signal"] != "HOLD":
                print(f"  [{sig['signal']}] {coin} at ${sig['price']:,.2f}")
        except Exception as e:
            print(f"  Error on {coin}: {e}")

# Schedule the bot to run every 5 minutes
schedule.every(5).minutes.do(run_bot)

# Run immediately, then on schedule
run_bot()

print("\nBot is running. Press Ctrl+C to stop.")
while True:
    schedule.run_pending()
    time.sleep(1)

API Usage Tip

Scanning 8 coins every 5 minutes uses ~2,304 calls/day (8 coins * 288 intervals). The free tier (1,000 calls/day) works for smaller watchlists or longer intervals. For 8+ coins at 5-minute intervals, the Pro tier (50,000 calls/day) is recommended. Use FOUNDER50 for 50% off -- just $24.50/mo.

Complete Bot Code

Here is the full working bot that ties everything together. Copy it, add your API key, and run it:

python
#!/usr/bin/env python3
"""Crypto Trading Bot -- MarketLens API
Get your API key: https://marketlens.dev/signup
Use FOUNDER50 for 50% off Pro: https://marketlens.dev/pricing
"""

import requests, pandas as pd, schedule, time
from datetime import datetime

API_KEY = "ml_your_api_key_here"
BASE    = "https://marketlens.dev/api/v1"
HEADERS = {"X-API-Key": API_KEY}
COINS   = ["BTC", "ETH", "SOL", "AVAX", "LINK"]

def price(sym):
    r = requests.get(f"{BASE}/crypto/{sym}", headers=HEADERS)
    r.raise_for_status()
    return r.json()["data"]

def history(sym, period="3m"):
    r = requests.get(f"{BASE}/crypto/{sym}/history",
                     headers=HEADERS, params={"period": period})
    r.raise_for_status()
    df = pd.DataFrame(r.json()["data"]["history"])
    df["date"] = pd.to_datetime(df["date"])
    return df.sort_values("date")

def signal(sym):
    df = history(sym)
    df["s7"]  = df["close"].rolling(7).mean()
    df["s25"] = df["close"].rolling(25).mean()
    cur, prev = df.iloc[-1], df.iloc[-2]
    if prev["s7"] <= prev["s25"] and cur["s7"] > cur["s25"]: return "BUY"
    if prev["s7"] >= prev["s25"] and cur["s7"] < cur["s25"]: return "SELL"
    return "HOLD"

def run():
    print(f"\n[{datetime.now():%H:%M}] Scanning...")
    for c in COINS:
        try:
            d = price(c)
            s = signal(c)
            tag = f"  ** {s} **" if s != "HOLD" else ""
            print(f"  {c:>5}  ${d['price']:>10,.2f}  {d['change_pct_24h']:>+6.2f}%{tag}")
        except Exception as e:
            print(f"  {c:>5}  error: {e}")

schedule.every(5).minutes.do(run)
run()
print("\nRunning every 5 min. Ctrl+C to stop.")
while True: schedule.run_pending(); time.sleep(1)

Next Steps

  • Add RSI signals: Combine SMA with the Relative Strength Index for more accurate signals
  • Connect to an exchange: Wire the BUY/SELL signals to Binance, Coinbase, or Kraken APIs for automated execution
  • Build a dashboard: Use Streamlit or Flask to create a web UI for your bot (see our dashboard tutorial)
  • Backtest strategies: Use MarketLens historical data to test your signals against past performance
  • Go Pro: Upgrade with FOUNDER50 for 50,000 calls/day and WebSocket streaming

Get Crypto Bot Tutorials in Your Inbox

Weekly trading bot tips, signal strategies, and API tutorials. Join 2,000+ developers building automated trading systems.

Ready to Build Your Crypto Bot?

Start free with 1,000 calls/day. Use FOUNDER50 for 50% off Pro -- 50,000 calls/day + WebSocket streaming.

Frequently Asked Questions

What is the best API for a crypto trading bot?

MarketLens is the best API for building a crypto trading bot in 2026. It supports 300+ coins, provides real-time prices and historical data, has a built-in alerts/webhooks system, and offers the most generous free tier at 1,000 calls/day.

Can I build a crypto trading bot for free?

Yes. The MarketLens free tier gives you 1,000 API calls per day with no credit card required. That is enough to monitor a 5-coin watchlist at 10-minute intervals with room to spare.

Does MarketLens support WebSocket for real-time crypto data?

Yes. The Pro tier includes WebSocket streaming for sub-second price updates on all 300+ supported cryptocurrencies. Use code FOUNDER50 for 50% off Pro at $24.50/mo.

Is this bot suitable for real trading?

This tutorial builds a monitoring and signal bot. To execute real trades, you would connect the signals to an exchange API like Binance or Coinbase. Always backtest your strategy with historical data before trading with real funds.

Related Tutorials

Get market data insights in your inbox

Weekly tutorials, API tips, and market data updates. No spam.