"""
Analyse et redéfinition des objectifs de patterns basée sur les opportunités réelles
Cas d'étude: SOPH creux 11h06, ETH 11h35, WIFUSDT 17h36
"""
import json
from datetime import datetime

print("=" * 100)
print("📊 ANALYSE DES OBJECTIFS DE PATTERNS - REDÉFINITION")
print("=" * 100)

# Définir les types d'opportunités à détecter
OPPORTUNITY_TYPES = {
    "CREUX_REBOND": {
        "description": "Acheter au creux juste avant rebond violent",
        "exemples": ["SOPH 11h06 (creux → +1.7% en 37min)", "WIFUSDT 17h36"],
        "indicateurs_clés": [
            "RSI < 30 (oversold)",
            "Prix touche BB inférieure",
            "Momentum commence à remonter (>0.01%)",
            "Volume augmente",
            "EMA peut être bearish (c'est un rebond technique)"
        ],
        "pattern_cible": "CREUX_REBOUND_EARLY",
        "score_min": 75,
        "timing": "Très important - acheter AU creux, pas après",
        "risque": "Faible si quick-exit rapide",
        "reward": "Fort (+1.5% à +3% en <1h)"
    },
    
    "SQUEEZE_BREAKOUT": {
        "description": "Consolidation suivie d'explosion haussière",
        "exemples": ["ETH après squeeze", "BTC breakout"],
        "indicateurs_clés": [
            "Bollinger Bands serrées (squeeze)",
            "Volume faible puis explosion",
            "RSI 40-60 (neutre)",
            "Momentum soudain >0.3%",
            "Direction claire (haussière)"
        ],
        "pattern_cible": "SQUEEZE_WAITING",
        "score_min": 80,
        "timing": "Attendre confirmation du breakout",
        "risque": "Moyen - faux breakouts possibles",
        "reward": "Très fort (+2% à +5%)"
    },
    
    "CONTINUATION_TREND": {
        "description": "Continuation d'une tendance haussière établie",
        "exemples": ["BTC en bull run", "ETH momentum"],
        "indicateurs_clés": [
            "EMA 8 > EMA 21 (bullish)",
            "RSI 50-70 (haussier sans overbought)",
            "Momentum constant >0.2%",
            "Volume soutenu",
            "Prix au-dessus EMA"
        ],
        "pattern_cible": "EMA_BULLISH",
        "score_min": 70,
        "timing": "Acheter sur pullback dans la tendance",
        "risque": "Faible dans tendance confirmée",
        "reward": "Moyen mais régulier (+1% à +2%)"
    },
    
    "PULLBACK_TREND": {
        "description": "Retour sur support dans tendance haussière",
        "exemples": ["Pullback sur EMA 21", "Retest support"],
        "indicateurs_clés": [
            "Tendance générale haussière",
            "Prix revient sur EMA 21",
            "RSI 40-50 (correction saine)",
            "Momentum ralentit mais >0",
            "Support tient"
        ],
        "pattern_cible": "PULLBACK",
        "score_min": 75,
        "timing": "Attendre rebond sur support",
        "risque": "Moyen - support peut casser",
        "reward": "Moyen (+1% à +2.5%)"
    },
    
    "REVERSAL_MOMENTUM": {
        "description": "Renversement de tendance baissière → haussière",
        "exemples": ["Rebond après chute", "V-shape recovery"],
        "indicateurs_clés": [
            "Tendance baissière s'affaiblit",
            "Momentum passe de négatif → positif",
            "RSI sort de oversold (>30)",
            "Volume augmente sur rebond",
            "EMA slope devient >0"
        ],
        "pattern_cible": "MOMENTUM_REVERSAL",
        "score_min": 70,
        "timing": "Dès confirmation du reversal",
        "risque": "Élevé - peut être faux signal",
        "reward": "Fort si confirmé (+2% à +4%)"
    }
}

# Patterns à ÉVITER (basé sur analyse 108 trades)
PATTERNS_TO_BLOCK = {
    "HIGH_SCORE_OVERRIDE": {
        "raison": "0% win rate (0/6 trades), -1.03% avg",
        "action": "DÉSACTIVÉ COMPLÈTEMENT",
        "problème": "Score élevé ne garantit pas la qualité"
    },
    "POSSIBLE": {
        "raison": "15% win rate (8/52 trades), -0.28% avg, 98% quick-exit",
        "action": "SCORE MIN 80 (au lieu de 65)",
        "problème": "Trop permissif, achète n'importe quoi"
    },
    "EARLY_BREAKOUT": {
        "raison": "14% win rate (1/7 trades), -1.15% avg",
        "action": "MOMENTUM 1.0% (quasi-impossible)",
        "problème": "Achète trop tôt avant confirmation"
    },
    "UNKNOWN": {
        "raison": "10% win rate (1/10 trades), -0.54% avg",
        "action": "NE DEVRAIT JAMAIS TRADER",
        "problème": "Pattern par défaut = problème de détection"
    }
}

print("\n" + "=" * 100)
print("✅ PATTERNS VIABLES (à favoriser)")
print("=" * 100)

for pattern_name, config in OPPORTUNITY_TYPES.items():
    print(f"\n🎯 {pattern_name} → {config['pattern_cible']}")
    print(f"   Description: {config['description']}")
    print(f"   Exemples: {', '.join(config['exemples'])}")
    print(f"   Score minimum: {config['score_min']}")
    print(f"   Timing: {config['timing']}")
    print(f"   Risk/Reward: {config['risque']} / {config['reward']}")
    print("   Indicateurs clés:")
    for ind in config['indicateurs_clés']:
        print(f"      • {ind}")

