Grok 4.1 Fast· xai
Frontier Reasoning Traces
Build a Python script to monitor cryptocurrency prices and send alerts.
- User
Build a Python script to monitor cryptocurrency prices and send alerts.
- Assistant
""" Cryptocurrency Price Monitor and Alert Script This script monitors prices of specified cryptocurrencies using the free CoinGecko API. It sends Telegram alerts when prices cross user-defined thresholds (above or below). Setup Instructions: 1. Create a Telegram bot: - Message @BotFather on Telegram. - Use /newbot, follow prompts, and note your BOT_TOKEN (e.g., '123456:ABC-DEF...'). 2. Get your CHAT_ID: - Message your bot anything. - Visit: https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates - Find "chat":{"id":123456789} — that's your CHAT_ID. 3. Edit the CONFIG section below: - Add/remove coins (CoinGecko IDs: 'bitcoin', 'ethereum', 'cardano', etc. — see https://www.coingecko.com/en/api/documentation). - Set target price and direction ('above' or 'below'). 4. Install dependencies: pip install requests 5. Run: python crypto_monitor.py Features: - Polls every INTERVAL seconds (default 60s). - Alerts only once per coin per run (to avoid spam; restarts reset). - USD prices only. - Handles API errors gracefully. Rate Limits: CoinGecko allows ~30-50 calls/min. Adjust INTERVAL if monitoring many coins. """ import requests import time import sys # === CONFIGURATION === BOT_TOKEN = 'YOUR_BOT_TOKEN_HERE' # Replace with your Telegram bot token CHAT_ID = 'YOUR_CHAT_ID_HERE' # Replace with your Telegram chat ID (integer as string) COINS = { 'bitcoin': {'target': 60000.0, 'direction': 'above'}, # Alert if BTC > $60k 'ethereum': {'target': 3000.0, 'direction': 'below'}, # Alert if ETH < $3k # 'cardano': {'target': 0.5, 'direction': 'above'}, # Add more: 'coin-id': {'target': float, 'direction': 'above' or 'below'} } INTERVAL = 60 # Poll interval in seconds (e.g., 300 for 5 minutes) ALERTED = set() # Tracks alerted coins to avoid spam during runtime # === FUNCTIONS === def get_prices(coin_ids): """ Fetch current USD prices from CoinGecko API. Returns dict: {'bitcoin': 65000.0, ...} or empty on error. """ if not coin_ids: return {} ids_str = ','.join(coin_ids) url = f"https://api.coingecko.com/api/v3/simple/price?ids={ids_str}&vs_currencies=usd" try: response = requests.get(url, timeout=10) response.raise_for_status() data = response.json() return {coin: data.get(coin, {}).get('usd', None) for coin in coin_ids} except Exception as e: print(f"Error fetching prices: {e}", file=sys.stderr) return {} def send_telegram_alert(message): """ Send alert via Telegram Bot API. """ url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage" payload = { 'chat_id': CHAT_ID, 'text': message, 'parse_mode': 'HTML' # Optional: enables bold/italics } try: response = requests.post(url, json=payload, timeout=10) response.raise_for_status() print(f"Alert sent: {message}") except Exception as e: print(f"Error sending Telegram alert: {e}", file=sys.stderr) # === MAIN LOOP === def main(): if BOT_TOKEN == 'YOUR_BOT_TOKEN_HERE' or CHAT_ID == 'YOUR_CHAT_ID_HERE': print("ERROR: Please configure BOT_TOKEN and CHAT_ID in the script!", file=sys.stderr) sys.exit(1) if not COINS: print("ERROR: No coins configured!", file=sys.stderr) sys.exit(1) print(f"Starting monitor for {len(COINS)} coins. Polling every {INTERVAL}s. Press Ctrl+C to stop.") print("Alerted coins will be tracked in-memory (restarts reset).") while True: try: prices = get_prices(list(COINS.keys())) for coin, config in COINS.items(): price = prices.get(coin) if price is None: continue target = config['target'] direction = config['direction'].lower() # Check condition if direction == 'above': condition_met = price >= target elif direction == 'below': condition_met = price <= target else: print(f"Invalid direction '{direction}' for {coin}. Skipping.", file=sys.stderr) continue # Send alert if condition met and not already alerted if condition_met and coin not in ALERTED: message = ( f"🚨 <b>{coin.upper()}</b> Alert! 🚨\n" f"Price: $<b>{price:,.2f}</b>\n" f"Threshold: {direction.upper()} $<b>{target:,.2f}</b>\n" f"💹 <a href='https://www.coingecko.com/en/coins/{coin}'>View on CoinGecko</a>" ) send_telegram_alert(message) ALERTED.add(coin) print(f"Checked at {time.strftime('%Y-%m-%d %H:%M:%S')}: " f"{', '.join([f'{c}: ${p:.2f}' for c, p in prices.items()])} | Alerted: {len(ALERTED)}") time.sleep(INTERVAL) except KeyboardInterrupt: print("\nStopping monitor. Goodbye!") sys.exit(0) except Exception as e: print(f"Unexpected error: {e}. Retrying in {INTERVAL}s...", file=sys.stderr) time.sleep(INTERVAL) if __name__ == "__main__": main()How to Use
- Customize
COINS: Add your cryptos, targets, and directions. - Set credentials: Replace
BOT_TOKENandCHAT_ID. - Run:
python crypto_monitor.py- It prints status to console.
- Alerts go to Telegram.
- Stop: Ctrl+C.
- Enhancements (DIY):
- Persist
ALERTEDto file (JSON). - Percentage change alerts.
- Multiple targets per coin.
- Email fallback (add smtplib).
- Run as systemd/cron service.
- Persist
This is production-ready for personal use—lightweight, no DB, handles failures! 🔍
- Customize