This guide covers the development workflow, architecture, and best practices for ForexSmartBot.
- Development Setup
- Architecture Overview
- Code Organization
- Development Workflow
- Testing
- Code Quality
- Documentation
- Release Process
- Contributing
- Python 3.11+
- Git
- Virtual environment (recommended)
-
Clone the repository:
git clone https://github.com/voxhash/ForexSmartBot.git cd ForexSmartBot -
Create virtual environment:
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies:
pip install -r requirements.txt pip install -r requirements-dev.txt
-
Install pre-commit hooks:
pre-commit install
-
Run tests to verify setup:
python -m pytest
-
Install Python extension
-
Install recommended extensions:
- Python
- Pylance
- Black Formatter
- Ruff
- GitLens
-
Configure settings (
.vscode/settings.json):{ "python.defaultInterpreterPath": "./venv/bin/python", "python.formatting.provider": "black", "python.linting.enabled": true, "python.linting.ruffEnabled": true, "editor.formatOnSave": true, "editor.codeActionsOnSave": { "source.organizeImports": true } }
- Open project
- Configure Python interpreter to use virtual environment
- Enable Black formatter
- Configure Ruff as external tool
ForexSmartBot follows a modular, layered architecture:
forexsmartbot/
├── core/ # Core business logic
│ ├── interfaces.py # Abstract base classes
│ ├── portfolio.py # Portfolio management
│ └── risk_engine.py # Risk management
├── adapters/ # External integrations
│ ├── brokers/ # Broker implementations
│ └── data/ # Data providers
├── strategies/ # Trading strategies
├── services/ # Application services
│ ├── backtest.py # Backtesting engine
│ ├── controller.py # Trading controller
│ └── persistence.py # Data persistence
└── ui/ # User interface
├── main_window.py # Main window
├── settings_dialog.py # Settings dialog
├── charts.py # Charting widgets
└── theme.py # Theme management
- Separation of Concerns: Each layer has a specific responsibility
- Dependency Inversion: High-level modules don't depend on low-level modules
- Interface Segregation: Small, focused interfaces
- Open/Closed Principle: Open for extension, closed for modification
Contains the fundamental business logic:
interfaces.py: Abstract base classes defining contractsportfolio.py: Portfolio state managementrisk_engine.py: Risk calculation and position sizing
Handles external system integration:
brokers/: Broker implementations (Paper, MT4, REST)data/: Data provider implementations (YFinance, CSV)
Trading strategy implementations:
- Each strategy is a separate module
- Implements
IStrategyinterface - Contains strategy-specific logic
Application services that orchestrate components:
controller.py: Main trading controllerbacktest.py: Backtesting enginepersistence.py: Data persistence
User interface components:
main_window.py: Main application windowsettings_dialog.py: Settings managementcharts.py: Charting functionalitytheme.py: Theme management
-
Create feature branch:
git checkout -b feature/your-feature-name
-
Make changes:
- Write code following style guidelines
- Add tests for new functionality
- Update documentation as needed
-
Test changes:
python -m pytest python -m ruff check . python -m mypy forexsmartbot/ -
Commit changes:
git add . git commit -m "feat: add your feature description"
-
Create bugfix branch:
git checkout -b bugfix/issue-description
-
Fix the issue:
- Write failing test first (if applicable)
- Implement fix
- Ensure all tests pass
-
Commit fix:
git commit -m "fix: description of the fix"
-
Push branch:
git push origin feature/your-feature-name
-
Create Pull Request:
- Use the PR template
- Provide clear description
- Link related issues
-
Code Review:
- Address reviewer feedback
- Update tests if needed
- Update documentation
-
Merge:
- Squash and merge
- Delete feature branch
tests/
├── __init__.py
├── test_risk.py # Risk engine tests
├── test_strategies.py # Strategy tests
├── test_backtest.py # Backtesting tests
└── integration/ # Integration tests
├── __init__.py
└── test_full_workflow.py
# Run all tests
python -m pytest
# Run specific test file
python -m pytest tests/test_risk.py
# Run with coverage
python -m pytest --cov=forexsmartbot
# Run specific test
python -m pytest tests/test_risk.py::TestRiskEngine::test_position_sizing- Test Naming: Use descriptive names that explain what is being tested
- Arrange-Act-Assert: Structure tests clearly
- Test Coverage: Aim for high coverage of business logic
- Mocking: Mock external dependencies
Example:
def test_position_sizing_with_volatility_targeting(self):
"""Test that position size is reduced for high volatility."""
# Arrange
config = RiskConfig(volatility_target=0.02)
engine = RiskEngine(config)
# Act
size_high_vol = engine.calculate_position_size("EURUSD", "SMA", 10000, 0.05)
size_low_vol = engine.calculate_position_size("EURUSD", "SMA", 10000, 0.01)
# Assert
assert size_high_vol < size_low_vol- Python Style: Follow PEP 8
- Line Length: 100 characters maximum
- Imports: Use absolute imports, group by standard/third-party/local
- Docstrings: Use Google style docstrings
- Type Hints: Use type hints for all public functions
- Ruff: Linting and formatting
- Black: Code formatting
- MyPy: Type checking
- Pre-commit: Automated quality checks
Configured hooks:
ruff: Lintingblack: Formattingmypy: Type checking
docs/
├── README.md # Main documentation
├── Installation-Guide.md # Installation instructions
├── Quick-Start-Tutorial.md # Getting started
├── Configuration-Guide.md # Configuration
├── STRATEGIES.md # Strategy development
├── RISK.md # Risk management
├── EXTENDING_BROKERS.md # Broker development
└── DEVELOPMENT.md # This file
- Use Markdown: All docs in Markdown format
- Code Examples: Include working code examples
- Screenshots: Add UI screenshots where helpful
- Keep Updated: Update docs with code changes
def calculate_position_size(self, symbol: str, strategy: str,
balance: float, volatility: Optional[float]) -> float:
"""Calculate position size using risk management rules.
Args:
symbol: Trading symbol (e.g., 'EURUSD')
strategy: Strategy name (e.g., 'SMA_Crossover')
balance: Current account balance
volatility: Recent volatility (0.0-1.0)
Returns:
Position size in account currency
Raises:
ValueError: If balance is negative
"""Follow Semantic Versioning:
- MAJOR: Breaking changes
- MINOR: New features (backward compatible)
- PATCH: Bug fixes (backward compatible)
-
Update version:
# Update pyproject.toml version # Update CHANGELOG.md
-
Create release branch:
git checkout -b release/v3.0.0
-
Final testing:
python -m pytest python -m ruff check . python -m mypy forexsmartbot/ -
Create tag:
git tag v3.0.0 git push origin v3.0.0
-
GitHub Actions will:
- Build the package
- Run tests
- Create GitHub release
- Publish to PyPI
-
Test installation:
pip install forexsmartbot==3.0.0
-
Test functionality:
python -m forexsmartbot
- Fork the repository
- Clone your fork
- Create feature branch
- Make changes
- Submit pull request
- Code Quality: Follow style guidelines
- Tests: Add tests for new features
- Documentation: Update docs as needed
- Commits: Use conventional commit messages
- PRs: Provide clear descriptions
type(scope): description
[optional body]
[optional footer]
Types:
feat: New featurefix: Bug fixdocs: Documentation changesstyle: Code style changesrefactor: Code refactoringtest: Test changeschore: Maintenance tasks
bug: Something isn't workingenhancement: New feature or requestdocumentation: Documentation improvementsgood first issue: Good for newcomershelp wanted: Extra attention neededquestion: Further information is requested
- Import Errors: Ensure virtual environment is activated
- Test Failures: Check test data and dependencies
- Type Errors: Run
mypyfor detailed type checking - Style Issues: Run
ruffandblackto fix
- Check existing issues
- Search documentation
- Create new issue with:
- Clear description
- Steps to reproduce
- Expected vs actual behavior
- Environment details
- Data Processing: Use pandas efficiently
- Memory Usage: Avoid large data copies
- UI Responsiveness: Use threading for long operations
- Database: Use connection pooling
# Profile memory usage
python -m memory_profiler app.py
# Profile execution time
python -m cProfile app.py- API Keys: Never commit API keys
- Sensitive Data: Use environment variables
- Input Validation: Validate all inputs
- Dependencies: Keep dependencies updated
- No hardcoded secrets
- Input validation implemented
- Dependencies up to date
- Security headers configured
- Error messages don't leak information