# 📊 SYSTÈME DE STRATÉGIE HYBRIDE BULL/BEAR/RANGE

## 🎯 Vue d'ensemble

Système de trading adaptatif qui switche entre 3 stratégies selon les conditions du marché :
- **BULL Strategy** : Positions LONG en marché haussier
- **BEAR Strategy** : Positions SHORT en marché baissier
- **V10 RANGE Strategy** : Trading de range (DÉJÀ OPTIMISÉE +132% PnL)

## 🏗️ Architecture

### 1. Détection de Marché (`market_detector_simple.py`)

**Priorité de détection :**
1. **RANGE** : Utilise `V10RangeDetector.is_range_market()` (cohérence avec V10)
2. **BULL vs BEAR** : Si pas RANGE, calcule scores de tendance

```python
# Exemple
detector = MarketDetector()
analysis = detector.detect(df)
# → regime: BULL/BEAR/RANGE/UNCERTAIN
```

### 2. Stratégies Spécialisées

#### **V10 Range Strategy** (params FIXES)
```python
{
    'rsi_oversold': 35,
    'rsi_overbought': 78,
    'range_atr_threshold': 0.32,
    'sl_atr_multiplier': 1.64,
    'trailing_pct': 0.05,
    'leverage': 250
}
```
✅ **NE JAMAIS MODIFIER** - Déjà optimisée

#### **Bull Strategy** (`bull_strategy.py`)
- Entry types: PULLBACK, BREAKOUT, MOMENTUM
- Direction: LONG uniquement
- Params optimisés automatiquement

#### **Bear Strategy** (`bear_strategy.py`)
- Entry types: RALLY SHORT, RESISTANCE REJECTION, BREAKDOWN
- Direction: SHORT uniquement
- Params optimisés automatiquement

### 3. Orchestrateur (`hybrid_strategy.py`)

Route les signaux selon le régime détecté :
```python
strategy = HybridStrategy()
signal = strategy.analyze('BTC', df)
# → Utilise bull_strategy, bear_strategy ou range_strategy
```

## 🔄 Optimisation Continue

### Service d'Optimisation (`continuous_optimizer_service.py`)

**Cycle automatique toutes les 6h :**

1. **Téléchargement** : Récupère 14 jours de candles BTC (5min) depuis Binance
2. **Optimisation** : Teste 200 configs BULL/BEAR (V10 Range fixe)
3. **Sauvegarde** : Exporte meilleurs params dans `optimal_params.json`
4. **Attente** : Sleep 6h puis recommence

**Fichiers générés :**
- `optimal_params.json` : Meilleurs params actuels
- `optimization_results_YYYYMMDD_HHMMSS.json` : Résultats détaillés
- `candles_14d_latest.csv` : Candles les plus récentes

### Lancer le service

```bash
# Mode manuel (1 seule fois)
python3 continuous_optimizer_service.py --once

# Mode continu toutes les 6h
python3 continuous_optimizer_service.py --interval 6

# Personnaliser
python3 continuous_optimizer_service.py \
  --interval 12 \      # Toutes les 12h
  --lookback 7 \       # 7 jours de données
  --tests 500          # 500 tests par run
```

### Service systemd

```bash
# Activer
systemctl enable crypto-optimizer.service

# Démarrer
systemctl start crypto-optimizer.service

# Status
systemctl status crypto-optimizer.service

# Logs
journalctl -u crypto-optimizer.service -f
```

## 📈 Optimisation Manuelle

### Optimiser BULL/BEAR sur 14 jours

```bash
# Télécharger candles
python3 << 'EOF'
import pandas as pd
from binance.client import Client
from datetime import datetime, timedelta

client = Client()
end_time = datetime.now()
start_time = end_time - timedelta(days=14)

klines = client.get_historical_klines(
    'BTCUSDT',
    Client.KLINE_INTERVAL_5MINUTE,
    start_time.strftime('%Y-%m-%d %H:%M:%S'),
    end_time.strftime('%Y-%m-%d %H:%M:%S')
)

df = pd.DataFrame(klines, columns=[
    'timestamp', 'open', 'high', 'low', 'close', 'volume',
    'close_time', 'quote_volume', 'trades', 'taker_buy_base',
    'taker_buy_quote', 'ignore'
])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
for col in ['open', 'high', 'low', 'close', 'volume']:
    df[col] = df[col].astype(float)
df.to_csv('btc_14days.csv', index=False)
print(f"✅ {len(df)} candles sauvegardées")
EOF

# Lancer optimisation
nohup python3 optimize_bull_bear.py > optimize_14d.log 2>&1 &

# Suivre progression
tail -f optimize_14d.log
```

### Analyser résultats

```python
import json

# Charger résultats
results = json.load(open('bull_bear_14d_results.json'))

# Filtrer profitables
profitable = [r for r in results
              if r['pnl_pct'] > 0 and r['profit_factor'] > 1.0]

# Meilleur config
best = sorted(profitable, key=lambda x: x['pnl_pct'], reverse=True)[0]

print(f"Meilleur PnL: {best['pnl_pct']:+.2f}%")
print(f"Config: {best['config']}")
```

## 📊 Monitoring

### Script de monitoring rapide

