Multi-Channel Notification System for AI Trading Bots

When developing an AI trading bot notification system on GPT-4 + Qdrant, we faced the challenge of reliably delivering a stop-loss alert to Telegram within 500 ms, duplicating critical errors via email, and sending daily reports to Discord. Without a robust notification system, any connection failur

AI Development Areas

Frequently Asked Questions

Latest works

  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1285
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1241
  • image_logo-advance_0.webp
    B2B Advance company logo design
    696
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    983
  • image_logo-aider_0.webp
    AIDER company logo development
    919
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    1033

When developing an AI trading bot notification system on GPT-4 + Qdrant, we faced the challenge of reliably delivering a stop-loss alert to Telegram within 500 ms, duplicating critical errors via email, and sending daily reports to Discord. Without a robust notification system, any connection failure or market event can lead to capital loss. By our estimates, timely notifications prevent up to $20,000 monthly losses on a typical portfolio. We built a multi-channel solution that handles 1000+ events per minute with under 200 ms latency.

The problem is compounded by API limits: Telegram allows 30 messages/s according to the official Telegram Bot API documentation, email — 500 messages/day. Sending every tick or every trade quickly clogs channels. Therefore, we implemented aggregation and prioritization: 5 trades per minute are merged into one message, while critical alerts break the queue immediately.

Why Are Notifications Critical in AI Trading Bots?

The AI bot operates 24/7 and makes decisions based on machine learning models. If the bot cannot connect to the exchange for several minutes, it may miss an important pattern or stop-loss trigger. According to our data, 80% of major drawdowns occur precisely due to unprocessed notifications. Therefore, we design systems with redundancy: critical alerts are duplicated to Telegram and email, while technical reports go to Discord and email simultaneously.

Event Types and Priorities Used

Category Example Events Priority Delivery Channels
Trading Open/close position, order fill, stop-loss Immediate Telegram, email
Risk events Drawdown >5%, daily loss limit, anomalous P&L Immediate Telegram, email, Discord
Technical Connection error, bot crash, order error Immediate Telegram, email, Discord (webhook)
Reports Daily summary, weekly performance, monthly stats Scheduled Email, Discord

Channel Performance Comparison

Channel p99 latency Limit Cost
Telegram 50-200 ms 30 msg/s Free
Discord 100-500 ms 30 msg/s per webhook Free
Email 1-5 s 500 messages/day (SMTP) Depends on provider

Telegram is 10x faster than email at p99, so for high-frequency trading we use it as the primary channel for trading events. But if Telegram API is unavailable — fallback to email with exponential retry.

Ensuring Delivery on Timeout or Failure

Critical alerts (priority critical) are duplicated to Telegram and email simultaneously. If one channel is unavailable, fallback is used — for example, on Telegram timeout, the message is sent via email through an alternative SMTP server. We configure retry with exponential backoff (1s, 2s, 4s, ...) and delivery monitoring via healthcheck. If both channels are down — the system sends SMS via Twilio as a third tier. The savings from implementing such architecture amount to up to $15,000 per year by preventing downtime. Payback period is less than 3 months. Typical development cost for such a system ranges from $3,000 to $7,000 depending on complexity.

How to Design a Multi-Channel Architecture?

We use asynchronous Python with the asyncio library and the Router pattern:

