1697 words
8 minutes
Creating a Real-Time Crypto Price Alert System with Python and Telegram Bots

Creating a real-time crypto price alert system with Python and Telegram bots provides a practical method for monitoring market fluctuations and receiving timely notifications. This approach leverages readily available tools and public APIs to build a custom, automated monitoring service.

A crypto price alert system automatically tracks the current price of selected cryptocurrencies. When the price reaches a predefined condition (e.g., goes above a certain level or below another), it triggers a notification. Real-time implies these checks and notifications happen with minimal delay, though the actual frequency depends on implementation and data source limitations.

Python serves as the programming language for fetching data, implementing the logic for checking price conditions, and interacting with APIs. Telegram bots, powered by the Telegram Bot API, act as the notification channel, sending messages directly to a user’s Telegram account or a specific chat. This combination offers flexibility, automation, and convenient access to alerts.

Essential Concepts for Building a Crypto Price Alert System#

Developing such a system requires understanding several core components and technologies:

  • Cryptocurrency Price APIs: These are web services that provide current and historical price data for various cryptocurrencies. Systems typically interact with these APIs using HTTP requests to fetch the latest price information. Popular free options include CoinGecko and CoinMarketCap (with varying levels of data access and rate limits on free tiers). Paid APIs offer higher request limits, more data points, and often lower latency.
  • Telegram Bot API: This interface allows external applications to interact with the Telegram messaging service as bots. Bots can send messages, receive commands, and participate in chats. To create a bot, one registers with Telegram’s BotFather and obtains a unique API token. Sending messages to a specific user or group requires identifying the target chat’s ID.
  • Python Programming: The core logic is written in Python. This involves:
    • Making HTTP requests to cryptocurrency price APIs.
    • Parsing the received data (often in JSON format).
    • Implementing conditional logic to check if the current price meets the alert criteria.
    • Making HTTP requests to the Telegram Bot API to send messages.
    • Structuring the code to run periodically for continuous monitoring.
  • Libraries: Specific Python libraries simplify interaction with APIs:
    • requests: Used for making HTTP requests to fetch data from price APIs and send messages via the Telegram Bot API.
    • json: For parsing data received from APIs, which is typically in JSON format.
    • time (or scheduling libraries): Used to pause the script execution between price checks, ensuring the system doesn’t overwhelm APIs with requests and runs continuously at a set interval.

Step-by-Step Guide to Creating the System#

Building the alert system involves configuring the notification channel, selecting a data source, and writing the core monitoring logic in Python.

1. Setting Up a Telegram Bot and Obtaining Chat ID#

The Telegram bot serves as the delivery mechanism for alerts.

  • Create a Bot: Open the Telegram app and search for “@BotFather”. Start a chat and use the command /newbot. Follow the instructions to name the bot and assign it a username. Upon successful creation, BotFather provides an API Token. This token is crucial for sending messages via the Bot API. Store this token securely.
  • Get Chat ID: To send a message to a specific user or group, the bot needs the target Chat ID.
    • For personal alerts, start a chat with the newly created bot.
    • To find the chat ID, one can use the Telegram Bot API’s getUpdates method or forward a message from the target chat to a bot specifically designed to echo chat IDs (like @JsonDumpBot). A simpler method for personal alerts is to send any message to your bot after starting the chat. Then, open a web browser and navigate to the following URL, replacing YOUR_BOT_TOKEN with the token received from BotFather: https://api.telegram.org/botYOUR_BOT_TOKEN/getUpdates
    • Look for the chat object in the JSON response. The id field within that object is the required Chat ID. It will be a negative number for group chats and a positive number for private chats with the bot.

2. Choosing a Cryptocurrency Price API#

Select an API that provides reliable price data and has a free tier suitable for the desired monitoring frequency.

  • CoinGecko API: Offers a free API with endpoints for current prices. The free tier has rate limits (e.g., 100 requests per minute), which is generally sufficient for personal alert systems checking prices every few minutes. Accessing data does not typically require an API key for basic endpoints.
  • CoinMarketCap API: Requires a free API key for access, even for basic endpoints. The free tier has stricter limits (e.g., 30 calls/minute, 10,000 calls/month).