```bash
#!/bin/bash
# check_optimizer.sh

python3 << 'EOF'
import json
from pathlib import Path

if Path('bull_bear_14d_results.json').exists():
    r = json.load(open('bull_bear_14d_results.json'))
    profitable = [x for x in r if x['pnl_pct'] > 0 and x['profit_factor'] > 1.0]

    print(f'Tests: {len(r)}/200')
    print(f'Profitables: {len(profitable)} ({len(profitable)/len(r)*100:.1f}%)')

    if profitable:
        profitable.sort(key=lambda x: x["pnl_pct"], reverse=True)
        print(f'\nTOP 3:')
        for i, x in enumerate(profitable[:3], 1):
            print(f'{i}. PnL {x["pnl_pct"]:+.1f}% | PF {x["profit_factor"]:.2f} | {x["trades_by_strategy"]}')
else:
    print('⏳ En cours...')
EOF
```

## 🚀 Déploiement

### 1. Attendre fin d'optimisation

```bash
# Vérifier
./check_optimizer.sh

# Ou attendre message dans logs
tail -f optimize_14d.log
```

### 2. Charger params optimaux

```python
import json

# Charger
optimal = json.load(open('optimal_params.json'))

# Appliquer à la stratégie
strategy.bull_strategy.params.update(optimal['best_config']['bull.*'])
strategy.bear_strategy.params.update(optimal['best_config']['bear.*'])
# V10 Range reste inchangée
```

### 3. Intégrer au bot live

```python
# Dans live_trader_v10_onchain.py
from hybrid_strategy import HybridStrategy

# Remplacer stratégie actuelle par hybride
self.strategy = HybridStrategy()

# Charger params optimaux si disponibles
if Path('optimal_params.json').exists():
    optimal = json.load(open('optimal_params.json'))
    self.strategy.load_optimal_params(optimal)
```

## 📁 Fichiers du Système

```
apollo_degen_bot/
├── market_detector_simple.py        # Détection régime marché
├── bull_strategy.py                 # Stratégie BULL
├── bear_strategy.py                 # Stratégie BEAR
├── hybrid_strategy.py               # Orchestrateur
├── optimize_bull_bear.py            # Optimiseur manuel
├── continuous_optimizer_service.py  # Service optimisation auto
├── analyze_bull_bear_results.py     # Analyse résultats
├── btc_14days.csv                   # Candles 14j
├── bull_bear_14d_results.json       # Résultats optimisation
└── optimal_params.json              # Meilleurs params actuels
```

## ⚙️ Configuration

### Paramètres BULL (à optimiser)

```python
{
    'min_trend_strength': 50-60,      # Score tendance minimum
    'rsi_pullback_max': 30-45,        # RSI max pour pullback
    'rsi_breakout_min': 55-70,        # RSI min pour breakout
    'volume_spike_threshold': 1.5-3.0, # Multiplicateur volume
    'sl_atr_multiplier': 1.0-3.0,     # Stop-loss (ATR)
    'tp_atr_multiplier': 2.0-5.0,     # Take-profit (ATR)
    'trailing_pct': 0.05-0.20,        # Trailing stop (%)
    'min_confidence': 60-75,          # Confiance minimum (%)
    'leverage': 50-250                # Leverage
}
```

### Paramètres BEAR (à optimiser)

```python
{
    'min_trend_strength': 50-60,
    'rsi_rally_min': 45-60,           # RSI min pour rally short
    'rsi_overbought': 65-75,          # RSI overbought
    'volume_spike_threshold': 1.5-3.0,
    'sl_atr_multiplier': 1.0-2.5,     # SL plus serré en BEAR
    'tp_atr_multiplier': 2.5-4.5,
    'trailing_pct': 0.05-0.15,
    'min_confidence': 60-75,
    'leverage': 50-200
}
```

## 🔍 Troubleshooting

### Optimisation bloquée

```bash
# Vérifier processus
ps aux | grep optimize_bull_bear

# Vérifier logs
tail -100 optimize_14d.log

# Redémarrer si bloqué
pkill -f optimize_bull_bear
nohup python3 optimize_bull_bear.py > optimize_14d.log 2>&1 &
```

### Service ne démarre pas

```bash
# Vérifier status
systemctl status crypto-optimizer.service

# Voir logs d'erreur
journalctl -u crypto-optimizer.service -n 50

# Recharger systemd
systemctl daemon-reload
systemctl restart crypto-optimizer.service
```

### Pas de configs profitables

Si l'optimisation ne trouve aucune config profitable :
- Vérifier période de marché (besoin de variation BULL/BEAR/RANGE)
- Augmenter nombre de tests (--tests 500)
- Élargir ranges de paramètres
- Vérifier qualité des candles

## 📈 Résultats Attendus

### Sur 14 jours de données variées

- **Taux profitable** : 30-50% des configs
- **Distribution trades** : Mix BULL/BEAR/RANGE selon période
- **PnL moyen** : +50% à +200%
- **Profit Factor** : >1.5

### Sur 24h mono-BULL (observé)

- **Taux profitable** : 44%
- **Tous BULL** : 100% des trades
- **PnL** : +191.8%
- **PF** : inf (aucune perte)

---

*Dernière mise à jour: 2025-10-30*
