DEV Community

Paarthurnax
Paarthurnax

Posted on

Get Real-Time Crypto Alerts on Telegram with a Local AI Agent

Get Real-Time Crypto Alerts on Telegram with a Local AI Agent

Staring at a price chart all day isn't a strategy — it's anxiety. A much better approach: set up a local AI agent that watches the market for you and fires a Telegram message the moment something important happens.

This guide shows you how to build that in under an hour, using a Telegram bot and Python — no cloud services required.


What You'll Build

  • A Telegram bot that sends you crypto price alerts
  • A local Python agent that monitors prices every 60 seconds
  • Custom threshold alerts: "Tell me when BTC drops below $28k"
  • AI-powered summaries (optional, via Ollama)

Step 1: Create Your Telegram Bot

  1. Open Telegram and search for @botfather
  2. Send /newbot and follow the prompts
  3. Name it something like CryptoWatcher or DragonEye
  4. Copy the API token — it looks like 6283947123:AAFxxxxxxxxxxxxxxxx

Then get your personal chat ID:

  • Search for @userinfobot on Telegram
  • Start a conversation and it will tell you your chat ID

Step 2: Install Dependencies

pip install requests python-binance
Enter fullscreen mode Exit fullscreen mode

No special frameworks needed — just standard HTTP requests.


Step 3: Build the Alert Engine

import requests
import time
from datetime import datetime

# Config
TELEGRAM_TOKEN = "your_bot_token_here"
CHAT_ID = "your_chat_id_here"

def send_telegram(message: str):
    url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
    payload = {
        "chat_id": CHAT_ID,
        "text": message,
        "parse_mode": "Markdown"
    }
    r = requests.post(url, json=payload)
    return r.json()

def get_price(symbol="BTCUSDT"):
    url = f"https://api.binance.com/api/v3/ticker/price?symbol={symbol}"
    r = requests.get(url)
    return float(r.json()['price'])

# Alert thresholds
ALERTS = {
    "BTCUSDT": {"low": 28000, "high": 40000},
    "ETHUSDT": {"low": 1500, "high": 2500},
}

triggered = set()

def check_alerts():
    for symbol, thresholds in ALERTS.items():
        price = get_price(symbol)
        low_key = f"{symbol}_low"
        high_key = f"{symbol}_high"

        if price < thresholds["low"] and low_key not in triggered:
            send_telegram(f"🔴 *{symbol}* dropped below ${thresholds['low']:,}!\nCurrent: ${price:,.2f}")
            triggered.add(low_key)
        elif price > thresholds["high"] and high_key not in triggered:
            send_telegram(f"🟢 *{symbol}* broke above ${thresholds['high']:,}!\nCurrent: ${price:,.2f}")
            triggered.add(high_key)
        # Reset trigger if price moves back into range
        elif thresholds["low"] < price < thresholds["high"]:
            triggered.discard(low_key)
            triggered.discard(high_key)

print("Crypto alert agent running...")
send_telegram("🐉 DragonEye alert agent started. Watching BTC and ETH...")

while True:
    try:
        check_alerts()
    except Exception as e:
        print(f"Error: {e}")
    time.sleep(60)
Enter fullscreen mode Exit fullscreen mode

Step 4: Add a Daily Summary

Instead of just threshold alerts, you can add a daily market summary at a fixed time:

from datetime import datetime

def send_daily_summary():
    btc = get_price("BTCUSDT")
    eth = get_price("ETHUSDT")
    sol = get_price("SOLUSDT")

    now = datetime.now().strftime("%Y-%m-%d %H:%M")
    msg = f"""
📊 *Daily Crypto Summary* — {now}

• BTC: ${btc:,.2f}
• ETH: ${eth:,.2f}  
• SOL: ${sol:,.2f}

_Next check in 24h. Paper trading only._
"""
    send_telegram(msg)

# Call this at 9am daily using schedule or OpenClaw's felix_loop
Enter fullscreen mode Exit fullscreen mode

Step 5: Connect to OpenClaw for Scheduling

If you're already running OpenClaw, you can hook the Telegram sender into felix_loop.py:

# In felix_loop.py, add to the loop:
from crypto_alerts import check_alerts, send_daily_summary

def run_crypto_cycle():
    check_alerts()
    # Send summary once a day
    if datetime.now().hour == 9 and datetime.now().minute == 0:
        send_daily_summary()
Enter fullscreen mode Exit fullscreen mode

OpenClaw handles the scheduling, error recovery, and logging automatically.


Step 6: Add AI-Powered Analysis (Optional)

If you have Ollama running locally, you can add brief AI commentary to your alerts:

import requests as req

def ai_comment(price: float, symbol: str, direction: str) -> str:
    prompt = f"{symbol} just hit ${price:,.0f} and is moving {direction}. Give a 1-sentence market observation."
    resp = req.post("http://localhost:11434/api/generate", json={
        "model": "llama3.2",
        "prompt": prompt,
        "stream": False
    })
    return resp.json().get("response", "").strip()
Enter fullscreen mode Exit fullscreen mode

Append the AI comment to your Telegram message for context.


Keeping It Running

To run the agent 24/7 on Windows:

# Run in background
pythonw crypto_alerts.py

# Or use Task Scheduler to start it on login
Enter fullscreen mode Exit fullscreen mode

On Linux/Mac, use nohup python crypto_alerts.py & or a systemd service.


What's Next?

This agent is a foundation. From here you can:

  • Add more symbols (DOGE, ADA, etc.)
  • Track percentage moves, not just absolute prices
  • Send charts using the Binance chart API
  • Connect to a paper trading account to log triggered signals

The complete setup guide with OpenClaw crypto integration is at dragonwhisper36.gumroad.com.

Top comments (0)