Telegram & WhatsApp Bots
Relevant source files
The following files were used as context for generating this wiki page:
The Telegram and WhatsApp bot integrations in OpenAlgo provide real-time notifications, automated trade alerts, and command-based interaction with the trading platform. These services allow users to monitor their Unified Broker API activity, check account balances, and manage positions directly from their mobile messaging applications.
The bot architecture is built on a service-oriented model where specialized bot services (TelegramBotService, WhatsAppBotService) handle the underlying protocol communication, while alert services (TelegramAlertService, WhatsAppAlertService) manage the formatting and asynchronous dispatch of trading events. Sources: README.md:154-162, services/whatsapp_alert_service.py:12-23
Architecture and Threading Model
Both bot services operate under a dedicated worker thread model to handle long-lived connections and protocol-specific constraints. This is particularly critical in production environments using Eventlet or Gunicorn, where standard asyncio loop management may conflict with green threads.
Thread Confinement
The WhatsAppBotService uses the wars library, which requires the wars.WhatsApp instance to be touched only by the thread that created it. Consequently, all interactions are funneled through a command queue (_cmd_queue) to a dedicated worker thread. Sources: services/whatsapp_bot_service.py:133-145
The diagram shows the command funneling and event marshaling mechanism used to maintain thread safety. Sources: services/whatsapp_bot_service.py:145-163
Alert Dispatch
Trading alerts are dispatched asynchronously using a ThreadPoolExecutor (typically named alert_executor) with a bounded number of workers (e.g., 5). This ensures that order execution is never blocked by notification delivery delays. Sources: services/whatsapp_alert_service.py:27-31, restx_api/telegram_bot.py:28
WhatsApp Bot Integration
The WhatsApp service is built around the wars library (a PyO3 binding). It follows a single-user model where a paired device serves as the operator for the OpenAlgo instance. Sources: services/whatsapp_bot_service.py:15-28
Pairing Process
Pairing is initiated via the React frontend and involves streaming a QR code or pair code via SocketIO.
- Start Pairing: A temporary SQLite database is created to handle the initial handshake. Sources: services/whatsapp_bot_service.py:211-224
- QR Streaming: The bot generates QR data URLs which are emitted via SocketIO to the frontend. Sources: services/whatsapp_bot_service.py:245-256
- Finalization: Once paired, the session is exported as an encrypted blob to the main
openalgo.dband the temporary database is unlinked. Sources: services/whatsapp_bot_service.py:326-360
WhatsApp Command Interface
Users can drive the bot using "slash commands" from their paired device.
| Command | Description |
|---|---|
/orderbook | Retrieves today's orders using the OpenAlgo SDK. |
/positions | Displays currently open positions and total P&L. |
/funds | Shows available cash, collateral, and utilized margin. |
/closeall | Triggers a square-off for all open positions. |
/quote <SYM> | Fetches the last traded price for a specific symbol. |
Sources: services/whatsapp_bot_service.py:534-554, services/whatsapp_bot_service.py:651-683
Telegram Bot Integration
The Telegram bot integration provides a robust notification system and an interactive menu-driven interface. It supports both polling and webhook modes for communication. Sources: restx_api/telegram_bot.py:147-158
SDK Integration and Data Fetching
The TelegramBotService utilizes the openalgo Python SDK to fetch real-time trading data for the user. It caches SDK clients per telegram_id to optimize performance. Sources: services/telegram_bot_service_v2.py:56-78
Chart Generation
The Telegram service includes a visualization engine that generates intraday (5-day, 5-minute) and daily (252-day) candlestick charts using plotly.
This flow illustrates how user requests are transformed into visual market data charts. Sources: services/telegram_bot_service_v2.py:93-195
Alert Services Logic
The alert services (TelegramAlertService and WhatsAppAlertService) are responsible for translating internal trading events into human-readable messages.
Message Templates
The services maintain a mapping of order types to message templates. Common order types include:
placeorder: Standard order placement details.placesmartorder: Position-aware smart order alerts.basketorder: Summary of multiple order executions.closeposition: Status of position square-offs.
Sources: services/whatsapp_alert_service.py:39-50, blueprints/telegram.py:211-231
Priority and Formatting
Telegram notifications support priority levels (1-10), where higher numbers indicate urgent alerts like stop-loss hits or risk management violations. Sources: restx_api/telegram_bot.py:73-77, restx_api/telegram_bot.py:382-390
# Example of formatting logic in services/whatsapp_alert_service.py:65-75
mode = response.get("mode", "live")
if mode == "analyze":
lines.append("*ANALYZE MODE - No Real Order*")
else:
lines.append("*LIVE MODE - Real Order*")
lines.append("---------------------")
Security and Constraints
- Rate Limiting: Telegram and WhatsApp messages are rate-limited (defaulting to 10 or 30 per minute) to prevent spamming and protocol bans. Sources: blueprints/telegram.py:27, blueprints/whatsapp.py:36, restx_api/telegram_bot.py:23
- Encryption: Bot tokens and session blobs are encrypted using Fernet symmetric encryption before being stored in the database. Sources: services/whatsapp_bot_service.py:346-350
- Attachment Safety: WhatsApp attachment paths are validated against a whitelist (
WHATSAPP_ATTACHMENT_ROOTS) and prohibited from accessing system directories like/etcor/root. Sources: services/whatsapp_bot_service.py:76-118 - Single User Invariant: The system is designed for a single operator per deployment. Multi-user fan-out is supported but typically defaults to the device owner who performed the initial pairing. Sources: services/whatsapp_alert_service.py:304-320
API Summary Table
The following table summarizes the primary REST endpoints for bot management:
| Endpoint | Method | Purpose |
|---|---|---|
/telegram/bot/start | POST | Initializes and starts the Telegram bot thread. |
/whatsapp/pair | POST | Triggers the WhatsApp pairing sequence. |
/api/v1/telegram/notify | POST | Programmatic endpoint for strategies to send alerts. |
/whatsapp/broadcast | POST | Fan-out message to all linked WhatsApp users. |
/telegram/stats | GET | Retrieves command usage analytics (7d/30d). |
Sources: blueprints/telegram.py:84-125, blueprints/whatsapp.py:73-108, restx_api/telegram_bot.py:350-420, frontend/src/api/whatsapp.ts:25-30
The Telegram and WhatsApp bots serve as the primary interface for remote platform monitoring. By utilizing asynchronous execution and thread-confined protocol clients, OpenAlgo ensures that trading performance is maintained while providing high-fidelity, real-time feedback to the user.