DEV Community

MFS CORP
MFS CORP

Posted on • Edited on

How I Built a Telegram Bot for Real-Time Crypto Alerts (And You Can Too)

How I Built a Telegram Bot for Real-Time Crypto Alerts (And You Can Too)

You know that sinking feeling when you check your portfolio and realize Bitcoin just pumped 15% while you were asleep? Or when you've been manually refreshing CoinGecko every ten minutes waiting for ETH to hit your target price?

Yeah, I got tired of that too.

I was missing critical price movements because I couldn't stare at charts 24/7. So I built a Telegram bot that watches the crypto markets for me and sends instant alerts when prices hit my targets. No more FOMO, no more missed opportunities.

In this tutorial, I'll show you exactly how I built it using Python, the CoinGecko API, and Telegram's bot framework. Best part? It took less than an afternoon and costs nothing to run.

The Problem: Manual Crypto Monitoring Doesn't Scale

Before building this bot, my crypto monitoring workflow was a mess:

  • Multiple browser tabs with different exchanges open
  • Setting phone alarms to check prices at odd hours
  • Missing significant price movements while in meetings or sleeping
  • Wasting mental energy on constant price checking

I needed a solution that would:

  • Monitor multiple cryptocurrencies simultaneously
  • Send real-time alerts when prices crossed my thresholds
  • Work 24/7 without manual intervention
  • Be lightweight and cost-effective to run

The Architecture: Simple but Effective

Here's how I designed the system:

  1. Telegram Bot - The user interface where I set alerts and receive notifications
  2. CoinGecko API - Free, reliable crypto price data
  3. Python Backend - The brain that coordinates everything
  4. Redis Cache - Stores alert configurations and prevents rate limiting

The flow is straightforward:

  • User sends commands to the Telegram bot (e.g., "Alert me when BTC hits $50,000")
  • Python backend stores this in Redis and starts monitoring
  • Every 60 seconds, the backend fetches current prices from CoinGecko
  • When a threshold is crossed, the bot sends a Telegram notification

Implementation: Let's Build It

Step 1: Setting Up the Telegram Bot

First, create a new bot by messaging @BotFather on Telegram. Save your bot token securely.

Install the required Python packages:

pip install python-telegram-bot requests redis
Enter fullscreen mode Exit fullscreen mode

Here's the basic bot setup:

from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
import os

# Initialize the bot
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "🚀 Crypto Alert Bot is ready!\n\n"
        "Commands:\n"
        "/alert <coin> <price> - Set a price alert\n"
        "/list - Show your active alerts\n"
        "/remove <id> - Remove an alert"
    )

def main():
    # Create application
    app = Application.builder().token(os.getenv("TELEGRAM_BOT_TOKEN")).build()

    # Add command handlers
    app.add_handler(CommandHandler("start", start))

    # Start the bot
    app.run_polling()

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

Step 2: Fetching Real-Time Prices from CoinGecko API

CoinGecko offers a free API with generous rate limits. Here's how to fetch crypto prices:

import requests
from typing import Dict, Optional

class CoinGeckoAPI:
    BASE_URL = "https://api.coingecko.com/api/v3"

    def get_price(self, coin_id: str) -> Optional[float]:
        """Fetch current price for a cryptocurrency"""
        try:
            response = requests.get(
                f"{self.BASE_URL}/simple/price",
                params={
                    "ids": coin_id,
                    "vs_currencies": "usd"
                },
                timeout=10
            )
            response.raise_for_status()
            data = response.json()
            return data.get(coin_id, {}).get("usd")
        except Exception as e:
            print(f"Error fetching price for {coin_id}: {e}")
            return None

    def get_multiple_prices(self, coin_ids: list) -> Dict[str, float]:
        """Fetch prices for multiple cryptocurrencies at once"""
        try:
            response = requests.get(
                f"{self.BASE_URL}/simple/price",
                params={
                    "ids": ",".join(coin_ids),
                    "vs_currencies": "usd"
                },
                timeout=10
            )
            response.raise_for_status()
            data = response.json()
            return {coin: data.get(coin, {}).get("usd", 0) for coin in coin_ids}
        except Exception as e:
            print(f"Error fetching prices: {e}")
            return {}
Enter fullscreen mode Exit fullscreen mode

Step 3: Alert Logic and Redis Storage

Now for the heart of the system - the alert logic. I used Redis to store alert configurations because it's fast and perfect for this use case:

import redis
import json
from dataclasses import dataclass
from typing import List

@dataclass
class PriceAlert:
    user_id: int
    coin_id: str
    target_price: float
    alert_type: str  # 'above' or 'below'
    alert_id: str

