Creating a Simple Telegram Bot for Real-Time Stock Alerts
Monitor stock prices and get instant notifications with an easy Python script
Creating a custom app for real-time notifications can be complex, time-consuming, and costly. Thankfully, Telegram offers a much simpler solution. With its robust API, accessible through a Python library, you can easily implement a reliable notification system without the need for extensive app development. Whether it's sending alerts, monitoring system performance, or reminding users of important events, Telegram provides a cost-effective and efficient alternative.
In this post, we’ll explore how Telegram’s built-in features and flexible API, utilized via a Python library, make it a superior choice over building a custom notification app. We’ll also use the wallstreet library for real-time stock data, which is ideal for tracking price fluctuations.
For today’s example, we’ll create a Telegram bot that checks stock prices every 5 seconds. If a stock drops by more than 5%, the bot will automatically send a notification using Python’s Telegram library. This simple setup demonstrates how quickly you can create real-time alerts without the hassle of developing a full app.
import time
from wallstreet import Stock
from telegram import Bot
# Telegram bot token and chat ID
TELEGRAM_TOKEN = 'your_telegram_token'
CHAT_ID = 'your_chat_id'
# Initialize Telegram bot
bot = Bot(token=TELEGRAM_TOKEN)
# Stock symbol and threshold for the price drop
STOCK_SYMBOL = 'AAPL' # Example: Apple stock
THRESHOLD_DROP = 5.0 # 5% drop
# Function to get current stock price
def get_stock_price(symbol):
stock = Stock(symbol)
return stock.price
# Function to send notification to Telegram
def send_notification(message):
bot.send_message(chat_id=CHAT_ID, text=message)
# Monitoring function
def monitor_stock():
initial_price = get_stock_price(STOCK_SYMBOL)
while True:
time.sleep(5) # Wait 5 seconds before checking again
current_price = get_stock_price(STOCK_SYMBOL)
percentage_drop = ((initial_price - current_price) / initial_price) * 100
if percentage_drop >= THRESHOLD_DROP:
message = f"{STOCK_SYMBOL} has dropped by more than {THRESHOLD_DROP}%! Current price: ${current_price:.2f}"
send_notification(message)
if __name__ == "__main__":
monitor_stock()
This is a very simple example, but it can be applied to many real-world scenarios. Whether you're monitoring stock prices or any other information, this kind of Telegram bot can be adapted for various use cases. With just a few lines of code, you're able to receive instant notifications on your phone, saving you time and effort compared to constantly checking prices manually.
In future posts, we’ll dive deeper into how you can run this bot on a server to keep it running continuously and handle more complex tasks, ensuring you never miss an important update. So don't forget to subscribe if you haven't already!