DEV Community

Otto
Otto

Posted on

Build a Bitcoin Price Alert Bot in Python (Under 60 Lines, No API Key)

Everyone says "buy the dip" — but who's watching the price at 3am?

I got tired of manually checking CoinGecko every hour. So I built a simple Python price alert bot. No API key, no crypto exchange account, no libraries to install.

Under 60 lines. Works on Mac, Windows, Linux.

Here's exactly how I built it.

What It Does

  • Fetches live BTC price from CoinGecko's free public API
  • Compares to your target buy/sell price
  • Prints a color-coded alert in your terminal
  • Runs on a loop (check every N minutes)
  • Logs price history to a local JSON file

The Code

import urllib.request
import json
import time
import datetime
import os

# ─── CONFIG ────────────────────────────────
BUY_ALERT_BELOW = 60000    # Alert if price drops BELOW this
SELL_ALERT_ABOVE = 90000   # Alert if price rises ABOVE this
CHECK_INTERVAL = 300        # Check every 5 minutes (300 seconds)
COIN = "bitcoin"
CURRENCY = "usd"
LOG_FILE = "btc_price_log.json"
# ───────────────────────────────────────────

def fetch_price(coin=COIN, currency=CURRENCY):
    url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin}&vs_currencies={currency}"
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    with urllib.request.urlopen(req, timeout=10) as r:
        data = json.loads(r.read())
    return data[coin][currency]

def log_price(price):
    entry = {"timestamp": datetime.datetime.now().isoformat(), "price": price}
    history = []
    if os.path.exists(LOG_FILE):
        with open(LOG_FILE) as f:
            history = json.load(f)
    history.append(entry)
    with open(LOG_FILE, "w") as f:
        json.dump(history[-500:], f, indent=2)  # Keep last 500 entries

def check_alert(price):
    if price <= BUY_ALERT_BELOW:
        print(f"\033[92m🟢 BUY ALERT: BTC = ${price:,.0f} (below ${BUY_ALERT_BELOW:,})\033[0m")
    elif price >= SELL_ALERT_ABOVE:
        print(f"\033[91m🔴 SELL ALERT: BTC = ${price:,.0f} (above ${SELL_ALERT_ABOVE:,})\033[0m")
    else:
        print(f"\033[93m⏳ Watching: BTC = ${price:,.0f}\033[0m")

def main():
    print(f"🤖 Bitcoin Alert Bot started")
    print(f"   Buy alert: below ${BUY_ALERT_BELOW:,}")
    print(f"   Sell alert: above ${SELL_ALERT_ABOVE:,}")
    print(f"   Checking every {CHECK_INTERVAL // 60} min\n")

    while True:
        try:
            price = fetch_price()
            log_price(price)
            check_alert(price)
            time.sleep(CHECK_INTERVAL)
        except Exception as e:
            print(f"⚠️  Error: {e} — retrying in 60s")
            time.sleep(60)

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

How to Run It

# No pip install needed — pure Python stdlib
python btc_alert.py
Enter fullscreen mode Exit fullscreen mode

Set your target prices in the CONFIG section. That's it.

Extending It

Want alerts for multiple coins? Change the COIN variable to "ethereum", "solana", etc.

Want email alerts? Add smtplib (also built-in Python) to send yourself an email when the alert fires.

Want to track your portfolio P&L in the same script? That's what my full DCA Crypto Bot does — it tracks buy history, calculates real P&L, and projects your returns.

The Full DCA Bot

If you want to go further — track your actual buys, calculate DCA breakeven price, project returns at different scenarios — I packaged the full version as a ready-to-use Python script.

👉 DCA Crypto Bot Python — €14.99 on Gumroad — tracks portfolio, simulates scenarios, logs everything locally. Zero dependencies, open to modify.


Tip: Run this in a tmux session on a cheap VPS and it'll watch prices 24/7 without keeping your laptop open.

Happy trading — and remember: the bot doesn't decide when to buy. You do.

Top comments (0)