print("\n" + "=" * 100)
print("🚫 PATTERNS À BLOQUER/LIMITER")
print("=" * 100)

for pattern_name, config in PATTERNS_TO_BLOCK.items():
    print(f"\n❌ {pattern_name}")
    print(f"   Raison: {config['raison']}")
    print(f"   Action: {config['action']}")
    print(f"   Problème: {config['problème']}")

# Analyse du cas SOPH
print("\n" + "=" * 100)
print("📈 CAS D'ÉTUDE: SOPH 11h06 (creux manqué)")
print("=" * 100)

with open('trade_history.json', 'r') as f:
    trades = json.load(f)
    soph_trades = [t for t in trades if t['symbol'] == 'SOPHUSDT']

print(f"\nHistorique SOPH: {len(soph_trades)} trades")
for i, trade in enumerate(soph_trades, 1):
    entry = datetime.fromisoformat(trade['entry_time']).strftime('%d/%m %Hh%M')
    exit_t = datetime.fromisoformat(trade['exit_time']).strftime('%d/%m %Hh%M')
    print(f"  {i}. {trade['pattern']:20} {entry} → {exit_t}  P&L: {trade['pnl']:+.2f}%")

print(f"\n💡 ANALYSE:")
print(f"   • Dernier trade: PULLBACK sorti à 11:00:51 (+0.27%)")
print(f"   • Creux 11h06: Bot ne pouvait PAS acheter (sorti 6 min avant)")
print(f"   • Problème: Pas de pattern pour RE-ENTRER après sortie rapide")
print(f"   • Score actuel: 44.5 (< 60 seuil)")
print(f"   • RSI trap détecté: RSI=20 en tendance baissière")

print(f"\n🔧 SOLUTIONS PROPOSÉES:")
print(f"   1. Pattern CREUX_REBOUND_EARLY:")
print(f"      - Détecter RSI <25 + Momentum qui repart >0.01%")
print(f"      - Ignorer EMA bearish (rebond technique)")
print(f"      - Score minimum 70 (au lieu de 60)")
print(f"      - Bonus +25 si rebond confirmé")
print(f"")
print(f"   2. Désactiver RSI trap pour pattern CREUX_REBOUND:")
print(f"      - RSI <25 = opportunité, pas danger")
print(f"      - Seulement si momentum repart >0.01%")
print(f"      - Et volume augmente >1.2x")
print(f"")
print(f"   3. Autoriser RE-ENTRY rapide:")
print(f"      - Si sorti avec profit <0.5%")
print(f"      - Et nouveau pattern détecté <15 min")
print(f"      - Pas de blocage end_of_cycle")

print("\n" + "=" * 100)
print("📋 RECOMMANDATIONS DE CODE")
print("=" * 100)

recommendations = """
1. CREUX_REBOUND_EARLY (ai_predictor.py ~1269):
   AVANT:
   - RSI > 25 (évite oversold)
   - Momentum > 0.0001
   - EMA slope > -0.03
   
   APRÈS:
   - RSI entre 15-35 (zone rebond)
   - Momentum > 0.0100 (0.1% - rebond confirmé)
   - Volume ratio > 1.3 (volume fort)
   - Ignorer EMA slope (peut être bearish)
   - Bonus +30 (au lieu de +20)

2. RSI TRAP (ai_predictor.py ~ligne 850):
   AVANT:
   - RSI < 30 en tendance baissière → bloqué
   
   APRÈS:
   - SI pattern = CREUX_REBOUND_EARLY:
     * RSI < 25 = BONUS +15 (opportunité)
   - SINON:
     * RSI < 30 en bearish → bloqué

3. END_OF_CYCLE (ai_predictor.py ~ligne 1750):
   AVANT:
   - Après sortie → bloqué pendant 1h
   
   APRÈS:
   - SI sorti avec profit <0.5%:
     * Bloqué seulement 10 minutes
   - SI nouveau creux détecté:
     * Autoriser re-entry immédiat

4. POSSIBLE (déjà fait):
   ✅ Score min 80
   ✅ Bloqué si <80

5. SQUEEZE_WAITING (déjà fait):
   ✅ Bonus +22
   ✅ Pattern prioritaire
"""

print(recommendations)

print("\n" + "=" * 100)
print("✅ PATTERN PRIORITY (ordre d'importance)")
print("=" * 100)

priority = [
    ("1. CREUX_REBOUND_EARLY", "Score 70+ | RSI <30 + Momentum >0.1% | BONUS +30"),
    ("2. SQUEEZE_WAITING", "Score 75+ | BB squeeze + breakout | BONUS +22"),
    ("3. MOMENTUM_REVERSAL", "Score 70+ | Reversal confirmé | BONUS +20"),
    ("4. PULLBACK", "Score 75+ | Pullback sur support | Momentum >0.1%"),
    ("5. EMA_BULLISH", "Score 70+ | Tendance haussière | Momentum >0.2%"),
    ("BLOQUÉ: POSSIBLE", "Score <80 → blocked"),
    ("BLOQUÉ: HIGH_SCORE_OVERRIDE", "Désactivé (0% win rate)"),
    ("BLOQUÉ: EARLY_BREAKOUT", "Momentum 1.0% (quasi-impossible)"),
]

for p in priority:
    print(f"   {p[0]:30} → {p[1]}")

print("\n" + "=" * 100)
