from binance.client import Client
import datetime
import numpy as np

def calculate_rsi(prices, period=14):
    """Calcule le RSI"""
    deltas = np.diff(prices)
    gains = np.where(deltas > 0, deltas, 0)
    losses = np.where(deltas < 0, -deltas, 0)
    
    avg_gain = np.mean(gains[:period])
    avg_loss = np.mean(losses[:period])
    
    for i in range(period, len(gains)):
        avg_gain = (avg_gain * (period - 1) + gains[i]) / period
        avg_loss = (avg_loss * (period - 1) + losses[i]) / period
    
    if avg_loss == 0:
        return 100
    rs = avg_gain / avg_loss
    rsi = 100 - (100 / (1 + rs))
    return rsi

def calculate_bb(prices, period=20):
    """Calcule les Bollinger Bands"""
    sma = np.mean(prices[-period:])
    std = np.std(prices[-period:])
    upper = sma + (2 * std)
    lower = sma - (2 * std)
    current = prices[-1]
    bb_pos = (current - lower) / (upper - lower) if (upper - lower) > 0 else 0.5
    return bb_pos, upper, lower, sma

# Récupération des données
c = Client()
klines = c.get_klines(symbol='ETHUSDT', interval='5m', limit=200)

print('\n📊 ETH - ANALYSE DÉTAILLÉE AUTOUR DE 9h20')
print('='*80)

# Analyser les bougies clés
target_times = ['09:15', '09:20', '09:25', '09:30']
analyses = []

for i, k in enumerate(klines):
    ts = datetime.datetime.fromtimestamp(k[0]/1000)
    ts_str = ts.strftime('%H:%M')
    
    if ts_str in target_times:
        # Calculer indicateurs jusqu'à ce point
        closes = np.array([float(kl[4]) for kl in klines[:i+1]])
        
        if len(closes) >= 20:
            rsi = calculate_rsi(closes[-50:] if len(closes) >= 50 else closes)
            bb_pos, bb_upper, bb_lower, bb_mid = calculate_bb(closes)
            
            price = float(k[4])
            high = float(k[2])
            low = float(k[3])
            
            # Momentum (variation sur 3 dernières bougies)
            if len(closes) >= 4:
                momentum = ((closes[-1] - closes[-4]) / closes[-4]) * 100
            else:
                momentum = 0
            
            analyses.append({
                'time': ts_str,
                'price': price,
                'high': high,
                'low': low,
                'rsi': rsi,
                'bb_pos': bb_pos,
                'bb_upper': bb_upper,
                'bb_lower': bb_lower,
                'bb_mid': bb_mid,
                'momentum': momentum
            })

# Affichage détaillé
for a in analyses:
    print(f"\n⏰ {a['time']} - ETH à {a['price']:.2f}€")
    print(f"   Prix: {a['price']:.2f}€  (High: {a['high']:.2f}€, Low: {a['low']:.2f}€)")
    print(f"   RSI: {a['rsi']:.1f}")
    print(f"   BB Position: {a['bb_pos']:.2f} (0=bas, 1=haut)")
    print(f"   BB: Lower={a['bb_lower']:.2f}€ | Mid={a['bb_mid']:.2f}€ | Upper={a['bb_upper']:.2f}€")
    print(f"   Momentum 15min: {a['momentum']:+.2f}%")
    
    # Évaluation
    print(f"\n   🔍 ÉVALUATION:")
    
    # RSI
    if a['rsi'] > 70:
        print(f"      RSI {a['rsi']:.1f} = ⚠️ SURACHAT (dangereux)")
    elif a['rsi'] < 30:
        print(f"      RSI {a['rsi']:.1f} = ✅ SURVENTE (opportunité)")
    elif 40 <= a['rsi'] <= 60:
        print(f"      RSI {a['rsi']:.1f} = ✅ ZONE NEUTRE (idéal)")
    else:
        print(f"      RSI {a['rsi']:.1f} = 🟡 Acceptable")
    
    # Bollinger
    if a['bb_pos'] > 0.85:
        print(f"      BB {a['bb_pos']:.2f} = ⚠️ PROCHE DU HAUT (risque correction)")
    elif a['bb_pos'] < 0.15:
        print(f"      BB {a['bb_pos']:.2f} = ✅ BAS DE BANDE (rebond probable)")
    elif 0.3 <= a['bb_pos'] <= 0.7:
        print(f"      BB {a['bb_pos']:.2f} = ✅ MILIEU DE BANDE (sain)")
    else:
        print(f"      BB {a['bb_pos']:.2f} = 🟡 Acceptable")
    
    # Momentum
    if a['momentum'] > 0.5:
        print(f"      Momentum {a['momentum']:+.2f}% = ✅ Positif")
    elif a['momentum'] < -0.5:
        print(f"      Momentum {a['momentum']:+.2f}% = ⚠️ Négatif")
    else:
        print(f"      Momentum {a['momentum']:+.2f}% = 🟡 Faible")
    
    # Verdict global
    print(f"\n   📋 VERDICT:")
    
    # Compter les signaux
    good_signals = 0
    bad_signals = 0
    
    if 30 <= a['rsi'] <= 60:
        good_signals += 1
    elif a['rsi'] > 75:
        bad_signals += 1
    
    if 0.2 <= a['bb_pos'] <= 0.75:
        good_signals += 1
    elif a['bb_pos'] > 0.85:
        bad_signals += 1
    
    if a['momentum'] > 0:
        good_signals += 1
    
    if bad_signals >= 1:
        print(f"      ❌ ACHAT DÉCONSEILLÉ ({bad_signals} signaux négatifs)")
        print(f"         Raison: Surachat technique (RSI/BB trop élevés)")
    elif good_signals >= 2:
        print(f"      ✅ BON MOMENT D'ACHAT ({good_signals} signaux positifs)")
    else:
        print(f"      🟡 NEUTRE (attendre meilleure opportunité)")

print('\n' + '='*80)
print('📊 COMPARAISON avec logs précédents:')
print('   ETH a été bloqué récemment avec: RSI 87-91, BB 0.86-0.96')
print('   Le bot refuse d\'acheter quand RSI > 85 ET BB > 0.85 (FIN_DE_CYCLE)')
print('='*80)
