Below is an expanded, detailed implementation for Telegram alerts along with security best practices and advanced alert strategies. This solution uses the popular python-telegram-bot library. You can integrate it within your trading framework to send alerts, summaries, errors, and even charts. The components include:
Detailed Implementation
Security Best Practices
Advanced Alert Strategies
1. Detailed Implementation
A. Setting Up the Environment
First, install the required packages:
bash
pip install python-telegram-bot python-dotenv
Create a .env file in your project root to securely store your credentials:
Below is a complete module that demonstrates how to build a robust Telegram alert system.
python
import os
import logging
from datetime import datetime
from dotenv import load_dotenv
from telegram import Bot, ParseMode, InputMediaPhoto
from telegram.error import TelegramError
# Load environment variables
load_dotenv()
TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
TELEGRAM_CHAT_ID = os.getenv('TELEGRAM_CHAT_ID')
# Configure logging for debugging and error tracking
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.INFO
)
logger = logging.getLogger(__name__)
class TelegramAlertSystem:
def __init__(self):
self.bot = Bot(token=TELEGRAM_BOT_TOKEN)
def send_message(self, message: str, parse_mode: str = ParseMode.MARKDOWN) -> None:
"""
Send a text message to Telegram.
"""
try:
self.bot.send_message(chat_id=TELEGRAM_CHAT_ID, text=message, parse_mode=parse_mode)
logger.info("Telegram alert sent successfully.")
except TelegramError as e:
logger.error(f"Telegram failed to send message: {e}")
def send_trade_alert(self, signal: dict) -> None:
"""
Send a detailed trade alert.
Expects signal to be a dictionary with the necessary keys.
"""
message = (
f"🚨 *WEALTH WARRIOR TRADE ALERT* 🚨\n\n"
f"📊 *Asset:* {signal.get('asset', 'N/A')}\n"
f"📈 *Direction:* {signal.get('direction', 'N/A')}\n"
f"💰 *Entry Price:* {signal.get('entry_price', 'N/A')}\n"
f"⏱️ *Timeframe:* {signal.get('timeframe', 'N/A')}\n\n"
f"*Indicators Triggered:*\n"
f"- EMA Trend: {'Bullish' if signal.get('ema_trend', False) else 'Bearish'}\n"
f"- RSI: {signal.get('rsi_value', 'N/A')}\n"
f"- MACD: {signal.get('macd_status', 'N/A')}\n\n"
f"*Risk Management:*\n"
f"- Position Size: {signal.get('position_size', 'N/A')}%\n"
f"- Stop Loss: {signal.get('stop_loss', 'N/A')}\n"
f"- Take Profit: {signal.get('take_profit', 'N/A')}\n"
f"_Reported on {datetime.utcnow().strftime('%Y-%m-%d %H:%M UTC')}_"
)
self.send_message(message)
def send_system_alert(self, alert_type: str, message: str) -> None:
"""
Send system alerts (errors, warnings, info) to Telegram.
"""
emoji_map = {
'error': '🚨',
'warning': '⚠️',
'info': 'ℹ️'
}
full_message = f"{emoji_map.get(alert_type, 'ℹ️')} {message} " \
f"_on {datetime.utcnow().strftime('%Y-%m-%d %H:%M UTC')}_"
self.send_message(full_message)
def send_trade_screenshot(self, image_path: str, caption: str = "Trade Analysis Chart") -> None:
"""
Send an image/screenshot of the trade chart.
"""
try:
with open(image_path, 'rb') as image:
self.bot.send_photo(chat_id=TELEGRAM_CHAT_ID, photo=image, caption=caption)
logger.info("Trade screenshot sent successfully.")
except TelegramError as e:
logger.error(f"Failed to send trade screenshot: {e}")
except FileNotFoundError:
logger.error("Image file not found.")
# Example of usage in your trading framework:
def example_trade_execution():
# Simulate a trade signal dictionary
trade_signal = {
'asset': 'BTCUSD',
'direction': 'Buy',
'entry_price': 45000,
'timeframe': '5min',
'ema_trend': True,
'rsi_value': 28,
'macd_status': 'Bullish Crossover',
'position_size': 2,
'stop_loss': 44500,
'take_profit': 45500,
}
telegram_alerts = TelegramAlertSystem()
telegram_alerts.send_trade_alert(trade_signal)
if __name__ == "__main__":
example_trade_execution()
C. Centralized Error Handling with Telegram Alerts
You can further encapsulate error handling to catch critical failures across your system. Consider a global error handler that sends system alerts:
python
def global_error_handler(error: Exception) -> None:
"""
Global error handler to log and report errors via Telegram.
"""
telegram_alerts = TelegramAlertSystem()
error_message = (
f"Critical Error Occurred:\n"
f"Type: {type(error).__name__}\n"
f"Message: {str(error)}\n"
f"Time: {datetime.utcnow().strftime('%Y-%m-%d %H:%M UTC')}"
)
telegram_alerts.send_system_alert('error', error_message)
logger.exception("Global error handler caught an exception.")
# Example using try-except with global_error_handler:
def some_trading_logic():
try:
# Your trading execution code
raise ValueError("Simulated trading failure")
except Exception as err:
global_error_handler(err)
if __name__ == "__main__":
some_trading_logic()
2. Security Best Practices
When deploying your Telegram alerts, consider the following security measures:
Secure Credential Management:
Use environment variables (via .env or secret management services) rather than hardcoding your bot token or chat IDs in your code.
Access Controls:
Ensure the API key (bot token) is kept secret. Avoid exposing your repository publicly if it contains sensitive configuration.
HTTPS for Webhooks:
If you decide to use webhooks for Telegram updates instead of polling, host your endpoint on a server with a valid SSL certificate (HTTPS).
Rate Limiting & Error Handling:
Handle rate limits gracefully by catching exceptions from Telegram and retrying after a delay if necessary.
Logging and Monitoring:
Integrate proper logging (as shown above) and monitor your logs to detect unusual activity or errors.
Minimal Permissions:
Only grant the minimum necessary permissions for your Telegram bot. For example, if you're only sending messages, you don't need to enable features like inline keyboards unless required.
Regular Token Rotation:
If there is any suspicion of token compromise, rotate the bot token immediately via BotFather.
3. Advanced Alert Strategies
Beyond basic trade alerts, here are some advanced capabilities you can build into your system:
A. Periodic Performance Summaries
Implement alerts that send a daily/weekly performance summary. This may include statistics like:
Deploy logic to monitor market conditions (like sudden volatility spikes) and send warnings even when no trades are executed. This can help in:
Avoiding high-risk periods
Triggering manual review or disabling auto-trading momentarily
python
def send_market_condition_alert(volatility: float) -> None:
"""
Send an alert if market volatility exceeds a threshold.
"""
threshold = 2.5 # Example threshold
if volatility > threshold:
message = f"⚠️ Market Alert: High volatility detected ({volatility}). Please review positions."
telegram_alert = TelegramAlertSystem()
telegram_alert.send_message(message)
C. Visualization Alerts
Sometimes a picture is worth a thousand words. Integrate a feature to capture and send chart screenshots with trade annotations. For example, generate a chart with Plotly or Matplotlib, save it as an image, and send via Telegram:
Consider adding interactive elements using inline keyboards (especially if you use a webhook setup). These can allow you to acknowledge receipt, ask for more details, or even execute certain commands manually.
For integrating interactive alerts, you would need to set up a webhook listener that can process callback queries.
Final Notes
Testing:
Always test each alert type in a sandbox or demo environment before integrating with live trading.
Extensibility:
Structure your alert system as a dedicated module so you can easily extend, modify, or replace parts without affecting the overall trading logic.
Documentation:
Document each function, expected inputs/outputs, and error handling protocols. This not only helps during debugging but also when onboarding team members.
By following this detailed implementation guide, adhering to security best practices, and exploring advanced alert strategies, you can build a robust Telegram integration that complements your Pocket Option trading strategy. If you’d like to explore further enhancements (like asynchronous alerting, multi-channel alerts, or integration testing), feel free to ask!