Files
Place-Order-Trading-Bot/session_filter_patch.py
T
cbazzaandClaude Opus 4.5 ce4e961541
Deploy to Windows VPS / deploy (push) Has been cancelled
feat: Add Trend Reversal Detector with multi-signal analysis
New features:
- Reversal Detector with 5 detection signals:
  - RSI Divergence (bearish/bullish)
  - EMA Slope Change detection
  - Volume Spike analysis
  - Candlestick patterns (Doji, Engulfing, Hammer, Pin Bar)
  - Break of Structure detection
- Integrated into enhanced_trading_check_wrapper (SCHRITT 2.5)
- Defensive mode: blocks trades at 70%+ reversal score
- Lot size reduction at 30-69% reversal score
- Enable Overlap session (13:00-16:00 UTC)

Files added:
- reversal_detector.py: Core detection algorithms
- reversal_integration.py: Bot integration wrapper
- REVERSAL_DETECTOR_INTEGRATION.md: Documentation

Modified:
- TradingBot notebook: Added reversal check integration
- session_filter_patch.py: Enabled overlap session

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-30 09:46:40 +01:00

323 lines
10 KiB
Python

"""
🎯 SESSION FILTER PATCH - TradingBot V1.6 to V1.7
Optimiert Trading basierend auf Performance-Analyse
ÄNDERUNGEN:
1. Deaktiviert Asian Session (25.6% Win-Rate, -$199 Verlust)
2. Aktiviert nur NY + Overlap (beste Performance)
3. Optional: London Session (Break-Even)
PERFORMANCE-IMPACT:
- Asian ausschalten: -$199 eliminiert
- Nur NY+Overlap: +$581 (49% mehr Profit)
- Win-Rate: 30.9% → ~38%
"""
# ==========================================
# SESSION WHITELIST CONFIGURATION
# ==========================================
SESSION_WHITELIST_CONFIG = {
# Welche Sessions erlauben?
'enabled_sessions': {
'asian': True, # ✅ BESTE SESSION: 54.2% Win-Rate, +$21/Trade
'london': False, # ❌ BLOCKIERT: 46.9% Win-Rate, +$8/Trade
'overlap': True, # ✅ TEST: Aktiviert 29.01.2026 mit V1.6 Adaptive
'ny': True, # ✅ AKTIV: 49.1% Win-Rate, +$6/Trade
},
# Session-spezifische Confidence Thresholds (NEU 26.12.2025)
'session_confidence_thresholds': {
'asian': 95, # Asian: >=95% OK (läuft perfekt mit 97.8% WR)
'ny': 97, # NY: >=97% benötigt (verbessert WR von 43% auf 56.5%!)
'london': 95, # London: blockiert, Threshold irrelevant
'overlap': 95, # Overlap: blockiert, Threshold irrelevant
},
# Trading Parameter
'base_confidence': 95, # 🎯 GLOBAL THRESHOLD (Minimum für alle Sessions)
'atr_mult': 1.5, # ATR Multiplikator für SL/TP
'max_risk_per_trade': 0.02, # Max Risk pro Trade (2%) - Erhöht am 20.12.2025 für Adaptive Sizing
'min_atr': 0.0008, # Minimum ATR für Risk Filter
# Lot Sizing (14.01.2026)
'min_lot': 0.10, # Minimum Lot Size
'max_lot': 0.20, # Maximum Lot Size
'default_lot': 0.10, # Default/Fallback Lot Size
# Trading Optionen
'risk_filter': True, # ATR-basierter Risk Filter
'use_pullback_entry': False, # Pullback Entry Strategie
# Debug-Modus
'debug': True,
}
# ==========================================
# SESSION FILTER FUNCTIONS
# ==========================================
def get_session_confidence_threshold(session_name, config=SESSION_WHITELIST_CONFIG):
"""
Holt den session-spezifischen Confidence Threshold
Args:
session_name: 'asian', 'london', 'overlap', 'ny'
config: Configuration Dictionary
Returns:
int: Minimum confidence threshold für diese Session
"""
thresholds = config.get('session_confidence_thresholds', {})
return thresholds.get(session_name, config.get('base_confidence', 95))
def is_confidence_sufficient(session_name, confidence, config=SESSION_WHITELIST_CONFIG):
"""
Prüft ob Confidence für diese Session ausreichend ist
Args:
session_name: 'asian', 'london', 'overlap', 'ny'
confidence: Signal Confidence (0-100)
config: Configuration Dictionary
Returns:
(sufficient: bool, reason: str)
"""
required = get_session_confidence_threshold(session_name, config)
sufficient = confidence >= required
if not sufficient:
reason = f"{session_name.upper()} requires >={required}% confidence (got {confidence:.1f}%)"
else:
reason = f"Confidence {confidence:.1f}% >= {required}% for {session_name.upper()}"
return sufficient, reason
def is_session_allowed(session_name, config=SESSION_WHITELIST_CONFIG):
"""
Prüft ob Trading in aktueller Session erlaubt ist
Args:
session_name: 'asian', 'london', 'overlap', 'ny'
config: Configuration Dictionary
Returns:
(allowed: bool, reason: str)
"""
# Standard: Whitelist-basiert
allowed = config['enabled_sessions'].get(session_name, False)
if not allowed:
reasons = {
'asian': "Asian: 97.8% WR but currently disabled",
'london': "London blocked: 12.5% win-rate, -$10/trade",
'overlap': "Overlap blocked: 14.3% win-rate, -$7/trade",
'ny': "NY: 43.3% WR but currently disabled",
}
reason = reasons.get(session_name, f"Session {session_name} not in whitelist")
else:
performance = {
'asian': "Asian allowed: 97.8% WR, $151/trade (EXCELLENT!)",
'ny': "NY allowed: 43.3% WR, $48/trade (needs >=97% conf)",
'london': "London allowed: 12.5% WR (low)",
'overlap': "Overlap allowed: 14.3% WR (low)",
}
reason = f"{performance.get(session_name, 'In whitelist')}"
return allowed, reason
# ==========================================
# SESSION FILTER WRAPPER
# ==========================================
def create_session_filtered_check(
rhythm_manager,
execute_func,
symbol,
strategy_name,
max_positions,
logger,
datetime,
config=None
):
"""
Factory-Funktion die eine gefilterte Trading-Check-Funktion erstellt
Args:
rhythm_manager: AdaptiveRhythmManager Instanz
execute_func: execute_trade_v2_adaptive Funktion
symbol: Trading Symbol (z.B. "XAUUSD")
strategy_name: Strategy Name
max_positions: Max Positionen
logger: Logger Instanz
datetime: datetime module
config: Optional custom config, sonst SESSION_WHITELIST_CONFIG
Returns:
Gefilterte adaptive_trading_check Funktion
"""
if config is None:
config = SESSION_WHITELIST_CONFIG
# Hole Trading-Parameter aus Config
confidence_threshold = config.get('base_confidence', 60)
atr_mult = config.get('atr_mult', 1.5)
max_risk = config.get('max_risk_per_trade', 0.01)
risk_filter = config.get('risk_filter', True)
min_atr = config.get('min_atr', 0.0008)
use_pullback = config.get('use_pullback_entry', False)
def adaptive_trading_check_filtered():
"""
🆕 V1.7: Session-gefilterte Trading Check Funktion
"""
try:
# 1. Prüfe aktuelle Session
session = rhythm_manager.get_current_session()
allowed, reason = is_session_allowed(session, config)
if not allowed:
if config['debug']:
logger.info(f"⏸️ Trading SKIP: {reason}")
return
# 2. Berechne optimales Intervall
optimal_interval = rhythm_manager.calculate_optimal_interval()
current_minute = datetime.now().minute
# 3. Trading nur zu berechneten Zeitpunkten
if current_minute % optimal_interval == 0:
logger.info(f"\n{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - ADAPTIVE Check")
logger.info(f"✅ Session: {session.upper()} - {reason}")
logger.info(f"📊 Confidence Threshold: {confidence_threshold}%")
logger.info(f"⏱️ Intervall: {optimal_interval} min")
# Führe Trading aus mit Parametern aus Config
execute_func(
symbol=symbol,
atr_mult=atr_mult,
base_confidence=confidence_threshold,
max_risk_per_trade=max_risk,
risk_filter=risk_filter,
min_atr=min_atr,
use_pullback_entry=use_pullback,
max_positions=max_positions,
strategy_name=strategy_name,
debug=True
)
except Exception as e:
logger.error(f"Fehler im Session-Filtered Trading Check: {e}")
return adaptive_trading_check_filtered
# ==========================================
# USAGE INSTRUCTIONS
# ==========================================
"""
📋 ANLEITUNG - Wie den Patch anwenden:
SCHRITT 1: Dieses File ins gleiche Verzeichnis wie das Notebook kopieren
SCHRITT 2: In Cell 24 (Adaptive Scheduler) folgendes ändern:
VORHER:
```python
def adaptive_trading_check():
try:
optimal_interval = rhythm_manager.calculate_optimal_interval()
...
```
NACHHER:
```python
# Importiere Session Filter
from session_filter_patch import (
adaptive_trading_check_with_session_filter,
SESSION_WHITELIST_CONFIG,
is_session_allowed
)
# Alias für Kompatibilität
adaptive_trading_check = adaptive_trading_check_with_session_filter
```
SCHRITT 3: Scheduler neu starten
SCHRITT 4: Teste mit verschiedenen Modi:
# Standard Mode (Asian + NY + Overlap)
SESSION_WHITELIST_CONFIG['enabled_sessions'] = {
'asian': True, 'london': False,
'overlap': True, 'ny': True
}
# Aggressive Mode (nur NY, 50% Win-Rate!)
SESSION_WHITELIST_CONFIG['aggressive_mode'] = True
# Conservative Mode (alles außer Asian)
SESSION_WHITELIST_CONFIG['conservative_mode'] = True
SCHRITT 5: Monitor Performance für 1-2 Wochen
"""
# ==========================================
# TESTING
# ==========================================
if __name__ == "__main__":
print("="*70)
print("🧪 SESSION FILTER TESTS")
print("="*70)
sessions = ['asian', 'london', 'overlap', 'ny']
print("\n📊 STANDARD MODE (NY + Overlap):")
print("-" * 70)
for session in sessions:
allowed, reason = is_session_allowed(session)
emoji = "✅" if allowed else "❌"
print(f"{emoji} {session.upper():8s}: {reason}")
print("\n📊 AGGRESSIVE MODE (nur NY):")
print("-" * 70)
test_config = SESSION_WHITELIST_CONFIG.copy()
test_config['aggressive_mode'] = True
for session in sessions:
allowed, reason = is_session_allowed(session, test_config)
emoji = "✅" if allowed else "❌"
print(f"{emoji} {session.upper():8s}: {reason}")
print("\n📊 CONSERVATIVE MODE (alles außer Asian):")
print("-" * 70)
test_config = SESSION_WHITELIST_CONFIG.copy()
test_config['conservative_mode'] = True
test_config['aggressive_mode'] = False
for session in sessions:
allowed, reason = is_session_allowed(session, test_config)
emoji = "✅" if allowed else "❌"
print(f"{emoji} {session.upper():8s}: {reason}")
print("\n" + "="*70)
print("✅ Tests complete")
print("="*70)
print("\n💡 ERWARTETE PERFORMANCE-VERBESSERUNG:")
print(" Standard Mode (NY + Overlap):")
print(" • Trades: 40 statt 110 (-64%)")
print(" • Profit: +$581 statt +$389 (+49%)")
print(" • Win-Rate: ~38% statt 30.9%")
print("\n Aggressive Mode (nur NY):")
print(" • Trades: 12 statt 110 (-89%)")
print(" • Profit: +$372 statt +$389 (-4%, aber 50% Win-Rate!)")
print(" • Win-Rate: 50% statt 30.9% (+19.1%)")