Architecture Docker (8 services), FastAPI, TimescaleDB, Redis, Streamlit. Stratégies : scalping, intraday, swing. MLEngine + RegimeDetector (HMM). BacktestEngine + WalkForwardAnalyzer + Optuna optimizer. Routes API complètes dont /optimize async. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
616 lines
12 KiB
Markdown
616 lines
12 KiB
Markdown
# 🤝 Guide de Contribution - Trading AI Secure
|
|
|
|
## 📋 Table des Matières
|
|
1. [Code of Conduct](#code-of-conduct)
|
|
2. [Comment Contribuer](#comment-contribuer)
|
|
3. [Standards de Code](#standards-de-code)
|
|
4. [Workflow Git](#workflow-git)
|
|
5. [Tests](#tests)
|
|
6. [Documentation](#documentation)
|
|
7. [Review Process](#review-process)
|
|
|
|
---
|
|
|
|
## 📜 Code of Conduct
|
|
|
|
### Nos Valeurs
|
|
|
|
- **Respect** : Traiter tous les contributeurs avec respect
|
|
- **Collaboration** : Travailler ensemble vers un objectif commun
|
|
- **Excellence** : Viser la qualité dans tout ce que nous faisons
|
|
- **Transparence** : Communication ouverte et honnête
|
|
- **Sécurité** : Priorité absolue dans le trading
|
|
|
|
### Comportements Attendus
|
|
|
|
✅ Être accueillant et inclusif
|
|
✅ Respecter les opinions différentes
|
|
✅ Accepter les critiques constructives
|
|
✅ Se concentrer sur ce qui est meilleur pour la communauté
|
|
✅ Faire preuve d'empathie
|
|
|
|
### Comportements Inacceptables
|
|
|
|
❌ Langage ou images inappropriés
|
|
❌ Attaques personnelles ou politiques
|
|
❌ Harcèlement public ou privé
|
|
❌ Publication d'informations privées sans permission
|
|
❌ Conduite non professionnelle
|
|
|
|
---
|
|
|
|
## 🚀 Comment Contribuer
|
|
|
|
### Types de Contributions
|
|
|
|
#### 1. Rapporter des Bugs
|
|
|
|
**Template Issue Bug** :
|
|
|
|
```markdown
|
|
**Description du Bug**
|
|
Description claire et concise du bug.
|
|
|
|
**Étapes pour Reproduire**
|
|
1. Aller à '...'
|
|
2. Cliquer sur '...'
|
|
3. Voir erreur
|
|
|
|
**Comportement Attendu**
|
|
Ce qui devrait se passer.
|
|
|
|
**Comportement Actuel**
|
|
Ce qui se passe réellement.
|
|
|
|
**Screenshots**
|
|
Si applicable.
|
|
|
|
**Environnement**
|
|
- OS: [e.g. Windows 11]
|
|
- Python: [e.g. 3.11.5]
|
|
- Version: [e.g. 0.1.0]
|
|
|
|
**Logs**
|
|
```
|
|
Coller logs pertinents
|
|
```
|
|
```
|
|
|
|
#### 2. Proposer des Features
|
|
|
|
**Template Issue Feature** :
|
|
|
|
```markdown
|
|
**Problème à Résoudre**
|
|
Description du problème que cette feature résout.
|
|
|
|
**Solution Proposée**
|
|
Description de la solution.
|
|
|
|
**Alternatives Considérées**
|
|
Autres approches envisagées.
|
|
|
|
**Contexte Additionnel**
|
|
Informations supplémentaires.
|
|
```
|
|
|
|
#### 3. Améliorer la Documentation
|
|
|
|
- Corriger typos
|
|
- Clarifier explications
|
|
- Ajouter exemples
|
|
- Traduire documentation
|
|
|
|
#### 4. Développer du Code
|
|
|
|
- Nouvelles stratégies
|
|
- Améliorations ML
|
|
- Optimisations performance
|
|
- Nouveaux connecteurs de données
|
|
|
|
---
|
|
|
|
## 💻 Standards de Code
|
|
|
|
### Style Python (PEP 8)
|
|
|
|
```python
|
|
# ✅ BON
|
|
def calculate_position_size(
|
|
portfolio_value: float,
|
|
risk_per_trade: float,
|
|
stop_distance: float
|
|
) -> float:
|
|
"""
|
|
Calcule taille position optimale.
|
|
|
|
Args:
|
|
portfolio_value: Valeur totale du portfolio
|
|
risk_per_trade: Risque par trade (0.0 à 1.0)
|
|
stop_distance: Distance au stop-loss
|
|
|
|
Returns:
|
|
Taille de position en unités
|
|
|
|
Raises:
|
|
ValueError: Si paramètres invalides
|
|
"""
|
|
if portfolio_value <= 0:
|
|
raise ValueError("Portfolio value must be positive")
|
|
|
|
risk_amount = portfolio_value * risk_per_trade
|
|
position_size = risk_amount / stop_distance
|
|
|
|
return position_size
|
|
|
|
|
|
# ❌ MAUVAIS
|
|
def calc_pos(pv,rpt,sd):
|
|
return pv*rpt/sd
|
|
```
|
|
|
|
### Type Hints (Obligatoires)
|
|
|
|
```python
|
|
# ✅ BON
|
|
from typing import Dict, List, Optional
|
|
from datetime import datetime
|
|
|
|
def analyze_market(
|
|
data: pd.DataFrame,
|
|
timeframe: str,
|
|
indicators: List[str]
|
|
) -> Optional[Dict[str, float]]:
|
|
pass
|
|
|
|
|
|
# ❌ MAUVAIS
|
|
def analyze_market(data, timeframe, indicators):
|
|
pass
|
|
```
|
|
|
|
### Docstrings (Google Style)
|
|
|
|
```python
|
|
def backtest_strategy(
|
|
strategy: BaseStrategy,
|
|
data: pd.DataFrame,
|
|
initial_capital: float = 10000.0
|
|
) -> Dict[str, float]:
|
|
"""
|
|
Backtest une stratégie sur données historiques.
|
|
|
|
Cette fonction exécute un backtest complet incluant:
|
|
- Simulation des trades
|
|
- Calcul des métriques
|
|
- Gestion du risque
|
|
|
|
Args:
|
|
strategy: Instance de stratégie à tester
|
|
data: DataFrame avec données OHLCV
|
|
initial_capital: Capital initial en USD
|
|
|
|
Returns:
|
|
Dictionnaire avec métriques:
|
|
- 'total_return': Return total (%)
|
|
- 'sharpe_ratio': Sharpe ratio
|
|
- 'max_drawdown': Drawdown maximum (%)
|
|
- 'win_rate': Taux de réussite (%)
|
|
|
|
Raises:
|
|
ValueError: Si données insuffisantes
|
|
|
|
Example:
|
|
>>> strategy = ScalpingStrategy(config)
|
|
>>> data = load_historical_data('EURUSD', '1h')
|
|
>>> results = backtest_strategy(strategy, data)
|
|
>>> print(f"Sharpe: {results['sharpe_ratio']:.2f}")
|
|
Sharpe: 1.85
|
|
"""
|
|
pass
|
|
```
|
|
|
|
### Naming Conventions
|
|
|
|
```python
|
|
# Classes: PascalCase
|
|
class RiskManager:
|
|
pass
|
|
|
|
# Functions/Methods: snake_case
|
|
def calculate_sharpe_ratio():
|
|
pass
|
|
|
|
# Constants: UPPER_SNAKE_CASE
|
|
MAX_POSITION_SIZE = 0.05
|
|
DEFAULT_RISK_PER_TRADE = 0.02
|
|
|
|
# Private: _leading_underscore
|
|
def _internal_helper():
|
|
pass
|
|
|
|
# Variables: snake_case
|
|
portfolio_value = 10000.0
|
|
current_drawdown = 0.05
|
|
```
|
|
|
|
### Imports Organization
|
|
|
|
```python
|
|
# 1. Standard library
|
|
import os
|
|
import sys
|
|
from datetime import datetime, timedelta
|
|
from typing import Dict, List, Optional
|
|
|
|
# 2. Third-party
|
|
import numpy as np
|
|
import pandas as pd
|
|
from fastapi import FastAPI, HTTPException
|
|
|
|
# 3. Local
|
|
from src.core.risk_manager import RiskManager
|
|
from src.strategies.base_strategy import BaseStrategy
|
|
from src.utils.logger import get_logger
|
|
```
|
|
|
|
---
|
|
|
|
## 🌿 Workflow Git
|
|
|
|
### Branches
|
|
|
|
```
|
|
main
|
|
├── develop
|
|
│ ├── feature/add-new-strategy
|
|
│ ├── feature/improve-ml-engine
|
|
│ ├── bugfix/fix-risk-calculation
|
|
│ └── hotfix/critical-security-patch
|
|
```
|
|
|
|
**Conventions de nommage** :
|
|
|
|
- `feature/description` : Nouvelles fonctionnalités
|
|
- `bugfix/description` : Corrections de bugs
|
|
- `hotfix/description` : Corrections urgentes
|
|
- `docs/description` : Documentation
|
|
- `refactor/description` : Refactoring
|
|
- `test/description` : Ajout de tests
|
|
|
|
### Workflow Contribution
|
|
|
|
#### 1. Fork et Clone
|
|
|
|
```bash
|
|
# Fork sur GitHub
|
|
# Puis cloner votre fork
|
|
git clone https://github.com/VOTRE-USERNAME/trading-ai-secure.git
|
|
cd trading-ai-secure
|
|
|
|
# Ajouter upstream
|
|
git remote add upstream https://github.com/ORIGINAL-OWNER/trading-ai-secure.git
|
|
```
|
|
|
|
#### 2. Créer Branche
|
|
|
|
```bash
|
|
# Mettre à jour develop
|
|
git checkout develop
|
|
git pull upstream develop
|
|
|
|
# Créer branche feature
|
|
git checkout -b feature/ma-nouvelle-feature
|
|
```
|
|
|
|
#### 3. Développer
|
|
|
|
```bash
|
|
# Faire vos modifications
|
|
# ...
|
|
|
|
# Commiter régulièrement
|
|
git add .
|
|
git commit -m "feat: add new scalping indicator"
|
|
|
|
# Suivre conventions de commit (voir ci-dessous)
|
|
```
|
|
|
|
#### 4. Tester
|
|
|
|
```bash
|
|
# Lancer tests
|
|
pytest tests/
|
|
|
|
# Vérifier couverture
|
|
pytest --cov=src tests/
|
|
|
|
# Linter
|
|
pylint src/
|
|
black src/
|
|
isort src/
|
|
```
|
|
|
|
#### 5. Push et Pull Request
|
|
|
|
```bash
|
|
# Push vers votre fork
|
|
git push origin feature/ma-nouvelle-feature
|
|
|
|
# Créer Pull Request sur GitHub
|
|
# Remplir template PR
|
|
```
|
|
|
|
### Conventions de Commit
|
|
|
|
Format : `<type>(<scope>): <description>`
|
|
|
|
**Types** :
|
|
|
|
- `feat`: Nouvelle fonctionnalité
|
|
- `fix`: Correction de bug
|
|
- `docs`: Documentation
|
|
- `style`: Formatage (pas de changement de code)
|
|
- `refactor`: Refactoring
|
|
- `test`: Ajout de tests
|
|
- `chore`: Maintenance
|
|
|
|
**Exemples** :
|
|
|
|
```bash
|
|
feat(strategies): add VWAP indicator to intraday strategy
|
|
fix(risk): correct position sizing calculation
|
|
docs(readme): update installation instructions
|
|
test(backtesting): add Monte Carlo simulation tests
|
|
refactor(ml): optimize feature engineering pipeline
|
|
```
|
|
|
|
---
|
|
|
|
## 🧪 Tests
|
|
|
|
### Structure Tests
|
|
|
|
```
|
|
tests/
|
|
├── unit/
|
|
│ ├── test_risk_manager.py
|
|
│ ├── test_strategies.py
|
|
│ └── test_ml_engine.py
|
|
├── integration/
|
|
│ ├── test_data_sources.py
|
|
│ └── test_ig_api.py
|
|
├── e2e/
|
|
│ └── test_full_trading_loop.py
|
|
└── fixtures/
|
|
└── sample_data.py
|
|
```
|
|
|
|
### Écrire Tests
|
|
|
|
```python
|
|
# tests/unit/test_risk_manager.py
|
|
|
|
import pytest
|
|
from src.core.risk_manager import RiskManager
|
|
|
|
class TestRiskManager:
|
|
"""Tests pour RiskManager"""
|
|
|
|
@pytest.fixture
|
|
def risk_manager(self):
|
|
"""Fixture RiskManager"""
|
|
return RiskManager()
|
|
|
|
def test_singleton_pattern(self):
|
|
"""Vérifie pattern singleton"""
|
|
rm1 = RiskManager()
|
|
rm2 = RiskManager()
|
|
assert rm1 is rm2
|
|
|
|
def test_validate_trade_success(self, risk_manager):
|
|
"""Test validation trade valide"""
|
|
is_valid, error = risk_manager.validate_trade(
|
|
symbol='EURUSD',
|
|
quantity=1000,
|
|
price=1.1000,
|
|
stop_loss=1.0950,
|
|
take_profit=1.1100,
|
|
strategy='intraday'
|
|
)
|
|
|
|
assert is_valid is True
|
|
assert error is None
|
|
|
|
def test_validate_trade_no_stop_loss(self, risk_manager):
|
|
"""Test rejet si pas de stop-loss"""
|
|
is_valid, error = risk_manager.validate_trade(
|
|
symbol='EURUSD',
|
|
quantity=1000,
|
|
price=1.1000,
|
|
stop_loss=None, # Pas de stop-loss
|
|
take_profit=1.1100,
|
|
strategy='intraday'
|
|
)
|
|
|
|
assert is_valid is False
|
|
assert "stop-loss" in error.lower()
|
|
|
|
@pytest.mark.parametrize("position_size,expected", [
|
|
(0.01, True), # 1% OK
|
|
(0.05, True), # 5% OK
|
|
(0.10, False), # 10% trop grand
|
|
])
|
|
def test_position_size_limits(self, risk_manager, position_size, expected):
|
|
"""Test limites taille position"""
|
|
# ... test paramétré
|
|
```
|
|
|
|
### Coverage Minimum
|
|
|
|
- **Global** : 85%
|
|
- **Core modules** : 90%
|
|
- **Stratégies** : 85%
|
|
- **ML** : 80%
|
|
- **UI** : 70%
|
|
|
|
---
|
|
|
|
## 📚 Documentation
|
|
|
|
### Documentation Code
|
|
|
|
Chaque module doit avoir :
|
|
|
|
1. **Module docstring** : Description du module
|
|
2. **Class docstrings** : Description de la classe
|
|
3. **Method docstrings** : Description des méthodes
|
|
4. **Type hints** : Sur tous les paramètres et retours
|
|
|
|
### Documentation Utilisateur
|
|
|
|
Mettre à jour si changements :
|
|
|
|
- `README.md` : Vue d'ensemble
|
|
- `docs/GETTING_STARTED.md` : Guide démarrage
|
|
- `docs/ARCHITECTURE.md` : Architecture
|
|
- `docs/API.md` : Documentation API
|
|
|
|
### Exemples
|
|
|
|
Ajouter exemples d'utilisation :
|
|
|
|
```python
|
|
# examples/strategies/custom_strategy_example.py
|
|
|
|
"""
|
|
Exemple de création d'une stratégie custom.
|
|
|
|
Cet exemple montre comment:
|
|
- Hériter de BaseStrategy
|
|
- Implémenter les méthodes requises
|
|
- Configurer les paramètres
|
|
- Backtester la stratégie
|
|
"""
|
|
|
|
from src.strategies.base_strategy import BaseStrategy
|
|
|
|
class MyCustomStrategy(BaseStrategy):
|
|
"""Ma stratégie personnalisée"""
|
|
|
|
def analyze(self, data):
|
|
# Implémentation
|
|
pass
|
|
|
|
# Usage
|
|
if __name__ == "__main__":
|
|
strategy = MyCustomStrategy(config)
|
|
results = backtest_strategy(strategy, data)
|
|
print(results)
|
|
```
|
|
|
|
---
|
|
|
|
## 👀 Review Process
|
|
|
|
### Checklist PR
|
|
|
|
Avant de soumettre PR, vérifier :
|
|
|
|
- [ ] Code suit standards (PEP 8, type hints, docstrings)
|
|
- [ ] Tests ajoutés et passent (coverage > 85%)
|
|
- [ ] Documentation mise à jour
|
|
- [ ] Pas de secrets/credentials dans le code
|
|
- [ ] Commits suivent conventions
|
|
- [ ] Branch à jour avec develop
|
|
- [ ] Pas de conflits
|
|
|
|
### Template Pull Request
|
|
|
|
```markdown
|
|
## Description
|
|
Description claire des changements.
|
|
|
|
## Type de Changement
|
|
- [ ] Bug fix
|
|
- [ ] Nouvelle feature
|
|
- [ ] Breaking change
|
|
- [ ] Documentation
|
|
|
|
## Tests
|
|
- [ ] Tests unitaires ajoutés
|
|
- [ ] Tests d'intégration ajoutés
|
|
- [ ] Tous les tests passent
|
|
- [ ] Coverage > 85%
|
|
|
|
## Checklist
|
|
- [ ] Code suit standards
|
|
- [ ] Documentation mise à jour
|
|
- [ ] Pas de secrets dans le code
|
|
- [ ] Commits conventionnels
|
|
|
|
## Screenshots (si applicable)
|
|
|
|
## Notes Additionnelles
|
|
```
|
|
|
|
### Process de Review
|
|
|
|
1. **Automated Checks** : CI/CD vérifie tests, linting
|
|
2. **Code Review** : Au moins 1 reviewer approuve
|
|
3. **Testing** : Reviewer teste localement
|
|
4. **Merge** : Squash and merge vers develop
|
|
|
|
---
|
|
|
|
## 🎯 Priorités Contributions
|
|
|
|
### High Priority
|
|
|
|
- 🔴 Corrections de bugs critiques
|
|
- 🔴 Améliorations sécurité
|
|
- 🔴 Optimisations performance
|
|
|
|
### Medium Priority
|
|
|
|
- 🟡 Nouvelles stratégies
|
|
- 🟡 Améliorations ML
|
|
- 🟡 Documentation
|
|
|
|
### Low Priority
|
|
|
|
- 🟢 Refactoring
|
|
- 🟢 Optimisations mineures
|
|
- 🟢 Traductions
|
|
|
|
---
|
|
|
|
## 💬 Communication
|
|
|
|
### Channels
|
|
|
|
- **GitHub Issues** : Bugs, features
|
|
- **GitHub Discussions** : Questions, idées
|
|
- **Discord** : Chat temps réel
|
|
- **Email** : contact@trading-ai-secure.com
|
|
|
|
### Réponse
|
|
|
|
- Issues : < 48h
|
|
- PRs : < 72h
|
|
- Questions : < 24h
|
|
|
|
---
|
|
|
|
## 🏆 Reconnaissance
|
|
|
|
Les contributeurs sont reconnus dans :
|
|
|
|
- `CONTRIBUTORS.md`
|
|
- Release notes
|
|
- Documentation
|
|
|
|
---
|
|
|
|
**Merci de contribuer à Trading AI Secure ! 🚀**
|