For simplicity and ease of access without an API key, the CoinGecko API is often preferred for initial development.

3. Writing the Python Script#

The Python script will fetch data, check the condition, and send alerts.

  • Install Libraries: Ensure requests is installed:
    Terminal window
    pip install requests
  • Structure the Code:
import requests
import time
import json # Although requests handles JSON, explicitly importing might be useful for debugging
# --- Configuration ---
TELEGRAM_BOT_TOKEN = "YOUR_TELEGRAM_BOT_TOKEN" # Replace with your token
TELEGRAM_CHAT_ID = "YOUR_TELEGRAM_CHAT_ID" # Replace with your chat ID
CRYPTO_ID = "bitcoin" # Example: "bitcoin", "ethereum", "cardano"
ALERT_PRICE_USD = 40000 # Set the price threshold for the alert
CHECK_INTERVAL_SECONDS = 300 # Check every 5 minutes (300 seconds)
# --- API Endpoints ---
COINGECKO_PRICE_API_URL = f"https://api.coingecko.com/api/v3/simple/price?ids={CRYPTO_ID}&vs_currencies=usd"
TELEGRAM_SEND_MESSAGE_URL = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
# --- Functions ---
def get_crypto_price(crypto_id, vs_currency="usd"):
"""Fetches the current price of a cryptocurrency from CoinGecko."""
url = f"https://api.coingcko.com/api/v3/simple/price?ids={crypto_id}&vs_currencies={vs_currency}"
try:
response = requests.get(url)
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
data = response.json()
# Navigating the JSON structure: data -> crypto_id -> vs_currency
price = data.get(crypto_id, {}).get(vs_currency)
if price is None:
print(f"Warning: Price data for {crypto_id} in {vs_currency} not found in response.")
return price
except requests.exceptions.RequestException as e:
print(f"Error fetching price for {crypto_id}: {e}")
return None
except json.JSONDecodeError:
print(f"Error decoding JSON response from CoinGecko.")
return None
except Exception as e:
print(f"An unexpected error occurred during price fetch: {e}")
return None
def send_telegram_message(chat_id, text):
"""Sends a message to the specified Telegram chat."""
payload = {
'chat_id': chat_id,
'text': text,
'parse_mode': 'Markdown' # Use Markdown for formatting
}
try:
response = requests.post(TELEGRAM_SEND_MESSAGE_URL, json=payload)
response.raise_for_status() # Raise an exception for bad status codes
print(f"Message sent to chat ID {chat_id}")
except requests.exceptions.RequestException as e:
print(f"Error sending Telegram message: {e}")
except Exception as e:
print(f"An unexpected error occurred during message sending: {e}")
# --- Main Logic ---
if __name__ == "__main__":
print(f"Starting price monitoring for {CRYPTO_ID}...")
print(f"Alert threshold set at ${ALERT_PRICE_USD}")
# State variable to prevent spamming alerts for the same condition
alert_triggered_above = False
alert_triggered_below = False # Can add logic for below threshold alerts too
while True:
current_price = get_crypto_price(CRYPTO_ID, "usd")
if current_price is not None:
print(f"Current price of {CRYPTO_ID}: ${current_price}")
# --- Check for Alert Condition (e.g., price goes ABOVE threshold) ---
if current_price > ALERT_PRICE_USD and not alert_triggered_above:
message = f"🚨 *Price Alert!* 🚨\n\n" \
f"The price of *{CRYPTO_ID.capitalize()}* ({CRYPTO_ID.upper()}) has exceeded your threshold!\n\n" \
f"Current Price: *${current_price:.2f}*\n" \
f"Threshold: *${ALERT_PRICE_USD:.2f}*\n\n" \
f"Check the market!"
send_telegram_message(TELEGRAM_CHAT_ID, message)
alert_triggered_above = True # Set flag to true after triggering
# --- Optional: Check for price dropping BELOW threshold ---
elif current_price < ALERT_PRICE_USD and not alert_triggered_below:
# Example for below threshold, modify condition and message as needed
# This simple example just checks ABOVE, so this part is illustrative
pass # Implement logic here if needed for below alerts
# message = f"... below threshold message ..."
# send_telegram_message(TELEGRAM_CHAT_ID, message)
# alert_triggered_below = True
# --- Optional: Reset alert trigger flag if price goes back below/above threshold ---
# This allows the alert to trigger again if the price fluctuates
if current_price <= ALERT_PRICE_USD and alert_triggered_above:
alert_triggered_above = False
print("Price dropped below threshold, resetting above-threshold alert flag.")
# Add similar logic here for resetting 'alert_triggered_below' if implemented
print(f"Waiting for {CHECK_INTERVAL_SECONDS} seconds before next check...")
time.sleep(CHECK_INTERVAL_SECONDS)

