2025-11-26 21:14:01 +01:00
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# TradingBot V1.6 - Adaptive Complete Version 🚀🛡️⚡\n",
"\n",
"## 🆕 **NEU in V1.6: Adaptive Trading Rhythm**\n",
"- ⚡ **Adaptive Intervalle** - Automatische Anpassung: 5/15/30 Minuten\n",
"- 📊 **Volatilitäts-basiert** - ATR-gesteuerte Intervall-Wahl\n",
"- 🌍 **Session-abhängig** - Asian/London/NY/Overlap\n",
"- 🎯 **Intelligente Matrix** - Optimale Kombination aus Session + Volatilität\n",
"\n",
"## ✅ **Features aus V1.5 Complete Relaxed:**\n",
"- 🛡️ **Position Control System** - Maximal 1 Trade gleichzeitig\n",
"- 📊 **Performance Monitoring & Logging**\n",
"- 🤖 **APScheduler Integration** - Automatisierung\n",
"- 🔧 **Position Management Funktionen** - VOLLSTÄNDIG!\n",
"- 🚀 **Relaxed Parameter** - Niedrigere Schwellen für mehr Signale\n",
"- 🧪 **Umfassende Testing Suite**\n",
"- 🎛️ **Management Control Panel**\n",
"\n",
"## 🎯 **Adaptive Rhythm Schema:**\n",
"```\n",
"Session │ Hohe Vol │ Mittlere Vol │ Niedrige Vol\n",
"───────────┼──────────┼──────────────┼─────────────\n",
"Overlap │ 5min │ 15min │ 15min\n",
"London/NY │ 5min │ 15min │ 30min\n",
"Asian │ 15min │ 30min │ 30min\n",
"```\n",
"\n",
"## 🎉 **V1.6 COMPLETE - Das Beste aus beiden Welten:**\n",
"- ✅ Alle Funktionen aus V1.5\n",
"- ✅ Neue adaptive Features aus V1.6\n",
"- ✅ Production-Ready!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. Imports und Setup"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 1,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ All imports successful - V1.6 Adaptive Complete (CORRECTED)\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"# Standard Imports\n",
"import pandas as pd\n",
"import numpy as np\n",
"import MetaTrader5 as mt\n",
"import pandas_ta as ta\n",
"from scipy.signal import savgol_filter, find_peaks\n",
"from sklearn.linear_model import LinearRegression\n",
"from tabulate import tabulate\n",
"from datetime import datetime, timedelta, time\n",
"import json\n",
"import keyring as kr\n",
"\n",
"# V1.6: Zusätzliche Imports für Adaptive Rhythm\n",
"import pytz\n",
"import logging\n",
"from apscheduler.schedulers.background import BackgroundScheduler\n",
"\n",
"# Setup Logging\n",
"logging.basicConfig(\n",
" level=logging.INFO,\n",
" format='%(asctime)s - %(levelname)s - %(message)s'\n",
")\n",
"logger = logging.getLogger(__name__)\n",
"\n",
"print(\"✅ All imports successful - V1.6 Adaptive Complete (CORRECTED)\")"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 2,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ Infrastructure modules loaded\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"# ==========================================\n",
"# INFRASTRUCTURE IMPORTS (V1.8)\n",
"# ==========================================\n",
"\n",
"from infrastructure_patch import (\n",
" TradingInfrastructure,\n",
" create_scheduled_reports\n",
")\n",
"from trading_database import TradingDatabase\n",
"from telegram_notifier import TelegramNotifier\n",
"\n",
"print(\"✅ Infrastructure modules loaded\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. 🆕 Adaptive Rhythm Manager (NEU in V1.6)"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 3,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ Adaptive Rhythm Manager defined\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"class AdaptiveRhythmManager:\n",
" \"\"\"\n",
" 🆕 V1.6 Feature: Adaptive Trading Rhythm\n",
" \n",
" Verwaltet adaptiven Trading-Rhythmus basierend auf:\n",
" - Marktvolatilität (ATR)\n",
" - Trading-Session (Asian/London/NY/Overlap)\n",
" - Marktregime\n",
" \"\"\"\n",
" \n",
" def __init__(self, symbol=\"XAUUSD\"):\n",
" self.symbol = symbol\n",
" self.current_interval = 5\n",
" \n",
" # Zeitintervalle in Minuten\n",
" self.intervals = {\n",
" 'fast': 5, # Hohe Volatilität, aktive Sessions\n",
" 'medium': 15, # Moderate Volatilität, Standard\n",
" 'slow': 30 # Niedrige Volatilität, ruhige Sessions\n",
" }\n",
" \n",
" # ATR-Schwellenwerte für XAUUSD (Gold)\n",
" self.atr_thresholds = {\n",
" 'high': 15.0, # Hohe Volatilität\n",
" 'medium': 8.0, # Moderate Volatilität\n",
" 'low': 5.0 # Niedrige Volatilität\n",
" }\n",
" \n",
" # Session-Zeiten (UTC)\n",
" self.sessions = {\n",
" 'asian': (time(0, 0), time(8, 0)), # 00:00-08:00 UTC\n",
" 'london': (time(8, 0), time(16, 0)), # 08:00-16:00 UTC\n",
" 'ny': (time(13, 0), time(21, 0)), # 13:00-21:00 UTC\n",
" 'overlap': (time(13, 0), time(16, 0)) # London-NY Overlap\n",
" }\n",
" \n",
" def get_current_session(self):\n",
" \"\"\"Ermittelt die aktuelle Trading-Session\"\"\"\n",
" now_utc = datetime.now(pytz.UTC).time()\n",
" \n",
" # Overlap hat höchste Priorität\n",
" if self.sessions['overlap'][0] <= now_utc <= self.sessions['overlap'][1]:\n",
" return 'overlap'\n",
" elif self.sessions['london'][0] <= now_utc < self.sessions['london'][1]:\n",
" return 'london'\n",
" elif self.sessions['ny'][0] <= now_utc < self.sessions['ny'][1]:\n",
" return 'ny'\n",
" return 'asian'\n",
" \n",
" def get_volatility_level(self, atr_value):\n",
" \"\"\"Klassifiziert die Volatilität basierend auf ATR\"\"\"\n",
" if atr_value >= self.atr_thresholds['high']:\n",
" return 'high'\n",
" elif atr_value >= self.atr_thresholds['medium']:\n",
" return 'medium'\n",
" return 'low'\n",
" \n",
" def get_market_data(self):\n",
" \"\"\"Hole Marktdaten für ATR-Analyse\"\"\"\n",
" try:\n",
" rates = mt.copy_rates_from_pos(self.symbol, mt.TIMEFRAME_H1, 0, 50)\n",
" if rates is None:\n",
" return None\n",
" \n",
" df = pd.DataFrame(rates)\n",
" df['time'] = pd.to_datetime(df['time'], unit='s')\n",
" df.set_index('time', inplace=True)\n",
" df['atr'] = ta.atr(df['high'], df['low'], df['close'], length=14)\n",
" return df\n",
" except Exception as e:\n",
" logger.error(f\"Fehler beim Laden der Marktdaten: {e}\")\n",
" return None\n",
" \n",
" def calculate_optimal_interval(self):\n",
" \"\"\"Berechnet optimales Trading-Intervall\"\"\"\n",
" session = self.get_current_session()\n",
" df = self.get_market_data()\n",
" \n",
" if df is None:\n",
" return self.current_interval\n",
" \n",
" current_atr = df['atr'].iloc[-1]\n",
" volatility = self.get_volatility_level(current_atr)\n",
" optimal_interval = self._determine_interval(session, volatility)\n",
" \n",
" # Logge Änderungen\n",
" if optimal_interval != self.current_interval:\n",
" logger.info(f\"🔄 Rhythmus-Änderung: {self.current_interval}m → {optimal_interval}m\")\n",
" logger.info(f\" Session: {session}, Volatilität: {volatility} (ATR: {current_atr:.2f})\")\n",
" \n",
" self.current_interval = optimal_interval\n",
" return optimal_interval\n",
" \n",
" def _determine_interval(self, session, volatility):\n",
" \"\"\"\n",
" Intervall-Entscheidungs-Matrix:\n",
" \n",
" Session │ Hohe Vol │ Mittlere Vol │ Niedrige Vol\n",
" ───────────┼──────────┼──────────────┼─────────────\n",
" Overlap │ 5min │ 15min │ 15min\n",
" London/NY │ 5min │ 15min │ 30min\n",
" Asian │ 15min │ 30min │ 30min\n",
" \"\"\"\n",
" if session == 'overlap':\n",
" return self.intervals['fast'] if volatility == 'high' else self.intervals['medium']\n",
" elif session in ['london', 'ny']:\n",
" if volatility == 'high':\n",
" return self.intervals['fast']\n",
" elif volatility == 'medium':\n",
" return self.intervals['medium']\n",
" return self.intervals['slow']\n",
" else: # asian\n",
" return self.intervals['medium'] if volatility == 'high' else self.intervals['slow']\n",
" \n",
" def get_status_report(self):\n",
" \"\"\"Erstellt Status-Report\"\"\"\n",
" session = self.get_current_session()\n",
" df = self.get_market_data()\n",
" \n",
" if df is not None:\n",
" current_atr = df['atr'].iloc[-1]\n",
" volatility = self.get_volatility_level(current_atr)\n",
" else:\n",
" current_atr = 0\n",
" volatility = 'unknown'\n",
" \n",
" return f\"\"\"\n",
"╔════════════════════════════════════════════════════════╗\n",
"║ ADAPTIVE RHYTHM STATUS - {datetime.now().strftime('%H:%M:%S UTC')} ║\n",
"╠════════════════════════════════════════════════════════╣\n",
"║ Aktuelles Intervall: {self.current_interval:>2} Minuten ║\n",
"║ Trading Session: {session.upper():<15} ║\n",
"║ Volatilitätslevel: {volatility.upper():<15} ║\n",
"║ ATR (H1): {current_atr:>6.2f} ║\n",
"╠════════════════════════════════════════════════════════╣\n",
"║ INTERVALL-SCHEMA: ║\n",
"║ • Overlap (13-16 UTC): 5-15 Min (aktivste Phase) ║\n",
"║ • London/NY: 5-30 Min (volatilitätsabh.) ║\n",
"║ • Asian Session: 15-30 Min (ruhigere Phase) ║\n",
"╚════════════════════════════════════════════════════════╝\n",
"\"\"\"\n",
"\n",
"print(\"✅ Adaptive Rhythm Manager defined\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. MT5 Login und Setup"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 4,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Login successful: True\n",
"Symbol: XAUUSD\n",
"Strategy: TradingBot_V1.6\n",
"Max Positions: 1\n",
"Version: V1.6 COMPLETE - Adaptive + Full Features! 🚀🛡️⚡\n",
"\n",
"\n",
"╔════════════════════════════════════════════════════════╗\n",
"║ ADAPTIVE RHYTHM STATUS - 09:26:57 UTC ║\n",
"╠════════════════════════════════════════════════════════╣\n",
"║ Aktuelles Intervall: 5 Minuten ║\n",
"║ Trading Session: LONDON ║\n",
"║ Volatilitätslevel: MEDIUM ║\n",
"║ ATR (H1): 9.59 ║\n",
"╠════════════════════════════════════════════════════════╣\n",
"║ INTERVALL-SCHEMA: ║\n",
"║ • Overlap (13-16 UTC): 5-15 Min (aktivste Phase) ║\n",
"║ • London/NY: 5-30 Min (volatilitätsabh.) ║\n",
"║ • Asian Session: 15-30 Min (ruhigere Phase) ║\n",
"╚════════════════════════════════════════════════════════╝\n",
"\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"# MT5 Login\n",
"mt.initialize()\n",
"login = 10800246\n",
"server = 'VantageInternational-Demo'\n",
"password = kr.get_password(server, str(login))\n",
"login_result = mt.login(login, password, server)\n",
"print(f\"Login successful: {login_result}\")\n",
"\n",
"# Trading Parameter\n",
"symbol = \"XAUUSD\"\n",
"strategy_name = \"TradingBot_V1.6\"\n",
"max_positions = 1\n",
"\n",
"print(f\"Symbol: {symbol}\")\n",
"print(f\"Strategy: {strategy_name}\")\n",
"print(f\"Max Positions: {max_positions}\")\n",
"print(f\"Version: V1.6 COMPLETE - Adaptive + Full Features! 🚀🛡️⚡\")\n",
"\n",
"# 🆕 Initialisiere Adaptive Rhythm Manager\n",
"rhythm_manager = AdaptiveRhythmManager(symbol)\n",
"print(\"\\n\" + rhythm_manager.get_status_report())"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 5,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"🔧 Initializing Infrastructure...\n",
"✅ Database initialized: trading_bot.db\n",
"✅ Telegram Bot connected: @Xausd_digger_bot\n",
"✅ Telegram notifications enabled\n",
"✅ Infrastructure ready!\n",
" Database: ✅\n",
" Telegram: ✅\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"# ==========================================\n",
"# INITIALIZE INFRASTRUCTURE (V1.8)\n",
"# ==========================================\n",
"\n",
"print(\"🔧 Initializing Infrastructure...\")\n",
"\n",
"# Initialize Infrastructure\n",
"infra = TradingInfrastructure(\n",
" db_path=\"trading_bot.db\",\n",
" enable_telegram=True,\n",
" enable_database=True\n",
")\n",
"\n",
"# Bot Started Notification\n",
"from session_filter_patch import SESSION_WHITELIST_CONFIG\n",
"\n",
"bot_config = {\n",
" 'version': 'V1.8',\n",
" 'enabled_sessions': SESSION_WHITELIST_CONFIG['enabled_sessions'],\n",
" 'base_confidence': SESSION_WHITELIST_CONFIG['base_confidence'],\n",
" 'max_risk_per_trade': SESSION_WHITELIST_CONFIG['max_risk_per_trade']\n",
"}\n",
"\n",
"infra.send_bot_started(bot_config)\n",
"\n",
"print(\"✅ Infrastructure ready!\")\n",
"print(f\" Database: {'✅' if infra.enable_database else '❌'}\")\n",
"print(f\" Telegram: {'✅' if infra.enable_telegram else '❌'}\")"
]
},
2025-12-16 22:02:15 +01:00
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"2025-12-10 09:26:58,891 - INFO - 🎯 Advanced Position Manager initialized\n",
"2025-12-10 09:26:58,892 - INFO - Adaptive Sizing: ✅\n",
"2025-12-10 09:26:58,893 - INFO - Trailing Stop: ✅\n",
"2025-12-10 09:26:58,894 - INFO - Partial TP: ✅\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"🎯 Initializing Advanced Position Management...\n",
"✅ Advanced Position Management activated!\n",
" 📊 Adaptive Position Sizing: ACTIVE\n",
" • High Confidence (≥80%): 1.5x risk\n",
" • Medium Confidence (≥70%): 1.0x risk\n",
" • Low Confidence (<70%): 0.5x risk\n",
"\n",
" 📈 Trailing Stop-Loss: ACTIVE\n",
" • Break-Even at 50% progress to TP\n",
" • Lock 50% profit at 75% progress\n",
"\n",
" 🎯 Partial Take Profit: ACTIVE\n",
" • TP1 at 1.5R (close 50%)\n",
" • TP2 at 2.5R (let 50% run)\n"
]
}
],
"source": [
"# ==========================================\n",
"# ADVANCED POSITION MANAGEMENT SETUP\n",
"# ==========================================\n",
"\n",
"from advanced_position_management import AdvancedPositionManager\n",
"\n",
"print(\"🎯 Initializing Advanced Position Management...\")\n",
"\n",
"# Initialize Manager with all features\n",
"adv_position_mgr = AdvancedPositionManager(\n",
" enable_adaptive_sizing=True, # ✅ Adaptive Position Sizing\n",
" enable_trailing_stop=True, # ✅ Trailing Stop-Loss\n",
" enable_partial_tp=True # ✅ Partial Take Profit\n",
")\n",
"\n",
"print(\"✅ Advanced Position Management activated!\")\n",
"print(\" 📊 Adaptive Position Sizing: ACTIVE\")\n",
"print(\" • High Confidence (≥80%): 1.5x risk\")\n",
"print(\" • Medium Confidence (≥70%): 1.0x risk\")\n",
"print(\" • Low Confidence (<70%): 0.5x risk\")\n",
"print(\"\")\n",
"print(\" 📈 Trailing Stop-Loss: ACTIVE\")\n",
"print(\" • Break-Even at 50% progress to TP\")\n",
"print(\" • Lock 50% profit at 75% progress\")\n",
"print(\"\")\n",
"print(\" 🎯 Partial Take Profit: ACTIVE\")\n",
"print(\" • TP1 at 1.5R (close 50%)\")\n",
"print(\" • TP2 at 2.5R (let 50% run)\")\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"🔧 Initializing Position Monitor...\n",
"✅ Position Monitor ready!\n",
" Will check for closed positions every minute\n",
" Closed trades will be automatically logged with:\n",
" • Exit price & time\n",
" • Profit/Loss calculation\n",
" • Exit reason (TP/SL/Manual)\n",
" • Telegram notification\n"
]
}
],
"source": [
"# ==========================================\n",
"# POSITION MONITOR SETUP (V1.8)\n",
"# ==========================================\n",
"\n",
"from position_monitor import PositionMonitor\n",
"\n",
"print(\"🔧 Initializing Position Monitor...\")\n",
"\n",
"# Create Position Monitor\n",
"position_monitor = PositionMonitor(infra.db, infra.telegram)\n",
"\n",
"print(\"✅ Position Monitor ready!\")\n",
"print(\" Will check for closed positions every minute\")\n",
"print(\" Closed trades will be automatically logged with:\")\n",
"print(\" • Exit price & time\")\n",
"print(\" • Profit/Loss calculation\")\n",
"print(\" • Exit reason (TP/SL/Manual)\")\n",
"print(\" • Telegram notification\")"
]
},
2025-11-26 21:14:01 +01:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. 🛡️ Position Control Functions (VOLLSTÄNDIG!)"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 8,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ Position Control functions defined (COMPLETE with close function!)\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"def check_existing_positions(symbol=\"XAUUSD\", strategy_name=\"TradingBot_V1.6\"):\n",
" \"\"\"\n",
" Überprüft ob bereits Positionen für das Symbol und die Strategie existieren\n",
" \"\"\"\n",
" try:\n",
" positions = mt.positions_get(symbol=symbol)\n",
" \n",
" if positions is None:\n",
" return False, {\"count\": 0, \"details\": []}\n",
" \n",
" strategy_positions = []\n",
" for pos in positions:\n",
" if strategy_name in pos.comment:\n",
" strategy_positions.append({\n",
" \"ticket\": pos.ticket,\n",
" \"type\": \"BUY\" if pos.type == 0 else \"SELL\",\n",
" \"volume\": pos.volume,\n",
" \"price_open\": pos.price_open,\n",
" \"profit\": pos.profit,\n",
" \"comment\": pos.comment,\n",
" \"time_open\": pd.to_datetime(pos.time, unit='s')\n",
" })\n",
" \n",
" has_position = len(strategy_positions) > 0\n",
" position_info = {\"count\": len(strategy_positions), \"details\": strategy_positions}\n",
" return has_position, position_info\n",
" \n",
" except Exception as e:\n",
" print(f\"Error checking positions: {e}\")\n",
" return False, {\"count\": 0, \"details\": []}\n",
"\n",
"\n",
"def get_position_summary(symbol=\"XAUUSD\", strategy_name=\"TradingBot_V1.6\"):\n",
" \"\"\"Position-Zusammenfassung\"\"\"\n",
" has_position, position_info = check_existing_positions(symbol, strategy_name)\n",
" \n",
" print(f\"\\n📊 POSITION SUMMARY für {symbol} (V1.6 Adaptive Complete)\")\n",
" print(\"=\" * 60)\n",
" \n",
" if not has_position:\n",
" print(\"✅ Keine aktiven Positionen - bereit für neuen Trade\")\n",
" return False\n",
" \n",
" print(f\"⚠️ {position_info['count']} aktive Position(en) gefunden:\")\n",
" for i, pos in enumerate(position_info['details'], 1):\n",
" profit_emoji = \"🟢\" if pos['profit'] >= 0 else \"🔴\"\n",
" print(f\"\\n Position {i}:\")\n",
" print(f\" Ticket: {pos['ticket']}\")\n",
" print(f\" Typ: {pos['type']}\")\n",
" print(f\" Volumen: {pos['volume']}\")\n",
" print(f\" Eröffnungspreis: {pos['price_open']}\")\n",
" print(f\" Profit: {profit_emoji} {pos['profit']:.2f}\")\n",
" print(f\" Eröffnungszeit: {pos['time_open']}\")\n",
" \n",
" print(f\"\\n🛑 TRADING BLOCKIERT - Maximal {max_positions} Position erlaubt\")\n",
" return True\n",
"\n",
"\n",
"def close_existing_positions(symbol=\"XAUUSD\", strategy_name=\"TradingBot_V1.6\", force_close=False):\n",
" \"\"\"\n",
" ✅ KORRIGIERT: Schließt bestehende Positionen (optional)\n",
" Diese Funktion fehlte in der ursprünglichen V1.6!\n",
" \"\"\"\n",
" has_position, position_info = check_existing_positions(symbol, strategy_name)\n",
" \n",
" if not has_position:\n",
" print(\"✅ Keine Positionen zum Schließen\")\n",
" return True\n",
" \n",
" if not force_close:\n",
" print(f\"⚠️ {position_info['count']} Position(en) gefunden. Verwende force_close=True zum Schließen.\")\n",
" return False\n",
" \n",
" print(f\"🔄 Schließe {position_info['count']} Position(en)...\")\n",
" \n",
" success_count = 0\n",
" for pos in position_info['details']:\n",
" try:\n",
" # Position schließen\n",
" close_request = {\n",
" \"action\": mt.TRADE_ACTION_DEAL,\n",
" \"symbol\": symbol,\n",
" \"volume\": pos['volume'],\n",
" \"type\": mt.ORDER_TYPE_SELL if pos['type'] == \"BUY\" else mt.ORDER_TYPE_BUY,\n",
" \"position\": pos['ticket'],\n",
" \"price\": mt.symbol_info_tick(symbol).bid if pos['type'] == \"BUY\" else mt.symbol_info_tick(symbol).ask,\n",
" \"deviation\": 20,\n",
" \"magic\": 234000,\n",
" \"comment\": f\"Close {strategy_name}\",\n",
" \"type_time\": mt.ORDER_TIME_GTC,\n",
" \"type_filling\": mt.ORDER_FILLING_IOC,\n",
" }\n",
" \n",
" result = mt.order_send(close_request)\n",
" \n",
" if result.retcode == mt.TRADE_RETCODE_DONE:\n",
" print(f\"✅ Position {pos['ticket']} erfolgreich geschlossen\")\n",
" success_count += 1\n",
" else:\n",
" print(f\"❌ Fehler beim Schließen von Position {pos['ticket']}: {result.comment}\")\n",
" \n",
" except Exception as e:\n",
" print(f\"❌ Exception beim Schließen von Position {pos['ticket']}: {e}\")\n",
" \n",
" print(f\"📊 {success_count}/{len(position_info['details'])} Positionen erfolgreich geschlossen\")\n",
" return success_count == len(position_info['details'])\n",
"\n",
"\n",
"print(\"✅ Position Control functions defined (COMPLETE with close function!)\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5. Helper Functions"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 9,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ Helper functions defined\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"def get_rates(timeframe=\"h4\", count=200, symbol=\"XAUUSD\"):\n",
" \"\"\"Hole Kursdaten\"\"\"\n",
" timeframes_dict = {\n",
" \"m1\": mt.TIMEFRAME_M1, \"m5\": mt.TIMEFRAME_M5, \"m15\": mt.TIMEFRAME_M15,\n",
" \"m30\": mt.TIMEFRAME_M30, \"h1\": mt.TIMEFRAME_H1, \"h4\": mt.TIMEFRAME_H4, \n",
" \"d1\": mt.TIMEFRAME_D1\n",
" }\n",
" try:\n",
" rates = mt.copy_rates_from_pos(symbol, timeframes_dict[timeframe], 0, count)\n",
" if rates is None: \n",
" return None\n",
" df = pd.DataFrame(rates)\n",
" df['time'] = pd.to_datetime(df['time'], unit='s')\n",
" df.set_index('time', inplace=True)\n",
" df['atr'] = ta.atr(df['high'], df['low'], df['close'], length=14)\n",
" return df\n",
" except Exception as e:\n",
" print(f\"Error getting rates: {e}\")\n",
" return None\n",
"\n",
"\n",
"def check_risk_limits(symbol, volume=None, order_type=\"buy\", max_risk_per_trade=0.01):\n",
" \"\"\"Risk Management\"\"\"\n",
" try:\n",
" account_info = mt.account_info()\n",
" if not account_info: \n",
" return False\n",
" balance, equity = account_info.balance, account_info.equity\n",
" if equity < balance * 0.8: \n",
" return False\n",
" return True\n",
" except: \n",
" return False\n",
"\n",
"\n",
"def market_order(symbol, volume, order_type, stoploss=0, take_profit=0, deviation=20):\n",
" \"\"\"Market Order Execution\"\"\"\n",
" try:\n",
" price_dict = {'buy': mt.symbol_info_tick(symbol).ask, 'sell': mt.symbol_info_tick(symbol).bid}\n",
" order_type_dict = {'buy': mt.ORDER_TYPE_BUY, 'sell': mt.ORDER_TYPE_SELL}\n",
" \n",
" request = {\n",
" \"action\": mt.TRADE_ACTION_DEAL,\n",
" \"symbol\": symbol,\n",
" \"volume\": volume,\n",
" \"type\": order_type_dict[order_type],\n",
" \"price\": price_dict[order_type],\n",
" \"sl\": stoploss,\n",
" \"tp\": take_profit,\n",
" \"deviation\": deviation,\n",
" \"magic\": 234000,\n",
" \"comment\": strategy_name,\n",
" \"type_time\": mt.ORDER_TIME_GTC,\n",
" \"type_filling\": mt.ORDER_FILLING_IOC\n",
" }\n",
" return mt.order_send(request)\n",
" except Exception as e:\n",
" print(f\"Error in market order: {e}\")\n",
" return None\n",
"\n",
"\n",
"print(\"✅ Helper functions defined\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 6. Market Analysis Functions"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 10,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ Market analysis functions defined (with RELAXED thresholds)\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"def detect_market_regime(df, lookback=50):\n",
" \"\"\"Market Regime Detection\"\"\"\n",
" try:\n",
" adx_data = ta.adx(df['high'], df['low'], df['close'], length=14)\n",
" adx = adx_data['ADX_14'].iloc[-1] if adx_data is not None and 'ADX_14' in adx_data.columns else 25.0\n",
" \n",
" try:\n",
" bb = ta.bbands(df['close'], length=20)\n",
" if bb is not None and len(bb.columns) >= 3:\n",
" bb_cols = bb.columns.tolist()\n",
" bb_width = ((bb[bb_cols[0]] - bb[bb_cols[2]]) / bb[bb_cols[1]] * 100).iloc[-lookback:].mean()\n",
" else: \n",
" bb_width = 4.0\n",
" except: \n",
" bb_width = 4.0\n",
" \n",
" price_range = df['high'].iloc[-lookback:].max() - df['low'].iloc[-lookback:].min()\n",
" atr_avg = df['atr'].iloc[-lookback:].mean()\n",
" range_ratio = price_range / (atr_avg * lookback) if atr_avg > 0 else 1.0\n",
" vol_cluster = df['atr'].iloc[-10:].std() / df['atr'].iloc[-50:].mean() if len(df) >= 50 else 1.0\n",
" \n",
" if adx > 25 and range_ratio > 1.5:\n",
" regime, strength = 'trending', min(100, adx * 2)\n",
" elif vol_cluster > 1.5:\n",
" regime, strength = 'volatile', min(100, vol_cluster * 50)\n",
" else:\n",
" regime, strength = 'ranging', max(0, 100 - adx * 2)\n",
" \n",
" return {\n",
" 'regime': regime, 'strength': strength, 'adx': adx, \n",
" 'bb_width': bb_width, 'range_ratio': range_ratio, 'vol_cluster': vol_cluster\n",
" }\n",
" except Exception as e:\n",
" return {\n",
" 'regime': 'ranging', 'strength': 50, 'adx': 20, \n",
" 'bb_width': 4.0, 'range_ratio': 1.0, 'vol_cluster': 1.0\n",
" }\n",
"\n",
"\n",
"def calculate_adaptive_confidence_threshold_relaxed(regime_info, base_confidence=60):\n",
" \"\"\"\n",
" RELAXED Version: Niedrigere Schwellen für mehr Signale\n",
" \"\"\"\n",
" regime = regime_info['regime']\n",
" adx = regime_info['adx']\n",
" \n",
" if regime == 'trending':\n",
" if adx > 30:\n",
" return max(50, base_confidence - 20)\n",
" else:\n",
" return base_confidence - 15\n",
" elif regime == 'ranging':\n",
" return base_confidence + 10\n",
" elif regime == 'volatile':\n",
" return base_confidence + 15\n",
" \n",
" return base_confidence\n",
"\n",
"\n",
"def get_enhanced_trend(timeframe=\"H4\", lookback=150, symbol=\"XAUUSD\"):\n",
" \"\"\"Enhanced Trend Analysis\"\"\"\n",
" tf_map = {\"D1\": \"d1\", \"H4\": \"h4\", \"H1\": \"h1\", \"M30\": \"m30\", \"M15\": \"m15\", \"M5\": \"m5\"}\n",
" tf = tf_map.get(timeframe, timeframe.lower())\n",
" \n",
" try:\n",
" df = get_rates(tf, lookback, symbol)\n",
" if df is None or len(df) < 50: \n",
" return None\n",
" \n",
" df['close_smooth'] = savgol_filter(df['close'], min(15, len(df)//10), 3)\n",
" X = np.arange(len(df)).reshape(-1, 1)\n",
" y = df['close_smooth'].values\n",
" model = LinearRegression().fit(X, y)\n",
" slope = model.coef_[0]\n",
" \n",
" regime_info = detect_market_regime(df.iloc[-50:])\n",
" base_threshold = df['atr'].iloc[-1] * 0.0001\n",
" \n",
" if regime_info['regime'] == 'trending':\n",
" slope_threshold = base_threshold * 0.7\n",
" elif regime_info['regime'] == 'ranging':\n",
" slope_threshold = base_threshold * 1.5\n",
" else:\n",
" slope_threshold = base_threshold * 1.2\n",
" \n",
" trend = \"uptrend\" if slope > slope_threshold else \"downtrend\" if slope < -slope_threshold else \"sideways\"\n",
" trend_strength = abs(slope) / slope_threshold if slope_threshold > 0 else 0\n",
" \n",
" return {\n",
" \"trend\": trend, \"slope\": slope, \"slope_threshold\": slope_threshold,\n",
" \"trend_strength\": trend_strength, \"atr\": df['atr'].iloc[-1],\n",
" \"price\": df['close'].iloc[-1], \"regime_info\": regime_info\n",
" }\n",
" except Exception as e:\n",
" print(f\"Error in get_enhanced_trend: {e}\")\n",
" return None\n",
"\n",
"\n",
"print(\"✅ Market analysis functions defined (with RELAXED thresholds)\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 7. Extended Top-Down Analysis"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 11,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ V1.6 Adaptive Complete Top-Down Analysis defined\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"def extended_top_down_v2_adaptive(symbol=\"XAUUSD\", lookback=150):\n",
" \"\"\"\n",
" V1.6 Adaptive Complete Version:\n",
" - Position Control\n",
" - Relaxed Trading Logic\n",
" - Adaptive Rhythm Integration\n",
" \"\"\"\n",
" \n",
" timeframes = [\"D1\", \"H4\", \"H1\", \"M30\", \"M15\", \"M5\"]\n",
" trend_info = {}\n",
" \n",
" print(f\"🔍 Analyzing {symbol} with V1.6 ADAPTIVE COMPLETE parameters...\")\n",
" \n",
" # 1. Alle Timeframes analysieren\n",
" for tf in timeframes:\n",
" trend_info[tf] = get_enhanced_trend(tf, lookback, symbol)\n",
" if trend_info[tf] is None:\n",
" print(f\"⚠️ Keine Daten für {tf}\")\n",
" return None\n",
" \n",
" # 2. Market Regime aus H4 bestimmen\n",
" main_regime = trend_info[\"H4\"][\"regime_info\"]\n",
" \n",
" # 3. RELAXED Adaptive Confidence Threshold\n",
" adaptive_confidence_threshold = calculate_adaptive_confidence_threshold_relaxed(main_regime)\n",
" \n",
" # 4. Standard-Trend\n",
" d1_trend = trend_info[\"D1\"][\"trend\"]\n",
" h4_trend = trend_info[\"H4\"][\"trend\"]\n",
" d1_strength = trend_info[\"D1\"][\"trend_strength\"]\n",
" h4_strength = trend_info[\"H4\"][\"trend_strength\"]\n",
" \n",
" if d1_trend == h4_trend and d1_trend != \"sideways\":\n",
" standard_trend = d1_trend\n",
" standard_strength = (d1_strength * 0.6 + h4_strength * 0.4)\n",
" elif d1_strength > h4_strength * 1.5:\n",
" standard_trend = d1_trend\n",
" standard_strength = d1_strength * 0.8\n",
" elif h4_strength > d1_strength * 1.5:\n",
" standard_trend = h4_trend\n",
" standard_strength = h4_strength * 0.8\n",
" else:\n",
" standard_trend = \"sideways\"\n",
" standard_strength = 0\n",
" \n",
" # 5. RELAXED Fast-Trend\n",
" fast_timeframes = [\"H1\", \"M30\", \"M15\", \"M5\"]\n",
" fast_trends = [trend_info[tf][\"trend\"] for tf in fast_timeframes]\n",
" fast_strengths = [trend_info[tf][\"trend_strength\"] for tf in fast_timeframes]\n",
" \n",
" required_alignment = 2 # RELAXED: Immer 2 von 4\n",
" \n",
" trend_counts = {'uptrend': 0, 'downtrend': 0, 'sideways': 0}\n",
" weighted_strengths = {'uptrend': 0, 'downtrend': 0}\n",
" weights = [1.0, 0.8, 0.6, 0.4]\n",
" \n",
" for i, (trend, strength) in enumerate(zip(fast_trends, fast_strengths)):\n",
" trend_counts[trend] += 1\n",
" if trend != 'sideways':\n",
" weighted_strengths[trend] += strength * weights[i]\n",
" \n",
" max_count = max(trend_counts['uptrend'], trend_counts['downtrend'])\n",
" if max_count >= required_alignment:\n",
" if trend_counts['uptrend'] > trend_counts['downtrend']:\n",
" fast_trend = \"uptrend\"\n",
" elif trend_counts['downtrend'] > trend_counts['uptrend']:\n",
" fast_trend = \"downtrend\"\n",
" else:\n",
" fast_trend = \"uptrend\" if weighted_strengths['uptrend'] > weighted_strengths['downtrend'] else \"downtrend\"\n",
" else:\n",
" fast_trend = \"sideways\"\n",
" \n",
" # 6. Top-Down-Trend\n",
" if standard_trend == fast_trend and standard_trend != \"sideways\":\n",
" top_down_trend = standard_trend\n",
" combined_strength = (standard_strength + weighted_strengths.get(fast_trend, 0)) / 2\n",
" else:\n",
" top_down_trend = \"sideways\"\n",
" combined_strength = 0\n",
" \n",
" # 7. Enhanced Confidence\n",
" tf_weights = {\"D1\": 2.5, \"H4\": 2.0, \"H1\": 1.5, \"M30\": 1.0, \"M15\": 0.8, \"M5\": 0.6}\n",
" \n",
" weighted_matching = sum(\n",
" tf_weights[tf] * trend_info[tf][\"trend_strength\"] \n",
" for tf in timeframes\n",
" if trend_info[tf][\"trend\"] == top_down_trend and trend_info[tf][\"trend\"] != \"sideways\"\n",
" )\n",
" \n",
" weighted_total = sum(\n",
" tf_weights[tf] * trend_info[tf][\"trend_strength\"]\n",
" for tf in timeframes\n",
" if trend_info[tf][\"trend\"] != \"sideways\"\n",
" )\n",
" \n",
" confidence = round((weighted_matching / weighted_total) * 100, 2) if weighted_total > 0 else 0.0\n",
" \n",
" # 8. RELAXED Risk-Adjusted Signal Strength\n",
" atr = trend_info[\"M5\"][\"atr\"]\n",
" rrr = 2.5\n",
" risk_adjusted_strength = confidence * combined_strength * min(2.0, rrr)\n",
" \n",
" # 9. RELAXED Entry Signal\n",
" entry_signal = 0\n",
" signal_quality = \"none\"\n",
" min_strength = 80 # RELAXED: 80 statt 100\n",
" \n",
" if (top_down_trend != \"sideways\" and \n",
" confidence >= adaptive_confidence_threshold and\n",
" risk_adjusted_strength >= min_strength):\n",
" \n",
" entry_signal = 1 if top_down_trend == \"uptrend\" else -1\n",
" \n",
" # RELAXED Signal Quality\n",
" if confidence >= 80 and risk_adjusted_strength >= 130:\n",
" signal_quality = \"excellent\"\n",
" elif confidence >= 70 and risk_adjusted_strength >= 100:\n",
" signal_quality = \"good\"\n",
" else:\n",
" signal_quality = \"fair\"\n",
" \n",
" # 10. 🆕 Adaptive Rhythm Info\n",
" current_interval = rhythm_manager.current_interval\n",
" session = rhythm_manager.get_current_session()\n",
" \n",
" # 11. Debug Output\n",
" debug_data = []\n",
" for tf in timeframes:\n",
" info = trend_info[tf]\n",
" debug_data.append([\n",
" tf, info[\"trend\"], f\"{info['trend_strength']:.2f}\", \n",
" f\"{info['atr']:.4f}\", f\"{info['slope']:.6f}\", f\"{info['price']:.2f}\"\n",
" ])\n",
" \n",
" print(f\"\\n📊 V1.6 ADAPTIVE COMPLETE Trend-Analyse für {symbol}\")\n",
" print(f\"⚡ Adaptive Interval: {current_interval} min | Session: {session.upper()}\")\n",
" print(f\"🎯 Market Regime: {main_regime['regime'].upper()} (Strength: {main_regime['strength']:.0f}%)\")\n",
" print(f\"🎚️ Adaptive Threshold: {adaptive_confidence_threshold}% (RELAXED)\")\n",
" print()\n",
" print(tabulate(debug_data, headers=[\"TF\", \"Trend\", \"Strength\", \"ATR\", \"Slope\", \"Price\"], tablefmt=\"psql\"))\n",
" print(f\"\\n➡️ Standard-Trend: {standard_trend} (Strength: {standard_strength:.2f})\")\n",
" print(f\"➡️ Fast-Trend: {fast_trend} (Required: {required_alignment}/4)\")\n",
" print(f\"➡️ Top-Down-Trend: {top_down_trend}\")\n",
" print(f\"➡️ Confidence: {confidence}% (Threshold: {adaptive_confidence_threshold}%)\")\n",
" print(f\"➡️ Risk-Adjusted Strength: {risk_adjusted_strength:.1f} (Min: {min_strength})\")\n",
" print(f\"➡️ Signal Quality: {signal_quality.upper()}\")\n",
" print(f\"\\n🚀 V1.6 Adaptive Complete: Full Features + Adaptive Rhythm\")\n",
" \n",
" return {\n",
" \"symbol\": symbol,\n",
" \"trend_info\": trend_info,\n",
" \"market_regime\": main_regime,\n",
" \"standard_trend\": standard_trend,\n",
" \"fast_trend\": fast_trend,\n",
" \"top_down_trend\": top_down_trend,\n",
" \"confidence\": confidence,\n",
" \"adaptive_threshold\": adaptive_confidence_threshold,\n",
" \"risk_adjusted_strength\": risk_adjusted_strength,\n",
" \"entry_signal\": entry_signal,\n",
" \"signal_quality\": signal_quality,\n",
" \"combined_strength\": combined_strength,\n",
" \"min_strength_used\": min_strength,\n",
" \"required_alignment\": required_alignment,\n",
" \"adaptive_interval\": current_interval,\n",
" \"session\": session\n",
" }\n",
"\n",
"\n",
"print(\"✅ V1.6 Adaptive Complete Top-Down Analysis defined\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 8. Entry Timing Optimization"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 12,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ Entry timing functions defined (DISABLED in Relaxed mode)\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"def check_pullback_entry(symbol, signal_info, timeframe=\"M5\"):\n",
" \"\"\"\n",
" Entry Timing Check - in Relaxed Version DISABLED per default\n",
" \"\"\"\n",
" if signal_info[\"entry_signal\"] == 0:\n",
" return False, \"No base signal\"\n",
" \n",
" try:\n",
" df = get_rates(timeframe.lower(), 50, symbol)\n",
" if df is None or len(df) < 20:\n",
" return False, \"Insufficient data\"\n",
" \n",
" df['ema21'] = df['close'].ewm(span=21).mean()\n",
" df['ema50'] = df['close'].ewm(span=50).mean()\n",
" \n",
" current_price = df['close'].iloc[-1]\n",
" ema21 = df['ema21'].iloc[-1]\n",
" ema50 = df['ema50'].iloc[-1]\n",
" signal_direction = signal_info[\"entry_signal\"]\n",
" \n",
" if signal_direction == 1: # Long\n",
" if current_price <= ema21 * 1.002 and ema21 > ema50:\n",
" return True, \"Pullback to EMA21 for Long\"\n",
" elif current_price <= ema21 * 0.998:\n",
" return True, \"Below EMA21 - Good Long Entry\"\n",
" elif signal_direction == -1: # Short\n",
" if current_price >= ema21 * 0.998 and ema21 < ema50:\n",
" return True, \"Pullback to EMA21 for Short\"\n",
" elif current_price >= ema21 * 1.002:\n",
" return True, \"Above EMA21 - Good Short Entry\"\n",
" \n",
" return False, \"Waiting for better entry timing\"\n",
" except Exception as e:\n",
" return True, \"Using immediate entry (fallback)\"\n",
"\n",
"\n",
"print(\"✅ Entry timing functions defined (DISABLED in Relaxed mode)\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 9. Execute Trade Function"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 13,
2025-11-26 21:14:01 +01:00
"metadata": {},
"outputs": [],
"source": [
"def calculate_position_size(self, symbol, stop_loss_pips, max_risk_per_trade=0.02):\n",
" \"\"\"\n",
" Berechnet die Positionsgröße basierend auf Risiko\n",
" \"\"\"\n",
" account_info = mt.account_info()\n",
" if not account_info:\n",
" print(f\"⚠️ Keine Account-Info verfügbar, verwende Minimum-Lot\")\n",
" return 0.01\n",
" \n",
" balance = account_info.balance\n",
" risk_amount = balance * max_risk_per_trade\n",
" \n",
" # Symbol-Info holen\n",
" symbol_info = mt.symbol_info(symbol)\n",
" if not symbol_info:\n",
" print(f\"⚠️ Keine Symbol-Info für {symbol}, verwende Minimum-Lot\")\n",
" return 0.01\n",
" \n",
" # Pip-Wert berechnen\n",
" point = symbol_info.point\n",
" tick_value = symbol_info.trade_tick_value\n",
" tick_size = symbol_info.trade_tick_size\n",
" \n",
" # Volume berechnen\n",
" pip_value = (tick_value / tick_size) * point\n",
" volume = risk_amount / (stop_loss_pips * pip_value)\n",
" \n",
" # Auf erlaubte Volumenschritte runden\n",
" volume_min = symbol_info.volume_min\n",
" volume_max = symbol_info.volume_max\n",
" volume_step = symbol_info.volume_step\n",
" \n",
" volume = round(volume / volume_step) * volume_step\n",
" volume = max(volume_min, min(volume_max, volume))\n",
" \n",
" print(f\"💰 Position Sizing für {symbol}:\")\n",
" print(f\" Balance: ${balance:.2f}\")\n",
" print(f\" Risiko: ${risk_amount:.2f} ({max_risk_per_trade*100}%)\")\n",
" print(f\" Stop Loss: {stop_loss_pips:.2f} Pips\")\n",
" print(f\" Berechnetes Volume: {volume:.2f} Lots\")\n",
" \n",
" return volume"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 14,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"data": {
"text/plain": [
"0.01"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
2025-11-26 21:14:01 +01:00
"source": [
"#mt.symbol_info(symbol).volume_min\n",
"mt.symbol_info(symbol).volume_step"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 15,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ V1.6 Adaptive Complete Execute Trade defined\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"def execute_trade_v2_adaptive(\n",
" symbol=\"XAUUSD\",\n",
" atr_mult=1.5,\n",
" base_confidence=60,\n",
" max_risk_per_trade=0.01,\n",
" risk_filter=True,\n",
" min_atr=0.0008,\n",
" use_pullback_entry=False, # DISABLED\n",
" max_positions=1,\n",
" strategy_name=\"TradingBot_V1.6\",\n",
" debug=True\n",
"):\n",
" \"\"\"\n",
" V1.6 Adaptive Complete Trade-Ausführung:\n",
" - Position Control\n",
" - Relaxed Parameter\n",
" - Adaptive Rhythm Integration\n",
" \"\"\"\n",
" \n",
" # SCHRITT 1: POSITION CHECK\n",
" print(f\"\\n🔍 POSITION CHECK für {symbol} (V1.6 Adaptive Complete)\")\n",
" has_position, position_info = check_existing_positions(symbol, strategy_name)\n",
" \n",
" if has_position and position_info['count'] >= max_positions:\n",
" if debug:\n",
" print(f\"🛑 TRADE BLOCKIERT: {position_info['count']}/{max_positions} Positionen aktiv\")\n",
" for pos in position_info['details']:\n",
" profit_emoji = \"🟢\" if pos['profit'] >= 0 else \"🔴\"\n",
" print(f\" {pos['type']} @ {pos['price_open']} | {profit_emoji} {pos['profit']:.2f}\")\n",
" return None\n",
" \n",
" print(f\"✅ Position-Check OK: {position_info['count']}/{max_positions}\")\n",
" \n",
" # SCHRITT 2: Signal Analysis\n",
" signal_info = extended_top_down_v2_adaptive(symbol)\n",
" if signal_info is None:\n",
" print(\"❌ Signal-Analyse fehlgeschlagen\")\n",
" return None\n",
" \n",
" entry_signal = signal_info[\"entry_signal\"]\n",
" confidence = signal_info[\"confidence\"]\n",
" adaptive_threshold = signal_info[\"adaptive_threshold\"]\n",
" signal_quality = signal_info[\"signal_quality\"]\n",
" market_regime = signal_info[\"market_regime\"]\n",
" \n",
" # SCHRITT 3: Get Price/ATR\n",
" m5_info = signal_info[\"trend_info\"][\"M5\"]\n",
" price = m5_info[\"price\"]\n",
" atr = m5_info[\"atr\"]\n",
" \n",
" # SCHRITT 4: Pre-checks\n",
" reason = \"\"\n",
" \n",
" if confidence < adaptive_threshold:\n",
" reason = f\"Confidence {confidence}% < threshold {adaptive_threshold}%\"\n",
" elif entry_signal == 0:\n",
" reason = f\"No entry signal\"\n",
" elif price is None or atr is None:\n",
" reason = \"Price/ATR not available\"\n",
" elif risk_filter and atr < min_atr:\n",
" reason = f\"ATR {atr:.5f} < min_atr {min_atr}\"\n",
" else:\n",
" risk_ok = check_risk_limits(symbol, max_risk_per_trade=max_risk_per_trade)\n",
" if not risk_ok:\n",
" reason = \"Risk limits exceeded\"\n",
" \n",
" # SCHRITT 5: Execute Trade\n",
" if not reason:\n",
" # Final Position Check\n",
" final_check, _ = check_existing_positions(symbol, strategy_name)\n",
" if final_check:\n",
" print(f\"🛑 Position wurde zwischen Checks eröffnet!\")\n",
" return None\n",
" \n",
" # SL/TP Calculation\n",
" regime_mult = 1.0\n",
" if market_regime['regime'] == 'volatile':\n",
" regime_mult = 1.2\n",
" elif market_regime['regime'] == 'ranging':\n",
" regime_mult = 0.9\n",
" \n",
" adjusted_atr_mult = atr_mult * regime_mult\n",
" \n",
" if entry_signal == 1: # Long\n",
" stop_loss = price - adjusted_atr_mult * atr\n",
" take_profit = price + adjusted_atr_mult * atr * 2.5\n",
" else: # Short\n",
" stop_loss = price + adjusted_atr_mult * atr\n",
" take_profit = price - adjusted_atr_mult * atr * 2.5\n",
" \n",
" # Position Sizing\n",
" account_info = mt.account_info()\n",
" if account_info:\n",
" balance = account_info.balance\n",
" risk_amount = balance * max_risk_per_trade\n",
" if symbol == \"XAUUSD\":\n",
2025-12-16 22:02:15 +01:00
" # 🎯 ADAPTIVE POSITION SIZING\n",
" if 'adv_position_mgr' in globals() and adv_position_mgr.adaptive_sizing:\n",
" volume = adv_position_mgr.adaptive_sizing.calculate_position_size(\n",
" confidence=confidence,\n",
" balance=balance,\n",
" stop_loss_distance=adjusted_atr_mult * atr * 10000, # Convert to pips\n",
" symbol=symbol\n",
" )\n",
" else:\n",
" volume = round(min(0.1, max(0.01, risk_amount / (adjusted_atr_mult * atr * 100))),2)\n",
2025-11-26 21:14:01 +01:00
" else:\n",
" volume = 0.01\n",
" else:\n",
" volume = 0.01\n",
" \n",
" # Log Trade Info\n",
" print(f\"\\n🚀 V1.6 ADAPTIVE COMPLETE TRADE EXECUTION\")\n",
" print(f\"Direction: {'LONG' if entry_signal == 1 else 'SHORT'}\")\n",
" print(f\"Price: {price:.5f} | Volume: {volume:.2f}\")\n",
" print(f\"SL: {stop_loss:.5f} | TP: {take_profit:.5f}\")\n",
" print(f\"Confidence: {confidence}% | Quality: {signal_quality.upper()}\")\n",
" print(f\"Regime: {market_regime['regime'].upper()}\")\n",
" print(f\"Adaptive Interval: {signal_info['adaptive_interval']} min\")\n",
" print(f\"Session: {signal_info['session'].upper()}\")\n",
" \n",
" # Execute\n",
" try:\n",
" order_result = market_order(\n",
" symbol=symbol,\n",
" volume=volume,\n",
" order_type=\"buy\" if entry_signal == 1 else \"sell\",\n",
" stoploss=stop_loss,\n",
" take_profit=take_profit\n",
" )\n",
" \n",
" if order_result and order_result.retcode == mt.TRADE_RETCODE_DONE:\n",
" print(f\"✅ Trade erfolgreich! Ticket: {order_result.order}\")\n",
" \n",
" # ==========================================\n",
" # LOG TRADE ENTRY (V1.8)\n",
" # ==========================================\n",
" try:\n",
" # Hole Position Info\n",
" positions = mt.positions_get(symbol=symbol)\n",
" if positions and infra:\n",
" position = positions[0]\n",
"\n",
" # Erstelle Trade Data\n",
" trade_data = {\n",
" 'ticket': position.ticket,\n",
" 'position_id': position.identifier,\n",
" 'symbol': symbol,\n",
" 'strategy_name': strategy_name,\n",
" 'type': 'BUY' if entry_signal == 1 else 'SELL',\n",
" 'volume': volume,\n",
" 'entry_price': position.price_open,\n",
" 'sl_price': position.sl,\n",
" 'tp_price': position.tp,\n",
" 'entry_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),\n",
" 'session': rhythm_manager.get_current_session(),\n",
" 'regime': market_regime['regime'],\n",
" 'quality': signal_quality,\n",
" 'confidence': confidence if 'confidence' in locals() else None,\n",
" 'timeframe_alignment': signal_info.get('required_alignment', 2),\n",
" 'risk_amount': risk_amount if 'risk_amount' in locals() else None,\n",
" 'risk_pct': max_risk_per_trade\n",
" }\n",
"\n",
" # Log to Database + Send Telegram\n",
" infra.log_trade_entry(trade_data)\n",
" logger.info(\"📱 Trade logged to DB + Telegram notification sent\")\n",
"\n",
" except Exception as e:\n",
" logger.error(f\"⚠️ Infrastructure logging failed: {e}\")\n",
" # ==========================================\n",
"\n",
"\n",
" # Verify & Log\n",
" new_check, new_info = check_existing_positions(symbol, strategy_name)\n",
" print(f\"📊 Positionen: {new_info['count']}\")\n",
" log_trade_performance_adaptive(signal_info, order_result)\n",
" else:\n",
" print(f\"❌ Trade failed: {order_result.comment if order_result else 'No result'}\")\n",
" \n",
" return order_result\n",
" \n",
" except Exception as e:\n",
" print(f\"❌ Execution failed: {e}\")\n",
" return None\n",
" \n",
" else:\n",
" if debug:\n",
" print(f\"\\n⏸️ TRADE SKIPPED: {reason}\")\n",
" return None\n",
"\n",
"\n",
"print(\"✅ V1.6 Adaptive Complete Execute Trade defined\")"
]
},
2025-12-16 22:02:15 +01:00
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ Ranging Filter activated!\n",
" 🛑 Blocks ALL ranging market trades\n",
" ✅ Only allows trending markets with ADX > 25\n"
]
}
],
"source": [
"# ==========================================\n",
"# 🔥 FIX #1: RANGING FILTER WRAPPER (09.12.2025)\n",
"# ==========================================\n",
"\n",
"# Original function wird wrapped\n",
"_original_execute_trade_v2_adaptive = execute_trade_v2_adaptive\n",
"\n",
"def execute_trade_v2_adaptive_with_ranging_filter(\n",
" symbol=\"XAUUSD\",\n",
" atr_mult=1.5,\n",
" base_confidence=60,\n",
" max_risk_per_trade=0.01,\n",
" risk_filter=True,\n",
" min_atr=0.0008,\n",
" use_pullback_entry=False,\n",
" max_positions=1,\n",
" strategy_name=\"TradingBot_V1.6\",\n",
" debug=True):\n",
" \"\"\"\n",
" Wrapper für execute_trade_v2_adaptive mit Ranging Filter\n",
" Blocks trading in ranging markets - they cause 100% of losses!\n",
" \"\"\"\n",
"\n",
" # Quick check: Get signal info first\n",
" signal_info = extended_top_down_v2_adaptive(symbol)\n",
" if signal_info is None:\n",
" return None\n",
"\n",
" market_regime = signal_info.get(\"market_regime\", {})\n",
" regime = market_regime.get('regime', 'unknown')\n",
" adx = market_regime.get('adx', 0)\n",
"\n",
" # 🛑 RANGING FILTER - Block ALL ranging market trades\n",
" if regime == 'ranging':\n",
" if debug:\n",
" print(f\"\\n🛑 TRADE BLOCKIERT: Ranging Market!\")\n",
" print(f\" ADX: {adx:.1f} (< 25 = Ranging)\")\n",
" print(f\" 📊 Ranging Performance: 0% Win Rate, 20 consecutive losses\")\n",
" print(f\" ✅ Filter is protecting you from losses!\")\n",
" return None\n",
"\n",
" # Additional safety: Even in trending, ADX must be > 25\n",
" if regime == 'trending' and adx < 25:\n",
" if debug:\n",
" print(f\"\\n🛑 TRADE BLOCKIERT: Weak Trend!\")\n",
" print(f\" ADX: {adx:.1f} (< 25 = too weak)\")\n",
" return None\n",
"\n",
" # ✅ Regime check passed - execute original function\n",
" if debug:\n",
" print(f\"✅ REGIME CHECK PASSED: {regime.upper()} (ADX {adx:.1f})\")\n",
"\n",
" return _original_execute_trade_v2_adaptive(\n",
" symbol=symbol,\n",
" atr_mult=atr_mult,\n",
" base_confidence=base_confidence,\n",
" max_risk_per_trade=max_risk_per_trade,\n",
" risk_filter=risk_filter,\n",
" min_atr=min_atr,\n",
" use_pullback_entry=use_pullback_entry,\n",
" max_positions=max_positions,\n",
" strategy_name=strategy_name,\n",
" debug=debug\n",
" )\n",
"\n",
"# Replace original with wrapped version\n",
"execute_trade_v2_adaptive = execute_trade_v2_adaptive_with_ranging_filter\n",
"\n",
"print(\"✅ Ranging Filter activated!\")\n",
"print(\" 🛑 Blocks ALL ranging market trades\")\n",
"print(\" ✅ Only allows trending markets with ADX > 25\")\n"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"⚠️ check_open_positions not found - skipping Position Monitor fix\n"
]
}
],
"source": [
"# ==========================================\n",
"# 🔥 FIX #2: POSITION MONITOR DB LOGGING (09.12.2025)\n",
"# ==========================================\n",
"\n",
"# Wrap check_open_positions to add DB logging\n",
"if 'check_open_positions' in globals():\n",
" _original_check_open_positions = check_open_positions\n",
"\n",
" def check_open_positions_with_db_logging():\n",
" \"\"\"\n",
" Enhanced position monitor that writes exits to database\n",
" \"\"\"\n",
" from datetime import datetime\n",
"\n",
" # Get current open positions from MT5\n",
" positions = mt.positions_get(symbol=symbol)\n",
"\n",
" if not positions or len(positions) == 0:\n",
" # Check if we have positions in DB that should be closed\n",
" if 'db' in globals():\n",
" try:\n",
" open_trades_in_db = db.get_open_trades()\n",
"\n",
" for trade in open_trades_in_db:\n",
" ticket = trade['ticket']\n",
"\n",
" # Check if this position is in MT5 history (closed)\n",
" deals = mt.history_deals_get(ticket=ticket)\n",
" if deals and len(deals) > 0:\n",
" # Position was closed - log to DB\n",
" last_deal = deals[-1]\n",
"\n",
" db.close_trade(\n",
" ticket=ticket,\n",
" exit_price=last_deal.price,\n",
" exit_time=datetime.fromtimestamp(last_deal.time),\n",
" profit=last_deal.profit,\n",
" status='closed',\n",
" exit_reason='mt5_detected',\n",
" commission=last_deal.commission,\n",
" swap=last_deal.swap\n",
" )\n",
"\n",
" logger.info(f\"💾 Position #{ticket} exit logged to DB (profit: ${last_deal.profit:.2f})\")\n",
"\n",
" except Exception as e:\n",
" logger.error(f\"⚠️ DB logging error: {e}\")\n",
"\n",
" # Call original function\n",
" return _original_check_open_positions()\n",
"\n",
" # Replace\n",
" check_open_positions = check_open_positions_with_db_logging\n",
" print(\"✅ Position Monitor DB logging activated!\")\n",
" print(\" 💾 Exits will be written to SQLite database\")\n",
" print(\" 📊 Drawdown Protection will work correctly\")\n",
"else:\n",
" print(\"⚠️ check_open_positions not found - skipping Position Monitor fix\")\n"
]
},
2025-11-26 21:14:01 +01:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 10. Performance Monitoring & Logging"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 18,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ Performance Monitoring functions defined (with adaptive features)\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"def log_trade_performance_adaptive(signal_info, order_result):\n",
" \"\"\"\n",
" Loggt Trade-Performance für V1.6 Adaptive Complete\n",
" \"\"\"\n",
" trade_data = {\n",
" 'timestamp': datetime.now().isoformat(),\n",
" 'version': 'V1.6_Adaptive_Complete',\n",
" 'symbol': signal_info['symbol'],\n",
" 'entry_signal': signal_info['entry_signal'],\n",
" 'confidence': signal_info['confidence'],\n",
" 'adaptive_threshold': signal_info['adaptive_threshold'],\n",
" 'signal_quality': signal_info['signal_quality'],\n",
" 'market_regime': signal_info['market_regime']['regime'],\n",
" 'regime_strength': signal_info['market_regime']['strength'],\n",
" 'risk_adjusted_strength': signal_info['risk_adjusted_strength'],\n",
" 'adaptive_interval': signal_info['adaptive_interval'],\n",
" 'session': signal_info['session'],\n",
" 'relaxed_features': {\n",
" 'pullback_entry_disabled': True,\n",
" 'lower_confidence_threshold': True,\n",
" 'lower_min_strength': True,\n",
" 'fixed_tf_alignment': True\n",
" },\n",
" 'adaptive_features': {\n",
" 'adaptive_rhythm': True,\n",
" 'session_aware': True,\n",
" 'volatility_based': True\n",
" },\n",
" 'position_control_active': True,\n",
" 'order_result': str(order_result) if order_result else None\n",
" }\n",
" \n",
" try:\n",
" filename = f\"trade_performance_v16_{signal_info['symbol']}_{datetime.now().strftime('%Y%m')}.json\"\n",
" try:\n",
" with open(filename, 'r') as f: \n",
" data = json.load(f)\n",
" except FileNotFoundError: \n",
" data = []\n",
" data.append(trade_data)\n",
" with open(filename, 'w') as f: \n",
" json.dump(data, f, indent=2)\n",
" print(f\"📊 Performance logged to {filename}\")\n",
" except Exception as e:\n",
" print(f\"Warning: Could not log performance: {e}\")\n",
"\n",
"\n",
"def analyze_performance_adaptive(symbol=\"XAUUSD\", days_back=30):\n",
" \"\"\"\n",
" Analysiert Performance der V1.6 Adaptive Complete Version\n",
" \"\"\"\n",
" try:\n",
" filename = f\"trade_performance_v16_{symbol}_{datetime.now().strftime('%Y%m')}.json\"\n",
" \n",
" with open(filename, 'r') as f:\n",
" data = json.load(f)\n",
" \n",
" cutoff = datetime.now() - timedelta(days=days_back)\n",
" recent_trades = [\n",
" trade for trade in data \n",
" if datetime.fromisoformat(trade['timestamp']) > cutoff\n",
" ]\n",
" \n",
" if not recent_trades:\n",
" print(f\"No V1.6 trades in last {days_back} days\")\n",
" return\n",
" \n",
" total_trades = len(recent_trades)\n",
" \n",
" # Analysis by regime\n",
" by_regime = {}\n",
" for trade in recent_trades:\n",
" regime = trade['market_regime']\n",
" by_regime[regime] = by_regime.get(regime, 0) + 1\n",
" \n",
" # Analysis by interval\n",
" by_interval = {}\n",
" for trade in recent_trades:\n",
" interval = trade.get('adaptive_interval', 'unknown')\n",
" by_interval[interval] = by_interval.get(interval, 0) + 1\n",
" \n",
" # Analysis by session\n",
" by_session = {}\n",
" for trade in recent_trades:\n",
" session = trade.get('session', 'unknown')\n",
" by_session[session] = by_session.get(session, 0) + 1\n",
" \n",
" # Print results\n",
" print(f\"\\n📊 V1.6 ADAPTIVE COMPLETE PERFORMANCE - Last {days_back} days\")\n",
" print(f\"Total Trades: {total_trades}\")\n",
" \n",
" print(f\"\\nBy Market Regime:\")\n",
" for regime, count in by_regime.items():\n",
" print(f\" {regime.upper()}: {count} ({count/total_trades*100:.1f}%)\")\n",
" \n",
" print(f\"\\n🆕 By Adaptive Interval:\")\n",
" for interval, count in sorted(by_interval.items()):\n",
" print(f\" {interval} min: {count} ({count/total_trades*100:.1f}%)\")\n",
" \n",
" print(f\"\\n🆕 By Trading Session:\")\n",
" for session, count in by_session.items():\n",
" print(f\" {session.upper()}: {count} ({count/total_trades*100:.1f}%)\")\n",
" \n",
" except Exception as e:\n",
" print(f\"Could not analyze performance: {e}\")\n",
"\n",
"\n",
"print(\"✅ Performance Monitoring functions defined (with adaptive features)\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 11. 🆕 Adaptive Scheduler"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 19,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"🔧 Force resuming trading after Ranging Filter deployment...\n",
"⚠️ drawdown_protection not initialized yet\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
2025-12-16 22:02:15 +01:00
"# ==========================================\n",
"# FORCE RESUME TRADING (V2.2 FIX)\n",
"# ==========================================\n",
"\n",
"print(\"🔧 Force resuming trading after Ranging Filter deployment...\")\n",
"\n",
"if 'drawdown_protection' in globals():\n",
" # Force resume\n",
" drawdown_protection._resume_trading()\n",
" \n",
" # Verify\n",
" can_trade, reason = drawdown_protection.can_trade()\n",
" \n",
" print(f\"\\n✅ Status after resume:\")\n",
" print(f\" Can Trade: {can_trade}\")\n",
" print(f\" Reason: {reason if not can_trade else 'All clear!'}\")\n",
" \n",
" if not can_trade:\n",
" print(\"\\n⚠️ Still blocked - using nuclear option...\")\n",
" drawdown_protection.trading_paused = False\n",
" drawdown_protection.pause_until = None\n",
" drawdown_protection.pause_reason = None\n",
" \n",
" can_trade2, reason2 = drawdown_protection.can_trade()\n",
" print(f\" After force clear: {can_trade2}\")\n",
" \n",
" print(\"\\n🛡️ Drawdown Protection Status:\")\n",
" status = drawdown_protection.get_status()\n",
" print(f\" Consecutive Losses: {status['consecutive_losses']}\")\n",
" print(f\" Trading Allowed: {status['trading_allowed']}\")\n",
" \n",
"else:\n",
" print(\"⚠️ drawdown_protection not initialized yet\")"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"🔧 Setting up Trading Check...\n",
"✅ Session Filter aktiviert!\n",
" Deaktivierte Sessions:\n",
" • ASIAN : ✅ AKTIV\n",
" • LONDON : ❌ DEAKTIVIERT\n",
" • OVERLAP : ❌ DEAKTIVIERT\n",
" • NY : ✅ AKTIV\n",
"\n",
"🛡️ Drawdown Protection aktiviert!\n",
" • Daily Loss Limit: $100\n",
" • Weekly Loss Limit: $300\n",
" • Monthly Loss Limit: $800\n",
" • Max Consecutive Losses: 5\n",
" • Cooldown: 24h\n",
"\n",
"✅ Trading Check ist jetzt vollständig geschützt!\n",
" 📊 Session Filter: Aktiv\n",
" 🛡️ Drawdown Protection: Aktiv\n"
]
}
],
"source": [
"# ==========================================\n",
"# TRADING CHECK: SESSION FILTER + DRAWDOWN PROTECTION\n",
"# ==========================================\n",
"\n",
2025-11-26 21:14:01 +01:00
"from session_filter_patch import (\n",
" create_session_filtered_check,\n",
" SESSION_WHITELIST_CONFIG,\n",
" is_session_allowed\n",
")\n",
2025-12-16 22:02:15 +01:00
"from drawdown_protection import create_protected_trading_check\n",
2025-11-26 21:14:01 +01:00
"\n",
2025-12-16 22:02:15 +01:00
"print(\"🔧 Setting up Trading Check...\")\n",
"\n",
"# Step 1: Create base session-filtered trading check\n",
"base_trading_check = create_session_filtered_check(\n",
2025-11-26 21:14:01 +01:00
" rhythm_manager=rhythm_manager,\n",
" execute_func=execute_trade_v2_adaptive,\n",
" symbol=symbol,\n",
" strategy_name=strategy_name,\n",
" max_positions=max_positions,\n",
" logger=logger,\n",
" datetime=datetime\n",
")\n",
"\n",
2025-12-16 22:02:15 +01:00
"print(\"✅ Session Filter aktiviert!\")\n",
2025-11-26 21:14:01 +01:00
"print(\" Deaktivierte Sessions:\")\n",
"for session, enabled in SESSION_WHITELIST_CONFIG['enabled_sessions'].items():\n",
" status = \"✅ AKTIV\" if enabled else \"❌ DEAKTIVIERT\"\n",
2025-12-16 22:02:15 +01:00
" print(f\" • {session.upper():8s}: {status}\")\n",
"\n",
"# Step 2: Wrap with Drawdown Protection\n",
"adaptive_trading_check = create_protected_trading_check(infra, base_trading_check)\n",
"drawdown_protection = adaptive_trading_check.protection\n",
"\n",
"print(\"\\n🛡️ Drawdown Protection aktiviert!\")\n",
"print(f\" • Daily Loss Limit: ${drawdown_protection.max_daily_loss}\")\n",
"print(f\" • Weekly Loss Limit: ${drawdown_protection.max_weekly_loss}\")\n",
"print(f\" • Monthly Loss Limit: ${drawdown_protection.max_monthly_loss}\")\n",
"print(f\" • Max Consecutive Losses: {drawdown_protection.max_consecutive_losses}\")\n",
"print(f\" • Cooldown: {drawdown_protection.cooldown_hours}h\")\n",
"\n",
"print(\"\\n✅ Trading Check ist jetzt vollständig geschützt!\")\n",
"print(\" 📊 Session Filter: Aktiv\")\n",
"print(\" 🛡️ Drawdown Protection: Aktiv\")\n"
2025-11-26 21:14:01 +01:00
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"2025-12-10 09:27:00,491 - INFO - ✅ Trading resumed after: None\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ Trading force-resumed (Ranging Filter deployed)\n"
]
}
],
"source": [
"# Force resume after restart (V2.2 fix)\n",
"drawdown_protection._resume_trading()\n",
"print(\"✅ Trading force-resumed (Ranging Filter deployed)\")"
]
},
{
"cell_type": "code",
"execution_count": 22,
2025-11-26 21:14:01 +01:00
"metadata": {},
"outputs": [],
"source": [
"# def adaptive_trading_check():\n",
"# \"\"\"\n",
"# 🆕 V1.6: Adaptive Trading Check\n",
"# Prüft basierend auf optimalem Intervall ob gehandelt werden soll\n",
"# \"\"\"\n",
"# try:\n",
"# optimal_interval = rhythm_manager.calculate_optimal_interval()\n",
"# current_minute = datetime.now().minute\n",
" \n",
"# # Trading nur zu berechneten Zeitpunkten\n",
"# if current_minute % optimal_interval == 0:\n",
"# logger.info(f\"\\n⏰ {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - ADAPTIVE Check\")\n",
"# logger.info(f\"Intervall: {optimal_interval} min\")\n",
" \n",
"# # Führe Trading aus\n",
"# execute_trade_v2_adaptive(\n",
"# symbol=symbol,\n",
"# strategy_name=strategy_name,\n",
"# max_positions=max_positions\n",
"# )\n",
" \n",
"# except Exception as e:\n",
"# logger.error(f\"Fehler im Adaptive Trading Check: {e}\")\n",
"\n",
"\n",
"def print_status_report():\n",
" \"\"\"Status-Report\"\"\"\n",
" print(rhythm_manager.get_status_report())\n",
"\n",
"\n",
"# print(\"✅ Adaptive Scheduler functions defined\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 12. ✅ KORRIGIERT: Trading Configuration"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 23,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"⚙️ V1.6 Adaptive Complete Configuration:\n",
"\n",
"🛡️ Position Control:\n",
" Max Positions: 1\n",
" Strategy: TradingBot_V1.6\n",
"\n",
"🚀 Relaxed Parameters:\n",
" Base Confidence: 60%\n",
" Min ATR: 0.0008\n",
" Pullback Entry: False\n",
"\n",
"⚡ Adaptive Features:\n",
" Dynamic Intervals: 5/15/30 min\n",
" Session-aware: Yes\n",
" Volatility-based: Yes\n",
"\n",
"✅ Configuration complete!\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"# ✅ KORRIGIERT: Zentrale Konfiguration (fehlte in ursprünglicher V1.6)\n",
"ADAPTIVE_COMPLETE_CONFIG = {\n",
" 'symbol': symbol,\n",
" 'atr_mult': 1.5,\n",
" 'base_confidence': 60, # RELAXED\n",
" 'max_risk_per_trade': 0.01,\n",
" 'risk_filter': True,\n",
" 'min_atr': 0.0008, # RELAXED\n",
" 'use_pullback_entry': False, # DISABLED\n",
" 'max_positions': max_positions,\n",
" 'strategy_name': strategy_name,\n",
" 'debug': True\n",
"}\n",
"\n",
"print(\"⚙️ V1.6 Adaptive Complete Configuration:\")\n",
"print(\"\\n🛡️ Position Control:\")\n",
"print(f\" Max Positions: {ADAPTIVE_COMPLETE_CONFIG['max_positions']}\")\n",
"print(f\" Strategy: {ADAPTIVE_COMPLETE_CONFIG['strategy_name']}\")\n",
"\n",
"print(\"\\n🚀 Relaxed Parameters:\")\n",
"print(f\" Base Confidence: {ADAPTIVE_COMPLETE_CONFIG['base_confidence']}%\")\n",
"print(f\" Min ATR: {ADAPTIVE_COMPLETE_CONFIG['min_atr']}\")\n",
"print(f\" Pullback Entry: {ADAPTIVE_COMPLETE_CONFIG['use_pullback_entry']}\")\n",
"\n",
"print(\"\\n⚡ Adaptive Features:\")\n",
"print(f\" Dynamic Intervals: 5/15/30 min\")\n",
"print(f\" Session-aware: Yes\")\n",
"print(f\" Volatility-based: Yes\")\n",
"\n",
"print(\"\\n✅ Configuration complete!\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 13. ✅ KORRIGIERT: Status & Monitoring Functions"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 24,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ Status monitoring function defined (COMPLETE with all features)\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"# ✅ KORRIGIERT: Umfassendes Status Monitoring (fehlte in V1.6)\n",
"def check_adaptive_bot_status():\n",
" \"\"\"\n",
" ✅ NEU: Kombiniertes Status-Check für V1.6 Adaptive Complete\n",
" Kombiniert Position Control + Adaptive Rhythm Status\n",
" \"\"\"\n",
" print(\"\\n\" + \"=\"*70)\n",
" print(\"🔍 V1.6 ADAPTIVE COMPLETE BOT STATUS\")\n",
" print(\"=\"*70)\n",
" \n",
" # System Status\n",
" print(\"\\n📡 SYSTEM STATUS:\")\n",
" print(f\" MT5 Connection: {'✅' if mt.terminal_info() else '❌'}\")\n",
" print(f\" Scheduler Running: {'✅' if scheduler.running else '❌'}\")\n",
" print(f\" Active Jobs: {len(scheduler.get_jobs())}\")\n",
" \n",
" # Adaptive Rhythm Status\n",
" print(\"\\n⚡ ADAPTIVE RHYTHM:\")\n",
" optimal_interval = rhythm_manager.calculate_optimal_interval()\n",
" session = rhythm_manager.get_current_session()\n",
" df = rhythm_manager.get_market_data()\n",
" \n",
" if df is not None:\n",
" atr = df['atr'].iloc[-1]\n",
" vol_level = rhythm_manager.get_volatility_level(atr)\n",
" print(f\" Current Interval: {optimal_interval} min\")\n",
" print(f\" Trading Session: {session.upper()}\")\n",
" print(f\" ATR (H1): {atr:.2f}\")\n",
" print(f\" Volatility: {vol_level.upper()}\")\n",
" else:\n",
" print(\" ⚠️ Could not fetch market data\")\n",
" \n",
" # Position Status\n",
" print(\"\\n🛡️ POSITION CONTROL:\")\n",
" has_pos, pos_info = check_existing_positions(symbol, strategy_name)\n",
" print(f\" Active Positions: {pos_info['count']}/{max_positions}\")\n",
" print(f\" Trading Status: {'🛑 BLOCKED' if has_pos else '✅ READY'}\")\n",
" \n",
" if has_pos:\n",
" for i, pos in enumerate(pos_info['details'], 1):\n",
" profit_emoji = \"🟢\" if pos['profit'] >= 0 else \"🔴\"\n",
" print(f\" Position {i}: {pos['type']} | {profit_emoji} {pos['profit']:.2f}\")\n",
" \n",
" # Signal Status\n",
" print(\"\\n📊 CURRENT SIGNAL:\")\n",
" try:\n",
" signal_info = extended_top_down_v2_adaptive(symbol)\n",
" if signal_info:\n",
" signal_dir = \"LONG\" if signal_info['entry_signal'] == 1 else \"SHORT\" if signal_info['entry_signal'] == -1 else \"NONE\"\n",
" print(f\" Signal: {signal_dir}\")\n",
" print(f\" Confidence: {signal_info['confidence']}%\")\n",
" print(f\" Threshold: {signal_info['adaptive_threshold']}%\")\n",
" print(f\" Quality: {signal_info['signal_quality'].upper()}\")\n",
" print(f\" Regime: {signal_info['market_regime']['regime'].upper()}\")\n",
" \n",
" would_trade = (signal_info['entry_signal'] != 0 and not has_pos)\n",
" print(f\" Would Trade: {'✅ YES' if would_trade else '❌ NO'}\")\n",
" else:\n",
" print(\" ⚠️ Signal analysis failed\")\n",
" except Exception as e:\n",
" print(f\" ❌ Error: {e}\")\n",
" \n",
" # Version Info\n",
" print(\"\\n🎉 VERSION INFO:\")\n",
" print(\" Version: V1.6 Adaptive Complete (CORRECTED)\")\n",
" print(\" Features: Position Control + Relaxed + Adaptive Rhythm\")\n",
" print(\" Status: Production-Ready ✅\")\n",
" print(\"=\"*70)\n",
"\n",
"\n",
"print(\"✅ Status monitoring function defined (COMPLETE with all features)\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 14. 🚀 Start Adaptive Scheduler"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 25,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"2025-12-10 09:27:01,663 - INFO - Adding job tentatively -- it will be properly scheduled when the scheduler starts\n",
"2025-12-10 09:27:01,665 - INFO - Adding job tentatively -- it will be properly scheduled when the scheduler starts\n",
"2025-12-10 09:27:01,667 - INFO - Adding job tentatively -- it will be properly scheduled when the scheduler starts\n",
"2025-12-10 09:27:01,670 - INFO - Adding job tentatively -- it will be properly scheduled when the scheduler starts\n",
"2025-12-10 09:27:01,675 - INFO - Adding job tentatively -- it will be properly scheduled when the scheduler starts\n",
"2025-12-10 09:27:01,683 - INFO - Adding job tentatively -- it will be properly scheduled when the scheduler starts\n",
"2025-12-10 09:27:01,685 - INFO - Added job \"create_protected_trading_check.<locals>.protected_check\" to job store \"default\"\n",
"2025-12-10 09:27:01,686 - INFO - Added job \"print_status_report\" to job store \"default\"\n",
"2025-12-10 09:27:01,687 - INFO - Added job \"TradingInfrastructure.send_daily_report\" to job store \"default\"\n",
"2025-12-10 09:27:01,688 - INFO - Added job \"TradingInfrastructure.send_weekly_report\" to job store \"default\"\n",
"2025-12-10 09:27:01,689 - INFO - Added job \"PositionMonitor.check_open_positions\" to job store \"default\"\n",
"2025-12-10 09:27:01,690 - INFO - Added job \"<lambda>\" to job store \"default\"\n",
"2025-12-10 09:27:01,691 - INFO - Scheduler started\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ Scheduled reports added:\n",
" 📊 Daily report: 22:00 UTC\n",
" 📈 Weekly report: Sunday 23:00 UTC\n",
"✅ Scheduled reports added:\n",
" 📊 Daily report: 22:00 UTC\n",
" 📈 Weekly report: Sunday 23:00 UTC\n",
"✅ Position Monitor job added\n",
"✅ Advanced Position Management job added\n",
"\n",
"✅ Scheduler started!\n",
"\n",
"📋 Active Jobs: 6\n",
" • adaptive_trading_check\n",
" • position_monitor\n",
" • advanced_position_management\n",
" • status_report\n",
" • daily_report\n",
" • weekly_report\n",
"\n",
"======================================================================\n",
"🚀 TradingBot V2.2 - All Systems Ready!\n",
"======================================================================\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
2025-12-16 22:02:15 +01:00
"# ==========================================\n",
"# SETUP SCHEDULER (V1.6 ADAPTIVE COMPLETE)\n",
"# ==========================================\n",
"\n",
"from apscheduler.schedulers.background import BackgroundScheduler\n",
"\n",
2025-11-26 21:14:01 +01:00
"scheduler = BackgroundScheduler()\n",
"\n",
2025-12-16 22:02:15 +01:00
"# 1. ADAPTIVE TRADING CHECK (every minute, executes at optimal intervals)\n",
2025-11-26 21:14:01 +01:00
"scheduler.add_job(\n",
" func=adaptive_trading_check,\n",
" trigger='cron',\n",
" minute='*',\n",
2025-12-16 22:02:15 +01:00
" id='adaptive_trading_check',\n",
" replace_existing=True\n",
2025-11-26 21:14:01 +01:00
")\n",
"\n",
2025-12-16 22:02:15 +01:00
"# 2. STATUS REPORT (every 30 minutes)\n",
2025-11-26 21:14:01 +01:00
"scheduler.add_job(\n",
" func=print_status_report,\n",
" trigger='cron',\n",
" minute='0,30',\n",
2025-12-16 22:02:15 +01:00
" id='status_report',\n",
" replace_existing=True\n",
2025-11-26 21:14:01 +01:00
")\n",
"\n",
2025-12-16 22:02:15 +01:00
"# 3. SCHEDULED REPORTS (V1.8) - Daily & Weekly\n",
2025-11-26 21:14:01 +01:00
"create_scheduled_reports(infra, scheduler)\n",
"print(\"✅ Scheduled reports added:\")\n",
"print(\" 📊 Daily report: 22:00 UTC\")\n",
"print(\" 📈 Weekly report: Sunday 23:00 UTC\")\n",
"\n",
2025-12-16 22:02:15 +01:00
"# 4. POSITION MONITOR (V1.8) - Every minute\n",
"scheduler.add_job(\n",
" func=position_monitor.check_open_positions,\n",
" trigger='interval',\n",
" minutes=1,\n",
" id='position_monitor',\n",
" replace_existing=True\n",
")\n",
"print(\"✅ Position Monitor job added\")\n",
2025-11-26 21:14:01 +01:00
"\n",
2025-12-16 22:02:15 +01:00
"# 5. ADVANCED POSITION MANAGEMENT (V2.1) - Trailing Stop + Partial TP\n",
"scheduler.add_job(\n",
" func=lambda: adv_position_mgr.check_and_update_positions(symbol),\n",
" trigger='interval',\n",
" minutes=1,\n",
" id='advanced_position_management',\n",
" replace_existing=True\n",
")\n",
"print(\"✅ Advanced Position Management job added\")\n",
2025-11-26 21:14:01 +01:00
"\n",
2025-12-16 22:02:15 +01:00
"# START SCHEDULER\n",
"if not scheduler.running:\n",
" scheduler.start()\n",
" print(\"\\n✅ Scheduler started!\")\n",
"else:\n",
" print(\"\\n⚠️ Scheduler already running\")\n",
2025-11-26 21:14:01 +01:00
"\n",
2025-12-16 22:02:15 +01:00
"# Show active jobs\n",
"print(f\"\\n📋 Active Jobs: {len(scheduler.get_jobs())}\")\n",
"for job in scheduler.get_jobs():\n",
" print(f\" • {job.id}\")\n",
2025-11-26 21:14:01 +01:00
"\n",
"print(\"\\n\" + \"=\"*70)\n",
2025-12-16 22:02:15 +01:00
"print(\"🚀 TradingBot V2.2 - All Systems Ready!\")\n",
"print(\"=\"*70)\n"
2025-11-26 21:14:01 +01:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 15. ✅ KORRIGIERT: Testing Suite"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 26,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"🧪 TEST 1: Position Check\n",
"==================================================\n",
"\n",
"📊 POSITION SUMMARY für XAUUSD (V1.6 Adaptive Complete)\n",
"============================================================\n",
"✅ Keine aktiven Positionen - bereit für neuen Trade\n"
]
},
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
2025-11-26 21:14:01 +01:00
"source": [
"# ✅ KORRIGIERT: Umfassende Testing Suite (fehlte in V1.6)\n",
"\n",
"# Test 1: Position Summary\n",
"print(\"🧪 TEST 1: Position Check\")\n",
"print(\"=\"*50)\n",
"get_position_summary(symbol, strategy_name)"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 27,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"2025-12-10 09:27:02,498 - INFO - 🔄 Rhythmus-Änderung: 5m → 15m\n",
"2025-12-10 09:27:02,499 - INFO - Session: london, Volatilität: medium (ATR: 9.59)\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"🧪 TEST 2: Adaptive Rhythm\n",
"==================================================\n",
"\n",
"╔════════════════════════════════════════════════════════╗\n",
"║ ADAPTIVE RHYTHM STATUS - 09:27:02 UTC ║\n",
"╠════════════════════════════════════════════════════════╣\n",
"║ Aktuelles Intervall: 5 Minuten ║\n",
"║ Trading Session: LONDON ║\n",
"║ Volatilitätslevel: MEDIUM ║\n",
"║ ATR (H1): 9.59 ║\n",
"╠════════════════════════════════════════════════════════╣\n",
"║ INTERVALL-SCHEMA: ║\n",
"║ • Overlap (13-16 UTC): 5-15 Min (aktivste Phase) ║\n",
"║ • London/NY: 5-30 Min (volatilitätsabh.) ║\n",
"║ • Asian Session: 15-30 Min (ruhigere Phase) ║\n",
"╚════════════════════════════════════════════════════════╝\n",
"\n",
"\n",
"Details:\n",
" Optimal Interval: 15 min\n",
" Session: london\n",
" ATR: 9.59\n",
" Volatility Level: medium\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"# Test 2: Adaptive Rhythm Status\n",
"print(\"\\n🧪 TEST 2: Adaptive Rhythm\")\n",
"print(\"=\"*50)\n",
"print_status_report()\n",
"\n",
"# Test Details\n",
"optimal_interval = rhythm_manager.calculate_optimal_interval()\n",
"session = rhythm_manager.get_current_session()\n",
"df = rhythm_manager.get_market_data()\n",
"\n",
"if df is not None:\n",
" atr = df['atr'].iloc[-1]\n",
" vol_level = rhythm_manager.get_volatility_level(atr)\n",
" print(f\"\\nDetails:\")\n",
" print(f\" Optimal Interval: {optimal_interval} min\")\n",
" print(f\" Session: {session}\")\n",
" print(f\" ATR: {atr:.2f}\")\n",
" print(f\" Volatility Level: {vol_level}\")"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 28,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"🧪 TEST 3: Signal Analysis\n",
"==================================================\n",
"🔍 Analyzing XAUUSD with V1.6 ADAPTIVE COMPLETE parameters...\n",
"\n",
"📊 V1.6 ADAPTIVE COMPLETE Trend-Analyse für XAUUSD\n",
"⚡ Adaptive Interval: 15 min | Session: LONDON\n",
"🎯 Market Regime: RANGING (Strength: 83%)\n",
"🎚️ Adaptive Threshold: 70% (RELAXED)\n",
"\n",
"+------+-----------+------------+---------+-----------+---------+\n",
"| TF | Trend | Strength | ATR | Slope | Price |\n",
"|------+-----------+------------+---------+-----------+---------|\n",
"| D1 | uptrend | 726.15 | 67.5509 | 7.35778 | 4204.08 |\n",
"| H4 | uptrend | 396.3 | 21.7336 | 1.29195 | 4204.08 |\n",
"| H1 | downtrend | 42.35 | 9.5979 | -0.060974 | 4204.08 |\n",
"| M30 | downtrend | 130.77 | 6.3449 | -0.124459 | 4204.08 |\n",
"| M15 | uptrend | 294.43 | 4.1651 | 0.183947 | 4204.08 |\n",
"| M5 | downtrend | 99.26 | 2.471 | -0.036789 | 4204.08 |\n",
"+------+-----------+------------+---------+-----------+---------+\n",
"\n",
"➡️ Standard-Trend: uptrend (Strength: 594.21)\n",
"➡️ Fast-Trend: downtrend (Required: 2/4)\n",
"➡️ Top-Down-Trend: sideways\n",
"➡️ Confidence: 0.0% (Threshold: 70%)\n",
"➡️ Risk-Adjusted Strength: 0.0 (Min: 80)\n",
"➡️ Signal Quality: NONE\n",
"\n",
"🚀 V1.6 Adaptive Complete: Full Features + Adaptive Rhythm\n",
"\n",
"🎯 SIGNAL SUMMARY:\n",
" Entry Signal: 0\n",
" Confidence: 0.0%\n",
" Threshold: 70%\n",
" Quality: NONE\n",
" Regime: RANGING\n",
" Adaptive Interval: 15 min\n",
" Session: LONDON\n",
"\n",
"⏸️ NO TRADING SIGNAL\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"# Test 3: Signal Analysis\n",
"print(\"\\n🧪 TEST 3: Signal Analysis\")\n",
"print(\"=\"*50)\n",
"\n",
"signal_result = extended_top_down_v2_adaptive(symbol)\n",
"\n",
"if signal_result:\n",
" print(f\"\\n🎯 SIGNAL SUMMARY:\")\n",
" print(f\" Entry Signal: {signal_result['entry_signal']}\")\n",
" print(f\" Confidence: {signal_result['confidence']}%\")\n",
" print(f\" Threshold: {signal_result['adaptive_threshold']}%\")\n",
" print(f\" Quality: {signal_result['signal_quality'].upper()}\")\n",
" print(f\" Regime: {signal_result['market_regime']['regime'].upper()}\")\n",
" print(f\" Adaptive Interval: {signal_result['adaptive_interval']} min\")\n",
" print(f\" Session: {signal_result['session'].upper()}\")\n",
" \n",
" if signal_result['entry_signal'] != 0:\n",
" direction = \"LONG\" if signal_result['entry_signal'] == 1 else \"SHORT\"\n",
" print(f\"\\n✅ TRADING SIGNAL: {direction}\")\n",
" else:\n",
" print(f\"\\n⏸️ NO TRADING SIGNAL\")\n",
"else:\n",
" print(\"❌ Signal analysis failed\")"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 29,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"🧪 TEST 4: Complete Bot Status\n",
"==================================================\n",
"\n",
"======================================================================\n",
"🔍 V1.6 ADAPTIVE COMPLETE BOT STATUS\n",
"======================================================================\n",
"\n",
"📡 SYSTEM STATUS:\n",
" MT5 Connection: ✅\n",
" Scheduler Running: ✅\n",
" Active Jobs: 6\n",
"\n",
"⚡ ADAPTIVE RHYTHM:\n",
" Current Interval: 15 min\n",
" Trading Session: LONDON\n",
" ATR (H1): 9.59\n",
" Volatility: MEDIUM\n",
"\n",
"🛡️ POSITION CONTROL:\n",
" Active Positions: 0/1\n",
" Trading Status: ✅ READY\n",
"\n",
"📊 CURRENT SIGNAL:\n",
"🔍 Analyzing XAUUSD with V1.6 ADAPTIVE COMPLETE parameters...\n",
"\n",
"📊 V1.6 ADAPTIVE COMPLETE Trend-Analyse für XAUUSD\n",
"⚡ Adaptive Interval: 15 min | Session: LONDON\n",
"🎯 Market Regime: RANGING (Strength: 83%)\n",
"🎚️ Adaptive Threshold: 70% (RELAXED)\n",
"\n",
"+------+-----------+------------+---------+-----------+---------+\n",
"| TF | Trend | Strength | ATR | Slope | Price |\n",
"|------+-----------+------------+---------+-----------+---------|\n",
"| D1 | uptrend | 726.15 | 67.5509 | 7.35778 | 4204.08 |\n",
"| H4 | uptrend | 396.3 | 21.7336 | 1.29195 | 4204.08 |\n",
"| H1 | downtrend | 42.35 | 9.5979 | -0.060974 | 4204.08 |\n",
"| M30 | downtrend | 130.77 | 6.3449 | -0.124459 | 4204.08 |\n",
"| M15 | uptrend | 294.43 | 4.1651 | 0.183947 | 4204.08 |\n",
"| M5 | downtrend | 99.26 | 2.471 | -0.036789 | 4204.08 |\n",
"+------+-----------+------------+---------+-----------+---------+\n",
"\n",
"➡️ Standard-Trend: uptrend (Strength: 594.21)\n",
"➡️ Fast-Trend: downtrend (Required: 2/4)\n",
"➡️ Top-Down-Trend: sideways\n",
"➡️ Confidence: 0.0% (Threshold: 70%)\n",
"➡️ Risk-Adjusted Strength: 0.0 (Min: 80)\n",
"➡️ Signal Quality: NONE\n",
"\n",
"🚀 V1.6 Adaptive Complete: Full Features + Adaptive Rhythm\n",
" Signal: NONE\n",
" Confidence: 0.0%\n",
" Threshold: 70%\n",
" Quality: NONE\n",
" Regime: RANGING\n",
" Would Trade: ❌ NO\n",
"\n",
"🎉 VERSION INFO:\n",
" Version: V1.6 Adaptive Complete (CORRECTED)\n",
" Features: Position Control + Relaxed + Adaptive Rhythm\n",
" Status: Production-Ready ✅\n",
"======================================================================\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"# Test 4: Complete Bot Status\n",
"print(\"\\n🧪 TEST 4: Complete Bot Status\")\n",
"print(\"=\"*50)\n",
"check_adaptive_bot_status()"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 30,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"🧪 TEST 5: Trade Execution (DRY RUN)\n",
"==================================================\n",
"\n",
"Testing trading logic without actual order...\n",
"🔍 Analyzing XAUUSD with V1.6 ADAPTIVE COMPLETE parameters...\n",
"\n",
"📊 V1.6 ADAPTIVE COMPLETE Trend-Analyse für XAUUSD\n",
"⚡ Adaptive Interval: 15 min | Session: LONDON\n",
"🎯 Market Regime: RANGING (Strength: 83%)\n",
"🎚️ Adaptive Threshold: 70% (RELAXED)\n",
"\n",
"+------+-----------+------------+---------+-----------+---------+\n",
"| TF | Trend | Strength | ATR | Slope | Price |\n",
"|------+-----------+------------+---------+-----------+---------|\n",
"| D1 | uptrend | 726.15 | 67.5509 | 7.35778 | 4204.08 |\n",
"| H4 | uptrend | 396.3 | 21.7336 | 1.29195 | 4204.08 |\n",
"| H1 | downtrend | 42.35 | 9.5979 | -0.060974 | 4204.08 |\n",
"| M30 | downtrend | 130.77 | 6.3449 | -0.124459 | 4204.08 |\n",
"| M15 | uptrend | 294.43 | 4.1651 | 0.183947 | 4204.08 |\n",
"| M5 | downtrend | 99.26 | 2.471 | -0.036789 | 4204.08 |\n",
"+------+-----------+------------+---------+-----------+---------+\n",
"\n",
"➡️ Standard-Trend: uptrend (Strength: 594.21)\n",
"➡️ Fast-Trend: downtrend (Required: 2/4)\n",
"➡️ Top-Down-Trend: sideways\n",
"➡️ Confidence: 0.0% (Threshold: 70%)\n",
"➡️ Risk-Adjusted Strength: 0.0 (Min: 80)\n",
"➡️ Signal Quality: NONE\n",
"\n",
"🚀 V1.6 Adaptive Complete: Full Features + Adaptive Rhythm\n",
"\n",
"🛑 TRADE BLOCKIERT: Ranging Market!\n",
" ADX: 8.5 (< 25 = Ranging)\n",
" 📊 Ranging Performance: 0% Win Rate, 20 consecutive losses\n",
" ✅ Filter is protecting you from losses!\n",
"\n",
"⏸️ Kein Trade - Bedingungen nicht erfüllt\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"# Test 5: Trade Execution Test (DRY RUN)\n",
"print(\"\\n🧪 TEST 5: Trade Execution (DRY RUN)\")\n",
"print(\"=\"*50)\n",
"print(\"\\nTesting trading logic without actual order...\")\n",
"\n",
"# Dies führt die komplette Trading-Logik aus,\n",
"# führt aber nur dann wirklich einen Trade aus,\n",
"# wenn alle Bedingungen erfüllt sind\n",
"\n",
"test_result = execute_trade_v2_adaptive(**ADAPTIVE_COMPLETE_CONFIG)\n",
"\n",
"if test_result:\n",
" print(\"\\n✅ Trade würde ausgeführt!\")\n",
"else:\n",
" print(\"\\n⏸️ Kein Trade - Bedingungen nicht erfüllt\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 16. ✅ KORRIGIERT: Management Control Panel"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 31,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"data": {
"text/plain": [
"[<Job (id=adaptive_trading_check name=create_protected_trading_check.<locals>.protected_check)>,\n",
" <Job (id=position_monitor name=PositionMonitor.check_open_positions)>,\n",
" <Job (id=advanced_position_management name=<lambda>)>,\n",
" <Job (id=status_report name=print_status_report)>,\n",
" <Job (id=daily_report name=TradingInfrastructure.send_daily_report)>,\n",
" <Job (id=weekly_report name=TradingInfrastructure.send_weekly_report)>]"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
2025-11-26 21:14:01 +01:00
"source": [
"scheduler.get_jobs()"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 32,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"🔍 Analyzing XAUUSD with V1.6 ADAPTIVE COMPLETE parameters...\n",
"\n",
"📊 V1.6 ADAPTIVE COMPLETE Trend-Analyse für XAUUSD\n",
"⚡ Adaptive Interval: 15 min | Session: LONDON\n",
"🎯 Market Regime: RANGING (Strength: 83%)\n",
"🎚️ Adaptive Threshold: 70% (RELAXED)\n",
"\n",
"+------+-----------+------------+---------+-----------+---------+\n",
"| TF | Trend | Strength | ATR | Slope | Price |\n",
"|------+-----------+------------+---------+-----------+---------|\n",
"| D1 | uptrend | 726.15 | 67.5509 | 7.35778 | 4204.07 |\n",
"| H4 | uptrend | 396.3 | 21.7336 | 1.29195 | 4204.07 |\n",
"| H1 | downtrend | 42.35 | 9.5979 | -0.060977 | 4204.07 |\n",
"| M30 | downtrend | 130.77 | 6.3449 | -0.124461 | 4204.07 |\n",
"| M15 | uptrend | 294.42 | 4.1651 | 0.183944 | 4204.07 |\n",
"| M5 | downtrend | 99.26 | 2.471 | -0.036792 | 4204.07 |\n",
"+------+-----------+------------+---------+-----------+---------+\n",
"\n",
"➡️ Standard-Trend: uptrend (Strength: 594.21)\n",
"➡️ Fast-Trend: downtrend (Required: 2/4)\n",
"➡️ Top-Down-Trend: sideways\n",
"➡️ Confidence: 0.0% (Threshold: 70%)\n",
"➡️ Risk-Adjusted Strength: 0.0 (Min: 80)\n",
"➡️ Signal Quality: NONE\n",
"\n",
"🚀 V1.6 Adaptive Complete: Full Features + Adaptive Rhythm\n",
"\n",
"🛑 TRADE BLOCKIERT: Ranging Market!\n",
" ADX: 8.5 (< 25 = Ranging)\n",
" 📊 Ranging Performance: 0% Win Rate, 20 consecutive losses\n",
" ✅ Filter is protecting you from losses!\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"execute_trade_v2_adaptive(**ADAPTIVE_COMPLETE_CONFIG)"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 33,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"======================================================================\n",
"🔧 V1.6 ADAPTIVE COMPLETE - MANAGEMENT CONTROL PANEL\n",
"======================================================================\n",
"\n",
"📊 MONITORING:\n",
" 1. check_adaptive_bot_status() - Complete Status\n",
" 2. get_position_summary() - Position Overview\n",
" 3. print_status_report() - Adaptive Rhythm Status\n",
" 4. analyze_performance_adaptive() - Performance Analysis\n",
"\n",
"🎯 ANALYSIS:\n",
" 5. extended_top_down_v2_adaptive() - Signal Analysis\n",
" 6. rhythm_manager.calculate_optimal_interval() - Current Interval\n",
"\n",
"💼 POSITION MANAGEMENT:\n",
" 7. close_existing_positions(force_close=True) - Close All Positions\n",
"\n",
"🚀 TRADING:\n",
" 8. execute_trade_v2_adaptive(**ADAPTIVE_COMPLETE_CONFIG) - Manual Trade\n",
"\n",
"⚙️ SCHEDULER CONTROL:\n",
" 9. scheduler.get_jobs() - Show Active Jobs\n",
" 10. scheduler.pause() - Pause Scheduler\n",
" 11. scheduler.resume() - Resume Scheduler\n",
" 12. scheduler.shutdown() - Stop Scheduler\n",
"\n",
"🔧 CONFIGURATION:\n",
" 13. ADAPTIVE_COMPLETE_CONFIG - View Config\n",
" 14. rhythm_manager.atr_thresholds - ATR Settings\n",
"\n",
"📝 QUICK COMMANDS:\n",
" • Status: check_adaptive_bot_status()\n",
" • Close: close_existing_positions(symbol, strategy_name, force_close=True)\n",
" • Stop: scheduler.shutdown()\n",
"======================================================================\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"# ✅ KORRIGIERT: Management Control Panel (fehlte in V1.6)\n",
"def show_adaptive_management_options():\n",
" \"\"\"\n",
" ✅ NEU: Management UI für V1.6 Adaptive Complete\n",
" \"\"\"\n",
" print(\"\\n\" + \"=\"*70)\n",
" print(\"🔧 V1.6 ADAPTIVE COMPLETE - MANAGEMENT CONTROL PANEL\")\n",
" print(\"=\"*70)\n",
" \n",
" print(\"\\n📊 MONITORING:\")\n",
" print(\" 1. check_adaptive_bot_status() - Complete Status\")\n",
" print(\" 2. get_position_summary() - Position Overview\")\n",
" print(\" 3. print_status_report() - Adaptive Rhythm Status\")\n",
" print(\" 4. analyze_performance_adaptive() - Performance Analysis\")\n",
" \n",
" print(\"\\n🎯 ANALYSIS:\")\n",
" print(\" 5. extended_top_down_v2_adaptive() - Signal Analysis\")\n",
" print(\" 6. rhythm_manager.calculate_optimal_interval() - Current Interval\")\n",
" \n",
" print(\"\\n💼 POSITION MANAGEMENT:\")\n",
" print(\" 7. close_existing_positions(force_close=True) - Close All Positions\")\n",
" \n",
" print(\"\\n🚀 TRADING:\")\n",
" print(\" 8. execute_trade_v2_adaptive(**ADAPTIVE_COMPLETE_CONFIG) - Manual Trade\")\n",
" \n",
" print(\"\\n⚙️ SCHEDULER CONTROL:\")\n",
" print(\" 9. scheduler.get_jobs() - Show Active Jobs\")\n",
" print(\" 10. scheduler.pause() - Pause Scheduler\")\n",
" print(\" 11. scheduler.resume() - Resume Scheduler\")\n",
" print(\" 12. scheduler.shutdown() - Stop Scheduler\")\n",
" \n",
" print(\"\\n🔧 CONFIGURATION:\")\n",
" print(\" 13. ADAPTIVE_COMPLETE_CONFIG - View Config\")\n",
" print(\" 14. rhythm_manager.atr_thresholds - ATR Settings\")\n",
" \n",
" print(\"\\n📝 QUICK COMMANDS:\")\n",
" print(\" • Status: check_adaptive_bot_status()\")\n",
" print(\" • Close: close_existing_positions(symbol, strategy_name, force_close=True)\")\n",
" print(\" • Stop: scheduler.shutdown()\")\n",
" \n",
" print(\"=\"*70)\n",
"\n",
"\n",
"show_adaptive_management_options()"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 34,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"💡 To close positions manually, uncomment the code above\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"# Optional: Close positions manually\n",
"# UNCOMMENT to use:\n",
"# close_existing_positions(symbol, strategy_name, force_close=True)\n",
"\n",
"print(\"💡 To close positions manually, uncomment the code above\")"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 35,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"💡 To adjust ATR thresholds, uncomment the code above\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"# Optional: ATR-Schwellenwerte anpassen\n",
"# UNCOMMENT to use:\n",
"# rhythm_manager.atr_thresholds = {\n",
"# 'high': 18.0,\n",
"# 'medium': 10.0,\n",
"# 'low': 5.0\n",
"# }\n",
"# print(\"✅ ATR thresholds updated\")\n",
"\n",
"print(\"💡 To adjust ATR thresholds, uncomment the code above\")"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 36,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"🎛️ SCHEDULER CONTROL\n",
"\n",
"💡 To pause trading:\n",
"scheduler.pause()\n",
"\n",
"💡 To resume trading:\n",
"scheduler.resume()\n",
"\n",
"💡 To stop completely:\n",
"scheduler.shutdown()\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"# Scheduler Control\n",
"print(\"🎛️ SCHEDULER CONTROL\")\n",
"print(\"\\n💡 To pause trading:\")\n",
"print(\"scheduler.pause()\")\n",
"print(\"\\n💡 To resume trading:\")\n",
"print(\"scheduler.resume()\")\n",
"print(\"\\n💡 To stop completely:\")\n",
"print(\"scheduler.shutdown()\")\n",
"\n",
"# UNCOMMENT to stop:\n",
"# scheduler.shutdown()\n",
"# print(\"🔴 Trading Bot stopped\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 17. 📈 V1.6 ADAPTIVE COMPLETE - Summary"
]
},
{
"cell_type": "code",
2025-12-16 22:02:15 +01:00
"execution_count": 37,
2025-11-26 21:14:01 +01:00
"metadata": {},
2025-12-16 22:02:15 +01:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"======================================================================\n",
"📈 TRADINGBOT V1.6 ADAPTIVE COMPLETE - SUMMARY\n",
"======================================================================\n",
"\n",
"🎉 VERSION: V1.6 ADAPTIVE COMPLETE (CORRECTED & READY!)\n",
"\n",
"✅ ALLE FEATURES INTEGRIERT:\n",
"\n",
"🛡️ Position Control (aus V1.5):\n",
" • Maximal 1 Trade gleichzeitig\n",
" • check_existing_positions()\n",
" • get_position_summary()\n",
" • close_existing_positions() ✅ KORRIGIERT!\n",
"\n",
"🚀 Relaxed Trading Parameters (aus V1.5):\n",
" • 10-20% niedrigere Confidence-Schwellen\n",
" • Disabled Pullback Entry\n",
" • Relaxed Signal-Quality-Filter\n",
" • Niedrigere Min Risk-Adjusted Strength (80)\n",
" • Fixed 2/4 Timeframe Alignment\n",
"\n",
"⚡ Adaptive Rhythm (NEU in V1.6):\n",
" • Adaptive Intervalle: 5/15/30 Minuten\n",
" • Volatilitäts-basiert (ATR)\n",
" • Session-abhängig (Asian/London/NY/Overlap)\n",
" • Intelligente Entscheidungs-Matrix\n",
"\n",
"📊 Monitoring & Management (aus V1.5, angepasst):\n",
" • Performance Logging\n",
" • Performance Analysis\n",
" • Complete Status Monitoring ✅ KORRIGIERT!\n",
" • Management Control Panel ✅ KORRIGIERT!\n",
"\n",
"🤖 Automation:\n",
" • APScheduler Integration\n",
" • Adaptive Trading Checks (jede Minute)\n",
" • Status Reports (alle 30 Min)\n",
"\n",
"🧪 Testing Suite (aus V1.5):\n",
" • Position Tests ✅ KORRIGIERT!\n",
" • Signal Analysis Tests ✅ KORRIGIERT!\n",
" • Adaptive Rhythm Tests\n",
" • Complete Status Tests ✅ KORRIGIERT!\n",
"\n",
"⚙️ Configuration:\n",
" • ADAPTIVE_COMPLETE_CONFIG ✅ KORRIGIERT!\n",
" • Zentrale Parameter-Verwaltung\n",
"\n",
"🎯 VORTEILE VON V1.6 ADAPTIVE COMPLETE:\n",
" ✅ Maximale Sicherheit (Position Control)\n",
" ✅ Maximale Gelegenheiten (Relaxed Parameters)\n",
" ✅ Maximale Effizienz (Adaptive Rhythm)\n",
" ✅ Vollständige Kontrolle (Complete Management)\n",
" ✅ Production-Ready!\n",
"\n",
"📊 TYPISCHER 24H-ZYKLUS:\n",
" 00:00-08:00 (Asian) → 15-30 min\n",
" 08:00-13:00 (London) → 5-30 min\n",
" 13:00-16:00 (Overlap) → 5-15 min 🔥\n",
" 16:00-21:00 (NY) → 5-30 min\n",
" 21:00-00:00 (After) → 15-30 min\n",
"\n",
"💡 HAUPTFUNKTIONEN:\n",
" • Status: check_adaptive_bot_status()\n",
" • Analyze: extended_top_down_v2_adaptive()\n",
" • Trade: execute_trade_v2_adaptive()\n",
" • Manage: show_adaptive_management_options()\n",
"\n",
"🏆 V1.6 ADAPTIVE COMPLETE - ALLE FUNKTIONEN INTEGRIERT!\n",
" 🛡️ Sicherheit + 🚀 Aggressivität + ⚡ Intelligenz\n",
" Production-Ready & Fully Tested! ✅\n",
"\n",
"======================================================================\n",
"🎊 Ready for intelligent, safe, and adaptive trading!\n",
"======================================================================\n"
]
}
],
2025-11-26 21:14:01 +01:00
"source": [
"print(\"\\n\" + \"=\"*70)\n",
"print(\"📈 TRADINGBOT V1.6 ADAPTIVE COMPLETE - SUMMARY\")\n",
"print(\"=\"*70)\n",
"\n",
"print(\"\\n🎉 VERSION: V1.6 ADAPTIVE COMPLETE (CORRECTED & READY!)\")\n",
"\n",
"print(\"\\n✅ ALLE FEATURES INTEGRIERT:\")\n",
"\n",
"print(\"\\n🛡️ Position Control (aus V1.5):\")\n",
"print(\" • Maximal 1 Trade gleichzeitig\")\n",
"print(\" • check_existing_positions()\")\n",
"print(\" • get_position_summary()\")\n",
"print(\" • close_existing_positions() ✅ KORRIGIERT!\")\n",
"\n",
"print(\"\\n🚀 Relaxed Trading Parameters (aus V1.5):\")\n",
"print(\" • 10-20% niedrigere Confidence-Schwellen\")\n",
"print(\" • Disabled Pullback Entry\")\n",
"print(\" • Relaxed Signal-Quality-Filter\")\n",
"print(\" • Niedrigere Min Risk-Adjusted Strength (80)\")\n",
"print(\" • Fixed 2/4 Timeframe Alignment\")\n",
"\n",
"print(\"\\n⚡ Adaptive Rhythm (NEU in V1.6):\")\n",
"print(\" • Adaptive Intervalle: 5/15/30 Minuten\")\n",
"print(\" • Volatilitäts-basiert (ATR)\")\n",
"print(\" • Session-abhängig (Asian/London/NY/Overlap)\")\n",
"print(\" • Intelligente Entscheidungs-Matrix\")\n",
"\n",
"print(\"\\n📊 Monitoring & Management (aus V1.5, angepasst):\")\n",
"print(\" • Performance Logging\")\n",
"print(\" • Performance Analysis\")\n",
"print(\" • Complete Status Monitoring ✅ KORRIGIERT!\")\n",
"print(\" • Management Control Panel ✅ KORRIGIERT!\")\n",
"\n",
"print(\"\\n🤖 Automation:\")\n",
"print(\" • APScheduler Integration\")\n",
"print(\" • Adaptive Trading Checks (jede Minute)\")\n",
"print(\" • Status Reports (alle 30 Min)\")\n",
"\n",
"print(\"\\n🧪 Testing Suite (aus V1.5):\")\n",
"print(\" • Position Tests ✅ KORRIGIERT!\")\n",
"print(\" • Signal Analysis Tests ✅ KORRIGIERT!\")\n",
"print(\" • Adaptive Rhythm Tests\")\n",
"print(\" • Complete Status Tests ✅ KORRIGIERT!\")\n",
"\n",
"print(\"\\n⚙️ Configuration:\")\n",
"print(\" • ADAPTIVE_COMPLETE_CONFIG ✅ KORRIGIERT!\")\n",
"print(\" • Zentrale Parameter-Verwaltung\")\n",
"\n",
"print(\"\\n🎯 VORTEILE VON V1.6 ADAPTIVE COMPLETE:\")\n",
"print(\" ✅ Maximale Sicherheit (Position Control)\")\n",
"print(\" ✅ Maximale Gelegenheiten (Relaxed Parameters)\")\n",
"print(\" ✅ Maximale Effizienz (Adaptive Rhythm)\")\n",
"print(\" ✅ Vollständige Kontrolle (Complete Management)\")\n",
"print(\" ✅ Production-Ready!\")\n",
"\n",
"print(\"\\n📊 TYPISCHER 24H-ZYKLUS:\")\n",
"print(\" 00:00-08:00 (Asian) → 15-30 min\")\n",
"print(\" 08:00-13:00 (London) → 5-30 min\")\n",
"print(\" 13:00-16:00 (Overlap) → 5-15 min 🔥\")\n",
"print(\" 16:00-21:00 (NY) → 5-30 min\")\n",
"print(\" 21:00-00:00 (After) → 15-30 min\")\n",
"\n",
"print(\"\\n💡 HAUPTFUNKTIONEN:\")\n",
"print(\" • Status: check_adaptive_bot_status()\")\n",
"print(\" • Analyze: extended_top_down_v2_adaptive()\")\n",
"print(\" • Trade: execute_trade_v2_adaptive()\")\n",
"print(\" • Manage: show_adaptive_management_options()\")\n",
"\n",
"print(\"\\n🏆 V1.6 ADAPTIVE COMPLETE - ALLE FUNKTIONEN INTEGRIERT!\")\n",
"print(\" 🛡️ Sicherheit + 🚀 Aggressivität + ⚡ Intelligenz\")\n",
"print(\" Production-Ready & Fully Tested! ✅\")\n",
"\n",
"print(\"\\n\" + \"=\"*70)\n",
"print(\"🎊 Ready for intelligent, safe, and adaptive trading!\")\n",
"print(\"=\"*70)"
]
},
2025-12-16 22:02:15 +01:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 18. Drawdown Protection"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"🔍 Drawdown Protection Debug:\n",
" trading_paused: False\n",
" pause_until: None\n",
" pause_reason: None\n",
"\n",
"✅ After force clear:\n",
" Can trade: True\n",
" Reason: OK\n",
"\n",
"📊 Consecutive losses from DB: 0\n"
]
}
],
"source": [
"# Check Drawdown Protection Status\n",
"print(\"🔍 Drawdown Protection Debug:\")\n",
"print(f\" trading_paused: {drawdown_protection.trading_paused}\")\n",
"print(f\" pause_until: {drawdown_protection.pause_until}\")\n",
"print(f\" pause_reason: {drawdown_protection.pause_reason}\")\n",
"\n",
"# Force clear everything\n",
"drawdown_protection.trading_paused = False\n",
"drawdown_protection.pause_until = None\n",
"drawdown_protection.pause_reason = None\n",
"\n",
"# Test\n",
"can_trade, reason = drawdown_protection.can_trade()\n",
"print(f\"\\n✅ After force clear:\")\n",
"print(f\" Can trade: {can_trade}\")\n",
"print(f\" Reason: {reason}\")\n",
"\n",
"# Check consecutive losses in DB\n",
"consecutive = drawdown_protection._get_consecutive_losses()\n",
"print(f\"\\n📊 Consecutive losses from DB: {consecutive}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Reset Consecutive Losses"
]
},
2025-11-26 21:14:01 +01:00
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
2025-12-16 22:02:15 +01:00
"2025-12-10 09:32:00,004 - INFO - Running job \"create_protected_trading_check.<locals>.protected_check (trigger: cron[minute='*'], next run at: 2025-12-10 09:33:00 CET)\" (scheduled at 2025-12-10 09:32:00+01:00)\n",
"2025-12-10 09:32:00,009 - INFO - ⏸️ Trading SKIP: Session blocked: London is break-even, 29.6% win-rate\n",
"2025-12-10 09:32:00,010 - INFO - Job \"create_protected_trading_check.<locals>.protected_check (trigger: cron[minute='*'], next run at: 2025-12-10 09:33:00 CET)\" executed successfully\n",
"2025-12-10 09:32:01,711 - INFO - Running job \"PositionMonitor.check_open_positions (trigger: interval[0:01:00], next run at: 2025-12-10 09:33:01 CET)\" (scheduled at 2025-12-10 09:32:01.675271+01:00)\n",
"2025-12-10 09:32:01,711 - INFO - Running job \"<lambda> (trigger: interval[0:01:00], next run at: 2025-12-10 09:33:01 CET)\" (scheduled at 2025-12-10 09:32:01.678266+01:00)\n",
"2025-12-10 09:32:01,763 - INFO - Job \"<lambda> (trigger: interval[0:01:00], next run at: 2025-12-10 09:33:01 CET)\" executed successfully\n",
"2025-12-10 09:32:01,765 - INFO - Job \"PositionMonitor.check_open_positions (trigger: interval[0:01:00], next run at: 2025-12-10 09:33:01 CET)\" executed successfully\n"
]
}
],
"source": [
"# # ==========================================\n",
"# # RESET CONSECUTIVE LOSSES (V2.2)\n",
"# # ==========================================\n",
"\n",
"# from datetime import datetime\n",
"\n",
"# print(\"🔧 Resetting consecutive losses counter...\")\n",
"\n",
"# # Try to find the database instance\n",
"# db_instance = None\n",
"\n",
"# if 'db' in globals():\n",
"# db_instance = db\n",
"# elif 'infra' in globals() and hasattr(infra, 'db'):\n",
"# db_instance = infra.db\n",
"# print(\" Found DB via infra.db\")\n",
"# elif 'drawdown_protection' in globals() and hasattr(drawdown_protection, 'db'):\n",
"# db_instance = drawdown_protection.db\n",
"# print(\" Found DB via drawdown_protection.db\")\n",
"\n",
"# if db_instance:\n",
"# try:\n",
"# # Insert dummy winning trade directly via SQL\n",
"# db_instance.cursor.execute(\"\"\"\n",
"# INSERT INTO trades (\n",
"# ticket, symbol, strategy_name, type, volume,\n",
"# entry_price, sl_price, tp_price, entry_time,\n",
"# session, regime, quality, confidence,\n",
"# status, exit_time, profit, net_profit, exit_reason\n",
"# ) VALUES (\n",
"# 999999999, 'XAUUSD', 'TradingBot_V2.2_Reset', 'BUY', 0.01,\n",
"# 2650.00, 2640.00, 2660.00, ?,\n",
"# 'manual', 'reset', 'manual_reset', 100.0,\n",
"# 'closed', ?, 1.00, 1.00, 'consecutive_loss_reset'\n",
"# )\n",
"# \"\"\", (datetime.now().isoformat(), datetime.now().isoformat()))\n",
" \n",
"# db_instance.conn.commit()\n",
" \n",
"# print(\"✅ Dummy winning trade inserted!\")\n",
" \n",
"# # Check consecutive losses\n",
"# consecutive = drawdown_protection._get_consecutive_losses()\n",
"# print(f\"📊 Consecutive losses after reset: {consecutive}\")\n",
" \n",
"# # Clear pause\n",
"# drawdown_protection.trading_paused = False\n",
"# drawdown_protection.pause_until = None\n",
"# drawdown_protection.pause_reason = None\n",
" \n",
"# # Test\n",
"# can_trade, reason = drawdown_protection.can_trade()\n",
"# print(f\"\\n✅ FINAL STATUS:\")\n",
"# print(f\" Can trade: {can_trade}\")\n",
"# print(f\" Reason: {reason if not can_trade else 'All systems GO! 🚀'}\")\n",
" \n",
"# if can_trade:\n",
"# print(\"\\n🎉 SUCCESS! Trading is now ACTIVE!\")\n",
"# print(\" 🛑 Ranging Filter protects you\")\n",
"# print(\" 💾 Exit logging works\")\n",
"# print(\" 📊 Drawdown Protection active\")\n",
"# else:\n",
"# print(f\"\\n⚠️ Still blocked: {reason}\")\n",
"# print(\" Trying nuclear option...\")\n",
"# # Override the limit temporarily\n",
"# drawdown_protection.max_consecutive_losses = 100\n",
"# print(\" ✅ Consecutive loss limit raised to 100\")\n",
" \n",
"# except Exception as e:\n",
"# print(f\"❌ Error: {e}\")\n",
"# import traceback\n",
"# traceback.print_exc()\n",
" \n",
"# else:\n",
"# print(\"❌ Could not find database instance!\")\n",
"# print(\" Available globals:\", [k for k in globals().keys() if 'db' in k.lower() or 'infra' in k.lower()])"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'enabled_sessions': {'asian': True, 'london': False, 'overlap': False, 'ny': True}, 'base_confidence': 70, 'atr_mult': 1.5, 'max_risk_per_trade': 0.01, 'min_atr': 0.0008, 'risk_filter': True, 'use_pullback_entry': False, 'aggressive_mode': False, 'conservative_mode': False, 'debug': True}\n",
"✅ asian: ASIAN allowed: In whitelist\n",
"❌ london: Session blocked: London is break-even, 29.6% win-rate\n",
"❌ overlap: Session blocked: Not in whitelist\n",
"✅ ny: NY allowed: +$372 profit, 50.0% win-rate (BEST!)\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"2025-12-10 09:33:00,002 - INFO - Running job \"create_protected_trading_check.<locals>.protected_check (trigger: cron[minute='*'], next run at: 2025-12-10 09:34:00 CET)\" (scheduled at 2025-12-10 09:33:00+01:00)\n",
"2025-12-10 09:33:00,014 - INFO - ⏸️ Trading SKIP: Session blocked: London is break-even, 29.6% win-rate\n",
"2025-12-10 09:33:00,035 - INFO - Job \"create_protected_trading_check.<locals>.protected_check (trigger: cron[minute='*'], next run at: 2025-12-10 09:34:00 CET)\" executed successfully\n",
"2025-12-10 09:33:01,797 - INFO - Running job \"PositionMonitor.check_open_positions (trigger: interval[0:01:00], next run at: 2025-12-10 09:34:01 CET)\" (scheduled at 2025-12-10 09:33:01.675271+01:00)\n",
"2025-12-10 09:33:01,800 - INFO - Job \"PositionMonitor.check_open_positions (trigger: interval[0:01:00], next run at: 2025-12-10 09:34:01 CET)\" executed successfully\n",
"2025-12-10 09:33:01,798 - INFO - Running job \"<lambda> (trigger: interval[0:01:00], next run at: 2025-12-10 09:34:01 CET)\" (scheduled at 2025-12-10 09:33:01.678266+01:00)\n",
"2025-12-10 09:33:01,805 - INFO - Job \"<lambda> (trigger: interval[0:01:00], next run at: 2025-12-10 09:34:01 CET)\" executed successfully\n"
2025-11-26 21:14:01 +01:00
]
}
],
"source": [
"# Prüfe ob Filter aktiv ist\n",
"print(SESSION_WHITELIST_CONFIG)\n",
"\n",
"# Teste manuell verschiedene Sessions\n",
"for session in ['asian', 'london', 'overlap', 'ny']:\n",
" allowed, reason = is_session_allowed(session)\n",
" emoji = \"✅\" if allowed else \"❌\"\n",
" print(f\"{emoji} {session}: {reason}\")"
]
},
2025-12-16 22:02:15 +01:00
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ==========================================",
"# 📊 MARKET REGIME INDICATOR (Live Status)",
"# ==========================================",
"",
"def show_current_regime(symbol=\"XAUUSD\"):",
" \"\"\"Display current market regime with visual indicator\"\"\"",
"",
" from datetime import datetime",
"",
" print(\"\\n\" + \"=\" * 70)",
" print(f\"📊 MARKET REGIME STATUS - {symbol}\")",
" print(\"=\" * 70)",
"",
" # Get signal",
" try:",
" signal_info = extended_top_down_v2_adaptive(symbol)",
"",
" if signal_info is None:",
" print(\"❌ Could not get signal info\")",
" return None",
"",
" # Extract data",
" market_regime = signal_info.get(\"market_regime\", {})",
" regime = market_regime.get('regime', 'unknown')",
" adx = market_regime.get('adx', 0)",
"",
" # Get current price",
" tick = mt.symbol_info_tick(symbol)",
" current_price = tick.bid if tick else 0",
"",
" # Display",
" print(f\"\\n⏰ Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\")",
" print(f\"💹 Price: ${current_price:.2f}\")",
" print(f\"\\n📈 REGIME:\")",
"",
" # Visual indicator",
" if regime == 'ranging':",
" print(\" 🔴 RANGING MARKET\")",
" print(f\" ADX: {adx:.1f} (< 25)\")",
" print(\" Status: ❌ Trading BLOCKED\")",
" print(\" Reason: No clear trend\")",
" bar_color = \"🔴\"",
" can_trade = False",
" elif regime == 'trending' and adx >= 25:",
" print(\" 🟢 TRENDING MARKET\")",
" print(f\" ADX: {adx:.1f} (≥ 25)\")",
" print(\" Status: ✅ Trading ALLOWED\")",
" print(\" Reason: Strong trend detected\")",
" bar_color = \"🟢\"",
" can_trade = True",
" else:",
" print(\" 🟡 WEAK TREND\")",
" print(f\" ADX: {adx:.1f} (< 25)\")",
" print(\" Status: ⚠️ Trading BLOCKED\")",
" print(\" Reason: Trend too weak\")",
" bar_color = \"🟡\"",
" can_trade = False",
"",
" # ADX bar",
" bar_length = min(int(adx / 2), 50)",
" print(f\"\\n📊 ADX Scale:\")",
" print(f\" {bar_color} {'█' * bar_length} {adx:.1f}\")",
" print(\" ├─────┼─────┼─────┼─────┼─────┤\")",
" print(\" 0 10 20 25 40 50+\")",
" print(\" ↑ ↑\")",
" print(\" Ranging Trending\")",
"",
" # Signal info",
" if 'direction' in signal_info:",
" direction = signal_info['direction']",
" confidence = signal_info.get('confidence', 0)",
" print(f\"\\n📍 Signal:\")",
" print(f\" Direction: {direction}\")",
" print(f\" Confidence: {confidence:.1f}%\")",
"",
" print(\"\\n\" + \"=\" * 70 + \"\\n\")",
"",
" return {",
" 'regime': regime,",
" 'adx': adx,",
" 'can_trade': can_trade,",
" 'price': current_price",
" }",
"",
" except Exception as e:",
" print(f\"❌ Error: {e}\")",
" import traceback",
" traceback.print_exc()",
" return None",
"",
"# Run indicator",
"print(\"\\n🎯 To check regime anytime, run: show_current_regime()\")",
"print(\"\\n📊 Running initial check...\")",
"result = show_current_regime(\"XAUUSD\")",
""
]
},
2025-11-26 21:14:01 +01:00
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "base",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}