Stock Price Drop Notifications by SMS or Telegram

As engineers, we appreciate systems that work for us, especially when they involve monitoring critical data. In the world of investing, staying informed about significant price movements in your portfolio is crucial. While most brokerage platforms offer some form of alerts, they often fall short in terms of customization, delivery channels, and real-time responsiveness. You might get an email an hour later, or a mobile notification that gets lost among dozens of others.

This article will guide you through setting up robust, custom stock price drop notifications delivered directly to your phone via SMS or Telegram. We'll leverage Surge's free public API for real-time price data and integrate with external messaging services to build a system that truly works for you.

The Problem with Manual Monitoring

Constantly checking stock prices manually is a drain on your time and mental energy. It's not scalable, and it's highly inefficient. Imagine trying to track a dozen different stocks and cryptocurrencies across various exchanges and market hours. You'd quickly find yourself glued to a screen, missing out on other productive tasks.

Brokerage-provided alerts, while a step up, often have their limitations:

  • Limited Channels: Many only offer email or in-app notifications, which aren't always immediate or attention-grabbing enough for urgent situations.
  • Lack of Granularity: You might be able to set a simple price threshold, but what about a percentage drop within a specific timeframe, or a drop relative to your average purchase price?
  • Delayed Delivery: Some alerts can be significantly delayed, especially during volatile market conditions, rendering them less useful for quick decision-making.
  • Vendor Lock-in: You're tied to their specific interface and alert mechanisms, which may not integrate well with your existing workflows.

For an engineer, this screams "automate it."

Leveraging Programmatic Alerts: The Foundation

The core idea is simple: periodically fetch current stock prices, compare them against your defined thresholds, and if a condition is met, trigger a notification. Surge provides a free public API that offers unified stock and crypto price feeds, making it an excellent data source for this kind of automation.

Here's a high-level overview of the process:

  1. Data Acquisition: Use Surge's API to fetch the latest price for a given stock or crypto asset.
  2. Logic Evaluation: Compare the fetched price against your predefined alert conditions (e.g., "if AAPL drops 2% from its previous close," or "if TSLA falls below $180").
  3. Notification Trigger: If the condition is met, send an alert using a chosen messaging service like Twilio (for SMS) or Telegram's Bot API.

Choosing Your Notification Channel

The choice between SMS and Telegram often comes down to urgency, cost, and personal preference.

SMS: The Ubiquitous Option

SMS is universal. Almost everyone with a mobile phone can receive an SMS, making it ideal for critical, high-urgency alerts that need to cut through notification noise.

Pros:

  • Ubiquity: No app required beyond the phone's native messaging client.
  • High Urgency: SMS alerts are often perceived as more urgent than other notifications.
  • Reliability: Highly reliable delivery, even in areas with limited internet connectivity.

Cons:

  • Cost: SMS is not free. You pay per message, which can add up if your alerts are frequent.
  • Character Limits: Messages are typically limited to 160 characters per segment, requiring concise communication.
  • Spam Filtering: Messages from programmatic senders can sometimes be flagged as spam by carriers, leading to delivery issues.

Example 1: Sending SMS with Twilio (Python)

Twilio is a popular choice for programmatic SMS. You'll need a Twilio account, an ACCOUNT_SID, AUTH_TOKEN, and a Twilio phone number.

import os
from twilio.rest import Client

def send_sms_alert(message_body, to_number):
    """
    Sends an SMS alert using Twilio.
    Ensure TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and TWILIO_FROM_NUMBER
    are set as environment variables.
    """
    account_sid = os.environ.get("TWILIO_ACCOUNT_SID")
    auth_token = os.environ.get("TWILIO_AUTH_TOKEN")
    from_number = os.environ.get("TWILIO_FROM_NUMBER") # Your Twilio phone number

    if not all([account_sid, auth_token, from_number]):
        print("Error: Twilio credentials not fully configured.")
        return False

    client = Client(account_sid, auth_token)

    try:
        message = client.messages.create(
            to=to_number,
            from_=from_number,
            body=message_body
        )
        print(f"SMS sent successfully! Message SID: {message.sid}")
        return True
    except Exception as e:
        print(f"Failed to send SMS: {e}")
        return False

# Example usage (replace with your actual recipient number)
# send_sms_alert("ALERT: AAPL just dropped 3%!", "+15551234567")

Remember to install the Twilio library (pip install twilio) and set your credentials as environment variables for security.

Telegram: The Free and Feature-Rich Alternative

Telegram offers a robust Bot API that allows you to send messages, photos, and even files to individual users or groups. It's free and highly flexible, making it an excellent choice for detailed alerts.

Pros:

  • Free: Sending messages via the Bot API is free.
  • Rich Messaging: No character limits, support for Markdown, inline buttons, and more.
  • Group Support: Send alerts to a group chat, useful for teams or shared portfolios.
  • No Spam Filtering Issues: Messages from your bot are delivered reliably within Telegram.

Cons:

  • Requires App: Both you and the recipient must have the Telegram app installed.
  • Initial Setup: Creating a bot and obtaining CHAT_IDs requires a few steps within Telegram.

Example 2: Sending Telegram Messages (Python)

You'll first need to create a new bot via BotFather on Telegram to get your BOT_TOKEN. Then, to get your CHAT_ID, you can message your new bot, then open https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates in your browser. Look for the chat object and extract the id.

```python import os import requests

def send_telegram_alert(message_body, chat_id): """ Sends a message via Telegram Bot API. Ensure TELEGRAM_BOT_TOKEN is set as an environment variable. """ bot_token = os.environ.get("TELEGRAM_BOT_TOKEN")

if not bot_token:
    print("Error: Telegram bot token not configured.")
    return False

api_url = f"https://api.telegram.