class AlertManager:
    def __init__(self, redis_client):
        self.redis = redis_client
        self.coingecko = CoinGeckoAPI()

    def add_alert(self, user_id: int, coin_id: str, target_price: float, alert_type: str):
        """Store a new price alert"""
        alert_id = f"{user_id}:{coin_id}:{target_price}"
        alert_data = {
            "user_id": user_id,
            "coin_id": coin_id,
            "target_price": target_price,
            "alert_type": alert_type
        }
        self.redis.set(f"alert:{alert_id}", json.dumps(alert_data))
        return alert_id

    def check_alerts(self) -> List[PriceAlert]:
        """Check all alerts and return triggered ones"""
        triggered = []

        # Get all alert keys
        alert_keys = self.redis.keys("alert:*")
        if not alert_keys:
            return triggered

        # Group alerts by coin to minimize API calls
        alerts_by_coin = {}
        for key in alert_keys:
            alert_data = json.loads(self.redis.get(key))
            coin_id = alert_data["coin_id"]
            if coin_id not in alerts_by_coin:
                alerts_by_coin[coin_id] = []
            alerts_by_coin[coin_id].append((key, alert_data))

        # Fetch prices for all coins at once
        prices = self.coingecko.get_multiple_prices(list(alerts_by_coin.keys()))

        # Check each alert
        for coin_id, alerts in alerts_by_coin.items():
            current_price = prices.get(coin_id)
            if not current_price:
                continue

            for key, alert_data in alerts:
                target = alert_data["target_price"]
                alert_type = alert_data["alert_type"]

                # Check if alert should trigger
                if (alert_type == "above" and current_price >= target) or \
                   (alert_type == "below" and current_price <= target):
                    triggered.append({
                        "key": key,
                        "data": alert_data,
                        "current_price": current_price
                    })

        return triggered
Enter fullscreen mode Exit fullscreen mode

Step 4: Bringing It All Together

Here's the monitoring loop that ties everything together:

import asyncio
from telegram import Bot

async def monitor_prices(bot: Bot, alert_manager: AlertManager):
    """Main monitoring loop"""
    while True:
        try:
            # Check for triggered alerts
            triggered_alerts = alert_manager.check_alerts()

            # Send notifications
            for alert in triggered_alerts:
                user_id = alert["data"]["user_id"]
                coin = alert["data"]["coin_id"].upper()
                current_price = alert["current_price"]
                target_price = alert["data"]["target_price"]

                message = (
                    f"🚨 PRICE ALERT!\n\n"
                    f"{coin} has reached ${current_price:,.2f}\n"
                    f"Target: ${target_price:,.2f}"
                )

                await bot.send_message(chat_id=user_id, text=message)

                # Remove the triggered alert
                alert_manager.redis.delete(alert["key"])

            # Wait 60 seconds before next check
            await asyncio.sleep(60)

        except Exception as e:
            print(f"Error in monitoring loop: {e}")
            await asyncio.sleep(60)
Enter fullscreen mode Exit fullscreen mode

Results: Never Miss a Price Movement Again

After deploying this bot, my crypto monitoring workflow completely transformed:

  • Set alerts in seconds - Just message the bot instead of setting manual reminders
  • Sleep peacefully - The bot watches markets 24/7
  • Catch opportunities - I've caught several profitable entries I would have missed
  • Reduced stress - No more compulsive chart checking

The bot handles everything: Bitcoin, Ethereum, altcoins - any cryptocurrency on CoinGecko. I typically run 5-10 alerts at a time, and it's been rock solid.

What's Next: Extending the Bot

This is just the foundation. Here are some features I'm planning to add:

  • Percentage-based alerts ("Alert me when BTC drops 10%")
  • Recurring alerts (alert every time price crosses a threshold)
  • Multiple currency support (EUR, GBP, not just USD)
  • Technical indicators (RSI, moving averages)
  • Portfolio tracking (monitor total portfolio value)

The beauty of building your own tool is that you can customize it exactly to your needs.

Try It Yourself

Building a Telegram bot for crypto alerts is easier than you might think. You don't need to be an expert - if you know some Python and can follow documentation, you can build this in an afternoon.

The complete architecture uses:

  • Python for the backend logic
  • python-telegram-bot for the Telegram integration
  • CoinGecko API for real-time price data
  • Redis for caching alert configurations

All free, all open-source, all running smoothly.

Want more tutorials like this? Follow me for weekly deep-dives into practical developer projects, or subscribe to my newsletter for exclusive tips and early access to new content.

What will you build with your crypto bot? Let me know in the comments! 🚀


📬 Want more like this?

Follow our journey building an AI-powered company from scratch. Weekly insights on AI agents, automation, and building in public.

👉 Subscribe to our newsletter — it's free.

Follow us on X: @Clawstredamus

Top comments (0)