Complete Directory Structure
๐ฏ Architecture Philosophy: This project follows enterprise-grade Python best practices with clear separation of concerns, comprehensive error handling, extensive logging, and modular design for maintainability and scalability.
ict-ml-trading/
โ
โโโ .env.example # Environment variables template
โโโ .env # Actual environment variables (git-ignored)
โโโ .gitignore # Git ignore patterns
โโโ .pre-commit-config.yaml # Pre-commit hooks configuration
โโโ README.md # Project documentation
โโโ requirements.txt # Production dependencies
โโโ requirements-dev.txt # Development dependencies
โโโ setup.py # Package installation configuration
โโโ pyproject.toml # Modern Python project configuration
โโโ Makefile # Common commands automation
โโโ CHANGELOG.md # Version history and changes
โโโ LICENSE # Software license
โ
โโโ config/ # Configuration files
โ โโโ config.yaml # Main application configuration
โ โโโ logging.yaml # Logging configuration
โ โโโ detectors.yaml # Pattern detector parameters
โ โโโ models.yaml # ML model hyperparameters
โ โโโ trading.yaml # Trading strategy parameters
โ โโโ alerts.yaml # Alert system configuration
โ โโโ database.yaml # Database connection settings
โ
โโโ src/ # Main source code
โ โโโ __init__.py
โ โ
โ โโโ core/ # Core business logic
โ โ โโโ __init__.py
โ โ โโโ exceptions.py # Custom exception classes
โ โ โโโ constants.py # Application-wide constants
โ โ โโโ enums.py # Enumerations (PatternType, Grade, etc.)
โ โ โโโ base_classes.py # Abstract base classes
โ โ
โ โโโ config/ # Configuration management
โ โ โโโ __init__.py
โ โ โโโ config_loader.py # Load and validate configurations
โ โ โโโ settings.py # Settings dataclasses
โ โ โโโ validators.py # Configuration validation logic
โ โ
โ โโโ logging/ # Logging system
โ โ โโโ __init__.py
โ โ โโโ logger.py # Logger setup and configuration
โ โ โโโ formatters.py # Custom log formatters
โ โ โโโ handlers.py # Custom log handlers
โ โ โโโ filters.py # Log filters
โ โ โโโ decorators.py # Logging decorators (@log_execution)
โ โ
โ โโโ data/ # Data management
โ โ โโโ __init__.py
โ โ โโโ database.py # Database connection and ORM
โ โ โโโ models.py # SQLAlchemy data models
โ โ โโโ repositories.py # Data access layer (repository pattern)
โ โ โโโ loaders.py # Data loading utilities
โ โ โโโ preprocessors.py # Data preprocessing and cleaning
โ โ โโโ validators.py # Data validation
โ โ โโโ schemas.py # Pydantic schemas for validation
โ โ
โ โโโ detectors/ # Pattern detection
โ โ โโโ __init__.py
โ โ โโโ base_detector.py # Abstract base detector class
โ โ โโโ fvg_detector.py # Fair Value Gap detection
โ โ โโโ order_block_detector.py # Order Block detection
โ โ โโโ liquidity_detector.py # Liquidity sweep detection
โ โ โโโ premium_discount.py # Premium/Discount calculator
โ โ โโโ structure_detector.py # Market structure (BOS, CHoCH)
โ โ โโโ scanner.py # Orchestrates all detectors
โ โ โโโ utils.py # Detector utility functions
โ โ
โ โโโ features/ # Feature engineering
โ โ โโโ __init__.py
โ โ โโโ base_features.py # Base feature engineering class
โ โ โโโ pattern_features.py # Pattern-specific features
โ โ โโโ technical_features.py # Technical indicators
โ โ โโโ temporal_features.py # Time-based features
โ โ โโโ context_features.py # Market context features
โ โ โโโ orderflow_features.py # Order flow features
โ โ โโโ feature_store.py # Feature storage and retrieval
โ โ
โ โโโ models/ # Machine learning models
โ โ โโโ __init__.py
โ โ โโโ base_model.py # Abstract base model class
โ โ โโโ pattern_grader.py # Individual pattern grading models
โ โ โโโ setup_classifier.py # Complete setup classification
โ โ โโโ training.py # Model training pipeline
โ โ โโโ evaluation.py # Model evaluation metrics
โ โ โโโ tuning.py # Hyperparameter tuning
โ โ โโโ inference.py # Real-time prediction
โ โ โโโ registry.py # Model versioning and registry
โ โ
โ โโโ labeling/ # Labeling system
โ โ โโโ __init__.py
โ โ โโโ interface.py # Labeling interface orchestrator
โ โ โโโ notion_integration.py # Notion API integration
โ โ โโโ web_ui.py # Flask/FastAPI web interface
โ โ โโโ quality_checker.py # Label quality validation
โ โ โโโ anchors.py # Anchor example management
โ โ โโโ export.py # Export labels to training format
โ โ
โ โโโ alerts/ # Alert system
โ โ โโโ __init__.py
โ โ โโโ base_alert.py # Abstract alert handler
โ โ โโโ telegram_bot.py # Telegram bot integration
โ โ โโโ slack_integration.py # Slack integration
โ โ โโโ email_alerts.py # Email notifications
โ โ โโโ alert_manager.py # Alert orchestration and routing
โ โ โโโ templates.py # Alert message templates
โ โ
โ โโโ trading/ # Trading execution
โ โ โโโ __init__.py
โ โ โโโ broker_interface.py # Broker API abstraction
โ โ โโโ order_manager.py # Order execution and tracking
โ โ โโโ risk_manager.py # Position sizing and risk controls
โ โ โโโ portfolio.py # Portfolio state management
โ โ โโโ execution_engine.py # Trade execution logic
โ โ โโโ validators.py # Pre-trade validation
โ โ
โ โโโ backtesting/ # Backtesting framework
โ โ โโโ __init__.py
โ โ โโโ engine.py # Backtest execution engine
โ โ โโโ metrics.py # Performance metrics calculation
โ โ โโโ reports.py # Backtest report generation
โ โ โโโ visualizations.py # Performance visualizations
โ โ โโโ validators.py # Backtest result validation
โ โ
โ โโโ monitoring/ # System monitoring
โ โ โโโ __init__.py
โ โ โโโ metrics_collector.py # Collect system metrics
โ โ โโโ health_checker.py # System health checks
โ โ โโโ performance_tracker.py # Track model performance
โ โ โโโ alerting.py # Monitoring alerts
โ โ โโโ dashboard.py # Monitoring dashboard
โ โ
โ โโโ visualization/ # Chart and data visualization
โ โ โโโ __init__.py
โ โ โโโ chart_generator.py # Generate trading charts
โ โ โโโ pattern_plotter.py # Plot detected patterns
โ โ โโโ performance_plots.py # Performance visualizations
โ โ โโโ screenshot.py # Screenshot capture for labeling
โ โ
โ โโโ utils/ # Utility functions
โ โโโ __init__.py
โ โโโ datetime_utils.py # Date/time helpers
โ โโโ file_utils.py # File operations
โ โโโ string_utils.py # String manipulation
โ โโโ math_utils.py # Mathematical utilities
โ โโโ decorators.py # Utility decorators
โ โโโ retry.py # Retry logic for API calls
โ โโโ validators.py # General validation functions
โ
โโโ data/ # Data storage
โ โโโ raw/ # Raw downloaded data
โ โ โโโ ohlcv/ # OHLCV market data
โ โ โ โโโ 1min/
โ โ โ โโโ 5min/
โ โ โ โโโ 15min/
โ โ โโโ orderflow/ # Order flow data (if available)
โ โ
โ โโโ processed/ # Cleaned and processed data
โ โ โโโ features/ # Computed features
โ โ โโโ patterns/ # Detected patterns
โ โ โโโ snapshots/ # OHLC snapshots for patterns
โ โ
โ โโโ labels/ # Labeled data
โ โ โโโ individual_patterns/ # Pattern-level labels
โ โ โโโ complete_setups/ # Setup-level labels
โ โ โโโ anchors/ # Anchor examples
โ โ โโโ label_metadata.json # Label versioning and metadata
โ โ
โ โโโ screenshots/ # Chart screenshots for labeling
โ โ โโโ patterns/ # Pattern screenshots
โ โ โโโ setups/ # Complete setup screenshots
โ โ
โ โโโ external/ # External data sources
โ โโโ economic_calendar/ # News events
โ โโโ reference/ # Reference data (holidays, etc.)
โ
โโโ models/ # Trained models storage
โ โโโ pattern_graders/ # Individual pattern models
โ โ โโโ fvg/
โ โ โ โโโ v1.0.0/ # Versioned models
โ โ โ โโโ v1.1.0/
โ โ โ โโโ latest/ # Symlink to latest version
โ โ โโโ order_block/
โ โ โโโ liquidity/
โ โ
โ โโโ strategy_models/ # Complete setup models
โ โ โโโ continuation/ # 3:00-3:15 continuation model
โ โ โโโ reversal/ # 3:30-3:50 reversal model
โ โ
โ โโโ metadata/ # Model metadata and configs
โ โ โโโ model_registry.json # Track all model versions
โ โ โโโ performance_history.json # Historical performance
โ โ
โ โโโ artifacts/ # Training artifacts
โ โโโ feature_importances/
โ โโโ training_curves/
โ โโโ validation_reports/
โ
โโโ logs/ # Application logs
โ โโโ application/ # General application logs
โ โ โโโ app.log # Current log file
โ โ โโโ archive/ # Rotated logs
โ โ
โ โโโ detectors/ # Pattern detection logs
โ โ โโโ fvg_detector.log
โ โ โโโ order_block_detector.log
โ โ โโโ scanner.log
โ โ
โ โโโ models/ # ML model logs
โ โ โโโ training.log # Training sessions
โ โ โโโ inference.log # Real-time predictions
โ โ โโโ evaluation.log # Model evaluation
โ โ
โ โโโ trading/ # Trading execution logs
โ โ โโโ orders.log # Order execution
โ โ โโโ risk.log # Risk management decisions
โ โ โโโ portfolio.log # Portfolio changes
โ โ
โ โโโ alerts/ # Alert system logs
โ โ โโโ telegram.log
โ โ โโโ notifications.log
โ โ
โ โโโ errors/ # Error logs
โ โ โโโ exceptions.log # All exceptions
โ โ โโโ critical.log # Critical errors only
โ โ
โ โโโ performance/ # Performance monitoring
โ โ โโโ metrics.log # System metrics
โ โ โโโ profiling.log # Performance profiling
โ โ
โ โโโ audit/ # Audit trail
โ โโโ data_access.log # Data access audit
โ โโโ config_changes.log # Configuration changes
โ โโโ model_deployments.log # Model deployment history
โ
โโโ tests/ # Test suite
โ โโโ __init__.py
โ โโโ conftest.py # Pytest configuration and fixtures
โ โ
โ โโโ unit/ # Unit tests
โ โ โโโ test_detectors/
โ โ โโโ test_features/
โ โ โโโ test_models/
โ โ โโโ test_utils/
โ โ
โ โโโ integration/ # Integration tests
โ โ โโโ test_pipeline.py # End-to-end pipeline
โ โ โโโ test_database.py # Database integration
โ โ โโโ test_alerts.py # Alert system integration
โ โ
โ โโโ validation/ # Validation tests
โ โ โโโ test_model_accuracy.py
โ โ โโโ test_backtest_results.py
โ โ โโโ test_data_quality.py
โ โ
โ โโโ fixtures/ # Test data and fixtures
โ โ โโโ sample_data/
โ โ โโโ mock_responses/
โ โ โโโ expected_outputs/
โ โ
โ โโโ performance/ # Performance tests
โ โโโ test_speed.py # Speed benchmarks
โ โโโ test_memory.py # Memory usage tests
โ
โโโ scripts/ # Utility scripts
โ โโโ download_data.py # Download historical data
โ โโโ process_data.py # Batch data processing
โ โโโ run_detection.py # Run pattern detection
โ โโโ train_models.py # Train ML models
โ โโโ evaluate_models.py # Evaluate model performance
โ โโโ backtest.py # Run backtests
โ โโโ live_trading.py # Live trading execution
โ โโโ setup_database.py # Initialize database
โ โโโ migrate_data.py # Data migration
โ โโโ cleanup.py # Cleanup old logs/data
โ โโโ export_labels.py # Export labels from Notion
โ
โโโ notebooks/ # Jupyter notebooks
โ โโโ 01_data_exploration.ipynb
โ โโโ 02_pattern_analysis.ipynb
โ โโโ 03_feature_engineering.ipynb
โ โโโ 04_model_training.ipynb
โ โโโ 05_model_evaluation.ipynb
โ โโโ 06_backtest_analysis.ipynb
โ โโโ 07_label_quality_check.ipynb
โ
โโโ docs/ # Documentation
โ โโโ architecture.md # System architecture
โ โโโ api_reference.md # API documentation
โ โโโ user_guide.md # User guide
โ โโโ deployment.md # Deployment guide
โ โโโ troubleshooting.md # Troubleshooting guide
โ โโโ contributing.md # Contribution guidelines
โ โโโ diagrams/ # Architecture diagrams
โ โโโ examples/ # Code examples
โ
โโโ deployment/ # Deployment configuration
โ โโโ Dockerfile # Docker container
โ โโโ docker-compose.yml # Multi-container setup
โ โโโ .dockerignore # Docker ignore patterns
โ โโโ kubernetes/ # Kubernetes manifests
โ โ โโโ deployment.yaml
โ โ โโโ service.yaml
โ โ โโโ configmap.yaml
โ โโโ systemd/ # Systemd service files
โ โ โโโ ict-trading.service
โ โโโ supervisor/ # Supervisor configuration
โ โโโ ict-trading.conf
โ
โโโ monitoring/ # Monitoring configuration
โ โโโ prometheus.yml # Prometheus config
โ โโโ grafana_dashboards/ # Grafana dashboards
โ โโโ alerts.yml # Alert rules
โ
โโโ backups/ # Backup directory
โโโ database/ # Database backups
โโโ models/ # Model backups
โโโ config/ # Configuration backups
Key File Descriptions
๐ Logging System (src/logging/)
Purpose: Comprehensive logging infrastructure for debugging, monitoring, and auditing
- logger.py: Central logger setup - creates module-specific loggers with configured handlers and formatters
- formatters.py: JSON formatter for machine parsing, colored console formatter, detailed/compact formatters
- handlers.py: Rotating file handlers (size/time-based), database handler for critical events, alert handler for CRITICAL logs
- filters.py: Sensitive data redaction (API keys, passwords), rate limiting for repeated messages
- decorators.py: @log_execution (entry/exit/timing), @log_exceptions (catch and log errors), @log_performance
โ ๏ธ Error Handling (src/core/exceptions.py)
Custom Exception Hierarchy:
ICTTradingException- Base exception with error codes and context dataDataError- Data loading/validation failuresDetectorError- Pattern detection failuresModelError- ML training/inference errorsConfigurationError- Invalid configurationTradingError- Order execution failures
Every exception is logged with full context and stack trace
๐ Data Management (data/)
| Directory | Purpose | Retention |
|---|---|---|
| data/raw/ | Downloaded OHLCV data (Parquet format) | 24 months |
| data/processed/ | Cleaned data, detected patterns, features | 12 months |
| data/labels/ | User labels (versioned), anchor examples | Permanent |
| data/screenshots/ | Chart images for labeling | 6 months |
๐ค Model Versioning (models/)
Every model version includes:
model.pkl- Trained model filehyperparameters.yaml- All configuration usedfeatures.json- Feature list and scaling parametersmetrics.json- Performance metrics (accuracy, precision, recall)training_log.txt- Full training session logfeature_importance.csv- Which features matter most
Symlink "latest/" always points to production model - easy rollback
๐ Logging Categories (logs/)
| Log Type | Contents | Rotation |
|---|---|---|
| application/ | Startup, shutdown, config loading | Daily or 10MB |
| detectors/ | Pattern detection runs, counts, timing | Daily or 10MB |
| models/ | Training, inference, evaluation | Per session |
| trading/ | Orders, fills, risk decisions, P&L | Never rotate (compliance) |
| errors/ | All exceptions with stack traces | Daily or 10MB |
| audit/ | Data access, config changes, deployments | Monthly |
All logs: 30-day retention, compressed archives for older logs
Best Practices Implementation
๐ Security
- All secrets in .env (never committed)
- Sensitive data filtered from logs automatically
- Database credentials from environment variables only
- API keys validated at startup, logged failures
- All external calls use HTTPS
โก Performance
- Async logging (non-blocking for high-volume logs)
- Parquet format for data (10x faster than CSV)
- Database indexes on frequently queried columns
- Connection pooling for database
- Retry logic with exponential backoff for API calls
- Performance profiling logs (identify bottlenecks)
๐งช Testing
- Unit tests for all detectors, features, models
- Integration tests for end-to-end pipeline
- Validation tests ensure model accuracy thresholds met
- Performance tests benchmark speed and memory
- Fixtures provide realistic test data
- Target: 80%+ code coverage
๐ Deployment
- Docker for reproducible environments
- docker-compose for multi-container setup
- Kubernetes manifests for cloud deployment
- systemd service for Linux servers
- Health checks and auto-restart
- Blue-green deployment support