Skip to main content

Overview

The Alert System provides configurable price and indicator alerts with condition-based triggering and notification capabilities.

AlertSystem Class

Constructor

AlertSystem()
Initializes a new AlertSystem instance with empty alert and history lists. Attributes:
  • alerts (List[Dict]): List of active alert configurations
  • history (List[Dict]): Historical record of triggered alerts
Example:
from utils.alerts import AlertSystem

alert_system = AlertSystem()

Methods

add_alert

add_alert(alert_config: Dict) -> None
Adds a new alert to the system with automatic ID assignment and timestamp. Parameters:
  • alert_config (Dict): Alert configuration dictionary with the following keys:
    • type (str): Alert type (e.g., “Precio”, “RSI”, “MACD”)
    • crypto (str): Cryptocurrency symbol (e.g., “BTC”, “ETH”)
    • condition (str): Condition operator (“Mayor que” or “Menor que”)
    • threshold (float): Threshold value to trigger the alert
    • methods (List[str], optional): Notification methods (e.g., [“App”, “Telegram”])
Returns: None Auto-added fields:
  • id (int): Unique alert identifier
  • active (bool): Alert status (default: True)
  • created (datetime): Creation timestamp
Example:
from utils.alerts import AlertSystem

alert_system = AlertSystem()

# Create a price alert
alert_config = {
    'type': 'Precio',
    'crypto': 'BTC',
    'condition': 'Mayor que',
    'threshold': 50000,
    'methods': ['App', 'Telegram']
}

alert_system.add_alert(alert_config)
print(f"Alert added with ID: {alert_config['id']}")

check_alerts

check_alerts(current_data: Dict) -> List[Dict]
Evaluates all active alerts against current market data and triggers notifications when conditions are met. Parameters:
  • current_data (Dict): Current market data with keys matching alert types (lowercase)
    • Example: {'precio': 51000, 'rsi': 72, 'macd': 'bullish'}
Returns: List[Dict]: List of triggered alerts Example:
from utils.alerts import AlertSystem

alert_system = AlertSystem()

# Add alerts
alert_system.add_alert({
    'type': 'Precio',
    'crypto': 'BTC',
    'condition': 'Mayor que',
    'threshold': 50000,
    'methods': ['App']
})

alert_system.add_alert({
    'type': 'RSI',
    'crypto': 'ETH',
    'condition': 'Mayor que',
    'threshold': 70,
    'methods': ['App']
})

# Check alerts with current data
current_data = {
    'precio': 51500,  # BTC price
    'rsi': 75         # ETH RSI
}

triggered = alert_system.check_alerts(current_data)

print(f"{len(triggered)} alerts triggered")
for alert in triggered:
    print(f"Alert: {alert['crypto']} - {alert['type']}")
Output:
2 alerts triggered
Alert: BTC - Precio
Alert: ETH - RSI

Private Methods

_evaluate_condition

_evaluate_condition(alert: Dict, data: Dict) -> bool
Internal method that evaluates whether an alert condition is met. Parameters:
  • alert (Dict): Alert configuration
  • data (Dict): Current market data
Returns: bool: True if condition is met, False otherwise Supported Conditions:
  • "Mayor que": Triggers when value > threshold
  • "Menor que": Triggers when value < threshold

_send_notification

_send_notification(alert: Dict, data: Dict) -> None
Internal method that sends notifications when an alert is triggered. Parameters:
  • alert (Dict): Triggered alert configuration
  • data (Dict): Current market data
Returns: None Notification Methods:
  • "App": Displays Streamlit toast notification

Global Instance

alert_system = AlertSystem()
A pre-initialized global instance is available for immediate use. Example:
from utils.alerts import alert_system

# Use the global instance
alert_system.add_alert({
    'type': 'Precio',
    'crypto': 'BTC',
    'condition': 'Menor que',
    'threshold': 45000,
    'methods': ['App']
})

Complete Usage Example

import streamlit as st
from utils.alerts import AlertSystem
from datetime import datetime

# Initialize alert system
alert_system = AlertSystem()

# Configure multiple alerts
alerts_config = [
    {
        'type': 'Precio',
        'crypto': 'BTC',
        'condition': 'Mayor que',
        'threshold': 50000,
        'methods': ['App', 'Telegram']
    },
    {
        'type': 'RSI',
        'crypto': 'BTC',
        'condition': 'Mayor que',
        'threshold': 70,
        'methods': ['App']
    },
    {
        'type': 'Precio',
        'crypto': 'ETH',
        'condition': 'Menor que',
        'threshold': 3000,
        'methods': ['App']
    }
]

# Add all alerts
for config in alerts_config:
    alert_system.add_alert(config)

print(f"Total alerts configured: {len(alert_system.alerts)}")

# Simulate real-time monitoring
market_data = {
    'precio': 52000,  # BTC price
    'rsi': 75,        # BTC RSI
    'volume': 1000000
}

# Check alerts
triggered_alerts = alert_system.check_alerts(market_data)

if triggered_alerts:
    print(f"\n⚠️ {len(triggered_alerts)} alert(s) triggered!")
    for alert in triggered_alerts:
        print(f"\n🔔 Alert #{alert['id']}")
        print(f"   Crypto: {alert['crypto']}")
        print(f"   Type: {alert['type']}")
        print(f"   Condition: {alert['condition']} {alert['threshold']}")
        print(f"   Created: {alert['created'].strftime('%Y-%m-%d %H:%M:%S')}")
else:
    print("\n✅ No alerts triggered")

# Manage alerts
print(f"\n📋 Active alerts: {sum(1 for a in alert_system.alerts if a['active'])}")
print(f"📋 Total alerts: {len(alert_system.alerts)}")

Alert Configuration Examples

Price Alert

{
    'type': 'Precio',
    'crypto': 'BTC',
    'condition': 'Mayor que',
    'threshold': 60000,
    'methods': ['App', 'Telegram']
}

RSI Overbought Alert

{
    'type': 'RSI',
    'crypto': 'ETH',
    'condition': 'Mayor que',
    'threshold': 70,
    'methods': ['App']
}

RSI Oversold Alert

{
    'type': 'RSI',
    'crypto': 'BTC',
    'condition': 'Menor que',
    'threshold': 30,
    'methods': ['App', 'Telegram']
}

Volume Alert

{
    'type': 'Volume',
    'crypto': 'BTC',
    'condition': 'Mayor que',
    'threshold': 1000000000,
    'methods': ['App']
}

Best Practices

  1. Set Realistic Thresholds: Use historical data to determine meaningful alert levels
  2. Avoid Alert Fatigue: Don’t set too many alerts that trigger frequently
  3. Use Multiple Conditions: Combine price and indicator alerts for better signals
  4. Monitor Active Alerts: Regularly review and update alert configurations
  5. Test Notifications: Verify notification methods work before relying on them

See Also

Build docs developers (and LLMs) love