Complete directory structure and file organization for the Hyperliquid Trading Bot
trader_hyperliquid/
├── 📂 src/ # Source code (modular architecture)
│ ├── 📂 backup/ # Archive
│ │ └── 📄 telegram_bot.py # Original 4,627-line monolithic file
│ ├── 📁 bot/ # Core bot functionality
│ │ └── 🤖 core.py # Core bot setup & authentication (264 lines)
│ ├── 📁 clients/ # Exchange connections
│ │ ├── 📄 __init__.py # Module init
│ │ └── 🔗 hyperliquid_client.py # Exchange client (528 lines)
│ ├── 📁 commands/ # Command handlers
│ │ ├── 📄 __init__.py # Module init
│ │ ├── 📊 info_commands.py # Balance, positions, stats (347 lines)
│ │ ├── ⚙️ management_commands.py # Monitoring, logs, debug (466 lines)
│ │ └── 📈 trading_commands.py # Trading operations (719 lines)
│ ├── 📁 config/ # Configuration
│ │ ├── 📄 __init__.py # Module init
│ │ ├── ⚙️ config.py # Main configuration (141 lines)
│ │ └── 📝 logging_config.py # Logging setup (240 lines)
│ ├── 📁 monitoring/ # Market monitoring
│ │ ├── 📄 __init__.py # Module init
│ │ ├── 🔔 alarm_manager.py # Price alarms (246 lines)
│ │ ├── 👁️ external_event_monitor.py # Monitors external trades and price alarms (NEW - 414 lines)
│ │ ├── 🔄 order_fill_processor.py # Processes order fills and disappeared orders (NEW - 324 lines)
│ │ ├── ⚖️ position_synchronizer.py # Synchronizes bot/exchange position states (NEW - 487 lines)
│ │ ├── 🛡️ risk_cleanup_manager.py # Handles risk management, cleanup of orphaned/pending orders (NEW - 501 lines)
│ │ └── 📊 market_monitor.py # Main coordinator for monitoring activities (NEW - 392 lines)
│ ├── 📁 notifications/ # Telegram notifications
│ │ ├── 📄 __init__.py # Module init
│ │ └── 📱 notification_manager.py # Rich notifications (343 lines)
│ ├── 📁 trading/ # Trading logic
│ │ ├── 🚀 trading_engine.py # Order execution (419 lines)
│ │ ├── 📊 trading_stats.py # Forwarding module (27 lines - DEPRECATED)
│ │ └── 📁 stats/ # 🆕 Modular statistics components (REFACTORED)
│ │ ├── 📄 __init__.py # Module exports
│ │ ├── 🗄️ database_manager.py # Database operations & schema (285 lines)
│ │ ├── 📋 order_manager.py # Order lifecycle tracking (265 lines)
│ │ ├── 🔄 trade_lifecycle_manager.py # Trade management & positions (450 lines)
│ │ ├── 📈 aggregation_manager.py # Statistics aggregation (350 lines)
│ │ ├── 📊 performance_calculator.py # Performance & risk metrics (400 lines)
│ │ └── 🚀 trading_stats_refactored.py # Main coordinator (400 lines)
│ └── 📊 trading_stats_original_backup.py # 🔄 Original backup (1,500+ lines)
│ ├── 📁 utils/ # Utility scripts
│ │ └── 📄 token_display_formatter.py # Utility for formatting token prices and amounts
│ └── 📄 __init__.py # Root module init
├── 📂 data/ # 🆕 Persistent data storage
│ ├── 📊 trading_stats.sqlite # SQLite database with all trading data
│ └── 🔔 price_alarms.json # Price alarm configurations
├── 📂 tests/ # Test suite
│ ├── 📋 README.md # Test documentation
│ ├── 🏃 run_all_tests.py # Test runner
│ ├── 🧪 test_config.py # Configuration tests
│ ├── 💰 test_balance.py # Balance tests
│ ├── 📈 test_perps_commands.py # Trading tests
│ ├── 🚪 test_exit_command.py # Exit command tests
│ └── 📋 test_order_management.py # Order management tests
├── 📂 docs/ # Documentation
│ ├── 📚 documentation-index.md # Documentation overview
│ ├── 📝 commands.md # Command reference
│ ├── 🚀 setup.md # Setup guide
│ ├── 🏗️ project-structure.md # This file
│ ├── 🚀 deployment.md # Deployment guide
│ ├── 📈 trade-lifecycle.md # NEW: Trade lifecycle explanation
│ └── 🔧 system-integration.md # System integration
├── 📂 config/ # Configuration files
│ └── 📄 .env.example # Environment template
├── 📂 logs/ # Log files (auto-created)
├── 📂 utils/ # Utility scripts
│ ├── 🔍 get_telegram_chat_id.py # Chat ID finder
│ ├── 🔍 simple_chat_id.py # Alternative chat ID finder
│ └── 📊 demo_stats.py # Demo statistics
├── 📂 __pycache__/ # Python cache (auto-created)
├── 📂 venv/ # Virtual environment
├── 📄 README.md # Main project README
├── 📄 requirements.txt # Python dependencies
├── 📄 .gitignore # Git ignore rules
├── 📄 .env # Environment configuration
├── 📄 LICENSE # MIT License
├── 🛠️ reset_data.sh # 🆕 Data reset utility script
└── 🚀 trading_bot.py # Main entry point
The bot has been refactored from a monolithic 4,627-line file into a professional modular architecture with single responsibility principle and clear separation of concerns.
Core bot functionality and authentication (264 lines)
Key Classes:
TelegramTradingBot
- Core bot orchestratorKey Responsibilities:
All trading operations and confirmations (719 lines)
Key Classes:
TradingCommands
- Trading command handlersKey Methods:
long_command()
- Long positions with validationshort_command()
- Short positions with validationexit_command()
- Position closuresl_command()
- Manual stop loss orderstp_command()
- Take profit orderscoo_command()
- Cancel all ordersbutton_callback()
- Confirmation handlingInformation and data display commands (347 lines)
Key Classes:
InfoCommands
- Information command handlersKey Methods:
balance_command()
- Account balance with performancepositions_command()
- Open positions with enhanced P&Lorders_command()
- Active orders grouped by symbolstats_command()
- Comprehensive trading statisticstrades_command()
- Recent trade historymarket_command()
- Market data and orderbookprice_command()
- Quick price checksSystem management and monitoring (466 lines)
Key Classes:
ManagementCommands
- Management command handlersKey Methods:
monitoring_command()
- System status overviewalarm_command()
- Price alert managementlogs_command()
- Log file management and cleanupdebug_command()
- System debugging informationversion_command()
- Version and system infoOrder execution and position tracking (419 lines)
Key Classes:
TradingEngine
- Core trading operationsKey Methods:
execute_long_order()
- Long position executionexecute_short_order()
- Short position executionexecute_exit_order()
- Position closureexecute_stop_loss_order()
- Stop loss placementexecute_take_profit_order()
- Take profit placementexecute_triggered_stop_order()
- Smart stop loss executionfind_position()
- Position detectionget_position_direction()
- CCXT position analysis🆕 Modular statistics architecture (2,150 lines total)
The original monolithic 1,500+ line TradingStats
class has been refactored into 6 focused, maintainable components:
Migration Benefits:
Backward Compatibility:
# Both import methods work:
from src.stats import TradingStats # Primary import
Hyperliquid API client using CCXT (528 lines)
Key Classes:
HyperliquidClient
- Exchange API wrapperKey Methods:
get_balance()
- Account balance with alternative methodsget_positions()
- Open positionsget_open_orders()
- Active ordersplace_market_order()
- Market order executionplace_limit_order()
- Limit order placementget_recent_fills()
- External trade detection🔥 Main coordinator for all market monitoring activities (Refactored - 392 lines)
OrderFillProcessor
, PositionSynchronizer
, ExternalEventMonitor
, RiskCleanupManager
.MarketMonitorCache
for efficient data access._monitor_loop
.last_processed_trade_time_helper
).AlarmManager
.Key Classes:
MarketMonitorCache
- Holds shared cached data.MarketMonitor
- Coordinates monitoring by delegating to specialized handlers.Key Methods:
start()
/ stop()
- Manages the monitoring lifecycle._monitor_loop()
- Main loop that orchestrates calls to delegate handlers._update_cached_data()
- Updates the shared MarketMonitorCache
._initialize_tracking()
- Sets up initial cache state and runs startup sync.last_processed_trade_time
for external fill processing.AlarmManager
.Key Classes:
ExternalEventMonitor
Key Methods:
_check_price_alarms()
_send_alarm_notification()
_check_external_trades()
last_known_orders
in the cache for detecting disappeared orders.last_processed_trade_time_helper
for its _check_for_recent_fills_for_order
helper.Key Classes:
OrderFillProcessor
Key Methods:
_check_order_fills()
_process_disappeared_orders()
_activate_pending_stop_losses_from_trades()
_check_for_recent_fills_for_order()
position_opened
lifecycle, exchange does not (closes the lifecycle).Key Classes:
PositionSynchronizer
Key Methods:
_auto_sync_orphaned_positions()
_immediate_startup_auto_sync()
_estimate_entry_price_for_orphaned_position()
_send_startup_auto_sync_notification()
Config.STOP_LOSS_PERCENTAGE
.stop_limit_trigger
orders.shared_state['external_stop_losses']
).pending_sl_activation
orders if their parent entry order is gone and no position exists.Key Classes:
RiskCleanupManager
Key Methods:
_check_pending_triggers()
_check_automatic_risk_management()
_cleanup_orphaned_stop_losses()
_check_external_stop_loss_orders()
_cleanup_external_stop_loss_tracking()
_cleanup_orphaned_pending_sl_activations()
price_alarms.json
.Rich Telegram notifications (343 lines)
Key Classes:
NotificationManager
- Notification orchestratorKey Methods:
send_long_success_notification()
- Long position confirmationssend_short_success_notification()
- Short position confirmationssend_exit_success_notification()
- Position closure confirmationssend_alarm_triggered_notification()
- Price alert notificationssend_external_trade_notification()
- External trade alertsConfiguration management (141 lines)
Key Classes:
Config
- Configuration managerKey Methods:
validate()
- Settings validationget_hyperliquid_config()
- CCXT configurationCentralized logging configuration (240 lines)
Key Classes:
LoggingManager
- Logging orchestratorKey Functions:
setup_logging()
- Initialize logging systemcleanup_logs()
- Remove old log filesget_log_stats()
- Log file statisticsTest runner for all test modules
Documentation overview and navigation
Complete command reference
Quick setup guide
This file - complete project organization
NEW: Detailed explanation of trade lifecycle management
orders
, trades
tables)TradingEngine
, TradingStats
, and MarketMonitor
Production deployment guide
Environment variable template
# Hyperliquid API
HYPERLIQUID_PRIVATE_KEY=0x...
HYPERLIQUID_TESTNET=true
# Telegram Bot
TELEGRAM_BOT_TOKEN=...
TELEGRAM_CHAT_ID=...
TELEGRAM_ENABLED=true
# Trading Settings
DEFAULT_TRADING_SYMBOL=BTC/USDC:USDC
DEFAULT_TRADE_AMOUNT=100
LOG_LEVEL=INFO
# Main bot (recommended)
python trading_bot.py
# Direct module execution
python -m src.bot.core
# All tests
python tests/run_all_tests.py
# Individual tests
python tests/test_config.py
python tests/test_balance.py
python tests/test_perps_commands.py
# Core modules
from src.config.config import Config
from src.bot.core import TelegramTradingBot
from src.trading.trading_engine import TradingEngine
from src.clients.hyperliquid_client import HyperliquidClient
# 🆕 New modular statistics (recommended)
from src.stats import TradingStats
# Individual components (for advanced usage)
from src.stats import (
DatabaseManager,
OrderManager,
TradeLifecycleManager,
AggregationManager,
PerformanceCalculator
)
# Clean primary import
from src.stats import TradingStats
ccxt>=4.2.0
python-telegram-bot>=20.0
python-dotenv>=1.0.0
requests>=2.31.0
hyperliquid>=0.1.0
python -m venv venv
source venv/bin/activate # Linux/Mac
venv\Scripts\activate # Windows
pip install -r requirements.txt
.env
docs/setup.md
tests/run_all_tests.py
src/*/
docs/
docs/deployment.md
The monolithic TradingStats
class has been successfully refactored into a modern modular architecture:
src/stats/
(6 modular components)src/backup/trading_stats_original_backup.py
# Recommended for new code
from src.stats import TradingStats
# All existing code works unchanged
stats = TradingStats()
stats.record_order_placed(...) # Same API
stats.get_performance_stats() # Same methods
Happy coding with the enhanced modular architecture! 🚀📱🏗️