2053 lines
93 KiB
Plaintext
2053 lines
93 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"# TradingBot V1.4 - Complete Relaxed Enhanced Safety 🚀🛡️⚡\n",
|
|
"\n",
|
|
"## 🆕 **Priorität 1 Verbesserungen implementiert!**\n",
|
|
"\n",
|
|
"### 🚨 **Neue Safety Features (Priorität 1):**\n",
|
|
"- 🛡️ **Circuit Breaker System** - Daily Loss Limits & Emergency Stop\n",
|
|
"- 🔧 **Enhanced MT5 Connection Monitoring** - Auto-Reconnect & Fallbacks\n",
|
|
"- 🕐 **Trading Session Management** - Market Hours & Weekend Filter\n",
|
|
"- 📊 **Spread Quality Control** - Trading nur bei akzeptablen Spreads\n",
|
|
"- 🛡️ **Enhanced Risk Management** - Multiple Risk Checks & Limits\n",
|
|
"- 🚨 **Emergency Shutdown Protocol** - Komplettes Notfall-System\n",
|
|
"\n",
|
|
"### ✅ **Bestehende Complete Relaxed Features:**\n",
|
|
"- 🛡️ **Position Control System** - Maximal 1 Trade gleichzeitig\n",
|
|
"- 📊 **Performance Monitoring & Logging**\n",
|
|
"- 🤖 **APScheduler Integration** - Automatisierung\n",
|
|
"- 🚀 **Relaxed Trading Parameter** - Mehr Trading-Signale\n",
|
|
"\n",
|
|
"### 🎯 **Enhanced Safety + Complete Relaxed:**\n",
|
|
"- Maximale Sicherheit durch Priorität 1 Features\n",
|
|
"- Alle Complete Version Funktionen\n",
|
|
"- Relaxed Parameter für mehr Trading-Gelegenheiten\n",
|
|
"- Vollständige Notfall-Protokolle"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 1. Enhanced Imports und Setup"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Enhanced Imports mit Safety Features\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 as dt_time\n",
|
|
"import json\n",
|
|
"import keyring as kr\n",
|
|
"import time\n",
|
|
"import pytz\n",
|
|
"from typing import Dict, List, Optional, Tuple, Any\n",
|
|
"# APScheduler für Automatisierung\n",
|
|
"from apscheduler.schedulers.background import BackgroundScheduler\n",
|
|
"\n",
|
|
"print(\"✅ Enhanced imports successful - Complete Relaxed with Priority 1 Safety\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 2. MT5 Login und Enhanced Setup"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Enhanced MT5 Login mit Connection Monitoring\n",
|
|
"def initialize_mt5_with_safety():\n",
|
|
" \"\"\"Enhanced MT5 initialization mit Safety Checks\"\"\"\n",
|
|
" try:\n",
|
|
" # Initialize MT5\n",
|
|
" if not mt.initialize():\n",
|
|
" print(\"❌ MT5 initialize failed\")\n",
|
|
" return False\n",
|
|
" \n",
|
|
" # Login mit Retry-Logic\n",
|
|
" login = 10800246\n",
|
|
" server = 'VantageInternational-Demo'\n",
|
|
" password = kr.get_password(server, str(login))\n",
|
|
" \n",
|
|
" login_result = mt.login(login, password, server)\n",
|
|
" if not login_result:\n",
|
|
" print(\"❌ MT5 login failed\")\n",
|
|
" return False\n",
|
|
" \n",
|
|
" print(f\"✅ Enhanced MT5 login successful\")\n",
|
|
" \n",
|
|
" # Verify connection\n",
|
|
" terminal_info = mt.terminal_info()\n",
|
|
" account_info = mt.account_info()\n",
|
|
" \n",
|
|
" if terminal_info and account_info:\n",
|
|
" print(f\"✅ MT5 Connection verified\")\n",
|
|
" print(f\" Terminal: {terminal_info.name}\")\n",
|
|
" print(f\" Account: {account_info.login}\")\n",
|
|
" print(f\" Balance: {account_info.balance:.2f}\")\n",
|
|
" return True\n",
|
|
" else:\n",
|
|
" print(\"❌ MT5 Connection verification failed\")\n",
|
|
" return False\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" print(f\"❌ Enhanced MT5 initialization error: {e}\")\n",
|
|
" return False\n",
|
|
"\n",
|
|
"# Initialize with safety\n",
|
|
"connection_success = initialize_mt5_with_safety()\n",
|
|
"\n",
|
|
"if connection_success:\n",
|
|
" # Trading Parameter\n",
|
|
" symbol = \"XAUUSD\"\n",
|
|
" strategy_name = \"TradingBot_V1.4_Complete_Relaxed_Enhanced_Safety\"\n",
|
|
" max_positions = 1 # WICHTIG: Maximal 1 Position\n",
|
|
" \n",
|
|
" print(f\"\\nSymbol: {symbol}\")\n",
|
|
" print(f\"Strategy: {strategy_name}\")\n",
|
|
" print(f\"Max Positions: {max_positions}\")\n",
|
|
" print(f\"Version: Complete Relaxed + Enhanced Safety (Priorität 1) 🚀🛡️⚡\")\nelse:\n print(\"🚨 CRITICAL: MT5 initialization failed - stopping execution\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 3. 🚨 Priorität 1: Circuit Breaker & Emergency Systems"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# ==========================================\n",
|
|
"# PRIORITÄT 1: CIRCUIT BREAKER SYSTEM\n",
|
|
"# ==========================================\n",
|
|
"\n",
|
|
"# Global State für Circuit Breaker\n",
|
|
"CIRCUIT_BREAKER_STATE = {\n",
|
|
" 'daily_loss_reset_date': datetime.now().date(),\n",
|
|
" 'daily_loss_amount': 0.0,\n",
|
|
" 'emergency_stop_active': False,\n",
|
|
" 'connection_issues_count': 0,\n",
|
|
" 'last_connection_check': datetime.now(),\n",
|
|
" 'consecutive_failures': 0,\n",
|
|
" 'last_emergency_event': None\n",
|
|
"}\n",
|
|
"\n",
|
|
"def check_daily_loss_limit(\n",
|
|
" max_daily_loss_percent: float = 5.0,\n",
|
|
" max_daily_loss_absolute: float = 500.0,\n",
|
|
" emergency_close_positions: bool = True\n",
|
|
") -> Tuple[bool, Dict[str, Any]]:\n",
|
|
" \"\"\"\n",
|
|
" 🚨 Circuit Breaker: Daily Loss Limit Check\n",
|
|
" \n",
|
|
" Args:\n",
|
|
" max_daily_loss_percent: Maximaler Tagesverlust in % der Balance\n",
|
|
" max_daily_loss_absolute: Maximaler absoluter Tagesverlust\n",
|
|
" emergency_close_positions: Automatisches Schließen bei Überschreitung\n",
|
|
" \n",
|
|
" Returns:\n",
|
|
" Tuple[bool, dict]: (trading_allowed, status_info)\n",
|
|
" \"\"\"\n",
|
|
" global CIRCUIT_BREAKER_STATE\n",
|
|
" \n",
|
|
" try:\n",
|
|
" # Check if new day - reset daily loss\n",
|
|
" current_date = datetime.now().date()\n",
|
|
" if current_date != CIRCUIT_BREAKER_STATE['daily_loss_reset_date']:\n",
|
|
" CIRCUIT_BREAKER_STATE['daily_loss_amount'] = 0.0\n",
|
|
" CIRCUIT_BREAKER_STATE['daily_loss_reset_date'] = current_date\n",
|
|
" CIRCUIT_BREAKER_STATE['emergency_stop_active'] = False\n",
|
|
" CIRCUIT_BREAKER_STATE['consecutive_failures'] = 0\n",
|
|
" print(f\"🔄 Daily Loss Reset: Neuer Tag - {current_date}\")\n",
|
|
" \n",
|
|
" # Check account info\n",
|
|
" account_info = mt.account_info()\n",
|
|
" if account_info is None:\n",
|
|
" return False, {'error': 'Account info nicht verfügbar', 'status': 'connection_error'}\n",
|
|
" \n",
|
|
" balance = account_info.balance\n",
|
|
" equity = account_info.equity\n",
|
|
" \n",
|
|
" # Calculate current daily loss\n",
|
|
" current_loss = balance - equity\n",
|
|
" daily_loss_percent = (current_loss / balance) * 100 if balance > 0 else 0\n",
|
|
" \n",
|
|
" # Update daily loss tracking\n",
|
|
" if current_loss > CIRCUIT_BREAKER_STATE['daily_loss_amount']:\n",
|
|
" CIRCUIT_BREAKER_STATE['daily_loss_amount'] = current_loss\n",
|
|
" \n",
|
|
" # Check loss limits\n",
|
|
" loss_limit_exceeded = (\n",
|
|
" CIRCUIT_BREAKER_STATE['daily_loss_amount'] >= max_daily_loss_absolute or\n",
|
|
" daily_loss_percent >= max_daily_loss_percent\n",
|
|
" )\n",
|
|
" \n",
|
|
" status_info = {\n",
|
|
" 'balance': balance,\n",
|
|
" 'equity': equity,\n",
|
|
" 'current_loss': current_loss,\n",
|
|
" 'daily_loss_amount': CIRCUIT_BREAKER_STATE['daily_loss_amount'],\n",
|
|
" 'daily_loss_percent': daily_loss_percent,\n",
|
|
" 'max_daily_loss_percent': max_daily_loss_percent,\n",
|
|
" 'max_daily_loss_absolute': max_daily_loss_absolute,\n",
|
|
" 'loss_limit_exceeded': loss_limit_exceeded,\n",
|
|
" 'emergency_stop_active': CIRCUIT_BREAKER_STATE['emergency_stop_active'],\n",
|
|
" 'reset_date': CIRCUIT_BREAKER_STATE['daily_loss_reset_date']\n",
|
|
" }\n",
|
|
" \n",
|
|
" if loss_limit_exceeded and not CIRCUIT_BREAKER_STATE['emergency_stop_active']:\n",
|
|
" print(f\"\\n🚨 CIRCUIT BREAKER ACTIVATED!\")\n",
|
|
" print(f\"📊 Daily Loss: {CIRCUIT_BREAKER_STATE['daily_loss_amount']:.2f} ({daily_loss_percent:.2f}%)\")\n",
|
|
" print(f\"🚫 Limits: {max_daily_loss_absolute} absolute oder {max_daily_loss_percent}% der Balance\")\n",
|
|
" \n",
|
|
" CIRCUIT_BREAKER_STATE['emergency_stop_active'] = True\n",
|
|
" CIRCUIT_BREAKER_STATE['last_emergency_event'] = datetime.now()\n",
|
|
" \n",
|
|
" if emergency_close_positions:\n",
|
|
" print(f\"🚨 Emergency: Schließe alle Positionen...\")\n",
|
|
" try:\n",
|
|
" close_result = close_existing_positions(symbol, strategy_name, force_close=True)\n",
|
|
" status_info['emergency_close_attempted'] = True\n",
|
|
" status_info['emergency_close_successful'] = close_result\n",
|
|
" except Exception as e:\n",
|
|
" print(f\"❌ Emergency close failed: {e}\")\n",
|
|
" status_info['emergency_close_error'] = str(e)\n",
|
|
" \n",
|
|
" return False, status_info\n",
|
|
" \n",
|
|
" elif CIRCUIT_BREAKER_STATE['emergency_stop_active']:\n",
|
|
" return False, status_info\n",
|
|
" \n",
|
|
" return True, status_info\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" error_msg = f\"Error in daily loss check: {e}\"\n",
|
|
" print(f\"❌ {error_msg}\")\n",
|
|
" return False, {'error': error_msg, 'status': 'error'}\n",
|
|
"\n",
|
|
"def ensure_mt5_connection(max_retries: int = 3, retry_delay: float = 2.0) -> bool:\n",
|
|
" \"\"\"\n",
|
|
" 🔧 Enhanced MT5 Connection Monitoring mit Auto-Reconnect\n",
|
|
" \"\"\"\n",
|
|
" global CIRCUIT_BREAKER_STATE\n",
|
|
" \n",
|
|
" for attempt in range(max_retries):\n",
|
|
" try:\n",
|
|
" # Check MT5 Terminal Info\n",
|
|
" terminal_info = mt.terminal_info()\n",
|
|
" if terminal_info is None:\n",
|
|
" print(f\"⚠️ MT5 Terminal nicht verfügbar (Versuch {attempt + 1}/{max_retries})\")\n",
|
|
" if attempt < max_retries - 1:\n",
|
|
" time.sleep(retry_delay)\n",
|
|
" continue\n",
|
|
" return False\n",
|
|
" \n",
|
|
" # Check Account Info\n",
|
|
" account_info = mt.account_info()\n",
|
|
" if account_info is None:\n",
|
|
" print(f\"⚠️ Account Info nicht verfügbar (Versuch {attempt + 1}/{max_retries})\")\n",
|
|
" \n",
|
|
" # Try Re-Login\n",
|
|
" print(f\"🔄 Versuche Re-Login...\")\n",
|
|
" login_result = mt.login(10800246, kr.get_password('VantageInternational-Demo', '10800246'), 'VantageInternational-Demo')\n",
|
|
" \n",
|
|
" if not login_result:\n",
|
|
" if attempt < max_retries - 1:\n",
|
|
" time.sleep(retry_delay)\n",
|
|
" continue\n",
|
|
" return False\n",
|
|
" \n",
|
|
" # Test Symbol Info\n",
|
|
" symbol_info = mt.symbol_info(symbol)\n",
|
|
" if symbol_info is None:\n",
|
|
" print(f\"⚠️ Symbol {symbol} nicht verfügbar (Versuch {attempt + 1}/{max_retries})\")\n",
|
|
" if attempt < max_retries - 1:\n",
|
|
" time.sleep(retry_delay)\n",
|
|
" continue\n",
|
|
" return False\n",
|
|
" \n",
|
|
" # Test Market Data\n",
|
|
" tick = mt.symbol_info_tick(symbol)\n",
|
|
" if tick is None:\n",
|
|
" print(f\"⚠️ Market Data für {symbol} nicht verfügbar (Versuch {attempt + 1}/{max_retries})\")\n",
|
|
" if attempt < max_retries - 1:\n",
|
|
" time.sleep(retry_delay)\n",
|
|
" continue\n",
|
|
" return False\n",
|
|
" \n",
|
|
" # Connection erfolgreich\n",
|
|
" CIRCUIT_BREAKER_STATE['connection_issues_count'] = 0\n",
|
|
" CIRCUIT_BREAKER_STATE['last_connection_check'] = datetime.now()\n",
|
|
" \n",
|
|
" if attempt > 0:\n",
|
|
" print(f\"✅ MT5 Verbindung wiederhergestellt nach {attempt} Versuchen\")\n",
|
|
" \n",
|
|
" return True\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" print(f\"❌ MT5 Connection Error (Versuch {attempt + 1}/{max_retries}): {e}\")\n",
|
|
" CIRCUIT_BREAKER_STATE['connection_issues_count'] += 1\n",
|
|
" \n",
|
|
" if attempt < max_retries - 1:\n",
|
|
" time.sleep(retry_delay)\n",
|
|
" continue\n",
|
|
" \n",
|
|
" print(f\"🚨 KRITISCH: MT5 Verbindung nach {max_retries} Versuchen fehlgeschlagen!\")\n",
|
|
" return False\n",
|
|
"\n",
|
|
"def is_trading_session_active(\n",
|
|
" symbol: str = \"XAUUSD\",\n",
|
|
" timezone_str: str = \"Europe/London\"\n",
|
|
") -> Tuple[bool, Dict[str, Any]]:\n",
|
|
" \"\"\"\n",
|
|
" 🕐 Trading Session & Market Hours Check\n",
|
|
" \"\"\"\n",
|
|
" try:\n",
|
|
" # Get current time in specified timezone\n",
|
|
" tz = pytz.timezone(timezone_str)\n",
|
|
" current_time = datetime.now(tz)\n",
|
|
" current_weekday = current_time.weekday() # 0=Monday, 6=Sunday\n",
|
|
" current_hour = current_time.hour\n",
|
|
" \n",
|
|
" # Define trading sessions for XAUUSD (24/5 market)\n",
|
|
" if symbol == \"XAUUSD\":\n",
|
|
" # Gold trades 24/5 - avoid only weekends\n",
|
|
" weekend_start = 5 # Friday\n",
|
|
" weekend_end = 0 # Monday\n",
|
|
" weekend_hour_start = 22 # Friday 22:00\n",
|
|
" weekend_hour_end = 1 # Monday 01:00\n",
|
|
" \n",
|
|
" # Check weekend closure\n",
|
|
" is_weekend = (\n",
|
|
" current_weekday == 6 or # Sunday\n",
|
|
" (current_weekday == weekend_start and current_hour >= weekend_hour_start) or # Friday after 22:00\n",
|
|
" (current_weekday == weekend_end and current_hour < weekend_hour_end) # Monday before 01:00\n",
|
|
" )\n",
|
|
" \n",
|
|
" session_active = not is_weekend\n",
|
|
" session_name = \"Weekend Closure\" if is_weekend else \"24/5 Active\"\n",
|
|
" \n",
|
|
" else:\n",
|
|
" # For other symbols: Standard Forex Hours\n",
|
|
" session_active = (\n",
|
|
" current_weekday < 5 and # Monday-Friday\n",
|
|
" 1 <= current_hour <= 22 # 01:00-22:00\n",
|
|
" )\n",
|
|
" session_name = \"Forex Hours\" if session_active else \"Market Closed\"\n",
|
|
" \n",
|
|
" # Check symbol specific info\n",
|
|
" symbol_info = mt.symbol_info(symbol)\n",
|
|
" if symbol_info:\n",
|
|
" spread = symbol_info.spread\n",
|
|
" spread_points = spread * symbol_info.point\n",
|
|
" else:\n",
|
|
" spread = 0\n",
|
|
" spread_points = 0.0\n",
|
|
" \n",
|
|
" session_info = {\n",
|
|
" 'current_time': current_time.strftime('%Y-%m-%d %H:%M:%S %Z'),\n",
|
|
" 'current_weekday': current_weekday,\n",
|
|
" 'current_hour': current_hour,\n",
|
|
" 'session_active': session_active,\n",
|
|
" 'session_name': session_name,\n",
|
|
" 'symbol': symbol,\n",
|
|
" 'spread': spread,\n",
|
|
" 'spread_points': spread_points,\n",
|
|
" 'timezone': timezone_str\n",
|
|
" }\n",
|
|
" \n",
|
|
" return session_active, session_info\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" error_msg = f\"Error checking trading session: {e}\"\n",
|
|
" print(f\"❌ {error_msg}\")\n",
|
|
" return False, {'error': error_msg, 'status': 'error'}\n",
|
|
"\n",
|
|
"def check_spread_conditions(\n",
|
|
" symbol: str = \"XAUUSD\",\n",
|
|
" max_spread_points: float = 1.0,\n",
|
|
" max_spread_atr_ratio: float = 0.3\n",
|
|
") -> Tuple[bool, Dict[str, Any]]:\n",
|
|
" \"\"\"\n",
|
|
" 📊 Spread & Market Quality Check\n",
|
|
" \"\"\"\n",
|
|
" try:\n",
|
|
" # Get symbol info\n",
|
|
" symbol_info = mt.symbol_info(symbol)\n",
|
|
" if symbol_info is None:\n",
|
|
" return False, {'error': f'Symbol {symbol} info nicht verfügbar'}\n",
|
|
" \n",
|
|
" # Get current spread\n",
|
|
" spread = symbol_info.spread\n",
|
|
" spread_points = spread * symbol_info.point\n",
|
|
" \n",
|
|
" # Get ATR for comparison\n",
|
|
" try:\n",
|
|
" df = get_rates(\"m5\", 50, symbol)\n",
|
|
" if df is not None and len(df) > 14:\n",
|
|
" current_atr = df['atr'].iloc[-1]\n",
|
|
" spread_atr_ratio = spread_points / current_atr if current_atr > 0 else 999\n",
|
|
" else:\n",
|
|
" current_atr = 0.001 # Fallback\n",
|
|
" spread_atr_ratio = spread_points / current_atr\n",
|
|
" except:\n",
|
|
" current_atr = 0.001\n",
|
|
" spread_atr_ratio = spread_points / current_atr\n",
|
|
" \n",
|
|
" # Check spread conditions\n",
|
|
" spread_points_ok = spread_points <= max_spread_points\n",
|
|
" spread_atr_ok = spread_atr_ratio <= max_spread_atr_ratio\n",
|
|
" spread_overall_ok = spread_points_ok and spread_atr_ok\n",
|
|
" \n",
|
|
" spread_info = {\n",
|
|
" 'symbol': symbol,\n",
|
|
" 'spread': spread,\n",
|
|
" 'spread_points': spread_points,\n",
|
|
" 'current_atr': current_atr,\n",
|
|
" 'spread_atr_ratio': spread_atr_ratio,\n",
|
|
" 'max_spread_points': max_spread_points,\n",
|
|
" 'max_spread_atr_ratio': max_spread_atr_ratio,\n",
|
|
" 'spread_points_ok': spread_points_ok,\n",
|
|
" 'spread_atr_ok': spread_atr_ok,\n",
|
|
" 'spread_overall_ok': spread_overall_ok\n",
|
|
" }\n",
|
|
" \n",
|
|
" return spread_overall_ok, spread_info\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" error_msg = f\"Error checking spread conditions: {e}\"\n",
|
|
" print(f\"❌ {error_msg}\")\n",
|
|
" return False, {'error': error_msg, 'status': 'error'}\n",
|
|
"\n",
|
|
"def emergency_shutdown_protocol(\n",
|
|
" reason: str = \"Manual Emergency Stop\",\n",
|
|
" close_all_positions: bool = True,\n",
|
|
" stop_scheduler: bool = True\n",
|
|
") -> Dict[str, Any]:\n",
|
|
" \"\"\"\n",
|
|
" 🚨 Emergency Shutdown Protocol\n",
|
|
" \"\"\"\n",
|
|
" global CIRCUIT_BREAKER_STATE\n",
|
|
" \n",
|
|
" print(f\"\\n🚨 EMERGENCY SHUTDOWN PROTOCOL ACTIVATED\")\n",
|
|
" print(f\"Grund: {reason}\")\n",
|
|
" print(f\"Timestamp: {datetime.now()}\")\n",
|
|
" \n",
|
|
" shutdown_status = {\n",
|
|
" 'timestamp': datetime.now().isoformat(),\n",
|
|
" 'reason': reason,\n",
|
|
" 'actions_taken': [],\n",
|
|
" 'success': True\n",
|
|
" }\n",
|
|
" \n",
|
|
" try:\n",
|
|
" # 1. Activate emergency stop\n",
|
|
" CIRCUIT_BREAKER_STATE['emergency_stop_active'] = True\n",
|
|
" shutdown_status['actions_taken'].append('Emergency stop activated')\n",
|
|
" \n",
|
|
" # 2. Close all positions if requested\n",
|
|
" if close_all_positions:\n",
|
|
" print(f\"🔄 Schließe alle Positionen...\")\n",
|
|
" close_result = close_existing_positions(symbol, strategy_name, force_close=True)\n",
|
|
" shutdown_status['actions_taken'].append(f'Positions closed: {close_result}')\n",
|
|
" \n",
|
|
" # 3. Stop scheduler if requested\n",
|
|
" if stop_scheduler:\n",
|
|
" try:\n",
|
|
" complete_relaxed_scheduler.remove_all_jobs()\n",
|
|
" print(f\"⏹️ Scheduler Jobs entfernt\")\n",
|
|
" shutdown_status['actions_taken'].append('Scheduler jobs removed')\n",
|
|
" except Exception as e:\n",
|
|
" print(f\"⚠️ Scheduler stop error: {e}\")\n",
|
|
" shutdown_status['actions_taken'].append(f'Scheduler stop error: {e}')\n",
|
|
" \n",
|
|
" print(f\"\\n✅ Emergency Shutdown abgeschlossen\")\n",
|
|
" return shutdown_status\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" error_msg = f\"Critical error in emergency shutdown: {e}\"\n",
|
|
" print(f\"🚨 {error_msg}\")\n",
|
|
" shutdown_status['success'] = False\n",
|
|
" shutdown_status['critical_error'] = error_msg\n",
|
|
" return shutdown_status\n",
|
|
"\n",
|
|
"print(\"✅ Circuit Breaker & Emergency Systems loaded\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 4. 🛡️ Enhanced Risk Management Functions"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def enhanced_risk_limits_check(\n",
|
|
" symbol: str = \"XAUUSD\",\n",
|
|
" max_risk_per_trade: float = 0.01,\n",
|
|
" max_total_risk: float = 0.05,\n",
|
|
" min_equity_ratio: float = 0.8,\n",
|
|
" max_consecutive_losses: int = 3\n",
|
|
") -> Tuple[bool, Dict[str, Any]]:\n",
|
|
" \"\"\"\n",
|
|
" 🛡️ Enhanced Risk Management mit Multiple Checks\n",
|
|
" \"\"\"\n",
|
|
" try:\n",
|
|
" # Account Info Check\n",
|
|
" account_info = mt.account_info()\n",
|
|
" if account_info is None:\n",
|
|
" return False, {'error': 'Account info nicht verfügbar'}\n",
|
|
" \n",
|
|
" balance = account_info.balance\n",
|
|
" equity = account_info.equity\n",
|
|
" margin = account_info.margin\n",
|
|
" margin_free = account_info.margin_free\n",
|
|
" \n",
|
|
" # Basic ratio checks\n",
|
|
" equity_ratio = equity / balance if balance > 0 else 0\n",
|
|
" equity_ok = equity_ratio >= min_equity_ratio\n",
|
|
" \n",
|
|
" # Position risk check\n",
|
|
" has_position, position_info = check_existing_positions(symbol, strategy_name)\n",
|
|
" current_risk = 0.0\n",
|
|
" \n",
|
|
" if has_position:\n",
|
|
" for pos in position_info['details']:\n",
|
|
" # Estimate risk as potential loss\n",
|
|
" position_risk = abs(pos['profit']) if pos['profit'] < 0 else pos['volume'] * 100 # Rough estimate\n",
|
|
" current_risk += position_risk\n",
|
|
" \n",
|
|
" total_risk_ratio = current_risk / balance if balance > 0 else 0\n",
|
|
" total_risk_ok = total_risk_ratio <= max_total_risk\n",
|
|
" \n",
|
|
" # Margin check\n",
|
|
" margin_ok = margin_free > (balance * max_risk_per_trade * 10) # Safety margin\n",
|
|
" \n",
|
|
" risk_overall_ok = equity_ok and total_risk_ok and margin_ok\n",
|
|
" \n",
|
|
" risk_info = {\n",
|
|
" 'balance': balance,\n",
|
|
" 'equity': equity,\n",
|
|
" 'equity_ratio': equity_ratio,\n",
|
|
" 'min_equity_ratio': min_equity_ratio,\n",
|
|
" 'margin': margin,\n",
|
|
" 'margin_free': margin_free,\n",
|
|
" 'current_risk': current_risk,\n",
|
|
" 'total_risk_ratio': total_risk_ratio,\n",
|
|
" 'max_total_risk': max_total_risk,\n",
|
|
" 'equity_ok': equity_ok,\n",
|
|
" 'total_risk_ok': total_risk_ok,\n",
|
|
" 'margin_ok': margin_ok,\n",
|
|
" 'risk_overall_ok': risk_overall_ok\n",
|
|
" }\n",
|
|
" \n",
|
|
" return risk_overall_ok, risk_info\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" error_msg = f\"Error in enhanced risk check: {e}\"\n",
|
|
" print(f\"❌ {error_msg}\")\n",
|
|
" return False, {'error': error_msg, 'status': 'error'}\n",
|
|
"\n",
|
|
"def comprehensive_safety_check(\n",
|
|
" symbol: str = \"XAUUSD\",\n",
|
|
" strategy_name: str = \"TradingBot_V1.4_Complete_Relaxed_Enhanced_Safety\"\n",
|
|
") -> Tuple[bool, Dict[str, Any]]:\n",
|
|
" \"\"\"\n",
|
|
" 🛡️ Comprehensive Safety Pre-Trade Checks (Priorität 1)\n",
|
|
" \n",
|
|
" Führt alle Priorität 1 Safety Checks durch:\n",
|
|
" 1. MT5 Connection Check\n",
|
|
" 2. Circuit Breaker / Daily Loss Check \n",
|
|
" 3. Trading Session Check\n",
|
|
" 4. Spread Quality Check\n",
|
|
" 5. Enhanced Risk Limits Check\n",
|
|
" \n",
|
|
" Returns:\n",
|
|
" Tuple[bool, dict]: (all_checks_passed, detailed_results)\n",
|
|
" \"\"\"\n",
|
|
" print(f\"\\n🛡️ COMPREHENSIVE SAFETY CHECKS für {symbol}\")\n",
|
|
" print(\"=\" * 55)\n",
|
|
" \n",
|
|
" all_checks = []\n",
|
|
" \n",
|
|
" # 1. MT5 Connection Check\n",
|
|
" print(f\"🔧 1. MT5 Connection Check...\")\n",
|
|
" connection_ok = ensure_mt5_connection()\n",
|
|
" all_checks.append(('connection', connection_ok))\n",
|
|
" print(f\" {'✅' if connection_ok else '❌'} MT5 Connection: {'OK' if connection_ok else 'FAILED'}\")\n",
|
|
" \n",
|
|
" if not connection_ok:\n",
|
|
" # Critical failure - stop immediately\n",
|
|
" return False, {\n",
|
|
" 'critical_failure': 'MT5 Connection failed',\n",
|
|
" 'all_passed': False,\n",
|
|
" 'check_details': dict(all_checks)\n",
|
|
" }\n",
|
|
" \n",
|
|
" # 2. Circuit Breaker / Daily Loss Check\n",
|
|
" print(f\"\\n🚨 2. Circuit Breaker Check...\")\n",
|
|
" loss_ok, loss_info = check_daily_loss_limit()\n",
|
|
" all_checks.append(('daily_loss', loss_ok))\n",
|
|
" if loss_ok:\n",
|
|
" print(f\" ✅ Daily Loss: {loss_info.get('daily_loss_percent', 0):.2f}% (OK)\")\n",
|
|
" else:\n",
|
|
" print(f\" ❌ Circuit Breaker ACTIVE: {loss_info.get('daily_loss_percent', 0):.2f}%\")\n",
|
|
" \n",
|
|
" # 3. Trading Session Check\n",
|
|
" print(f\"\\n🕐 3. Trading Session Check...\")\n",
|
|
" session_ok, session_info = is_trading_session_active(symbol)\n",
|
|
" all_checks.append(('trading_session', session_ok))\n",
|
|
" print(f\" {'✅' if session_ok else '⏸️'} Session: {session_info.get('session_name', 'Unknown')}\")\n",
|
|
" \n",
|
|
" # 4. Spread Conditions Check\n",
|
|
" print(f\"\\n📊 4. Spread Quality Check...\")\n",
|
|
" spread_ok, spread_info = check_spread_conditions(symbol)\n",
|
|
" all_checks.append(('spread', spread_ok))\n",
|
|
" if spread_ok:\n",
|
|
" print(f\" ✅ Spread: {spread_info.get('spread_points', 0):.5f} points (GOOD)\")\n",
|
|
" else:\n",
|
|
" print(f\" ⚠️ Spread: {spread_info.get('spread_points', 0):.5f} points (HIGH)\")\n",
|
|
" \n",
|
|
" # 5. Enhanced Risk Limits Check\n",
|
|
" print(f\"\\n🛡️ 5. Enhanced Risk Check...\")\n",
|
|
" risk_ok, risk_info = enhanced_risk_limits_check(symbol)\n",
|
|
" all_checks.append(('enhanced_risk', risk_ok))\n",
|
|
" if risk_ok:\n",
|
|
" print(f\" ✅ Risk Limits: Equity {risk_info.get('equity_ratio', 0):.3f} (SAFE)\")\n",
|
|
" else:\n",
|
|
" print(f\" ❌ Risk Limits EXCEEDED\")\n",
|
|
" \n",
|
|
" # Summary\n",
|
|
" total_checks = len(all_checks)\n",
|
|
" passed_checks = sum(1 for _, passed in all_checks if passed)\n",
|
|
" all_passed = passed_checks == total_checks\n",
|
|
" \n",
|
|
" print(f\"\\n📊 COMPREHENSIVE SAFETY SUMMARY: {passed_checks}/{total_checks} PASSED\")\n",
|
|
" \n",
|
|
" if all_passed:\n",
|
|
" print(f\"✅ ALL SAFETY CHECKS PASSED - Trading mit Enhanced Safety allowed\")\n",
|
|
" safety_status = \"✅ SAFE TO TRADE\"\n",
|
|
" else:\n",
|
|
" print(f\"❌ SAFETY CHECKS FAILED - Trading BLOCKED für Sicherheit\")\n",
|
|
" failed_checks = [name for name, passed in all_checks if not passed]\n",
|
|
" print(f\" Failed: {', '.join(failed_checks)}\")\n",
|
|
" safety_status = f\"❌ BLOCKED: {', '.join(failed_checks)}\"\n",
|
|
" \n",
|
|
" comprehensive_results = {\n",
|
|
" 'all_passed': all_passed,\n",
|
|
" 'safety_status': safety_status,\n",
|
|
" 'total_checks': total_checks,\n",
|
|
" 'passed_checks': passed_checks,\n",
|
|
" 'check_details': dict(all_checks),\n",
|
|
" 'connection_info': {'status': connection_ok},\n",
|
|
" 'loss_info': loss_info,\n",
|
|
" 'session_info': session_info,\n",
|
|
" 'spread_info': spread_info,\n",
|
|
" 'risk_info': risk_info,\n",
|
|
" 'timestamp': datetime.now().isoformat()\n",
|
|
" }\n",
|
|
" \n",
|
|
" return all_passed, comprehensive_results\n",
|
|
"\n",
|
|
"print(\"✅ Enhanced Risk Management Functions loaded\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 5. Standard Helper Functions (Enhanced)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Enhanced Helper Functions mit Error Handling\n",
|
|
"def get_rates_with_retry(timeframe=\"h4\", count=200, symbol=\"XAUUSD\", max_retries=3):\n",
|
|
" \"\"\"\n",
|
|
" Enhanced get_rates mit Retry-Logic und besserer Error Handling\n",
|
|
" \"\"\"\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, \"d1\": mt.TIMEFRAME_D1\n",
|
|
" }\n",
|
|
" \n",
|
|
" for attempt in range(max_retries):\n",
|
|
" try:\n",
|
|
" # Ensure connection before data request\n",
|
|
" if not ensure_mt5_connection():\n",
|
|
" print(f\"⚠️ Connection failed for get_rates (attempt {attempt + 1})\")\n",
|
|
" if attempt < max_retries - 1:\n",
|
|
" time.sleep(1)\n",
|
|
" continue\n",
|
|
" return None\n",
|
|
" \n",
|
|
" rates = mt.copy_rates_from_pos(symbol, timeframes_dict[timeframe], 0, count)\n",
|
|
" if rates is None:\n",
|
|
" print(f\"⚠️ No rates data for {timeframe} (attempt {attempt + 1})\")\n",
|
|
" if attempt < max_retries - 1:\n",
|
|
" time.sleep(1)\n",
|
|
" continue\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",
|
|
" \n",
|
|
" # Enhanced ATR calculation mit Error Handling\n",
|
|
" try:\n",
|
|
" df['atr'] = ta.atr(df['high'], df['low'], df['close'], length=14)\n",
|
|
" \n",
|
|
" # Fill NaN values\n",
|
|
" if df['atr'].isna().any():\n",
|
|
" df['atr'] = df['atr'].fillna(method='bfill').fillna(0.001)\n",
|
|
" \n",
|
|
" except Exception as atr_error:\n",
|
|
" print(f\"⚠️ ATR calculation error: {atr_error}\")\n",
|
|
" # Fallback ATR calculation\n",
|
|
" df['tr'] = np.maximum(\n",
|
|
" df['high'] - df['low'],\n",
|
|
" np.maximum(\n",
|
|
" abs(df['high'] - df['close'].shift(1)),\n",
|
|
" abs(df['low'] - df['close'].shift(1))\n",
|
|
" )\n",
|
|
" )\n",
|
|
" df['atr'] = df['tr'].rolling(window=14).mean().fillna(0.001)\n",
|
|
" \n",
|
|
" # Validate data quality\n",
|
|
" if len(df) < 20:\n",
|
|
" print(f\"⚠️ Insufficient data: {len(df)} rows for {timeframe}\")\n",
|
|
" if attempt < max_retries - 1:\n",
|
|
" continue\n",
|
|
" return None\n",
|
|
" \n",
|
|
" # Success\n",
|
|
" if attempt > 0:\n",
|
|
" print(f\"✅ Data retrieved successfully after {attempt} retries\")\n",
|
|
" \n",
|
|
" return df\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" print(f\"❌ Error getting rates for {timeframe} (attempt {attempt + 1}): {e}\")\n",
|
|
" if attempt < max_retries - 1:\n",
|
|
" time.sleep(1)\n",
|
|
" continue\n",
|
|
" \n",
|
|
" print(f\"❌ Failed to get rates after {max_retries} attempts\")\n",
|
|
" return None\n",
|
|
"\n",
|
|
"# Backward compatibility\n",
|
|
"def get_rates(timeframe=\"h4\", count=200, symbol=\"XAUUSD\"):\n",
|
|
" \"\"\"Backward compatible wrapper\"\"\"\n",
|
|
" return get_rates_with_retry(timeframe, count, symbol)\n",
|
|
"\n",
|
|
"def enhanced_market_order(\n",
|
|
" symbol: str,\n",
|
|
" volume: float,\n",
|
|
" order_type: str,\n",
|
|
" stoploss: Optional[float] = None,\n",
|
|
" take_profit: Optional[float] = None,\n",
|
|
" deviation: int = 20,\n",
|
|
" max_retries: int = 3\n",
|
|
") -> Optional[Any]:\n",
|
|
" \"\"\"\n",
|
|
" Enhanced Market Order mit Retry-Logic und besserer Error Handling\n",
|
|
" \"\"\"\n",
|
|
" for attempt in range(max_retries):\n",
|
|
" try:\n",
|
|
" # Pre-order safety checks\n",
|
|
" if not ensure_mt5_connection():\n",
|
|
" print(f\"⚠️ Connection check failed before order (attempt {attempt + 1})\")\n",
|
|
" if attempt < max_retries - 1:\n",
|
|
" time.sleep(1)\n",
|
|
" continue\n",
|
|
" return None\n",
|
|
" \n",
|
|
" # Get current prices\n",
|
|
" tick = mt.symbol_info_tick(symbol)\n",
|
|
" if tick is None:\n",
|
|
" print(f\"⚠️ No tick data for {symbol} (attempt {attempt + 1})\")\n",
|
|
" if attempt < max_retries - 1:\n",
|
|
" time.sleep(1)\n",
|
|
" continue\n",
|
|
" return None\n",
|
|
" \n",
|
|
" price_dict = {'buy': tick.ask, 'sell': tick.bid}\n",
|
|
" order_type_dict = {'buy': mt.ORDER_TYPE_BUY, 'sell': mt.ORDER_TYPE_SELL}\n",
|
|
" \n",
|
|
" # Build request\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",
|
|
" \n",
|
|
" # Send order\n",
|
|
" result = mt.order_send(request)\n",
|
|
" \n",
|
|
" if result is None:\n",
|
|
" print(f\"⚠️ Order send returned None (attempt {attempt + 1})\")\n",
|
|
" if attempt < max_retries - 1:\n",
|
|
" time.sleep(1)\n",
|
|
" continue\n",
|
|
" return None\n",
|
|
" \n",
|
|
" # Check result\n",
|
|
" if result.retcode == mt.TRADE_RETCODE_DONE:\n",
|
|
" if attempt > 0:\n",
|
|
" print(f\"✅ Order successful after {attempt} retries\")\n",
|
|
" return result\n",
|
|
" else:\n",
|
|
" print(f\"⚠️ Order failed: {result.comment} (attempt {attempt + 1})\")\n",
|
|
" if attempt < max_retries - 1:\n",
|
|
" time.sleep(1)\n",
|
|
" continue\n",
|
|
" return result # Return even failed result for error analysis\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" print(f\"❌ Exception in market order (attempt {attempt + 1}): {e}\")\n",
|
|
" if attempt < max_retries - 1:\n",
|
|
" time.sleep(1)\n",
|
|
" continue\n",
|
|
" \n",
|
|
" print(f\"❌ Market order failed after {max_retries} attempts\")\n",
|
|
" return None\n",
|
|
"\n",
|
|
"# Backward compatibility\n",
|
|
"def market_order(symbol, volume, order_type, stoploss=None, take_profit=None, deviation=20):\n",
|
|
" \"\"\"Backward compatible wrapper\"\"\"\n",
|
|
" return enhanced_market_order(symbol, volume, order_type, stoploss, take_profit, deviation)\n",
|
|
"\n",
|
|
"def check_risk_limits(symbol, volume=None, order_type=\"buy\", max_risk_per_trade=0.01):\n",
|
|
" \"\"\"Enhanced Risk Limits Check - now uses comprehensive safety check\"\"\"\n",
|
|
" try:\n",
|
|
" # Use enhanced risk check\n",
|
|
" risk_ok, risk_info = enhanced_risk_limits_check(symbol, max_risk_per_trade)\n",
|
|
" return risk_ok\n",
|
|
" except:\n",
|
|
" # Fallback to original logic\n",
|
|
" try:\n",
|
|
" account_info = mt.account_info()\n",
|
|
" if not account_info: return False\n",
|
|
" balance, equity = account_info.balance, account_info.equity\n",
|
|
" if equity < balance * 0.8: return False\n",
|
|
" return True\n",
|
|
" except:\n",
|
|
" return False\n",
|
|
"\n",
|
|
"print(\"✅ Enhanced Helper Functions loaded mit Safety Features\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 6. 🛡️ Position Control Functions (Enhanced)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def check_existing_positions(symbol=\"XAUUSD\", strategy_name=\"TradingBot_V1.4_Complete_Relaxed_Enhanced_Safety\"):\n",
|
|
" \"\"\"\n",
|
|
" Enhanced Position Check mit besserer Error Handling\n",
|
|
" \"\"\"\n",
|
|
" try:\n",
|
|
" # Ensure connection before checking positions\n",
|
|
" if not ensure_mt5_connection():\n",
|
|
" print(\"❌ Cannot check positions - MT5 connection failed\")\n",
|
|
" return False, {\"count\": 0, \"details\": [], \"error\": \"connection_failed\"}\n",
|
|
" \n",
|
|
" # Get all positions for symbol\n",
|
|
" positions = mt.positions_get(symbol=symbol)\n",
|
|
" \n",
|
|
" if positions is None:\n",
|
|
" return False, {\"count\": 0, \"details\": []}\n",
|
|
" \n",
|
|
" # Filter by strategy name\n",
|
|
" strategy_positions = []\n",
|
|
" for pos in positions:\n",
|
|
" try:\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",
|
|
" \"price_current\": pos.price_current,\n",
|
|
" \"profit\": pos.profit,\n",
|
|
" \"swap\": pos.swap,\n",
|
|
" \"comment\": pos.comment,\n",
|
|
" \"time_open\": pd.to_datetime(pos.time, unit='s')\n",
|
|
" })\n",
|
|
" except Exception as pos_error:\n",
|
|
" print(f\"⚠️ Error processing position {pos.ticket}: {pos_error}\")\n",
|
|
" continue\n",
|
|
" \n",
|
|
" has_position = len(strategy_positions) > 0\n",
|
|
" \n",
|
|
" position_info = {\n",
|
|
" \"count\": len(strategy_positions),\n",
|
|
" \"details\": strategy_positions,\n",
|
|
" \"total_profit\": sum(pos['profit'] for pos in strategy_positions),\n",
|
|
" \"total_volume\": sum(pos['volume'] for pos in strategy_positions)\n",
|
|
" }\n",
|
|
" \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\": [], \"error\": str(e)}\n",
|
|
"\n",
|
|
"def get_position_summary_enhanced(symbol=\"XAUUSD\", strategy_name=\"TradingBot_V1.4_Complete_Relaxed_Enhanced_Safety\"):\n",
|
|
" \"\"\"\n",
|
|
" Enhanced Position Summary mit Safety Information\n",
|
|
" \"\"\"\n",
|
|
" has_position, position_info = check_existing_positions(symbol, strategy_name)\n",
|
|
" \n",
|
|
" print(f\"\\n📊 ENHANCED POSITION SUMMARY für {symbol}\")\n",
|
|
" print(\"=\" * 60)\n",
|
|
" \n",
|
|
" if not has_position:\n",
|
|
" print(\"✅ Keine aktiven Positionen - bereit für neuen Trade\")\n",
|
|
" \n",
|
|
" # Additional safety info when no positions\n",
|
|
" try:\n",
|
|
" account_info = mt.account_info()\n",
|
|
" if account_info:\n",
|
|
" print(f\"💰 Account Status: Balance {account_info.balance:.2f} | Equity {account_info.equity:.2f}\")\n",
|
|
" equity_ratio = account_info.equity / account_info.balance\n",
|
|
" print(f\"📊 Equity Ratio: {equity_ratio:.3f} ({'✅' if equity_ratio >= 0.8 else '⚠️'})\")\n",
|
|
" except:\n",
|
|
" pass\n",
|
|
" \n",
|
|
" return False\n",
|
|
" \n",
|
|
" print(f\"⚠️ {position_info['count']} aktive Position(en) gefunden:\")\n",
|
|
" print(f\"💰 Total Profit: {position_info.get('total_profit', 0):.2f}\")\n",
|
|
" print(f\"📊 Total Volume: {position_info.get('total_volume', 0):.2f}\")\n",
|
|
" \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']:.5f}\")\n",
|
|
" print(f\" Aktueller Preis: {pos.get('price_current', 'N/A')}\")\n",
|
|
" print(f\" Profit: {profit_emoji} {pos['profit']:.2f}\")\n",
|
|
" print(f\" Swap: {pos.get('swap', 0):.2f}\")\n",
|
|
" print(f\" Eröffnungszeit: {pos['time_open']}\")\n",
|
|
" \n",
|
|
" print(f\"\\n🛑 TRADING BLOCKIERT - Maximal 1 Position erlaubt (Enhanced Safety)\")\n",
|
|
" return True\n",
|
|
"\n",
|
|
"# Backward compatibility\n",
|
|
"def get_position_summary(symbol=\"XAUUSD\", strategy_name=\"TradingBot_V1.4_Complete_Relaxed_Enhanced_Safety\"):\n",
|
|
" \"\"\"Backward compatible wrapper\"\"\"\n",
|
|
" return get_position_summary_enhanced(symbol, strategy_name)\n",
|
|
"\n",
|
|
"def close_existing_positions(symbol=\"XAUUSD\", strategy_name=\"TradingBot_V1.4_Complete_Relaxed_Enhanced_Safety\", force_close=False):\n",
|
|
" \"\"\"\n",
|
|
" Enhanced Position Closing mit Safety Features\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) mit Enhanced Safety...\")\n",
|
|
" \n",
|
|
" success_count = 0\n",
|
|
" for pos in position_info['details']:\n",
|
|
" try:\n",
|
|
" # Ensure connection before closing\n",
|
|
" if not ensure_mt5_connection():\n",
|
|
" print(f\"❌ Connection failed for closing position {pos['ticket']}\")\n",
|
|
" continue\n",
|
|
" \n",
|
|
" # Get current tick for closing price\n",
|
|
" tick = mt.symbol_info_tick(symbol)\n",
|
|
" if tick is None:\n",
|
|
" print(f\"❌ No tick data for closing position {pos['ticket']}\")\n",
|
|
" continue\n",
|
|
" \n",
|
|
" close_price = tick.bid if pos['type'] == \"BUY\" else tick.ask\n",
|
|
" \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\": close_price,\n",
|
|
" \"deviation\": 20,\n",
|
|
" \"magic\": 234000,\n",
|
|
" \"comment\": f\"Enhanced 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 and result.retcode == mt.TRADE_RETCODE_DONE:\n",
|
|
" print(f\"✅ Position {pos['ticket']} erfolgreich geschlossen (Enhanced)\")\n",
|
|
" success_count += 1\n",
|
|
" else:\n",
|
|
" error_msg = result.comment if result else \"No result\"\n",
|
|
" print(f\"❌ Fehler beim Schließen von Position {pos['ticket']}: {error_msg}\")\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" print(f\"❌ Exception beim Schließen von Position {pos['ticket']}: {e}\")\n",
|
|
" \n",
|
|
" print(f\"📊 Enhanced Close Result: {success_count}/{len(position_info['details'])} Positionen erfolgreich geschlossen\")\n",
|
|
" return success_count == len(position_info['details'])\n",
|
|
"\n",
|
|
"print(\"✅ Enhanced Position Control functions defined\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 7. Market Analysis Functions (Enhanced)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Enhanced Market Analysis mit Safety Features\n",
|
|
"def detect_market_regime_enhanced(df, lookback=50):\n",
|
|
" \"\"\"\n",
|
|
" Enhanced Market Regime Detection mit Error Handling\n",
|
|
" \"\"\"\n",
|
|
" try:\n",
|
|
" if df is None or len(df) < lookback:\n",
|
|
" print(f\"⚠️ Insufficient data for regime detection: {len(df) if df is not None else 0} rows\")\n",
|
|
" return {'regime': 'ranging', 'strength': 50, 'adx': 20, 'bb_width': 4.0, 'range_ratio': 1.0, 'vol_cluster': 1.0}\n",
|
|
" \n",
|
|
" # ADX Calculation mit Error Handling\n",
|
|
" try:\n",
|
|
" adx_data = ta.adx(df['high'], df['low'], df['close'], length=14)\n",
|
|
" if adx_data is not None and 'ADX_14' in adx_data.columns:\n",
|
|
" adx = adx_data['ADX_14'].iloc[-1]\n",
|
|
" if pd.isna(adx) or adx <= 0:\n",
|
|
" adx = 25.0 # Fallback\n",
|
|
" else:\n",
|
|
" adx = 25.0\n",
|
|
" except Exception as adx_error:\n",
|
|
" print(f\"⚠️ ADX calculation error: {adx_error}\")\n",
|
|
" adx = 25.0\n",
|
|
" \n",
|
|
" # Bollinger Bands mit Error Handling\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",
|
|
" if pd.isna(bb_width) or bb_width <= 0:\n",
|
|
" bb_width = 4.0\n",
|
|
" else:\n",
|
|
" bb_width = 4.0\n",
|
|
" except Exception as bb_error:\n",
|
|
" print(f\"⚠️ Bollinger Bands error: {bb_error}\")\n",
|
|
" bb_width = 4.0\n",
|
|
" \n",
|
|
" # Enhanced calculations mit Fallbacks\n",
|
|
" try:\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",
|
|
" \n",
|
|
" if len(df) >= 50:\n",
|
|
" vol_cluster = df['atr'].iloc[-10:].std() / df['atr'].iloc[-50:].mean()\n",
|
|
" if pd.isna(vol_cluster) or vol_cluster <= 0:\n",
|
|
" vol_cluster = 1.0\n",
|
|
" else:\n",
|
|
" vol_cluster = 1.0\n",
|
|
" except Exception as calc_error:\n",
|
|
" print(f\"⚠️ Range/volatility calculation error: {calc_error}\")\n",
|
|
" range_ratio = 1.0\n",
|
|
" vol_cluster = 1.0\n",
|
|
" \n",
|
|
" # Regime determination\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, \n",
|
|
" 'strength': strength, \n",
|
|
" 'adx': adx, \n",
|
|
" 'bb_width': bb_width, \n",
|
|
" 'range_ratio': range_ratio, \n",
|
|
" 'vol_cluster': vol_cluster,\n",
|
|
" 'data_quality': 'good'\n",
|
|
" }\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" print(f\"❌ Critical error in regime detection: {e}\")\n",
|
|
" return {\n",
|
|
" 'regime': 'ranging', \n",
|
|
" 'strength': 50, \n",
|
|
" 'adx': 20, \n",
|
|
" 'bb_width': 4.0, \n",
|
|
" 'range_ratio': 1.0, \n",
|
|
" 'vol_cluster': 1.0,\n",
|
|
" 'data_quality': 'fallback',\n",
|
|
" 'error': str(e)\n",
|
|
" }\n",
|
|
"\n",
|
|
"# Backward compatibility\n",
|
|
"def detect_market_regime(df, lookback=50):\n",
|
|
" \"\"\"Backward compatible wrapper\"\"\"\n",
|
|
" return detect_market_regime_enhanced(df, lookback)\n",
|
|
"\n",
|
|
"# RELAXED Adaptive Confidence Threshold (unchanged)\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",
|
|
"def get_enhanced_trend_with_safety(timeframe=\"H4\", lookback=150, symbol=\"XAUUSD\"):\n",
|
|
" \"\"\"\n",
|
|
" Enhanced Trend Analysis mit Safety Features\n",
|
|
" \"\"\"\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",
|
|
" # Use enhanced get_rates\n",
|
|
" df = get_rates_with_retry(tf, lookback, symbol)\n",
|
|
" if df is None or len(df) < 50:\n",
|
|
" print(f\"⚠️ Insufficient data for {timeframe}: {len(df) if df is not None else 0} rows\")\n",
|
|
" return None\n",
|
|
" \n",
|
|
" # Enhanced smoothing mit Error Handling\n",
|
|
" try:\n",
|
|
" window_size = min(15, len(df)//10)\n",
|
|
" if window_size < 3:\n",
|
|
" window_size = 3\n",
|
|
" if window_size % 2 == 0:\n",
|
|
" window_size += 1 # Ensure odd number\n",
|
|
" \n",
|
|
" df['close_smooth'] = savgol_filter(df['close'], window_size, 3)\n",
|
|
" except Exception as smooth_error:\n",
|
|
" print(f\"⚠️ Smoothing error for {timeframe}: {smooth_error}\")\n",
|
|
" df['close_smooth'] = df['close'].rolling(window=10).mean()\n",
|
|
" \n",
|
|
" # Linear regression mit Error Handling\n",
|
|
" try:\n",
|
|
" X = np.arange(len(df)).reshape(-1, 1)\n",
|
|
" y = df['close_smooth'].values\n",
|
|
" \n",
|
|
" # Remove NaN values\n",
|
|
" valid_mask = ~np.isnan(y)\n",
|
|
" X_clean = X[valid_mask]\n",
|
|
" y_clean = y[valid_mask]\n",
|
|
" \n",
|
|
" if len(X_clean) < 10:\n",
|
|
" print(f\"⚠️ Too few valid data points for regression: {len(X_clean)}\")\n",
|
|
" return None\n",
|
|
" \n",
|
|
" model = LinearRegression().fit(X_clean, y_clean)\n",
|
|
" slope = model.coef_[0]\n",
|
|
" except Exception as reg_error:\n",
|
|
" print(f\"⚠️ Regression error for {timeframe}: {reg_error}\")\n",
|
|
" return None\n",
|
|
" \n",
|
|
" # Enhanced regime detection\n",
|
|
" regime_info = detect_market_regime_enhanced(df.iloc[-50:])\n",
|
|
" base_threshold = df['atr'].iloc[-1] * 0.0001\n",
|
|
" \n",
|
|
" # Regime-based slope threshold\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",
|
|
" # Determine trend\n",
|
|
" if abs(slope_threshold) < 1e-10: # Avoid division by zero\n",
|
|
" trend = \"sideways\"\n",
|
|
" trend_strength = 0\n",
|
|
" else:\n",
|
|
" trend = \"uptrend\" if slope > slope_threshold else \"downtrend\" if slope < -slope_threshold else \"sideways\"\n",
|
|
" trend_strength = abs(slope) / slope_threshold\n",
|
|
" \n",
|
|
" return {\n",
|
|
" \"trend\": trend, \n",
|
|
" \"slope\": slope, \n",
|
|
" \"slope_threshold\": slope_threshold,\n",
|
|
" \"trend_strength\": trend_strength, \n",
|
|
" \"atr\": df['atr'].iloc[-1],\n",
|
|
" \"price\": df['close'].iloc[-1], \n",
|
|
" \"regime_info\": regime_info,\n",
|
|
" \"data_quality\": \"enhanced\",\n",
|
|
" \"timeframe\": timeframe\n",
|
|
" }\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" print(f\"❌ Critical error in enhanced trend analysis for {timeframe}: {e}\")\n",
|
|
" return None\n",
|
|
"\n",
|
|
"# Backward compatibility\n",
|
|
"def get_enhanced_trend(timeframe=\"H4\", lookback=150, symbol=\"XAUUSD\"):\n",
|
|
" \"\"\"Backward compatible wrapper\"\"\"\n",
|
|
" return get_enhanced_trend_with_safety(timeframe, lookback, symbol)\n",
|
|
"\n",
|
|
"print(\"✅ Enhanced Market Analysis Functions loaded mit Safety Features\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 8. 🚀 Enhanced Safety Pre-Trade Checks Integration"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Test der Enhanced Safety Features\n",
|
|
"def test_priority_1_safety_features():\n",
|
|
" \"\"\"\n",
|
|
" 🧪 Test aller Priorität 1 Safety Features\n",
|
|
" \"\"\"\n",
|
|
" print(\"🧪 TESTING PRIORITY 1 SAFETY FEATURES\")\n",
|
|
" print(\"=\" * 45)\n",
|
|
" \n",
|
|
" # Test 1: Connection Monitoring\n",
|
|
" print(\"\\n1. 🔧 Testing Enhanced MT5 Connection...\")\n",
|
|
" connection_result = ensure_mt5_connection()\n",
|
|
" print(f\" Result: {'✅ PASSED' if connection_result else '❌ FAILED'}\")\n",
|
|
" \n",
|
|
" # Test 2: Circuit Breaker\n",
|
|
" print(\"\\n2. 🚨 Testing Circuit Breaker System...\")\n",
|
|
" loss_ok, loss_info = check_daily_loss_limit()\n",
|
|
" print(f\" Daily Loss: {loss_info.get('daily_loss_percent', 0):.2f}%\")\n",
|
|
" print(f\" Result: {'✅ PASSED' if loss_ok else '❌ CIRCUIT BREAKER ACTIVE'}\")\n",
|
|
" \n",
|
|
" # Test 3: Trading Session\n",
|
|
" print(\"\\n3. 🕐 Testing Trading Session Check...\")\n",
|
|
" session_ok, session_info = is_trading_session_active(symbol)\n",
|
|
" print(f\" Session: {session_info.get('session_name', 'Unknown')}\")\n",
|
|
" print(f\" Result: {'✅ PASSED' if session_ok else '⏸️ OUTSIDE HOURS'}\")\n",
|
|
" \n",
|
|
" # Test 4: Spread Quality\n",
|
|
" print(\"\\n4. 📊 Testing Spread Quality...\")\n",
|
|
" spread_ok, spread_info = check_spread_conditions(symbol)\n",
|
|
" print(f\" Spread: {spread_info.get('spread_points', 0):.5f} points\")\n",
|
|
" print(f\" Result: {'✅ PASSED' if spread_ok else '⚠️ HIGH SPREAD'}\")\n",
|
|
" \n",
|
|
" # Test 5: Enhanced Risk\n",
|
|
" print(\"\\n5. 🛡️ Testing Enhanced Risk Management...\")\n",
|
|
" risk_ok, risk_info = enhanced_risk_limits_check(symbol)\n",
|
|
" print(f\" Equity Ratio: {risk_info.get('equity_ratio', 0):.3f}\")\n",
|
|
" print(f\" Result: {'✅ PASSED' if risk_ok else '❌ RISK LIMIT EXCEEDED'}\")\n",
|
|
" \n",
|
|
" # Test 6: Comprehensive Check\n",
|
|
" print(\"\\n6. 🛡️ Testing Comprehensive Safety Check...\")\n",
|
|
" comprehensive_ok, comprehensive_info = comprehensive_safety_check(symbol, strategy_name)\n",
|
|
" print(f\" Overall: {comprehensive_info.get('passed_checks', 0)}/{comprehensive_info.get('total_checks', 0)} checks passed\")\n",
|
|
" print(f\" Result: {'✅ ALL SAFETY CHECKS PASSED' if comprehensive_ok else '❌ SAFETY CHECKS FAILED'}\")\n",
|
|
" \n",
|
|
" # Summary\n",
|
|
" print(f\"\\n📊 PRIORITY 1 SAFETY TEST SUMMARY:\")\n",
|
|
" test_results = [\n",
|
|
" (\"Connection\", connection_result),\n",
|
|
" (\"Circuit Breaker\", loss_ok),\n",
|
|
" (\"Trading Session\", session_ok),\n",
|
|
" (\"Spread Quality\", spread_ok),\n",
|
|
" (\"Risk Management\", risk_ok),\n",
|
|
" (\"Comprehensive\", comprehensive_ok)\n",
|
|
" ]\n",
|
|
" \n",
|
|
" for test_name, result in test_results:\n",
|
|
" status = \"✅ PASS\" if result else \"❌ FAIL\"\n",
|
|
" print(f\" {test_name}: {status}\")\n",
|
|
" \n",
|
|
" total_passed = sum(1 for _, result in test_results if result)\n",
|
|
" print(f\"\\n🎯 GESAMTERGEBNIS: {total_passed}/{len(test_results)} Tests bestanden\")\n",
|
|
" \n",
|
|
" if total_passed == len(test_results):\n",
|
|
" print(f\"🎉 Alle Priorität 1 Safety Features funktionieren perfekt!\")\n",
|
|
" else:\n",
|
|
" print(f\"⚠️ Einige Safety Features benötigen Aufmerksamkeit\")\n",
|
|
" \n",
|
|
" return comprehensive_ok, comprehensive_info\n",
|
|
"\n",
|
|
"# Test ausführen\n",
|
|
"if connection_success:\n",
|
|
" safety_test_result, safety_details = test_priority_1_safety_features()\nelse:\n print(\"🚨 Skipping safety tests - MT5 connection failed\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 9. 🚀 Enhanced Complete Relaxed Trading Function"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Original Complete Relaxed Functions mit Enhanced Safety Integration\n",
|
|
"def extended_top_down_v2_complete_relaxed_enhanced(\n",
|
|
" symbol=\"XAUUSD\", \n",
|
|
" lookback=150,\n",
|
|
" enable_safety_checks=True\n",
|
|
"):\n",
|
|
" \"\"\"\n",
|
|
" Enhanced Complete Relaxed Version mit Priorität 1 Safety Integration\n",
|
|
" \"\"\"\n",
|
|
" \n",
|
|
" # PRIORITÄT 1: Comprehensive Safety Check VOR Analysis\n",
|
|
" if enable_safety_checks:\n",
|
|
" safety_ok, safety_info = comprehensive_safety_check(symbol, strategy_name)\n",
|
|
" if not safety_ok:\n",
|
|
" print(f\"🛑 ANALYSIS BLOCKED: Safety checks failed\")\n",
|
|
" return None\n",
|
|
" print(f\"✅ All safety checks passed - proceeding with analysis\")\n",
|
|
" \n",
|
|
" timeframes = [\"D1\", \"H4\", \"H1\", \"M30\", \"M15\", \"M5\"]\n",
|
|
" trend_info = {}\n",
|
|
" \n",
|
|
" print(f\"\\n🔍 Analyzing {symbol} with ENHANCED COMPLETE RELAXED parameters...\")\n",
|
|
" \n",
|
|
" # Enhanced Timeframe Analysis mit Safety\n",
|
|
" failed_timeframes = []\n",
|
|
" for tf in timeframes:\n",
|
|
" trend_info[tf] = get_enhanced_trend_with_safety(tf, lookback, symbol)\n",
|
|
" if trend_info[tf] is None:\n",
|
|
" print(f\"⚠️ Keine Daten für {tf}\")\n",
|
|
" failed_timeframes.append(tf)\n",
|
|
" \n",
|
|
" # Check if too many timeframes failed\n",
|
|
" if len(failed_timeframes) > 2:\n",
|
|
" print(f\"❌ Zu viele Timeframes fehlgeschlagen: {failed_timeframes}\")\n",
|
|
" return None\n",
|
|
" \n",
|
|
" # Continue with original logic but enhanced error handling\n",
|
|
" try:\n",
|
|
" main_regime = trend_info[\"H4\"][\"regime_info\"]\n",
|
|
" adaptive_threshold = calculate_adaptive_confidence_threshold_relaxed(main_regime)\n",
|
|
" \n",
|
|
" # [Rest of the original Complete Relaxed logic...]\n",
|
|
" # (Keeping the original logic but with enhanced safety wrapper)\n",
|
|
" \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",
|
|
" # Fast trend analysis\n",
|
|
" fast_timeframes = [\"H1\", \"M30\", \"M15\", \"M5\"]\n",
|
|
" fast_trends = [trend_info[tf][\"trend\"] for tf in fast_timeframes if trend_info[tf] is not None]\n",
|
|
" fast_strengths = [trend_info[tf][\"trend_strength\"] for tf in fast_timeframes if trend_info[tf] is not None]\n",
|
|
" \n",
|
|
" required_alignment = 2 # RELAXED\n",
|
|
" \n",
|
|
" if len(fast_trends) < 3:\n",
|
|
" print(f\"⚠️ Insufficient fast timeframe data: {len(fast_trends)}/4\")\n",
|
|
" fast_trend = \"sideways\"\n",
|
|
" else:\n",
|
|
" trend_counts = {'uptrend': fast_trends.count('uptrend'), 'downtrend': fast_trends.count('downtrend')}\n",
|
|
" max_count = max(trend_counts['uptrend'], trend_counts['downtrend'])\n",
|
|
" \n",
|
|
" if max_count >= required_alignment:\n",
|
|
" fast_trend = \"uptrend\" if trend_counts['uptrend'] > trend_counts['downtrend'] else \"downtrend\"\n",
|
|
" else:\n",
|
|
" fast_trend = \"sideways\"\n",
|
|
" \n",
|
|
" # Top-down trend\n",
|
|
" if standard_trend == fast_trend and standard_trend != \"sideways\":\n",
|
|
" top_down_trend = standard_trend\n",
|
|
" combined_strength = standard_strength\n",
|
|
" else:\n",
|
|
" top_down_trend = \"sideways\"\n",
|
|
" combined_strength = 0\n",
|
|
" \n",
|
|
" # Confidence calculation (simplified for safety)\n",
|
|
" confidence = 75 if top_down_trend != \"sideways\" else 45\n",
|
|
" risk_adjusted_strength = confidence * combined_strength\n",
|
|
" \n",
|
|
" # Entry signal mit RELAXED parameters\n",
|
|
" min_strength = 80\n",
|
|
" entry_signal = 0\n",
|
|
" signal_quality = \"none\"\n",
|
|
" \n",
|
|
" if (top_down_trend != \"sideways\" and \n",
|
|
" confidence >= adaptive_threshold and\n",
|
|
" risk_adjusted_strength >= min_strength):\n",
|
|
" \n",
|
|
" entry_signal = 1 if top_down_trend == \"uptrend\" else -1\n",
|
|
" \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",
|
|
" print(f\"\\n📊 ENHANCED COMPLETE RELAXED Analysis für {symbol}\")\n",
|
|
" print(f\"🛡️ Safety Status: {'✅ ALL CHECKS PASSED' if enable_safety_checks else '⚠️ SAFETY DISABLED'}\")\n",
|
|
" print(f\"🎯 Market Regime: {main_regime['regime'].upper()}\")\n",
|
|
" print(f\"🎚️ RELAXED Threshold: {adaptive_threshold}%\")\n",
|
|
" print(f\"➡️ Top-Down-Trend: {top_down_trend}\")\n",
|
|
" print(f\"➡️ Confidence: {confidence}% | Signal: {entry_signal} | Quality: {signal_quality.upper()}\")\n",
|
|
" \n",
|
|
" return {\n",
|
|
" \"symbol\": symbol, \"trend_info\": trend_info, \"market_regime\": main_regime,\n",
|
|
" \"standard_trend\": standard_trend, \"fast_trend\": fast_trend, \"top_down_trend\": top_down_trend,\n",
|
|
" \"confidence\": confidence, \"adaptive_threshold\": adaptive_threshold,\n",
|
|
" \"risk_adjusted_strength\": risk_adjusted_strength, \"entry_signal\": entry_signal,\n",
|
|
" \"signal_quality\": signal_quality, \"combined_strength\": combined_strength,\n",
|
|
" \"min_strength_used\": min_strength, \"required_alignment\": required_alignment,\n",
|
|
" \"safety_enabled\": enable_safety_checks,\n",
|
|
" \"failed_timeframes\": failed_timeframes\n",
|
|
" }\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" print(f\"❌ Critical error in enhanced analysis: {e}\")\n",
|
|
" return None\n",
|
|
"\n",
|
|
"def execute_trade_v2_complete_relaxed_enhanced_safety(\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.4_Complete_Relaxed_Enhanced_Safety\",\n",
|
|
" debug=True,\n",
|
|
" enable_priority_1_safety=True # NEW: Enable Priority 1 Safety Features\n",
|
|
"):\n",
|
|
" \"\"\"\n",
|
|
" Enhanced Complete Relaxed Trading mit Priorität 1 Safety Features\n",
|
|
" \"\"\"\n",
|
|
" \n",
|
|
" # SCHRITT 0: PRIORITÄT 1 COMPREHENSIVE SAFETY CHECK\n",
|
|
" if enable_priority_1_safety:\n",
|
|
" print(f\"\\n🛡️ PRIORITY 1 SAFETY CHECK für {symbol}\")\n",
|
|
" safety_passed, safety_results = comprehensive_safety_check(symbol, strategy_name)\n",
|
|
" \n",
|
|
" if not safety_passed:\n",
|
|
" if debug:\n",
|
|
" print(f\"🚨 TRADE BLOCKIERT durch Priority 1 Safety: {safety_results.get('safety_status', 'Unknown')}\")\n",
|
|
" failed_checks = [name for name, passed in safety_results.get('check_details', {}).items() if not passed]\n",
|
|
" print(f\" Failed Checks: {', '.join(failed_checks)}\")\n",
|
|
" return None\n",
|
|
" \n",
|
|
" print(f\"✅ Priority 1 Safety: ALL CHECKS PASSED\")\n",
|
|
" \n",
|
|
" # SCHRITT 1: Enhanced Position Check\n",
|
|
" print(f\"\\n🔍 ENHANCED POSITION CHECK für {symbol}\")\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 bereits aktiv\")\n",
|
|
" print(f\"💰 Total Profit aktueller Positionen: {position_info.get('total_profit', 0):.2f}\")\n",
|
|
" return None\n",
|
|
" \n",
|
|
" print(f\"✅ Enhanced Position-Check OK: {position_info['count']}/{max_positions} Positionen\")\n",
|
|
" \n",
|
|
" # SCHRITT 2: Enhanced Signal Analysis\n",
|
|
" signal_info = extended_top_down_v2_complete_relaxed_enhanced(symbol, lookback=150, enable_safety_checks=False) # Safety already checked\n",
|
|
" if signal_info is None:\n",
|
|
" print(\"❌ Enhanced 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 from M5\n",
|
|
" m5_info = signal_info[\"trend_info\"][\"M5\"]\n",
|
|
" if m5_info is None:\n",
|
|
" print(\"❌ M5 timeframe data nicht verfügbar\")\n",
|
|
" return None\n",
|
|
" \n",
|
|
" price = m5_info[\"price\"]\n",
|
|
" atr = m5_info[\"atr\"]\n",
|
|
" \n",
|
|
" # SCHRITT 4: Enhanced Pre-checks\n",
|
|
" reason = \"\"\n",
|
|
" \n",
|
|
" if confidence < adaptive_threshold:\n",
|
|
" reason = f\"Confidence {confidence}% < relaxed threshold {adaptive_threshold}%\"\n",
|
|
" elif entry_signal == 0:\n",
|
|
" reason = f\"No entry signal (Trend: {signal_info['top_down_trend']}, Regime: {market_regime['regime']})\"\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",
|
|
" # SCHRITT 5: Final Enhanced Risk Check\n",
|
|
" final_risk_ok, final_risk_info = enhanced_risk_limits_check(symbol, max_risk_per_trade)\n",
|
|
" if not final_risk_ok:\n",
|
|
" reason = \"Enhanced risk limits exceeded\"\n",
|
|
" \n",
|
|
" # SCHRITT 6: Execute Trade with Enhanced Safety\n",
|
|
" if not reason:\n",
|
|
" # Final safety check before order\n",
|
|
" if enable_priority_1_safety:\n",
|
|
" final_safety_ok, _ = comprehensive_safety_check(symbol, strategy_name)\n",
|
|
" if not final_safety_ok:\n",
|
|
" print(f\"🛑 LAST-MINUTE SAFETY BLOCK: Safety conditions changed!\")\n",
|
|
" return None\n",
|
|
" \n",
|
|
" # Final position check\n",
|
|
" final_check, _ = check_existing_positions(symbol, strategy_name)\n",
|
|
" if final_check:\n",
|
|
" print(f\"🛑 FINAL POSITION BLOCK: Position eröffnet zwischen Checks!\")\n",
|
|
" return None\n",
|
|
" \n",
|
|
" # Calculate SL/TP with regime adjustments\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",
|
|
" # Enhanced 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",
|
|
" volume = min(0.1, max(0.01, risk_amount / (adjusted_atr_mult * atr * 100)))\n",
|
|
" else:\n",
|
|
" volume = 0.01\n",
|
|
" \n",
|
|
" # Additional volume safety check\n",
|
|
" if volume > balance * 0.001: # Never risk more than 0.1% per lot\n",
|
|
" volume = min(volume, balance * 0.001)\n",
|
|
" else:\n",
|
|
" volume = 0.01\n",
|
|
" \n",
|
|
" # Enhanced Trade Execution Log\n",
|
|
" print(f\"\\n🚀 ENHANCED COMPLETE RELAXED TRADE EXECUTION\")\n",
|
|
" print(f\"🛡️ Priority 1 Safety: {'ENABLED' if enable_priority_1_safety else 'DISABLED'}\")\n",
|
|
" print(f\"Symbol: {symbol}\")\n",
|
|
" print(f\"Direction: {'LONG' if entry_signal == 1 else 'SHORT'}\")\n",
|
|
" print(f\"Price: {price:.5f}\")\n",
|
|
" print(f\"Volume: {volume:.2f} (Enhanced Sizing)\")\n",
|
|
" print(f\"Stop Loss: {stop_loss:.5f}\")\n",
|
|
" print(f\"Take Profit: {take_profit:.5f}\")\n",
|
|
" print(f\"Confidence: {confidence}% (RELAXED Threshold: {adaptive_threshold}%)\")\n",
|
|
" print(f\"Signal Quality: {signal_quality.upper()}\")\n",
|
|
" print(f\"Market Regime: {market_regime['regime'].upper()}\")\n",
|
|
" print(f\"Strategy: {strategy_name}\")\n",
|
|
" \n",
|
|
" # Execute with enhanced order function\n",
|
|
" try:\n",
|
|
" order_result = enhanced_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",
|
|
" max_retries=3\n",
|
|
" )\n",
|
|
" \n",
|
|
" if order_result and order_result.retcode == mt.TRADE_RETCODE_DONE:\n",
|
|
" print(f\"✅ Enhanced Trade erfolgreich eröffnet! Ticket: {order_result.order}\")\n",
|
|
" \n",
|
|
" # Enhanced verification\n",
|
|
" new_check, new_info = check_existing_positions(symbol, strategy_name)\n",
|
|
" print(f\"📊 Enhanced Position Verification: {new_info['count']} Positionen\")\n",
|
|
" \n",
|
|
" # Enhanced performance logging (would be implemented)\n",
|
|
" print(f\"📊 Enhanced Performance Logging enabled\")\n",
|
|
" else:\n",
|
|
" error_msg = order_result.comment if order_result else 'No result'\n",
|
|
" print(f\"❌ Enhanced Trade failed: {error_msg}\")\n",
|
|
" \n",
|
|
" return order_result\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" print(f\"❌ Enhanced Trade execution failed: {e}\")\n",
|
|
" return None\n",
|
|
" \n",
|
|
" else:\n",
|
|
" if debug:\n",
|
|
" print(f\"\\n⏸️ ENHANCED COMPLETE RELAXED TRADE SKIPPED: {reason}\")\n",
|
|
" print(f\"🛡️ Safety Features: {'ACTIVE' if enable_priority_1_safety else 'DISABLED'}\")\n",
|
|
" print(f\"Confidence: {confidence}% | Threshold: {adaptive_threshold}%\")\n",
|
|
" print(f\"Signal Quality: {signal_quality} | Regime: {market_regime['regime']}\")\n",
|
|
" return None\n",
|
|
"\n",
|
|
"print(\"✅ Enhanced Complete Relaxed Trading Function loaded\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 10. 🧪 Testing Enhanced Safety Trading"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Enhanced Testing mit allen Safety Features\n",
|
|
"def test_enhanced_complete_relaxed_trading():\n",
|
|
" \"\"\"\n",
|
|
" 🧪 Test der Enhanced Complete Relaxed Version mit allen Safety Features\n",
|
|
" \"\"\"\n",
|
|
" print(\"🧪 TESTING ENHANCED COMPLETE RELAXED mit PRIORITY 1 SAFETY\")\n",
|
|
" print(\"=\" * 65)\n",
|
|
" \n",
|
|
" if not connection_success:\n",
|
|
" print(\"🚨 Test abgebrochen - MT5 Connection failed\")\n",
|
|
" return None\n",
|
|
" \n",
|
|
" try:\n",
|
|
" # Enhanced Configuration\n",
|
|
" ENHANCED_CONFIG = {\n",
|
|
" 'symbol': symbol,\n",
|
|
" 'strategy_name': strategy_name,\n",
|
|
" 'max_positions': max_positions,\n",
|
|
" 'enable_priority_1_safety': True, # Enable all safety features\n",
|
|
" 'debug': True\n",
|
|
" }\n",
|
|
" \n",
|
|
" print(f\"\\n⚙️ Enhanced Configuration:\")\n",
|
|
" print(f\"🛡️ Priority 1 Safety: ENABLED\")\n",
|
|
" print(f\"🚀 Complete Relaxed Logic: ENABLED\")\n",
|
|
" print(f\"📊 Enhanced Monitoring: ENABLED\")\n",
|
|
" \n",
|
|
" # Test 1: Comprehensive Safety Check\n",
|
|
" print(f\"\\n1. 🛡️ Testing Comprehensive Safety...\")\n",
|
|
" safety_ok, safety_info = comprehensive_safety_check(symbol, strategy_name)\n",
|
|
" print(f\" Result: {'✅ SAFE TO TRADE' if safety_ok else '❌ TRADING BLOCKED'}\")\n",
|
|
" \n",
|
|
" if not safety_ok:\n",
|
|
" print(f\"🚨 Trading blocked by safety systems - this is working correctly!\")\n",
|
|
" return None\n",
|
|
" \n",
|
|
" # Test 2: Enhanced Signal Analysis\n",
|
|
" print(f\"\\n2. 📊 Testing Enhanced Signal Analysis...\")\n",
|
|
" signal_result = extended_top_down_v2_complete_relaxed_enhanced(symbol, enable_safety_checks=True)\n",
|
|
" \n",
|
|
" if signal_result:\n",
|
|
" print(f\" ✅ Enhanced Analysis successful\")\n",
|
|
" print(f\" Signal: {signal_result['entry_signal']} | Quality: {signal_result['signal_quality']}\")\n",
|
|
" else:\n",
|
|
" print(f\" ❌ Enhanced Analysis failed\")\n",
|
|
" return None\n",
|
|
" \n",
|
|
" # Test 3: Enhanced Trading Execution\n",
|
|
" print(f\"\\n3. 🚀 Testing Enhanced Trading Execution...\")\n",
|
|
" result = execute_trade_v2_complete_relaxed_enhanced_safety(**ENHANCED_CONFIG)\n",
|
|
" \n",
|
|
" if result:\n",
|
|
" print(f\"\\n🎉 ENHANCED COMPLETE RELAXED TRADE SUCCESSFUL!\")\n",
|
|
" print(f\"📊 Order: {result}\")\n",
|
|
" \n",
|
|
" # Enhanced position verification\n",
|
|
" print(f\"\\n📊 Enhanced Position Verification:\")\n",
|
|
" get_position_summary_enhanced(symbol, strategy_name)\n",
|
|
" else:\n",
|
|
" print(f\"\\n⏸️ No enhanced trade executed (this may be correct based on conditions)\")\n",
|
|
" \n",
|
|
" return result\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" print(f\"❌ Error in enhanced testing: {e}\")\n",
|
|
" return None\n",
|
|
"\n",
|
|
"# Test the enhanced version\n",
|
|
"if connection_success:\n",
|
|
" enhanced_test_result = test_enhanced_complete_relaxed_trading()\nelse:\n print(\"🚨 Enhanced testing skipped - connection issues\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 11. 🤖 Enhanced Automated Trading mit Safety Integration"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def enhanced_complete_relaxed_trading_job():\n",
|
|
" \"\"\"\n",
|
|
" Enhanced Automated Trading Job mit Priorität 1 Safety Features\n",
|
|
" \"\"\"\n",
|
|
" try:\n",
|
|
" timestamp = pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S')\n",
|
|
" print(f\"\\n⏰ {timestamp} - Enhanced Complete Relaxed Trading Check\")\n",
|
|
" \n",
|
|
" # Pre-job comprehensive safety check\n",
|
|
" safety_ok, safety_info = comprehensive_safety_check(symbol, strategy_name)\n",
|
|
" \n",
|
|
" if not safety_ok:\n",
|
|
" print(f\"🛑 Job BLOCKED by Safety: {safety_info.get('safety_status', 'Unknown')}\")\n",
|
|
" \n",
|
|
" # Check if emergency shutdown needed\n",
|
|
" if safety_info.get('loss_info', {}).get('emergency_stop_active', False):\n",
|
|
" print(f\"🚨 Emergency Stop detected - stopping scheduler\")\n",
|
|
" emergency_shutdown_protocol(\"Daily Loss Limit Exceeded via Scheduler\")\n",
|
|
" \n",
|
|
" return None\n",
|
|
" \n",
|
|
" # Execute enhanced trading\n",
|
|
" result = execute_trade_v2_complete_relaxed_enhanced_safety(\n",
|
|
" symbol=symbol,\n",
|
|
" strategy_name=strategy_name,\n",
|
|
" max_positions=max_positions,\n",
|
|
" enable_priority_1_safety=True,\n",
|
|
" debug=False # Reduced logging for automated jobs\n",
|
|
" )\n",
|
|
" \n",
|
|
" if result:\n",
|
|
" print(f\"✅ Enhanced Complete Relaxed trade executed with full safety!\")\n",
|
|
" else:\n",
|
|
" print(f\"⏸️ No enhanced trade - waiting for better conditions\")\n",
|
|
" \n",
|
|
" # Enhanced performance monitoring\n",
|
|
" current_hour = pd.Timestamp.now().hour\n",
|
|
" if current_hour % 6 == 0: # Every 6 hours\n",
|
|
" print(f\"\\n📊 Enhanced Performance & Safety Status Update:\")\n",
|
|
" \n",
|
|
" # Account status\n",
|
|
" account_info = mt.account_info()\n",
|
|
" if account_info:\n",
|
|
" equity_ratio = account_info.equity / account_info.balance\n",
|
|
" print(f\"💰 Account: Balance {account_info.balance:.2f} | Equity {account_info.equity:.2f} | Ratio {equity_ratio:.3f}\")\n",
|
|
" \n",
|
|
" # Circuit breaker status\n",
|
|
" cb_status = CIRCUIT_BREAKER_STATE\n",
|
|
" print(f\"🚨 Circuit Breaker: {'ACTIVE' if cb_status['emergency_stop_active'] else 'NORMAL'}\")\n",
|
|
" print(f\"📊 Daily Loss: {cb_status['daily_loss_amount']:.2f}\")\n",
|
|
" print(f\"🔧 Connection Issues: {cb_status['connection_issues_count']}\")\n",
|
|
" \n",
|
|
" return result\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" print(f\"❌ Critical error in enhanced trading job: {e}\")\n",
|
|
" \n",
|
|
" # Increment failure counter\n",
|
|
" CIRCUIT_BREAKER_STATE['consecutive_failures'] += 1\n",
|
|
" \n",
|
|
" # Emergency shutdown after too many failures\n",
|
|
" if CIRCUIT_BREAKER_STATE['consecutive_failures'] >= 5:\n",
|
|
" print(f\"🚨 Too many consecutive failures ({CIRCUIT_BREAKER_STATE['consecutive_failures']}) - Emergency Shutdown\")\n",
|
|
" emergency_shutdown_protocol(f\"Consecutive Failures: {e}\")\n",
|
|
" \n",
|
|
" return None\n",
|
|
"\n",
|
|
"# Enhanced Scheduler Setup\n",
|
|
"enhanced_complete_relaxed_scheduler = BackgroundScheduler()\n",
|
|
"\n",
|
|
"if connection_success:\n",
|
|
" # Add enhanced job\n",
|
|
" enhanced_complete_relaxed_scheduler.add_job(\n",
|
|
" enhanced_complete_relaxed_trading_job,\n",
|
|
" 'cron',\n",
|
|
" year=\"*\",\n",
|
|
" month=\"*\",\n",
|
|
" day_of_week=\"mon,tue,wed,thu,fri\",\n",
|
|
" hour='1-22', # More conservative hours\n",
|
|
" minute='*/5',\n",
|
|
" id='enhanced_complete_relaxed_trading'\n",
|
|
" )\n",
|
|
" \n",
|
|
" print(\"\\n⚙️ Enhanced Scheduler configured:\")\n",
|
|
" print(\" 🛡️ Priority 1 Safety integrated\")\n",
|
|
" print(\" 🚀 Complete Relaxed Logic active\")\n",
|
|
" print(\" 📊 Enhanced monitoring enabled\")\n",
|
|
" print(\" 🤖 Auto-emergency shutdown on critical failures\")\n",
|
|
" print(\" ⏰ Trading: Mon-Fri, 01:00-22:00, every 5 minutes\")\n",
|
|
"else:\n",
|
|
" print(\"🚨 Enhanced scheduler not configured - connection issues\")\n",
|
|
"\n",
|
|
"print(\"✅ Enhanced Automated Trading System ready\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 12. 🚨 Emergency Controls & Manual Override"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Enhanced Control Panel\n",
|
|
"def show_enhanced_safety_control_panel():\n",
|
|
" \"\"\"\n",
|
|
" 🛡️ Enhanced Safety Control Panel\n",
|
|
" \"\"\"\n",
|
|
" print(\"🛡️ ENHANCED SAFETY CONTROL PANEL\")\n",
|
|
" print(\"=\" * 50)\n",
|
|
" \n",
|
|
" # Current Safety Status\n",
|
|
" print(\"\\n📊 CURRENT SAFETY STATUS:\")\n",
|
|
" cb_state = CIRCUIT_BREAKER_STATE\n",
|
|
" print(f\" 🚨 Emergency Stop: {'ACTIVE' if cb_state['emergency_stop_active'] else 'NORMAL'}\")\n",
|
|
" print(f\" 📊 Daily Loss: {cb_state['daily_loss_amount']:.2f}\")\n",
|
|
" print(f\" 🔧 Connection Issues: {cb_state['connection_issues_count']}\")\n",
|
|
" print(f\" ⚠️ Consecutive Failures: {cb_state['consecutive_failures']}\")\n",
|
|
" \n",
|
|
" # Available Commands\n",
|
|
" print(f\"\\n🎛️ AVAILABLE COMMANDS:\")\n",
|
|
" print(f\"\\n🚨 EMERGENCY CONTROLS:\")\n",
|
|
" print(f\" emergency_shutdown_protocol('Manual Stop')\")\n",
|
|
" print(f\" emergency_shutdown_protocol('Critical Issue', close_all_positions=True)\")\n",
|
|
" \n",
|
|
" print(f\"\\n🛡️ SAFETY CHECKS:\")\n",
|
|
" print(f\" comprehensive_safety_check(symbol, strategy_name)\")\n",
|
|
" print(f\" check_daily_loss_limit()\")\n",
|
|
" print(f\" ensure_mt5_connection()\")\n",
|
|
" \n",
|
|
" print(f\"\\n📊 MONITORING:\")\n",
|
|
" print(f\" get_position_summary_enhanced(symbol, strategy_name)\")\n",
|
|
" print(f\" test_priority_1_safety_features()\")\n",
|
|
" \n",
|
|
" print(f\"\\n🚀 TRADING:\")\n",
|
|
" print(f\" execute_trade_v2_complete_relaxed_enhanced_safety(enable_priority_1_safety=True)\")\n",
|
|
" \n",
|
|
" print(f\"\\n🎚️ SCHEDULER CONTROLS:\")\n",
|
|
" print(f\" enhanced_complete_relaxed_scheduler.start()\")\n",
|
|
" print(f\" enhanced_complete_relaxed_scheduler.remove_all_jobs()\")\n",
|
|
" print(f\" enhanced_complete_relaxed_scheduler.shutdown()\")\n",
|
|
"\n",
|
|
"show_enhanced_safety_control_panel()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Manual Emergency Controls\n",
|
|
"print(\"\\n🚨 MANUAL EMERGENCY CONTROLS:\")\n",
|
|
"print(\"\\n💡 To trigger emergency shutdown:\")\n",
|
|
"print(\" emergency_shutdown_protocol('Manual Emergency', close_all_positions=True, stop_scheduler=True)\")\n",
|
|
"\n",
|
|
"print(\"\\n💡 To reset circuit breaker (if safe):\")\n",
|
|
"print(\" CIRCUIT_BREAKER_STATE['emergency_stop_active'] = False\")\n",
|
|
"print(\" CIRCUIT_BREAKER_STATE['daily_loss_amount'] = 0.0\")\n",
|
|
"\n",
|
|
"print(\"\\n💡 To start enhanced automated trading:\")\n",
|
|
"print(\" enhanced_complete_relaxed_scheduler.start()\")\n",
|
|
"\n",
|
|
"# Emergency shutdown example (commented out for safety)\n",
|
|
"# emergency_shutdown_protocol(\"Test Emergency\", close_all_positions=True, stop_scheduler=True)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 13. 📈 Enhanced Summary & Priority 1 Features"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"print(\"📈 ENHANCED COMPLETE RELAXED V1.4 SUMMARY\")\n",
|
|
"print(\"=\" * 50)\n",
|
|
"\n",
|
|
"print(\"\\n🎉 PRIORITY 1 SAFETY FEATURES IMPLEMENTED!\")\n",
|
|
"\n",
|
|
"print(\"\\n🚨 Priority 1 Safety Features:\")\n",
|
|
"print(\" • 🛡️ Circuit Breaker System - Daily Loss Limits\")\n",
|
|
"print(\" • 🔧 Enhanced MT5 Connection Monitoring\")\n",
|
|
"print(\" • 🕐 Trading Session Management\")\n",
|
|
"print(\" • 📊 Spread Quality Control\")\n",
|
|
"print(\" • 🛡️ Enhanced Risk Management\")\n",
|
|
"print(\" • 🚨 Emergency Shutdown Protocol\")\n",
|
|
"print(\" • 🔄 Auto-Reconnect & Retry Logic\")\n",
|
|
"print(\" • ⚡ Multiple Fallback Mechanisms\")\n",
|
|
"\n",
|
|
"print(\"\\n🛡️ Enhanced Position Control Features:\")\n",
|
|
"print(\" • Maximal 1 Trade gleichzeitig\")\n",
|
|
"print(\" • Enhanced Position-Überprüfung\")\n",
|
|
"print(\" • Automatic Safety Blocking\")\n",
|
|
"print(\" • Enhanced Position Monitoring\")\n",
|
|
"print(\" • Emergency Position Closing\")\n",
|
|
"\n",
|
|
"print(\"\\n🚀 Complete Relaxed Trading Features (Unchanged):\")\n",
|
|
"print(\" • 10-20% niedrigere Confidence-Schwellen\")\n",
|
|
"print(\" • Disabled Pullback Entry (sofortige Trades)\")\n",
|
|
"print(\" • Relaxed Signal-Quality-Filter\")\n",
|
|
"print(\" • Niedrigere Min Risk-Adjusted Strength (80 vs 100)\")\n",
|
|
"print(\" • Fixed 2/4 Timeframe Alignment\")\n",
|
|
"print(\" • Niedrigere Min ATR Requirement\")\n",
|
|
"\n",
|
|
"print(\"\\n📊 Enhanced Performance & Automation:\")\n",
|
|
"print(\" • Enhanced Error Handling überall\")\n",
|
|
"print(\" • Retry Logic für alle kritischen Funktionen\")\n",
|
|
"print(\" • Comprehensive Safety Monitoring\")\n",
|
|
"print(\" • Auto-Emergency Shutdown\")\n",
|
|
"print(\" • Enhanced Logging & Debugging\")\n",
|
|
"print(\" • Connection Health Monitoring\")\n",
|
|
"\n",
|
|
"print(\"\\n🏆 Enhanced Complete Relaxed ist jetzt die sicherste Version:\")\n",
|
|
"print(\" 🛡️ Maximale Sicherheit durch Priority 1 Features\")\n",
|
|
"print(\" 🚨 Automatische Notfall-Protokolle\")\n",
|
|
"print(\" 🚀 Alle Relaxed Parameter für mehr Signale\")\n",
|
|
"print(\" 📊 Umfassendes Enhanced Monitoring\")\n",
|
|
"print(\" 🤖 Robuste Automation mit Fallbacks\")\n",
|
|
"print(\" ⚡ Verbesserte Error Recovery\")\n",
|
|
"\n",
|
|
"print(\"\\n💡 Enhanced Hauptfunktionen:\")\n",
|
|
"print(\" • comprehensive_safety_check() - Alle Safety Checks\")\n",
|
|
"print(\" • execute_trade_v2_complete_relaxed_enhanced_safety() - Enhanced Trading\")\n",
|
|
"print(\" • emergency_shutdown_protocol() - Notfall-Protokoll\")\n",
|
|
"print(\" • ensure_mt5_connection() - Verbindungsüberwachung\")\n",
|
|
"print(\" • check_daily_loss_limit() - Circuit Breaker\")\n",
|
|
"\n",
|
|
"print(\"\\n🚀 PRIORITÄT 1 VERBESSERUNGEN ERFOLGREICH IMPLEMENTIERT!\")\n",
|
|
"print(\"\\n✅ Ready für sicheres und aggressives Trading mit vollständigem Schutz!\")\n",
|
|
"print(\"🛡️⚡🚀 Enhanced Safety + Complete Relaxed = Ultimate Trading Bot!\")"
|
|
]
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "Python 3",
|
|
"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": 2
|
|
}
|