import requests
import time
from datetime import datetime

# --- DEINE V2 BACKTEST-PARAMETER ---
# Wir testen eine Mischung aus deinen Trades und starken Markt-Coins
COINS_TO_TEST = ["MON", "CC", "AXS", "FTT", "HEMI", "SUI", "FET", "WLD", "BTC"]
HOURS_BACK = 12
INTERVAL = "5m"
TRIGGER_PCT = 0.015      # 1,6% Preisexplosion in 10 Minuten
TRAILING_STOP = 0.020    # Der harte 3,5% Stop deines CIOs
TRADE_AMOUNT = 30.0      # 30 USD Einsatz pro Trade
LEVERAGE = 5             # 5x Hebel

def get_candles(coin, start_time_ms):
    url = "https://api.hyperliquid.xyz/info"
    payload = {
        "type": "candleSnapshot",
        "req": {
            "coin": coin,
            "interval": INTERVAL,
            "startTime": start_time_ms
        }
    }
    try:
        r = requests.post(url, json=payload)
        return r.json()
    except Exception:
        return []

def run_backtest():
    print(f"🔄 Starte 12-Stunden-Simulation für {len(COINS_TO_TEST)} Coins...\n")
    
    now_ms = int(time.time() * 1000)
    start_ms = now_ms - (HOURS_BACK * 3600 * 1000)
    
    total_pnl = 0.0
    total_trades = 0
    
    for coin in COINS_TO_TEST:
        candles = get_candles(coin, start_ms)
        if not candles or len(candles) < 3:
            continue
            
        in_trade = False
        entry_price = 0.0
        high_price = 0.0
        
        # Wir laufen chronologisch durch jede 5-Minuten-Kerze der Nacht
        for i in range(2, len(candles)):
            current = candles[i]
            past = candles[i-2] # Vergleich mit dem Preis von vor 10 Minuten
            
            curr_close = float(current["c"])
            curr_low = float(current["l"])
            curr_high = float(current["h"])
            past_close = float(past["c"])
            
            # Zeitstempel lesbar machen
            time_str = datetime.fromtimestamp(current["t"]/1000).strftime('%H:%M')
            
            if not in_trade:
                # 1. KAUF-LOGIK (Hat der Coin um 1,6% gepumpt?)
                price_change = (curr_close - past_close) / past_close
                if price_change >= TRIGGER_PCT:
                    in_trade = True
                    entry_price = curr_close
                    high_price = curr_close
                    print(f"🟢 {time_str} | KAUF {coin} zu ${entry_price:.4f} (Spike: +{price_change*100:.2f}%)")
            
            else:
                # 2. VERKAUF-LOGIK (Trailing Stop Überwachung)
                if curr_high > high_price:
                    high_price = curr_high
                    
                stop_price = high_price * (1 - TRAILING_STOP)
                
                # Fällt der tiefste Punkt der Kerze unter unseren Stop?
                if curr_low <= stop_price:
                    exit_price = stop_price
                    
                    # Hebel-Mathematik für den echten Gewinn/Verlust (ROE)
                    price_diff_pct = (exit_price - entry_price) / entry_price
                    roe_pct = price_diff_pct * LEVERAGE * 100
                    pnl_usd = TRADE_AMOUNT * (roe_pct / 100)
                    
                    total_pnl += pnl_usd
                    total_trades += 1
                    in_trade = False
                    
                    symbol = "✅" if pnl_usd > 0 else "❌"
                    print(f"   {symbol} {time_str} | VERKAUF {coin} zu ${exit_price:.4f} | G/V: {pnl_usd:+.2f} USD ({roe_pct:+.2f}% ROE)")

    print("\n" + "="*45)
    print(f"📊 BACKTEST-ERGEBNIS (Letzte {HOURS_BACK} Stunden)")
    print(f"Anzahl Trades: {total_trades}")
    print(f"Netto-Gewinn/Verlust: {total_pnl:+.2f} USD")
    print("="*45 + "\n")

if __name__ == "__main__":
    run_backtest()