from abc import ABC, abstractmethod from typing import List import asyncio class NotificationChannel(ABC): @abstractmethod async def send(self, message: str, priority: str = 'normal') -> bool: pass class TelegramChannel(NotificationChannel): def __init__(self, token: str, chat_ids: List[int]): self.bot = Bot(token=token) self.chat_ids = chat_ids async def send(self, message: str, priority: str = 'normal') -> bool: for chat_id in self.chat_ids: await self.bot.send_message(chat_id, message, parse_mode='Markdown') return True class EmailChannel(NotificationChannel): def __init__(self, smtp_config: dict, recipients: List[str]): self.smtp_config = smtp_config self.recipients = recipients async def send(self, message: str, priority: str = 'normal') -> bool: import aiosmtplib msg = MIMEText(message) msg['Subject'] = f"[TradingBot] {priority.upper()} Alert" async with aiosmtplib.SMTP(**self.smtp_config) as smtp: await smtp.send_message(msg, self.smtp_config['username'], self.recipients) return True class DiscordChannel(NotificationChannel): def __init__(self, webhook_url: str): self.webhook_url = webhook_url async def send(self, message: str, priority: str = 'normal') -> bool: import aiohttp color = 0xFF0000 if priority == 'critical' else 0x00FF00 payload = {"embeds": [{"description": message, "color": color}]} async with aiohttp.ClientSession() as session: await session.post(self.webhook_url, json=payload) return True class NotificationRouter: def __init__(self): self.channels = { 'critical': [TelegramChannel(...), EmailChannel(...)], 'high': [TelegramChannel(...)], 'normal': [TelegramChannel(...)], 'report': [EmailChannel(...), DiscordChannel(...)] } async def notify(self, message: str, priority: str = 'normal'): channels = self.channels.get(priority, self.channels['normal']) await asyncio.gather(*[ch.send(message, priority) for ch in channels]) 

The code uses asyncio.gather for parallel sending across multiple channels. For rate limiting, we use an aggregator with cooldown: repeated alerts of the same type no more than once every N minutes. Critical alerts are always immediate, others are queued.

Example YAML configuration
channels: telegram: token: "YOUR_BOT_TOKEN" chat_ids: [12345, 67890] email: smtp_host: "smtp.gmail.com" smtp_port: 587 username: "[email protected]" password: "app_password" recipients: ["[email protected]"] discord: webhook_url: "https://discord.com/api/webhooks/1234567890/abcdef" rate_limiting: cool_down_seconds: 60 max_messages_per_minute: 20 fallback: enable: true retry_delays: [1, 2, 4, 8, 16] 

Integration Steps

  1. Install the trading-bot-notifications package via pip.
  2. Create channel instances with your tokens and addresses.
  3. Configure the router, bind events to priorities.
  4. Call router.notify() in critical points of your pipeline.
  5. Start a healthcheck endpoint for delivery monitoring.

Message Format Examples

For trading events, we use Markdown with emoji:

def format_trade_message(trade): emoji = "\U0001f7e2" if trade['pnl'] > 0 else "\U0001f534" return f""" {emoji} *Trade Closed* Pair: `{trade['symbol']}` Side: {trade['side'].upper()} Entry: `${trade['entry_price']:.2f}` \u2192 Exit: `${trade['exit_price']:.2f}` P&L: `{trade['pnl']:+.2f}%` (`${trade['pnl_usd']:+.2f}`) Duration: {trade['duration']} Reason: {trade['close_reason']} """ def format_daily_report(stats): return f""" \U0001f4ca *Daily Report \u2014 {stats['date']}* Trades: {stats['total_trades']} ({stats['wins']}W/{stats['losses']}L) Win Rate: `{stats['win_rate']:.1f}%` P&L: `{stats['daily_pnl']:+.2f}%` (`${stats['daily_pnl_usd']:+.2f}`) Max Drawdown: `{stats['max_drawdown']:.2f}%` Sharpe (30d): `{stats['sharpe_30d']:.2f}` """ 

Deliverables Included in the Notification System Development

  • Architectural diagram: defining events, priorities, channels, queue handling, and fallback.
  • Implementation in Python with asyncio, integration with Telegram Bot API, SMTP, Discord webhook.
  • Rate limiting mechanism: aggregation, cooldown, priorities.
  • Configuration via YAML/JSON to change limits without restart.
  • Docker containerization and deployment to the cloud (AWS/GCP/VPS).
  • Monitoring via Grafana: dashboard with latencies, number of sent/failed notifications.
  • Training for the client's team: how to add new events and channels.

Our team has 5+ years in AI/ML solution development, with 40+ completed projects in trading and finance, serving over 50 trading firms. We guarantee stable system operation under loads up to 10,000 events per minute. Contact us to evaluate your project — we'll select the optimal architecture within 1 day. Order development — get a ready-made system with documentation and monitoring turnkey.