4. Running the Script#

Save the code as a Python file (e.g., crypto_alert.py). Replace the placeholder values for TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID with the actual token and chat ID obtained in Step 1. Adjust CRYPTO_ID, ALERT_PRICE_USD, and CHECK_INTERVAL_SECONDS according to requirements.

Execute the script from the terminal:

Terminal window
python crypto_alert.py

The script will start fetching prices periodically. When the price of the specified cryptocurrency crosses the ALERT_PRICE_USD threshold, it will send a message to the configured Telegram chat. The alert_triggered_above flag prevents the system from sending repeated alerts every interval once the price stays above the threshold; it will only send another alert after the price drops back below the threshold and then rises above it again.

Real-World Application Example#

Consider an individual monitoring the price of Bitcoin (BTCBTC). They wish to be notified immediately if the price rises above $40,000 USD, as this might indicate a significant market movement prompting a review of their holdings or trading strategy.

Using the Python script provided:

  • CRYPTO_ID is set to "bitcoin".
  • ALERT_PRICE_USD is set to 40000.
  • CHECK_INTERVAL_SECONDS is set to 300 (5 minutes).
  • The individual sets up a Telegram bot and obtains their personal chat ID.
  • They replace the placeholders in the script with their actual token and chat ID.

When the script runs, it fetches the Bitcoin price every 5 minutes. If the price is 39,500,noalertissent.Ifthepricethenrisesto39,500, no alert is sent. If the price then rises to 40,100 in a subsequent check, the condition current_price > ALERT_PRICE_USD becomes true, and a Telegram message is sent:

🚨 *Price Alert!* 🚨
The price of *Bitcoin* (BTC) has exceeded your threshold!
Current Price: *$40100.50*
Threshold: *$40000.00*
Check the market!

The alert_triggered_above flag is set to True. If the price remains above 40,000inthenextfewchecks(e.g.,40,000 in the next few checks (e.g., 40,200, 40,050),nofurtheralertsaresentuntilthepricedropsbackbelow40,050), no further alerts are sent until the price drops back below 40,000, resetting the flag. This prevents excessive notifications for the same event.

Key Takeaways#

  • Building a real-time crypto price alert system with Python and Telegram bots is achievable with basic programming knowledge and free APIs.
  • Essential components include a cryptocurrency price API (like CoinGecko), the Telegram Bot API, and a Python script to connect them.
  • Setting up the Telegram bot via BotFather and obtaining the correct Chat ID are prerequisites for sending alerts.
  • The Python requests library is fundamental for interacting with both the price API and the Telegram Bot API.
  • Periodic execution of the price check logic is necessary for monitoring; time.sleep() provides a simple method for this.
  • Implementing flags (like alert_triggered_above) helps manage alert frequency and prevent spamming notifications for persistent conditions.
  • Understanding API rate limits is important, especially when choosing the check interval, to avoid service interruptions. Free APIs typically have limitations that affect how frequently prices can be fetched.
Creating a Real-Time Crypto Price Alert System with Python and Telegram Bots
https://dev-resources.site/posts/creating-a-realtime-crypto-price-alert-system-with-python-and-telegram-bots/
Author
Dev-Resources
Published at
2025-06-30
License
CC BY-NC-SA 4.0