Files
The-Ouroboros/src/notifications
agentson 6b74e4cc77
Some checks failed
CI / test (pull_request) Has been cancelled
feat: 해외주식 미체결 주문 감지 및 처리 (#229)
- OverseasBroker에 get_overseas_pending_orders (TTTS3018R, 실전전용)
  및 cancel_overseas_order (거래소별 TR_ID, hashkey 필수) 추가
- TelegramClient에 notify_unfilled_order 추가
  (BUY취소=MEDIUM, SELL미체결=HIGH 우선순위)
- handle_overseas_pending_orders 함수 추가:
  · BUY 미체결 → 취소 + 쿨다운 설정
  · SELL 미체결 → 취소 후 -0.4% 재주문 (최대 1회)
  · 미국 거래소(NASD/NYSE/AMEX) 중복 조회 방지
- daily/realtime 두 모드 모두 market 루프 시작 전 호출
- 테스트 13개 추가 (test_overseas_broker.py 8개, test_main.py 5개)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-23 21:12:34 +09:00
..

Telegram Notifications

Real-time trading event notifications via Telegram Bot API.

Setup

1. Create a Telegram Bot

  1. Open Telegram and message @BotFather
  2. Send /newbot command
  3. Follow prompts to name your bot
  4. Save the bot token (looks like 1234567890:ABCdefGHIjklMNOpqrsTUVwxyz)

2. Get Your Chat ID

Option A: Using @userinfobot

  1. Message @userinfobot on Telegram
  2. Send /start
  3. Save your numeric chat ID (e.g., 123456789)

Option B: Using @RawDataBot

  1. Message @RawDataBot on Telegram
  2. Look for "id": in the JSON response
  3. 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_limit parameter

Troubleshooting

No notifications received

  1. Check bot configuration

    # Verify env variables are set
    grep TELEGRAM .env
    
  2. Start conversation with bot

    • Open bot in Telegram
    • Send /start command
    • Bot cannot message users who haven't started a conversation
  3. Check logs

    # Look for Telegram-related errors
    python -m src.main --mode=paper 2>&1 | grep -i telegram
    
  4. Verify bot token

    curl https://api.telegram.org/bot<YOUR_TOKEN>/getMe
    # Should return bot info (not 401 error)
    
  5. 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 /start to 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 .env file 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

  1. Add bot to Telegram group
  2. Get group chat ID (negative number like -123456789)
  3. 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
)

Bidirectional Commands

Control your trading bot remotely via Telegram commands. The bot not only sends notifications but also accepts commands for real-time control.

Available Commands

Command Description
/start Welcome message with quick start guide
/help List all available commands
/status Current trading status (mode, markets, P&L, circuit breaker)
/positions View current holdings grouped by market
/stop Pause all trading operations
/resume Resume trading operations

Command Examples

Check Trading Status

You: /status

Bot:
📊 Trading Status

Mode: PAPER
Markets: Korea, United States
Trading: Active

Current P&L: +2.50%
Circuit Breaker: -3.0%

View Holdings

You: /positions

Bot:
💼 Current Holdings

🇰🇷 Korea
• 005930: 10 shares @ 70,000
• 035420: 5 shares @ 200,000

🇺🇸 Overseas
• AAPL: 15 shares @ 175
• TSLA: 8 shares @ 245

Cash: ₩5,000,000

Pause Trading

You: /stop

Bot:
⏸️ Trading Paused

All trading operations have been suspended.
Use /resume to restart trading.

Resume Trading

You: /resume

Bot:
▶️ Trading Resumed

Trading operations have been restarted.

Security

Chat ID Verification

  • Commands are only accepted from the configured TELEGRAM_CHAT_ID
  • Unauthorized users receive no response
  • Command attempts from wrong chat IDs are logged

Authorization Required

  • Only the bot owner (chat ID in .env) can control trading
  • No way for unauthorized users to discover or use commands
  • All command executions are logged for audit

Configuration

Add to your .env file:

# Commands are enabled by default
TELEGRAM_COMMANDS_ENABLED=true

# Polling interval (seconds) - how often to check for commands
TELEGRAM_POLLING_INTERVAL=1.0

To disable commands but keep notifications:

TELEGRAM_COMMANDS_ENABLED=false

How It Works

  1. Long Polling: Bot checks Telegram API every second for new messages
  2. Command Parsing: Messages starting with / are parsed as commands
  3. Authentication: Chat ID is verified before executing any command
  4. Execution: Command handler is called with current bot state
  5. Response: Result is sent back via Telegram

Error Handling

  • Command parsing errors → "Unknown command" response
  • API failures → Graceful degradation, error logged
  • Invalid state → Appropriate message (e.g., "Trading is already paused")
  • Trading loop isolation → Command errors never crash trading

Troubleshooting Commands

Commands not responding

  1. Check TELEGRAM_COMMANDS_ENABLED=true in .env
  2. Verify you started conversation with /start
  3. Check logs for command handler errors
  4. Confirm chat ID matches .env configuration

Wrong chat ID

  • Commands from unauthorized chats are silently ignored
  • Check logs for "unauthorized chat_id" warnings

Delayed responses

  • Polling interval is 1 second by default
  • Network latency may add delay
  • Check TELEGRAM_POLLING_INTERVAL setting

API Reference

See telegram_client.py for full API documentation.

Notification Methods

  • notify_trade_execution() - Trade alerts
  • notify_circuit_breaker() - Emergency stops
  • notify_fat_finger() - Order rejections
  • notify_market_open/close() - Session tracking
  • notify_system_start/shutdown() - Lifecycle events
  • notify_error() - Error alerts

Command Handler

  • TelegramCommandHandler - Bidirectional command processing
  • register_command() - Register custom command handlers
  • start_polling() / stop_polling() - Lifecycle management