Some checks failed
CI / test (pull_request) Has been cancelled
Add TelegramClient for real-time trading notifications: - NotificationPriority enum (LOW/MEDIUM/HIGH/CRITICAL) - LeakyBucket rate limiter (1 msg/sec) - 8 notification methods (trade, circuit breaker, fat finger, market open/close, system start/shutdown, errors) - Graceful degradation (optional API, never crashes) - Session management pattern from KISBroker - Comprehensive README with setup guide and troubleshooting Follows NewsAPI pattern for optional APIs. Uses existing aiohttp dependency. Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
4.6 KiB
4.6 KiB
Telegram Notifications
Real-time trading event notifications via Telegram Bot API.
Setup
1. Create a Telegram Bot
- Open Telegram and message @BotFather
- Send
/newbotcommand - Follow prompts to name your bot
- Save the bot token (looks like
1234567890:ABCdefGHIjklMNOpqrsTUVwxyz)
2. Get Your Chat ID
Option A: Using @userinfobot
- Message @userinfobot on Telegram
- Send
/start - Save your numeric chat ID (e.g.,
123456789)
Option B: Using @RawDataBot
- Message @RawDataBot on Telegram
- Look for
"id":in the JSON response - Save your numeric chat ID
3. Configure Environment
Add to your .env file:
TELEGRAM_BOT_TOKEN=1234567890:ABCdefGHIjklMNOpqrsTUVwxyz
TELEGRAM_CHAT_ID=123456789
TELEGRAM_ENABLED=true
4. Test the Bot
Start a conversation with your bot on Telegram first (send /start), then run:
python -m src.main --mode=paper
You should receive a startup notification.
Message Examples
Trade Execution
🟢 BUY
Symbol: AAPL (United States)
Quantity: 10 shares
Price: 150.25
Confidence: 85%
Circuit Breaker
🚨 CIRCUIT BREAKER TRIPPED
P&L: -3.15% (threshold: -3.0%)
Trading halted for safety
Fat-Finger Protection
⚠️ Fat-Finger Protection
Order rejected: TSLA
Attempted: 45.0% of cash
Max allowed: 30%
Amount: 45,000 / 100,000
Market Open/Close
ℹ️ Market Open
Korea trading session started
ℹ️ Market Close
Korea trading session ended
📈 P&L: +1.25%
System Status
📝 System Started
Mode: PAPER
Markets: KRX, NASDAQ
System Shutdown
Normal shutdown
Notification Priorities
| Priority | Emoji | Use Case |
|---|---|---|
| LOW | ℹ️ | Market open/close |
| MEDIUM | 📊 | Trade execution, system start/stop |
| HIGH | ⚠️ | Fat-finger protection, errors |
| CRITICAL | 🚨 | Circuit breaker trips |
Rate Limiting
- Default: 1 message per second
- Prevents hitting Telegram's global rate limits
- Configurable via
rate_limitparameter
Troubleshooting
No notifications received
-
Check bot configuration
# Verify env variables are set grep TELEGRAM .env -
Start conversation with bot
- Open bot in Telegram
- Send
/startcommand - Bot cannot message users who haven't started a conversation
-
Check logs
# Look for Telegram-related errors python -m src.main --mode=paper 2>&1 | grep -i telegram -
Verify bot token
curl https://api.telegram.org/bot<YOUR_TOKEN>/getMe # Should return bot info (not 401 error) -
Verify chat ID
curl -X POST https://api.telegram.org/bot<YOUR_TOKEN>/sendMessage \ -H 'Content-Type: application/json' \ -d '{"chat_id": "<YOUR_CHAT_ID>", "text": "Test"}' # Should send a test message
Notifications delayed
- Check rate limiter settings
- Verify network connection
- Look for timeout errors in logs
"Chat not found" error
- Incorrect chat ID
- Bot blocked by user
- Need to send
/startto bot first
"Unauthorized" error
- Invalid bot token
- Token revoked (regenerate with @BotFather)
Graceful Degradation
The system works without Telegram notifications:
- Missing credentials → notifications disabled automatically
- API errors → logged but trading continues
- Network timeouts → trading loop unaffected
- Rate limiting → messages queued, trading proceeds
Notifications never crash the trading system.
Security Notes
- Never commit
.envfile with credentials - Bot token grants full bot control
- Chat ID is not sensitive (just a number)
- Messages are sent over HTTPS
- No trading credentials in notifications
Advanced Usage
Group Notifications
- Add bot to Telegram group
- Get group chat ID (negative number like
-123456789) - Use group chat ID in
TELEGRAM_CHAT_ID
Multiple Recipients
Create multiple bots or use a broadcast group with multiple members.
Custom Rate Limits
Not currently exposed in config, but can be modified in code:
telegram = TelegramClient(
bot_token=settings.TELEGRAM_BOT_TOKEN,
chat_id=settings.TELEGRAM_CHAT_ID,
rate_limit=2.0, # 2 messages per second
)
API Reference
See telegram_client.py for full API documentation.
Key methods:
notify_trade_execution()- Trade alertsnotify_circuit_breaker()- Emergency stopsnotify_fat_finger()- Order rejectionsnotify_market_open/close()- Session trackingnotify_system_start/shutdown()- Lifecycle eventsnotify_error()- Error alerts