Background Monitoring Threads
Relevant source files
The following files were used as context for generating this wiki page:
The GentelmeN-CorE system utilizes background monitoring threads to perform asynchronous tasks that operate independently of the primary Telegram bot polling loop. The primary implementation of this is the Price Monitor, which continuously tracks cryptocurrency market data to trigger user-defined alerts.
This architecture ensures that time-consuming operations, such as network requests to exchange APIs and database polling, do not block the bot's responsiveness to user messages.
Sources: core/bot.py:54-94, bot.py:1-7
Architecture and Thread Management
The application initializes its background infrastructure during the startup sequence. While the main thread handles the bot's infinity polling for incoming Telegram updates, a separate daemon thread is spawned specifically for monitoring.
Thread Initialization
The system uses the Python threading library to start the price_monitor function. By setting the thread as a daemon (daemon=True), the system ensures that the background process terminates automatically when the main program exits.
The diagram shows the parallel execution of the main polling loop and the daemonized monitoring thread.
Sources: core/bot.py:44-46, core/bot.py:94, core/bot.py:101-106
Price Monitor Implementation
The price_monitor function is the core of the background system. It operates on a 60-second cycle, interacting with both the PostgreSQL database and the KuCoin exchange.
Logic Flow
- Sleep Phase: The thread waits for 60 seconds to avoid overwhelming external APIs and the local database.
- Database Retrieval: It queries the
alertstable to fetch all active price alerts. - External API Call: It identifies unique symbols from the alerts and performs a bulk
fetch_tickerscall via theccxtKuCoin integration. - Validation: For each alert, it compares the
curr_priceagainst thetarget_pricebased on the specifieddirection('UP' or 'DOWN'). - Notification & Cleanup: If a price threshold is hit, the bot sends a notification to the user, and the alert is deleted from the database.
| Component | Responsibility | Source Reference |
|---|---|---|
time.sleep(60) | Controls monitoring frequency | core/bot.py:56 |
psycopg2.connect | Manages database connection within the thread | core/bot.py:61 |
kucoin.fetch_tickers | Retrieves real-time market data | core/bot.py:73 |
bot.send_message | Dispatches Telegram notifications to users | core/bot.py:86-90 |
Data Comparison Logic
The monitoring logic evaluates two conditions for a "hit":
- UP: Current Price >= Target Price.
- DOWN: Current Price <= Target Price.
Sources: core/bot.py:54-94, core/database.py:24-35
Database Schema for Monitoring
The background threads rely on the alerts table created during system initialization. This table acts as the state store for all background tasks.
| Field | Type | Description |
|---|---|---|
id | SERIAL | Primary key for the alert |
user_id | BIGINT | The Telegram user ID to notify |
symbol | TEXT | The trading pair (e.g., BTC/USDT) |
target_price | NUMERIC | The price threshold |
direction | TEXT | Either 'UP' or 'DOWN' |
Sources: core/database.py:24-35
Alert Lifecycle Sequence
The following diagram illustrates the interaction between the user setting an alert via a command and the background thread eventually triggering it.
Sources: core/commands.py:46-77, core/bot.py:54-94
Error Handling and Resilience
The background thread is wrapped in a comprehensive try...except block to prevent the entire bot from crashing if a network error or database timeout occurs. Errors are caught and printed to the console, allowing the thread to continue to the next iteration of the loop.
- KuCoin Offline: If the KuCoin client fails to initialize or the API is unreachable, the thread skips the iteration.
- Database Errors: If the connection to
DATABASE_URLfails, the thread logs the error and continues. - Polling Stability: The main thread also implements an auto-restart mechanism for the
bot.infinity_pollingloop with a 15-second delay on failure.
Sources: core/bot.py:40-43, core/bot.py:93, core/bot.py:101-106
Summary
Background monitoring in GentelmeN-CorE is implemented as a dedicated daemon thread focused on real-time cryptocurrency price alerts. By decoupling this logic from the message handling system, the bot maintains high responsiveness while providing reliable, periodic checks against market data from external APIs like KuCoin.