PQAP Telegram Alerting System

Overview

PQAP includes a comprehensive Telegram alerting system that keeps you informed about: - System startup/shutdown - Hourly portfolio status - Trade executions - Errors and issues - Risk alerts - Daily summaries

Configuration

Alerts are configured via environment variables in .env:

TELEGRAM_BOT_TOKEN=<your_bot_token>
TELEGRAM_CHAT_ID=<your_chat_id>

Getting Telegram Credentials

  1. Create a Bot:
  2. Message @BotFather on Telegram
  3. Send /newbot and follow instructions
  4. Save the bot token

  5. Get Your Chat ID:

  6. Message @userinfobot on Telegram
  7. It will reply with your chat ID

  8. Add to .env: bash TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz TELEGRAM_CHAT_ID=123456789

Alert Types

1. Startup Notification

Sent when PQAP starts:

🚀 PQAP Started

Mode: MONITORING
Environment: DEV
Capital: $5,000
Strategies: 4 enabled
Hourly updates: ON

2. Hourly Status Updates

Sent every hour with portfolio performance:

⏰ PQAP Hourly Update
Time: 2025-12-24 15:00 UTC

📈 Portfolio:
  P&L: $+123.45 (+2.47%)
  Capital: $4,876.55
  Positions: 3
  Trades: 15

📊 Data Collection:
  Markets: 50
  Snapshots: 1,234
  Anomalies: 7

⚠️ Errors: 2 (check logs)

3. Trade Execution Alerts

Sent when a trade is executed:

📈 Trade Executed
Strategy: dual_arb_v1
P&L: $+25.50
Cumulative: $148.95

4. Error Alerts

Sent immediately when critical errors occur:

 Error Alert

Error: Failed to execute trade: insufficient capital
location: execute_signal
strategy_id: dual_arb_v1
market_id: 0x1234567890abcdef

5. Risk Alerts

Sent when risk limits are breached:

⚠️ Risk Alert
Type: daily_loss_limit
Strategy: momentum_v1
Action: DISABLED

6. Kill Switch Alerts

Sent when the kill switch is triggered:

🚨 KILL SWITCH ACTIVATED

Reason: Daily loss limit exceeded

All trading has been halted.
Manual intervention required.

7. Daily Summary

Sent at end of day with full P&L breakdown:

🟢 Daily Summary
Date: 2025-12-24

Total P&L: $+148.95
Trades: 15
Win Rate: 67.0%

By Strategy:
📈 dual_arb_v1: $+75.25
📈 momentum_v1: $+48.50
📈 stat_arb_v1: $+25.20

8. Shutdown Notification

Sent when PQAP stops:

🛑 PQAP Stopped
Trading system has shut down.

Testing

Quick Test

Send a simple message:

python scripts/send_telegram.py "Test message"

Comprehensive Test

Test all alert types:

python scripts/test_telegram_alerts.py

This will send: 1. Startup notification 2. Hourly status update 3. Error alert 4. Trade execution alert 5. Daily summary 6. System status 7. Shutdown notification

Check your Telegram to verify all messages were received.

Integration

The alerting system is automatically integrated into PQAP's main loop:

  1. Startup: Sends startup notification when PQAP initializes
  2. Hourly Loop: Background task sends status updates every hour
  3. Event Bus: Listens for trade executions, risk events, kill switch
  4. Error Tracking: Counts errors and reports in hourly updates
  5. Shutdown: Sends shutdown notification on graceful exit

Error Handling

  • Messages are queued with rate limiting (1 sec between messages)
  • Failed sends are logged but don't crash the system
  • Critical alerts (kill switch, errors) are sent immediately
  • Network issues are retried automatically

Customization

To customize alert messages, edit /src/alerts/telegram.py:

  • send_hourly_status() - Hourly update format
  • send_error_alert() - Error alert format
  • _on_trade() - Trade execution format
  • send_daily_summary() - Daily summary format

Disabling Alerts

To disable Telegram alerts, simply leave the credentials empty in .env:

TELEGRAM_BOT_TOKEN=
TELEGRAM_CHAT_ID=

The system will log a warning and continue without sending alerts.

Troubleshooting

Messages not being received

  1. Verify bot token and chat ID are correct
  2. Make sure you've started a conversation with your bot
  3. Check logs for error messages
  4. Test with scripts/send_telegram.py

Too many messages

  1. Adjust hourly update interval in _hourly_status_loop()
  2. Disable trade alerts by commenting out event subscription
  3. Filter error alerts by severity

Rate limiting

  1. Increase rate_limit_seconds in TelegramAlerter initialization
  2. Messages are queued automatically, but may be delayed

System Overview

Polymarket API

Market data source

Data Collector

Every 5 minutes

SQLite Database

Price history + trades

Strategy Engine

Signal generation

ML Model

XGBoost (72% acc)

Execution Engine

Paper trading

Dashboard

You are here!

Telegram

Alerts & updates

Trading Strategies

Each strategy looks for different market inefficiencies:

Dual Arbitrage Active

Finds when YES + NO prices don't add to 100%. Risk-free profit.

Mean Reversion Active

Buys when price drops too far from average, sells when it recovers.

Market Maker Active

Places bid/ask orders to capture the spread.

Time Arbitrage Active

Exploits predictable price patterns at certain hours.

ML Prediction Active

Uses machine learning to predict 6-hour price direction.

Value Betting Disabled

Finds underpriced outcomes based on implied probability.

Data Storage (Single Source of Truth)

All data lives on EC2. Local machines are for development only. The EC2 instance is the authoritative source for all market data, trades, and positions.
Database Purpose Location
market_history.db Price snapshots every 5 minutes (8.2 MB) EC2 (primary)
pqap_staging.db Trades, positions, P&L history EC2 (primary)
paper_trading_state.json Current portfolio state EC2 (primary)

Environment Architecture

EC2 (Production)

  • Runs 24/7
  • All databases live here
  • Executes all trades
  • Single source of truth

Local (Development)

  • For code changes only
  • Syncs code to EC2
  • No production data
  • Can be turned off

Environment Details

Component Details
Dashboard URL https://pqap.tailwindtech.ai
Server AWS EC2 (us-east-1)
SSL Let's Encrypt via Traefik
Mode Paper Trading (simulated)

How It Works (Simple Version)

1. Data Collection: Every 5 minutes, we fetch prices from Polymarket for 50 markets and save them to our database.

2. Analysis: Our strategies analyze this data looking for patterns - like prices that moved too far from normal, or markets where the math doesn't add up.

3. Signals: When a strategy finds an opportunity, it generates a "signal" - a recommendation to buy or sell.

4. Execution: The execution engine takes these signals and simulates trades (paper trading). Eventually, this will place real orders.

5. Monitoring: This dashboard shows you what's happening. Telegram sends alerts for important events.