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! ๐๐ฑ๐๏ธ