#!/usr/bin/env python3 """ 🔧 Notebook Patch V2: Drawdown Protection Integration (CORRECTED) Fügt Drawdown Protection korrekt nach Session Filter ein """ import json import sys from pathlib import Path NOTEBOOK_PATH = "TradingBot_V1.6_Adaptive_Complete_CORRECTED.ipynb" def patch_notebook(): """Patcht das Notebook mit Drawdown Protection (V2 - CORRECTED)""" print("=" * 70) print("🔧 NOTEBOOK PATCH V2: Drawdown Protection (CORRECTED)") print("=" * 70) # Load notebook print(f"\n1️⃣ Loading notebook: {NOTEBOOK_PATH}") try: with open(NOTEBOOK_PATH, 'r', encoding='utf-8') as f: notebook = json.load(f) except FileNotFoundError: print(f"❌ Error: Notebook not found: {NOTEBOOK_PATH}") print(" Make sure you're in the correct directory!") return False print(f"✅ Loaded {len(notebook['cells'])} cells") # Find Session Filter cell (Cell 27) print("\n2️⃣ Finding Session Filter cell...") session_filter_cell_index = None for i, cell in enumerate(notebook['cells']): if cell['cell_type'] == 'code': source = ''.join(cell['source']) if 'create_session_filtered_check' in source and 'adaptive_trading_check =' in source: session_filter_cell_index = i print(f"✅ Found Session Filter at cell {i}") break if session_filter_cell_index is None: print("❌ Error: Could not find Session Filter cell!") print(" Looking for cell with 'create_session_filtered_check' and 'adaptive_trading_check ='") return False # Create new cell with CORRECT integration print("\n3️⃣ Creating enhanced Session Filter + Drawdown Protection cell...") new_cell_source = """# ========================================== # TRADING CHECK: SESSION FILTER + DRAWDOWN PROTECTION # ========================================== from session_filter_patch import ( create_session_filtered_check, SESSION_WHITELIST_CONFIG, is_session_allowed ) from drawdown_protection import create_protected_trading_check print("🔧 Setting up Trading Check...") # Step 1: Create base session-filtered trading check base_trading_check = create_session_filtered_check( rhythm_manager=rhythm_manager, execute_func=execute_trade_v2_adaptive, symbol=symbol, strategy_name=strategy_name, max_positions=max_positions, logger=logger, datetime=datetime ) print("✅ Session Filter aktiviert!") print(" Deaktivierte Sessions:") for session, enabled in SESSION_WHITELIST_CONFIG['enabled_sessions'].items(): status = "✅ AKTIV" if enabled else "❌ DEAKTIVIERT" print(f" • {session.upper():8s}: {status}") # Step 2: Wrap with Drawdown Protection adaptive_trading_check = create_protected_trading_check(infra, base_trading_check) drawdown_protection = adaptive_trading_check.protection print("\\n🛡️ Drawdown Protection aktiviert!") print(f" • Daily Loss Limit: ${drawdown_protection.max_daily_loss}") print(f" • Weekly Loss Limit: ${drawdown_protection.max_weekly_loss}") print(f" • Monthly Loss Limit: ${drawdown_protection.max_monthly_loss}") print(f" • Max Consecutive Losses: {drawdown_protection.max_consecutive_losses}") print(f" • Cooldown: {drawdown_protection.cooldown_hours}h") print("\\n✅ Trading Check ist jetzt vollständig geschützt!") print(" 📊 Session Filter: Aktiv") print(" 🛡️ Drawdown Protection: Aktiv") """ new_cell = { "cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], "source": new_cell_source.split('\n') } # Replace the Session Filter cell print(f"✅ Replacing cell {session_filter_cell_index} with enhanced version") notebook['cells'][session_filter_cell_index] = new_cell # Backup original backup_path = NOTEBOOK_PATH.replace('.ipynb', '_backup_before_drawdown_v2.ipynb') print(f"\n4️⃣ Creating backup: {backup_path}") with open(backup_path, 'w', encoding='utf-8') as f: json.dump(notebook, f, indent=1, ensure_ascii=False) print("✅ Backup created") # Save patched notebook print(f"\n5️⃣ Saving patched notebook: {NOTEBOOK_PATH}") with open(NOTEBOOK_PATH, 'w', encoding='utf-8') as f: json.dump(notebook, f, indent=1, ensure_ascii=False) print("✅ Notebook patched successfully!") print("\n" + "=" * 70) print("✅ PATCH V2 COMPLETE!") print("=" * 70) print("\nNext steps:") print("1. Open Jupyter Notebook") print("2. Kernel → Restart & Run All") print("3. Verify both Session Filter and Drawdown Protection are active") print("\nBackup saved to:", backup_path) print("\n💡 Expected output after restart:") print(" ✅ Session Filter aktiviert!") print(" 🛡️ Drawdown Protection aktiviert!") print(" ✅ Trading Check ist jetzt vollständig geschützt!") return True if __name__ == "__main__": success = patch_notebook() sys.exit(0 if success else 1)