FEATURE: Session-Specific Confidence Thresholds - Asian: >=95% Confidence (unchanged, 97.8% WR) - NY: >=97% Confidence (NEW, improves WR from 43.3% to 56.5%!) - London/Overlap: Blocked (as before) EXPECTED IMPACT: - Eliminates 7 poor NY trades (all <97% confidence) - NY Win-Rate: 43.3% → 56.5% (+13.2 pp) - NY Profit: $1,418 → $1,655 (+$237) - Total Profit: $8,306 → $8,598 (+$292) - Overall Win-Rate: 67.8% → ~71% IMPLEMENTATION: 1. session_filter_patch.py - Added session_confidence_thresholds config - New function: get_session_confidence_threshold() - New function: is_confidence_sufficient() 2. session_confidence_filter.py (NEW) - Wrapper for execute_trade_v2_adaptive - Session-specific confidence checks - Test suite (6/6 tests passed ✅) 3. analyze_ny_session.py (NEW) - Detailed NY session analysis - Simulations for different thresholds - Data shows 97-98% trades had 100% WR TESTING: All 6 test cases passed: - Asian 96%: ALLOWED ✅ - Asian 94%: BLOCKED ✅ - NY 98%: ALLOWED ✅ - NY 96%: BLOCKED ✅ - London 99%: BLOCKED ✅ - Overlap 99%: BLOCKED ✅ NEXT STEPS: 1. Integrate wrapper into notebook 2. Restart kernel 3. Monitor for 1 week 4. Review performance improvement FILES: - session_filter_patch.py: Updated config + new functions - session_confidence_filter.py: Wrapper implementation - analyze_ny_session.py: Analysis tool - NY_SESSION_FINETUNING.md: Complete documentation
318 lines
10 KiB
Python
318 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: 97.8% Win-Rate, $151/Trade
|
|
'london': False, # ❌ BLOCKIERT: 12.5% Win-Rate, -$10/Trade
|
|
'overlap': False, # ❌ BLOCKIERT: 14.3% Win-Rate, -$7/Trade
|
|
'ny': True, # ✅ AKTIV: 43.3% Win-Rate, aber profitabel ($48/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
|
|
|
|
# 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 (NY + Overlap)
|
|
SESSION_WHITELIST_CONFIG['enabled_sessions'] = {
|
|
'asian': False, '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%)")
|