many ki generated scripts and versions added
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
"""
|
||||
QUICK FIX: Position Control Patch
|
||||
Füge diese Funktionen zu deinem bestehenden TradingBot_V1.4_Complete.ipynb hinzu
|
||||
"""
|
||||
|
||||
def check_existing_positions_simple(symbol="XAUUSD", strategy_name="TradingBot_V1.4_Complete"):
|
||||
"""
|
||||
Einfache Position-Überprüfung für bestehende Notebooks
|
||||
"""
|
||||
try:
|
||||
positions = mt.positions_get(symbol=symbol)
|
||||
if positions is None:
|
||||
return False, 0
|
||||
|
||||
# Zähle Positionen mit unserem Strategy-Namen
|
||||
strategy_positions = 0
|
||||
for pos in positions:
|
||||
if strategy_name in pos.comment:
|
||||
strategy_positions += 1
|
||||
|
||||
return strategy_positions > 0, strategy_positions
|
||||
except:
|
||||
return False, 0
|
||||
|
||||
def execute_trade_v2_with_simple_position_control(
|
||||
symbol="XAUUSD",
|
||||
atr_mult=1.5,
|
||||
base_confidence=70,
|
||||
max_risk_per_trade=0.01,
|
||||
risk_filter=True,
|
||||
min_atr=0.0010,
|
||||
use_pullback_entry=True,
|
||||
debug=True
|
||||
):
|
||||
"""
|
||||
QUICK FIX: Füge diese Funktion zu deinem bestehenden Notebook hinzu
|
||||
Ersetzt deine bestehende execute_trade_v2() Funktion
|
||||
"""
|
||||
|
||||
# WICHTIG: Position-Check ZUERST!
|
||||
has_position, position_count = check_existing_positions_simple(symbol, strategy_name)
|
||||
|
||||
if has_position:
|
||||
if debug:
|
||||
print(f"🛑 TRADE BLOCKIERT: {position_count} Position(en) bereits aktiv für {symbol}")
|
||||
|
||||
# Zeige bestehende Positionen
|
||||
positions = mt.positions_get(symbol=symbol)
|
||||
if positions:
|
||||
for pos in positions:
|
||||
if strategy_name in pos.comment:
|
||||
profit_emoji = "🟢" if pos.profit >= 0 else "🔴"
|
||||
print(f" Aktive Position: {'BUY' if pos.type == 0 else 'SELL'} {pos.volume} @ {pos.price_open} | Profit: {profit_emoji} {pos.profit:.2f}")
|
||||
return None
|
||||
|
||||
print(f"✅ Position-Check OK: Keine aktiven Positionen für {symbol}")
|
||||
|
||||
# AB HIER: Deine bestehende execute_trade_v2 Logik
|
||||
# (Kopiere deine bestehende Funktion hier hin, aber mit Position-Check am Anfang)
|
||||
|
||||
# Vereinfachte Version für Demonstration:
|
||||
signal_info = extended_top_down_v2(symbol)
|
||||
if signal_info is None:
|
||||
print("❌ Signal-Analyse fehlgeschlagen")
|
||||
return None
|
||||
|
||||
entry_signal = signal_info["entry_signal"]
|
||||
confidence = signal_info["confidence"]
|
||||
adaptive_threshold = signal_info["adaptive_threshold"]
|
||||
|
||||
if entry_signal == 0:
|
||||
print(f"⏸️ No entry signal (Confidence: {confidence}%, Threshold: {adaptive_threshold}%)")
|
||||
return None
|
||||
|
||||
if confidence < adaptive_threshold:
|
||||
print(f"⏸️ Confidence too low: {confidence}% < {adaptive_threshold}%")
|
||||
return None
|
||||
|
||||
# FINAL POSITION CHECK vor Order (Sicherheit)
|
||||
final_check, _ = check_existing_positions_simple(symbol, strategy_name)
|
||||
if final_check:
|
||||
print(f"🛑 LAST-MINUTE BLOCK: Position wurde zwischen Checks eröffnet!")
|
||||
return None
|
||||
|
||||
# Hier würde deine normale Trading-Logik kommen
|
||||
print(f"🚀 WOULD EXECUTE TRADE: {'LONG' if entry_signal == 1 else 'SHORT'}")
|
||||
print(f"Confidence: {confidence}% | Quality: {signal_info['signal_quality']}")
|
||||
|
||||
# Für echte Ausführung: Uncomment die nächste Zeile und füge deine market_order Logik hinzu
|
||||
# return market_order(symbol, volume, order_type, stoploss, take_profit)
|
||||
|
||||
return "DEMO_ORDER_RESULT" # Placeholder für Demo
|
||||
|
||||
print("✅ Simple Position Control Patch ready")
|
||||
|
||||
# ANLEITUNG FÜR DEIN BESTEHENDES NOTEBOOK:
|
||||
print("\\n📋 ANLEITUNG für dein bestehendes Notebook:")
|
||||
print("1. Kopiere check_existing_positions_simple() in eine neue Zelle")
|
||||
print("2. Ersetze deine execute_trade_v2() durch execute_trade_v2_with_simple_position_control()")
|
||||
print("3. Oder füge am Anfang deiner bestehenden execute_trade_v2() den Position-Check hinzu:")
|
||||
print("\\n # Position-Check am Anfang der Funktion:")
|
||||
print(" has_position, position_count = check_existing_positions_simple(symbol, strategy_name)")
|
||||
print(" if has_position:")
|
||||
print(" print(f'🛑 TRADE BLOCKIERT: {position_count} Position(en) aktiv')")
|
||||
print(" return None")
|
||||
print("\\n4. Fertig! Dein Bot handelt jetzt maximal 1x gleichzeitig.")
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
# TradingBot V1.4 - Optimized Version
|
||||
|
||||
## 🚀 Überblick
|
||||
|
||||
TradingBot V1.4 ist eine erheblich verbesserte Version deines ursprünglichen Trading Bots mit intelligenten Anpassungen an verschiedene Marktbedingungen.
|
||||
|
||||
## 📁 Dateien
|
||||
|
||||
- `TradingBot_V1.4_Optimized.py` - Hauptfunktionen der optimierten Logik
|
||||
- `TradingBot_V1.4_Integration.ipynb` - Jupyter Notebook mit vollständiger Integration
|
||||
- `config_v1.4.json` - Konfigurationsdatei für alle Parameter
|
||||
- `TradingBot_V1.3_backup_*` - Backup deiner ursprünglichen Datei
|
||||
|
||||
## 🎯 Hauptverbesserungen
|
||||
|
||||
### 1. **Adaptive Confidence Threshold**
|
||||
```python
|
||||
# Statt fixer 80% wird automatisch angepasst:
|
||||
Trending Markets: 60-75%
|
||||
Ranging Markets: 85%
|
||||
Volatile Markets: 90%
|
||||
```
|
||||
|
||||
### 2. **Market Regime Detection**
|
||||
- **Trending**: ADX > 25, klare Richtung
|
||||
- **Ranging**: ADX < 20, seitwärts bewegung
|
||||
- **Volatile**: Hohe Volatilitäts-Cluster
|
||||
|
||||
### 3. **Entry Timing Optimization**
|
||||
- Wartet auf Pullbacks zu EMA21
|
||||
- Bessere Risk/Reward durch optimiertes Timing
|
||||
- Regime-abhängige Entry-Kriterien
|
||||
|
||||
### 4. **Risk-Adjusted Signal Strength**
|
||||
```python
|
||||
signal_strength = confidence × trend_strength × rrr
|
||||
# Mindestens 100 für Entry, 150+ für "excellent" Signals
|
||||
```
|
||||
|
||||
### 5. **Performance Monitoring**
|
||||
- Automatisches Logging aller Signale
|
||||
- JSON-Export für Analyse
|
||||
- Regime-basierte Performance-Statistiken
|
||||
|
||||
## 📊 Vergleich V1.3 vs V1.4
|
||||
|
||||
| Feature | V1.3 | V1.4 |
|
||||
|---------|------|------|
|
||||
| Confidence Threshold | Fixed 80% | Adaptive 60-90% |
|
||||
| Market Regime | Ignoriert | Aktive Erkennung |
|
||||
| Entry Timing | Sofort | Pullback-optimiert |
|
||||
| Performance Tracking | Manuell | Automatisch |
|
||||
| Parameter | Statisch | Dynamisch |
|
||||
|
||||
## 🛠️ Installation & Setup
|
||||
|
||||
### 1. Dateien kopieren
|
||||
```bash
|
||||
# Alle V1.4 Dateien sind bereits in deinem Verzeichnis:
|
||||
/Users/sebastianfrohlich/Library/Mobile Documents/com~apple~CloudDocs/Jupyter Notebooks/FinancialTrading/PlaceOrder/placeorder/
|
||||
```
|
||||
|
||||
### 2. Jupyter Notebook öffnen
|
||||
```bash
|
||||
# Öffne: TradingBot_V1.4_Integration.ipynb
|
||||
# Führe alle Zellen aus
|
||||
```
|
||||
|
||||
### 3. Konfiguration anpassen (optional)
|
||||
```json
|
||||
// Editiere config_v1.4.json für deine Bedürfnisse
|
||||
{
|
||||
"trading_config": {
|
||||
"symbol": "XAUUSD",
|
||||
"base_confidence": 70,
|
||||
"max_risk_per_trade": 0.01
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🔄 Migration von V1.3 zu V1.4
|
||||
|
||||
### Option 1: Komplette Migration (empfohlen)
|
||||
1. Verwende `TradingBot_V1.4_Integration.ipynb` als neues Hauptnotebook
|
||||
2. Deine bestehenden Funktionen werden automatisch integriert
|
||||
3. Alle Verbesserungen sind sofort aktiv
|
||||
|
||||
### Option 2: Schrittweise Integration
|
||||
1. Kopiere einzelne Funktionen aus `TradingBot_V1.4_Optimized.py`
|
||||
2. Ersetze in deinem V1.3 Notebook:
|
||||
- `extended_top_down()` → `extended_top_down_v2()`
|
||||
- `execute_trade()` → `execute_trade_v2()`
|
||||
|
||||
## 📈 Verwendung
|
||||
|
||||
### Schnellstart
|
||||
```python
|
||||
from TradingBot_V1.4_Optimized import extended_top_down_v2, execute_trade_v2
|
||||
|
||||
# Analysiere aktuelles Signal
|
||||
signal_info = extended_top_down_v2("XAUUSD")
|
||||
print(f"Signal: {signal_info['entry_signal']}")
|
||||
print(f"Quality: {signal_info['signal_quality']}")
|
||||
print(f"Regime: {signal_info['market_regime']['regime']}")
|
||||
|
||||
# Führe optimierten Trade aus
|
||||
result = execute_trade_v2(
|
||||
symbol="XAUUSD",
|
||||
base_confidence=70,
|
||||
use_pullback_entry=True
|
||||
)
|
||||
```
|
||||
|
||||
### Automatisierung
|
||||
```python
|
||||
# Setup für automatisierten Handel
|
||||
from apscheduler.schedulers.background import BackgroundScheduler
|
||||
|
||||
scheduler = BackgroundScheduler()
|
||||
scheduler.add_job(
|
||||
execute_trade_v2,
|
||||
'cron',
|
||||
minute='*/5', # Alle 5 Minuten
|
||||
kwargs={'symbol': 'XAUUSD', 'debug': True}
|
||||
)
|
||||
scheduler.start()
|
||||
```
|
||||
|
||||
## 📊 Performance Monitoring
|
||||
|
||||
### Logs prüfen
|
||||
```python
|
||||
from TradingBot_V1.4_Optimized import analyze_performance
|
||||
|
||||
# Analysiere letzte 7 Tage
|
||||
analyze_performance("XAUUSD", days_back=7)
|
||||
```
|
||||
|
||||
### Output:
|
||||
```
|
||||
📊 PERFORMANCE ANALYSIS - Last 7 days
|
||||
Total Trades: 12
|
||||
|
||||
By Market Regime:
|
||||
TRENDING: 8 (66.7%)
|
||||
RANGING: 3 (25.0%)
|
||||
VOLATILE: 1 (8.3%)
|
||||
|
||||
By Signal Quality:
|
||||
EXCELLENT: 4 (33.3%)
|
||||
GOOD: 6 (50.0%)
|
||||
FAIR: 2 (16.7%)
|
||||
```
|
||||
|
||||
## ⚙️ Konfiguration
|
||||
|
||||
### Wichtige Parameter
|
||||
```python
|
||||
# In config_v1.4.json oder direkt im Code:
|
||||
|
||||
ADAPTIVE_THRESHOLDS = {
|
||||
'trending': -10, # 10% niedrigere Confidence in Trends
|
||||
'ranging': +15, # 15% höhere Confidence in Ranges
|
||||
'volatile': +20 # 20% höhere Confidence bei Volatilität
|
||||
}
|
||||
|
||||
RISK_SETTINGS = {
|
||||
'max_risk_per_trade': 0.01, # 1% pro Trade
|
||||
'max_daily_loss': 0.05, # 5% maximaler Tagesverlust
|
||||
'use_pullback_entry': True # Warte auf besseres Timing
|
||||
}
|
||||
```
|
||||
|
||||
## 🧪 Testing & Validation
|
||||
|
||||
### 1. Demo-Modus Test
|
||||
```python
|
||||
# Führe 1-2 Wochen im Demo-Modus aus
|
||||
# Überwache Performance-Logs
|
||||
# Validiere Verbesserungen gegenüber V1.3
|
||||
```
|
||||
|
||||
### 2. Parameter-Optimierung
|
||||
```python
|
||||
# Basierend auf Demo-Ergebnissen:
|
||||
# - Anpassung der Confidence-Schwellen
|
||||
# - Feintuning der Regime-Erkennung
|
||||
# - Optimierung der Entry-Timing-Parameter
|
||||
```
|
||||
|
||||
## ⚠️ Wichtige Hinweise
|
||||
|
||||
### Risiken
|
||||
- **Neue Logik**: Teste ausführlich im Demo-Modus
|
||||
- **Parameter**: Beginne mit konservativen Einstellungen
|
||||
- **Monitoring**: Überwache Performance täglich in der ersten Woche
|
||||
|
||||
### Backup
|
||||
```bash
|
||||
# Dein Original V1.3 ist gesichert als:
|
||||
TradingBot_V1.3_backup_YYYYMMDD_HHMMSS.ipynb
|
||||
```
|
||||
|
||||
### Support
|
||||
Bei Fragen oder Problemen:
|
||||
1. Prüfe die Debug-Ausgaben
|
||||
2. Analysiere Performance-Logs
|
||||
3. Validiere MT5-Verbindung
|
||||
|
||||
## 📝 Changelog V1.3 → V1.4
|
||||
|
||||
### ✅ Neue Features
|
||||
- Market Regime Detection
|
||||
- Adaptive Confidence Thresholds
|
||||
- Pullback Entry Timing
|
||||
- Risk-Adjusted Signal Strength
|
||||
- Automatic Performance Logging
|
||||
- Enhanced Debug Output
|
||||
|
||||
### 🔧 Verbesserungen
|
||||
- Weighted Timeframe Analysis
|
||||
- Dynamic Parameter Adjustment
|
||||
- Better Risk Management
|
||||
- Signal Quality Grading
|
||||
- Configuration Management
|
||||
|
||||
### 🐛 Fixes
|
||||
- Over-filtering durch zu hohe Confidence-Schwellen
|
||||
- Fehlende Markt-Adaptation
|
||||
- Späte Entry-Signale durch zu viele Filter
|
||||
|
||||
## 🎯 Nächste Schritte
|
||||
|
||||
1. **Sofort**: Teste V1.4 im Demo-Modus
|
||||
2. **1 Woche**: Analysiere erste Performance-Daten
|
||||
3. **2 Wochen**: Optimiere Parameter basierend auf Ergebnissen
|
||||
4. **1 Monat**: Bei positiven Ergebnissen → Live-Trading
|
||||
|
||||
---
|
||||
|
||||
**Version**: 1.4.0
|
||||
**Datum**: 2025-01-17
|
||||
**Status**: Ready for Demo Testing
|
||||
**Kompatibilität**: MT5, Python 3.7+
|
||||
@@ -0,0 +1,354 @@
|
||||
"""
|
||||
TradingBot Diagnosis Tool
|
||||
Hilft bei der Identifikation, warum der Bot nicht handelt
|
||||
"""
|
||||
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
import MetaTrader5 as mt
|
||||
import pandas_ta as ta
|
||||
from tabulate import tabulate
|
||||
|
||||
def diagnose_trading_issue(symbol="XAUUSD"):
|
||||
"""
|
||||
Umfassende Diagnose warum der Bot nicht handelt
|
||||
"""
|
||||
print("🔍 TRADING BOT DIAGNOSIS")
|
||||
print("=" * 50)
|
||||
|
||||
issues_found = []
|
||||
|
||||
# 1. MT5 Connection Check
|
||||
print("\n1️⃣ MT5 Connection Check:")
|
||||
terminal_info = mt.terminal_info()
|
||||
if terminal_info:
|
||||
print(" ✅ MT5 connected")
|
||||
print(f" Company: {terminal_info.company}")
|
||||
print(f" Connected: {terminal_info.connected}")
|
||||
print(f" Trade allowed: {terminal_info.trade_allowed}")
|
||||
if not terminal_info.trade_allowed:
|
||||
issues_found.append("Trading not allowed in terminal")
|
||||
else:
|
||||
print(" ❌ MT5 not connected")
|
||||
issues_found.append("MT5 connection failed")
|
||||
return issues_found
|
||||
|
||||
# 2. Account Info Check
|
||||
print("\n2️⃣ Account Info Check:")
|
||||
account_info = mt.account_info()
|
||||
if account_info:
|
||||
print(f" ✅ Account: {account_info.login}")
|
||||
print(f" Balance: {account_info.balance}")
|
||||
print(f" Equity: {account_info.equity}")
|
||||
print(f" Trade allowed: {account_info.trade_allowed}")
|
||||
print(f" Trade mode: {account_info.trade_mode}")
|
||||
if not account_info.trade_allowed:
|
||||
issues_found.append("Trading not allowed on account")
|
||||
else:
|
||||
print(" ❌ Cannot get account info")
|
||||
issues_found.append("Account info unavailable")
|
||||
|
||||
# 3. Symbol Info Check
|
||||
print(f"\n3️⃣ Symbol Info Check ({symbol}):")
|
||||
symbol_info = mt.symbol_info(symbol)
|
||||
if symbol_info:
|
||||
print(f" ✅ Symbol exists: {symbol_info.name}")
|
||||
print(f" Trade mode: {symbol_info.trade_mode}")
|
||||
print(f" Min volume: {symbol_info.volume_min}")
|
||||
print(f" Max volume: {symbol_info.volume_max}")
|
||||
print(f" Volume step: {symbol_info.volume_step}")
|
||||
if symbol_info.trade_mode == 0:
|
||||
issues_found.append(f"Trading disabled for {symbol}")
|
||||
else:
|
||||
print(f" ❌ Symbol {symbol} not found")
|
||||
issues_found.append(f"Symbol {symbol} not available")
|
||||
|
||||
# 4. Market Hours Check
|
||||
print("\n4️⃣ Market Hours Check:")
|
||||
tick = mt.symbol_info_tick(symbol)
|
||||
if tick:
|
||||
print(f" ✅ Current price: Bid={tick.bid}, Ask={tick.ask}")
|
||||
print(f" Last tick time: {pd.to_datetime(tick.time, unit='s')}")
|
||||
spread = tick.ask - tick.bid
|
||||
print(f" Spread: {spread:.5f}")
|
||||
if spread > 0.01: # Sehr hoher Spread
|
||||
issues_found.append(f"High spread: {spread:.5f}")
|
||||
else:
|
||||
print(" ❌ No current price data")
|
||||
issues_found.append("No price data available")
|
||||
|
||||
# 5. Data Availability Check
|
||||
print("\n5️⃣ Data Availability Check:")
|
||||
timeframes_to_check = ["M5", "M15", "M30", "H1", "H4", "D1"]
|
||||
tf_map = {"M5": mt.TIMEFRAME_M5, "M15": mt.TIMEFRAME_M15, "M30": mt.TIMEFRAME_M30,
|
||||
"H1": mt.TIMEFRAME_H1, "H4": mt.TIMEFRAME_H4, "D1": mt.TIMEFRAME_D1}
|
||||
|
||||
data_status = []
|
||||
for tf in timeframes_to_check:
|
||||
rates = mt.copy_rates_from_pos(symbol, tf_map[tf], 0, 50)
|
||||
if rates is not None and len(rates) > 0:
|
||||
data_status.append([tf, "✅", len(rates), pd.to_datetime(rates[-1]['time'], unit='s')])
|
||||
else:
|
||||
data_status.append([tf, "❌", 0, "No data"])
|
||||
issues_found.append(f"No data for {tf}")
|
||||
|
||||
print(tabulate(data_status, headers=["Timeframe", "Status", "Bars", "Last Update"], tablefmt="psql"))
|
||||
|
||||
return issues_found
|
||||
|
||||
def compare_v13_vs_v14_logic(symbol="XAUUSD"):
|
||||
"""
|
||||
Vergleicht warum V1.3 gehandelt hat aber V1.4 nicht
|
||||
"""
|
||||
print("\n🔄 COMPARING V1.3 vs V1.4 LOGIC")
|
||||
print("=" * 50)
|
||||
|
||||
try:
|
||||
# Simuliere V1.3 Logik (vereinfacht)
|
||||
from TradingBot_V1.4_Fixed import extended_top_down_v2, get_rates
|
||||
|
||||
# Hole aktuelle Daten
|
||||
signal_info = extended_top_down_v2(symbol, lookback=100)
|
||||
|
||||
if signal_info is None:
|
||||
print("❌ Cannot get signal info")
|
||||
return
|
||||
|
||||
confidence = signal_info['confidence']
|
||||
trend = signal_info['top_down_trend']
|
||||
signal_quality = signal_info['signal_quality']
|
||||
regime = signal_info['market_regime']['regime']
|
||||
adaptive_threshold = signal_info['adaptive_threshold']
|
||||
|
||||
# V1.3 Logic (fixed 80% threshold)
|
||||
v13_threshold = 80
|
||||
v13_would_trade = (trend != "sideways" and confidence >= v13_threshold)
|
||||
|
||||
# V1.4 Logic (adaptive threshold + quality filter)
|
||||
v14_would_trade = (signal_info['entry_signal'] != 0)
|
||||
|
||||
print(f"\n📊 SIGNAL COMPARISON:")
|
||||
comparison_data = [
|
||||
["Metric", "V1.3 (Old)", "V1.4 (New)", "Impact"],
|
||||
["Confidence", f"{confidence:.1f}%", f"{confidence:.1f}%", "Same"],
|
||||
["Threshold", f"{v13_threshold}%", f"{adaptive_threshold}%", f"{adaptive_threshold-v13_threshold:+d}%"],
|
||||
["Trend", trend, trend, "Same"],
|
||||
["Would Trade", "✅" if v13_would_trade else "❌", "✅" if v14_would_trade else "❌", ""],
|
||||
["Market Regime", "Not considered", regime, "New Filter"],
|
||||
["Signal Quality", "Not checked", signal_quality, "New Filter"],
|
||||
]
|
||||
|
||||
print(tabulate(comparison_data, headers="firstrow", tablefmt="psql"))
|
||||
|
||||
# Analyse warum nicht gehandelt wird
|
||||
print(f"\n🔍 WHY NOT TRADING:")
|
||||
|
||||
if not v13_would_trade and not v14_would_trade:
|
||||
print(" • Both versions agree: Confidence too low")
|
||||
print(f" • Need: {v13_threshold}% (V1.3) or {adaptive_threshold}% (V1.4)")
|
||||
print(f" • Have: {confidence:.1f}%")
|
||||
|
||||
elif v13_would_trade and not v14_would_trade:
|
||||
print(" 🛡️ V1.4 is MORE SELECTIVE (this is good!)")
|
||||
print(f" • V1.3 would trade with {confidence:.1f}% confidence")
|
||||
print(f" • V1.4 requires {adaptive_threshold}% in {regime} market")
|
||||
print(f" • Signal quality: {signal_quality}")
|
||||
|
||||
if regime == 'ranging':
|
||||
print(" • RANGING market detected - higher threshold prevents false breakouts")
|
||||
elif regime == 'volatile':
|
||||
print(" • VOLATILE market detected - avoiding choppy conditions")
|
||||
|
||||
elif not v13_would_trade and v14_would_trade:
|
||||
print(" 🚀 V1.4 FOUND OPPORTUNITY that V1.3 missed!")
|
||||
print(f" • Adaptive threshold {adaptive_threshold}% < fixed 80%")
|
||||
print(f" • Trading in {regime} market with {signal_quality} quality")
|
||||
|
||||
else:
|
||||
print(" 🤝 Both versions would trade - check other filters")
|
||||
|
||||
return {
|
||||
'v13_would_trade': v13_would_trade,
|
||||
'v14_would_trade': v14_would_trade,
|
||||
'confidence': confidence,
|
||||
'adaptive_threshold': adaptive_threshold,
|
||||
'regime': regime,
|
||||
'signal_quality': signal_quality
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error in comparison: {e}")
|
||||
return None
|
||||
|
||||
def check_position_limits(symbol="XAUUSD"):
|
||||
"""
|
||||
Prüft ob Position-Limits das Trading verhindern
|
||||
"""
|
||||
print("\n📊 POSITION LIMITS CHECK")
|
||||
print("=" * 30)
|
||||
|
||||
# Aktuelle Positionen
|
||||
positions = mt.positions_get(symbol=symbol)
|
||||
total_positions = mt.positions_total()
|
||||
|
||||
print(f"Current positions for {symbol}: {len(positions) if positions else 0}")
|
||||
print(f"Total positions: {total_positions}")
|
||||
|
||||
if positions:
|
||||
print("\nExisting positions:")
|
||||
for pos in positions:
|
||||
print(f" • {pos.type_str} {pos.volume} lots @ {pos.price_open}")
|
||||
print(f" Comment: {pos.comment}")
|
||||
print(f" Profit: {pos.profit}")
|
||||
|
||||
# Position Limits prüfen
|
||||
# (Hier würdest du deine spezifischen Limits einbauen)
|
||||
max_positions = 3 # Beispiel
|
||||
if total_positions >= max_positions:
|
||||
return f"Position limit reached: {total_positions}/{max_positions}"
|
||||
|
||||
return None
|
||||
|
||||
def suggest_quick_fixes():
|
||||
"""
|
||||
Schlägt schnelle Lösungen vor
|
||||
"""
|
||||
print("\n🔧 QUICK FIXES TO TRY")
|
||||
print("=" * 30)
|
||||
|
||||
fixes = [
|
||||
"1️⃣ Lower adaptive threshold temporarily:",
|
||||
" adaptive_threshold = max(60, adaptive_threshold - 10)",
|
||||
"",
|
||||
"2️⃣ Bypass pullback entry timing:",
|
||||
" use_pullback_entry = False",
|
||||
"",
|
||||
"3️⃣ Reduce minimum signal quality:",
|
||||
" Allow 'fair' quality signals temporarily",
|
||||
"",
|
||||
"4️⃣ Check if V1.3 logic still works:",
|
||||
" Run your original extended_top_down() function",
|
||||
"",
|
||||
"5️⃣ Force a test trade:",
|
||||
" market_order(symbol, 0.01, 'buy') # Small test",
|
||||
]
|
||||
|
||||
for fix in fixes:
|
||||
print(fix)
|
||||
|
||||
def emergency_v13_mode(symbol="XAUUSD"):
|
||||
"""
|
||||
Notfall-Modus: Nutze V1.3 Logik mit V1.4 Verbesserungen
|
||||
"""
|
||||
print("\n🚨 EMERGENCY V1.3 MODE")
|
||||
print("=" * 30)
|
||||
|
||||
emergency_code = '''
|
||||
def emergency_trading_signal(symbol="XAUUSD"):
|
||||
"""
|
||||
Vereinfachte V1.3-ähnliche Logik als Fallback
|
||||
"""
|
||||
from TradingBot_V1.4_Fixed import get_rates
|
||||
import pandas_ta as ta
|
||||
from scipy.signal import savgol_filter
|
||||
from sklearn.linear_model import LinearRegression
|
||||
import numpy as np
|
||||
|
||||
# Hole H4 und M5 Daten
|
||||
h4_df = get_rates("h4", 150, symbol)
|
||||
m5_df = get_rates("m5", 100, symbol)
|
||||
|
||||
if h4_df is None or m5_df is None:
|
||||
return 0, "No data"
|
||||
|
||||
# Einfache Trend-Analyse H4
|
||||
h4_df['close_smooth'] = savgol_filter(h4_df['close'], 15, 3)
|
||||
X = np.arange(len(h4_df)).reshape(-1, 1)
|
||||
y = h4_df['close_smooth'].values
|
||||
model = LinearRegression().fit(X, y)
|
||||
slope = model.coef_[0]
|
||||
|
||||
atr = h4_df['atr'].iloc[-1]
|
||||
slope_threshold = atr * 0.0001
|
||||
|
||||
if slope > slope_threshold:
|
||||
h4_trend = "uptrend"
|
||||
elif slope < -slope_threshold:
|
||||
h4_trend = "downtrend"
|
||||
else:
|
||||
h4_trend = "sideways"
|
||||
|
||||
# Einfache Confidence (Prozent der letzten 6 Timeframes die aligned sind)
|
||||
# Vereinfacht: nur prüfen ob H4 und M5 aligned sind
|
||||
m5_df['close_smooth'] = savgol_filter(m5_df['close'], 15, 3)
|
||||
X_m5 = np.arange(len(m5_df)).reshape(-1, 1)
|
||||
y_m5 = m5_df['close_smooth'].values
|
||||
model_m5 = LinearRegression().fit(X_m5, y_m5)
|
||||
slope_m5 = model_m5.coef_[0]
|
||||
|
||||
atr_m5 = m5_df['atr'].iloc[-1]
|
||||
slope_threshold_m5 = atr_m5 * 0.0001
|
||||
|
||||
if slope_m5 > slope_threshold_m5:
|
||||
m5_trend = "uptrend"
|
||||
elif slope_m5 < -slope_threshold_m5:
|
||||
m5_trend = "downtrend"
|
||||
else:
|
||||
m5_trend = "sideways"
|
||||
|
||||
# Confidence basierend auf Alignment
|
||||
if h4_trend == m5_trend and h4_trend != "sideways":
|
||||
confidence = 85 # Hoch wenn aligned
|
||||
signal = 1 if h4_trend == "uptrend" else -1
|
||||
else:
|
||||
confidence = 45 # Niedrig wenn nicht aligned
|
||||
signal = 0
|
||||
|
||||
# V1.3-ähnliche Schwelle (niedriger als adaptive)
|
||||
threshold = 70 # Niedrigere Schwelle als V1.4
|
||||
|
||||
if confidence >= threshold and signal != 0:
|
||||
return signal, f"Emergency signal: {h4_trend}, confidence: {confidence}%"
|
||||
else:
|
||||
return 0, f"No signal: confidence {confidence}% < {threshold}%"
|
||||
|
||||
# Test:
|
||||
signal, reason = emergency_trading_signal("XAUUSD")
|
||||
print(f"Emergency Signal: {signal}")
|
||||
print(f"Reason: {reason}")
|
||||
'''
|
||||
|
||||
print("Copy this code to test emergency V1.3-like logic:")
|
||||
print(emergency_code)
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Hauptdiagnose
|
||||
symbol = "XAUUSD"
|
||||
|
||||
print("🚨 TRADING BOT NOT WORKING - DIAGNOSIS")
|
||||
print("=" * 60)
|
||||
|
||||
# 1. Grundlegende Checks
|
||||
issues = diagnose_trading_issue(symbol)
|
||||
|
||||
# 2. Logic Comparison
|
||||
comparison = compare_v13_vs_v14_logic(symbol)
|
||||
|
||||
# 3. Position Limits
|
||||
position_issue = check_position_limits(symbol)
|
||||
if position_issue:
|
||||
issues.append(position_issue)
|
||||
|
||||
# 4. Zusammenfassung
|
||||
print(f"\n📋 ISSUES SUMMARY:")
|
||||
if issues:
|
||||
for i, issue in enumerate(issues, 1):
|
||||
print(f" {i}. {issue}")
|
||||
else:
|
||||
print(" ✅ No technical issues found")
|
||||
|
||||
# 5. Lösungsvorschläge
|
||||
suggest_quick_fixes()
|
||||
|
||||
# 6. Emergency Mode
|
||||
emergency_v13_mode(symbol)
|
||||
@@ -0,0 +1,367 @@
|
||||
"""
|
||||
Position Control für TradingBot V1.4
|
||||
Verhindert mehrfache gleichzeitige Trades
|
||||
"""
|
||||
|
||||
import MetaTrader5 as mt
|
||||
import pandas as pd
|
||||
from datetime import datetime
|
||||
|
||||
def check_existing_positions(symbol="XAUUSD", strategy_name="TradingBot_V1.4_Complete"):
|
||||
"""
|
||||
Überprüft ob bereits Positionen für das Symbol und die Strategie existieren
|
||||
|
||||
Returns:
|
||||
- has_position: bool - True wenn bereits Position existiert
|
||||
- position_info: dict - Info über bestehende Position(en)
|
||||
"""
|
||||
try:
|
||||
# Alle Positionen für das Symbol abrufen
|
||||
positions = mt.positions_get(symbol=symbol)
|
||||
|
||||
if positions is None:
|
||||
return False, {"count": 0, "details": []}
|
||||
|
||||
# Filter nach Strategie-Namen im Kommentar
|
||||
strategy_positions = []
|
||||
for pos in positions:
|
||||
if strategy_name in pos.comment:
|
||||
strategy_positions.append({
|
||||
"ticket": pos.ticket,
|
||||
"type": "BUY" if pos.type == 0 else "SELL",
|
||||
"volume": pos.volume,
|
||||
"price_open": pos.price_open,
|
||||
"profit": pos.profit,
|
||||
"comment": pos.comment,
|
||||
"time_open": pd.to_datetime(pos.time, unit='s')
|
||||
})
|
||||
|
||||
has_position = len(strategy_positions) > 0
|
||||
|
||||
position_info = {
|
||||
"count": len(strategy_positions),
|
||||
"details": strategy_positions
|
||||
}
|
||||
|
||||
return has_position, position_info
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error checking positions: {e}")
|
||||
return False, {"count": 0, "details": []}
|
||||
|
||||
def get_position_summary(symbol="XAUUSD", strategy_name="TradingBot_V1.4_Complete"):
|
||||
"""
|
||||
Gibt eine übersichtliche Zusammenfassung der aktuellen Positionen
|
||||
"""
|
||||
has_position, position_info = check_existing_positions(symbol, strategy_name)
|
||||
|
||||
print(f"\n📊 POSITION SUMMARY für {symbol}")
|
||||
print("=" * 50)
|
||||
|
||||
if not has_position:
|
||||
print("✅ Keine aktiven Positionen - bereit für neuen Trade")
|
||||
return False
|
||||
|
||||
print(f"⚠️ {position_info['count']} aktive Position(en) gefunden:")
|
||||
|
||||
for i, pos in enumerate(position_info['details'], 1):
|
||||
profit_emoji = "🟢" if pos['profit'] >= 0 else "🔴"
|
||||
print(f"\n Position {i}:")
|
||||
print(f" Ticket: {pos['ticket']}")
|
||||
print(f" Typ: {pos['type']}")
|
||||
print(f" Volumen: {pos['volume']}")
|
||||
print(f" Eröffnungspreis: {pos['price_open']}")
|
||||
print(f" Profit: {profit_emoji} {pos['profit']:.2f}")
|
||||
print(f" Eröffnungszeit: {pos['time_open']}")
|
||||
print(f" Kommentar: {pos['comment']}")
|
||||
|
||||
print(f"\n🛑 TRADING BLOCKIERT - Maximal 1 Position erlaubt")
|
||||
return True
|
||||
|
||||
def close_existing_positions(symbol="XAUUSD", strategy_name="TradingBot_V1.4_Complete", force_close=False):
|
||||
"""
|
||||
Schließt bestehende Positionen (optional)
|
||||
|
||||
Args:
|
||||
force_close: bool - Wenn True, schließt alle Positionen sofort
|
||||
"""
|
||||
has_position, position_info = check_existing_positions(symbol, strategy_name)
|
||||
|
||||
if not has_position:
|
||||
print("✅ Keine Positionen zum Schließen")
|
||||
return True
|
||||
|
||||
if not force_close:
|
||||
print(f"⚠️ {position_info['count']} Position(en) gefunden. Verwende force_close=True zum Schließen.")
|
||||
return False
|
||||
|
||||
print(f"🔄 Schließe {position_info['count']} Position(en)...")
|
||||
|
||||
success_count = 0
|
||||
for pos in position_info['details']:
|
||||
try:
|
||||
# Position schließen
|
||||
close_request = {
|
||||
"action": mt.TRADE_ACTION_DEAL,
|
||||
"symbol": symbol,
|
||||
"volume": pos['volume'],
|
||||
"type": mt.ORDER_TYPE_SELL if pos['type'] == "BUY" else mt.ORDER_TYPE_BUY,
|
||||
"position": pos['ticket'],
|
||||
"price": mt.symbol_info_tick(symbol).bid if pos['type'] == "BUY" else mt.symbol_info_tick(symbol).ask,
|
||||
"deviation": 20,
|
||||
"magic": 234000,
|
||||
"comment": f"Close {strategy_name}",
|
||||
"type_time": mt.ORDER_TIME_GTC,
|
||||
"type_filling": mt.ORDER_FILLING_IOC,
|
||||
}
|
||||
|
||||
result = mt.order_send(close_request)
|
||||
|
||||
if result.retcode == mt.TRADE_RETCODE_DONE:
|
||||
print(f"✅ Position {pos['ticket']} erfolgreich geschlossen")
|
||||
success_count += 1
|
||||
else:
|
||||
print(f"❌ Fehler beim Schließen von Position {pos['ticket']}: {result.comment}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Exception beim Schließen von Position {pos['ticket']}: {e}")
|
||||
|
||||
print(f"📊 {success_count}/{len(position_info['details'])} Positionen erfolgreich geschlossen")
|
||||
return success_count == len(position_info['details'])
|
||||
|
||||
def enhanced_execute_trade_v2_with_position_control(
|
||||
symbol="XAUUSD",
|
||||
atr_mult=1.5,
|
||||
base_confidence=70,
|
||||
max_risk_per_trade=0.01,
|
||||
risk_filter=True,
|
||||
min_atr=0.0010,
|
||||
use_pullback_entry=True,
|
||||
max_positions=1, # NEU: Maximale Anzahl Positionen
|
||||
strategy_name="TradingBot_V1.4_Complete",
|
||||
debug=True
|
||||
):
|
||||
"""
|
||||
Enhanced Execute Trade mit Position-Kontrolle
|
||||
"""
|
||||
|
||||
# WICHTIG: Zuerst Position-Check
|
||||
print(f"\n🔍 POSITION CHECK für {symbol}")
|
||||
has_position, position_info = check_existing_positions(symbol, strategy_name)
|
||||
|
||||
if has_position and position_info['count'] >= max_positions:
|
||||
if debug:
|
||||
print(f"🛑 TRADE BLOCKIERT: {position_info['count']}/{max_positions} Positionen bereits aktiv")
|
||||
for pos in position_info['details']:
|
||||
profit_emoji = "🟢" if pos['profit'] >= 0 else "🔴"
|
||||
print(f" Position: {pos['type']} {pos['volume']} @ {pos['price_open']} | Profit: {profit_emoji} {pos['profit']:.2f}")
|
||||
return None
|
||||
|
||||
print(f"✅ Position-Check OK: {position_info['count']}/{max_positions} Positionen")
|
||||
|
||||
# Hier würde deine bestehende execute_trade_v2 Logik kommen
|
||||
# Ich importiere sie von deinem bestehenden Code
|
||||
|
||||
try:
|
||||
# Import der bestehenden Funktionen (angepasst an deine Struktur)
|
||||
from TradingBot_V1_4_Complete import extended_top_down_v2, check_risk_limits, market_order, check_pullback_entry
|
||||
|
||||
# Signal-Analyse
|
||||
signal_info = extended_top_down_v2(symbol)
|
||||
if signal_info is None:
|
||||
print("❌ Signal-Analyse fehlgeschlagen")
|
||||
return None
|
||||
|
||||
entry_signal = signal_info["entry_signal"]
|
||||
confidence = signal_info["confidence"]
|
||||
adaptive_threshold = signal_info["adaptive_threshold"]
|
||||
signal_quality = signal_info["signal_quality"]
|
||||
market_regime = signal_info["market_regime"]
|
||||
|
||||
# Get Price/ATR from M5
|
||||
m5_info = signal_info["trend_info"]["M5"]
|
||||
price = m5_info["price"]
|
||||
atr = m5_info["atr"]
|
||||
|
||||
# Enhanced Pre-checks
|
||||
reason = ""
|
||||
|
||||
if confidence < adaptive_threshold:
|
||||
reason = f"Confidence {confidence}% < adaptive threshold {adaptive_threshold}%"
|
||||
elif entry_signal == 0:
|
||||
reason = f"No entry signal (Trend: {signal_info['top_down_trend']}, Regime: {market_regime['regime']})"
|
||||
elif price is None or atr is None:
|
||||
reason = "Price/ATR not available"
|
||||
elif risk_filter and atr < min_atr:
|
||||
reason = f"ATR {atr:.5f} < min_atr {min_atr}"
|
||||
elif signal_quality == "none":
|
||||
reason = "Signal quality insufficient"
|
||||
else:
|
||||
# Entry Timing Check
|
||||
if use_pullback_entry:
|
||||
pullback_ok, pullback_reason = check_pullback_entry(symbol, signal_info)
|
||||
if not pullback_ok:
|
||||
reason = f"Entry timing: {pullback_reason}"
|
||||
|
||||
if not reason:
|
||||
# Risk Checks
|
||||
risk_ok = check_risk_limits(symbol, max_risk_per_trade=max_risk_per_trade)
|
||||
if not risk_ok:
|
||||
reason = "Risk limits exceeded"
|
||||
|
||||
# Execute Trade if all checks pass
|
||||
if not reason:
|
||||
# Enhanced SL/TP calculation based on regime
|
||||
regime_mult = 1.0
|
||||
if market_regime['regime'] == 'volatile':
|
||||
regime_mult = 1.3 # Wider stops in volatile markets
|
||||
elif market_regime['regime'] == 'ranging':
|
||||
regime_mult = 0.8 # Tighter stops in ranging markets
|
||||
|
||||
adjusted_atr_mult = atr_mult * regime_mult
|
||||
|
||||
if entry_signal == 1: # Long
|
||||
stop_loss = price - adjusted_atr_mult * atr
|
||||
take_profit = price + adjusted_atr_mult * atr * 2.5
|
||||
else: # Short
|
||||
stop_loss = price + adjusted_atr_mult * atr
|
||||
take_profit = price - adjusted_atr_mult * atr * 2.5
|
||||
|
||||
# Dynamic Position Sizing
|
||||
stop_distance = adjusted_atr_mult * atr
|
||||
account_info = mt.account_info()
|
||||
if account_info:
|
||||
balance = account_info.balance
|
||||
risk_amount = balance * max_risk_per_trade
|
||||
if symbol == "XAUUSD":
|
||||
volume = min(0.1, max(0.01, risk_amount / (stop_distance * 100)))
|
||||
else:
|
||||
volume = 0.01
|
||||
else:
|
||||
volume = 0.01
|
||||
|
||||
# FINAL POSITION CHECK vor Order
|
||||
final_check, _ = check_existing_positions(symbol, strategy_name)
|
||||
if final_check:
|
||||
print(f"🛑 LAST-MINUTE BLOCK: Position wurde zwischen Checks eröffnet!")
|
||||
return None
|
||||
|
||||
# Log Enhanced Trade Info
|
||||
print(f"\n🚀 ENHANCED TRADE EXECUTION (mit Position Control)")
|
||||
print(f"Symbol: {symbol}")
|
||||
print(f"Direction: {'LONG' if entry_signal == 1 else 'SHORT'}")
|
||||
print(f"Price: {price:.5f}")
|
||||
print(f"Volume: {volume:.2f}")
|
||||
print(f"Stop Loss: {stop_loss:.5f}")
|
||||
print(f"Take Profit: {take_profit:.5f}")
|
||||
print(f"Confidence: {confidence}% (Threshold: {adaptive_threshold}%)")
|
||||
print(f"Signal Quality: {signal_quality.upper()}")
|
||||
print(f"Market Regime: {market_regime['regime'].upper()}")
|
||||
print(f"Position Limit: {position_info['count']}/{max_positions}")
|
||||
|
||||
# Execute the actual trade
|
||||
try:
|
||||
order_result = market_order(
|
||||
symbol=symbol,
|
||||
volume=volume,
|
||||
order_type="buy" if entry_signal == 1 else "sell",
|
||||
stoploss=stop_loss,
|
||||
take_profit=take_profit,
|
||||
comment=strategy_name # Wichtig für Position-Tracking
|
||||
)
|
||||
|
||||
if order_result and order_result.retcode == mt.TRADE_RETCODE_DONE:
|
||||
print(f"✅ Trade erfolgreich eröffnet! Ticket: {order_result.order}")
|
||||
|
||||
# Verify position was created
|
||||
new_check, new_info = check_existing_positions(symbol, strategy_name)
|
||||
print(f"📊 Neue Position-Anzahl: {new_info['count']}")
|
||||
|
||||
return order_result
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Trade execution failed: {e}")
|
||||
return None
|
||||
|
||||
else:
|
||||
if debug:
|
||||
print(f"\n⏸️ TRADE SKIPPED: {reason}")
|
||||
print(f"Confidence: {confidence}% | Threshold: {adaptive_threshold}%")
|
||||
print(f"Signal Quality: {signal_quality} | Regime: {market_regime['regime']}")
|
||||
print(f"Positions: {position_info['count']}/{max_positions}")
|
||||
return None
|
||||
|
||||
except ImportError:
|
||||
print("❌ Konnte bestehende Funktionen nicht importieren. Verwende vereinfachte Version.")
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"❌ Fehler in enhanced_execute_trade_v2_with_position_control: {e}")
|
||||
return None
|
||||
|
||||
def position_management_menu():
|
||||
"""
|
||||
Interaktives Menü für Position-Management
|
||||
"""
|
||||
symbol = "XAUUSD"
|
||||
strategy_name = "TradingBot_V1.4_Complete"
|
||||
|
||||
while True:
|
||||
print(f"\n🔧 POSITION MANAGEMENT MENU")
|
||||
print("=" * 40)
|
||||
print("1. Position Status anzeigen")
|
||||
print("2. Alle Positionen schließen")
|
||||
print("3. Position-Check für neuen Trade")
|
||||
print("4. Trading mit Position-Control testen")
|
||||
print("5. Exit")
|
||||
|
||||
choice = input("\nWähle Option (1-5): ").strip()
|
||||
|
||||
if choice == "1":
|
||||
get_position_summary(symbol, strategy_name)
|
||||
|
||||
elif choice == "2":
|
||||
confirm = input("❗ Alle Positionen schließen? (yes/no): ").strip().lower()
|
||||
if confirm in ['yes', 'y', 'ja', 'j']:
|
||||
close_existing_positions(symbol, strategy_name, force_close=True)
|
||||
else:
|
||||
print("❌ Abgebrochen")
|
||||
|
||||
elif choice == "3":
|
||||
has_pos, pos_info = check_existing_positions(symbol, strategy_name)
|
||||
if has_pos:
|
||||
print(f"🛑 {pos_info['count']} Position(en) aktiv - KEIN neuer Trade möglich")
|
||||
else:
|
||||
print("✅ Keine Positionen - neuer Trade möglich")
|
||||
|
||||
elif choice == "4":
|
||||
print("🧪 Testing Trading mit Position Control...")
|
||||
result = enhanced_execute_trade_v2_with_position_control(
|
||||
symbol=symbol,
|
||||
strategy_name=strategy_name,
|
||||
debug=True
|
||||
)
|
||||
if result:
|
||||
print(f"✅ Test-Trade ausgeführt: {result}")
|
||||
else:
|
||||
print("⏸️ Kein Test-Trade ausgeführt")
|
||||
|
||||
elif choice == "5":
|
||||
print("👋 Exit Position Management")
|
||||
break
|
||||
|
||||
else:
|
||||
print("❌ Ungültige Option")
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Teste Position Control
|
||||
symbol = "XAUUSD"
|
||||
strategy_name = "TradingBot_V1.4_Complete"
|
||||
|
||||
print("🔍 TESTING POSITION CONTROL")
|
||||
print("=" * 40)
|
||||
|
||||
# Check current positions
|
||||
get_position_summary(symbol, strategy_name)
|
||||
|
||||
# Start interactive menu
|
||||
position_management_menu()
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,680 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# TradingBot V1.4 - Complete Version\n",
|
||||
"\n",
|
||||
"## 🚀 Optimierte Entry Signal Logik\n",
|
||||
"\n",
|
||||
"### Hauptverbesserungen:\n",
|
||||
"1. **Adaptive Confidence Threshold** - Automatische Anpassung an Marktbedingungen\n",
|
||||
"2. **Market Regime Detection** - Erkennung von Trending/Ranging/Volatile Märkten\n",
|
||||
"3. **Entry Timing Optimization** - Pullback-basierte Entries\n",
|
||||
"4. **Risk-Adjusted Signal Strength** - Kombiniert Confidence mit Trend-Stärke\n",
|
||||
"5. **Performance Monitoring** - Automatisches Tracking"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Imports\n",
|
||||
"import pandas as pd\n",
|
||||
"import numpy as np\n",
|
||||
"import MetaTrader5 as mt\n",
|
||||
"import pandas_ta as ta\n",
|
||||
"from scipy.signal import savgol_filter, find_peaks\n",
|
||||
"from sklearn.linear_model import LinearRegression\n",
|
||||
"from tabulate import tabulate\n",
|
||||
"from datetime import datetime, timedelta\n",
|
||||
"import json\n",
|
||||
"import keyring as kr\n",
|
||||
"\n",
|
||||
"print(\"✅ All imports successful\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# MT5 Login\n",
|
||||
"mt.initialize()\n",
|
||||
"login = 10800246\n",
|
||||
"server = 'VantageInternational-Demo'\n",
|
||||
"password = kr.get_password(server, str(login))\n",
|
||||
"login_result = mt.login(login, password, server)\n",
|
||||
"print(f\"Login successful: {login_result}\")\n",
|
||||
"\n",
|
||||
"# Trading Parameter\n",
|
||||
"symbol = \"XAUUSD\"\n",
|
||||
"strategy_name = \"TradingBot_V1.4_Complete\"\n",
|
||||
"print(f\"Symbol: {symbol}\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Helper Functions\n",
|
||||
"def get_rates(timeframe=\"h4\", count=200, symbol=\"XAUUSD\"):\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",
|
||||
" try:\n",
|
||||
" rates = mt.copy_rates_from_pos(symbol, timeframes_dict[timeframe], 0, count)\n",
|
||||
" if rates is None: return None\n",
|
||||
" df = pd.DataFrame(rates)\n",
|
||||
" df['time'] = pd.to_datetime(df['time'], unit='s')\n",
|
||||
" df.set_index('time', inplace=True)\n",
|
||||
" df['atr'] = ta.atr(df['high'], df['low'], df['close'], length=14)\n",
|
||||
" return df\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"Error getting rates: {e}\")\n",
|
||||
" return None\n",
|
||||
"\n",
|
||||
"def check_risk_limits(symbol, volume=None, order_type=\"buy\", max_risk_per_trade=0.01):\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: return False\n",
|
||||
"\n",
|
||||
"def market_order(symbol, volume, order_type, stoploss=None, take_profit=None, deviation=20):\n",
|
||||
" try:\n",
|
||||
" price_dict = {'buy': mt.symbol_info_tick(symbol).ask, 'sell': mt.symbol_info_tick(symbol).bid}\n",
|
||||
" order_type_dict = {'buy': mt.ORDER_TYPE_BUY, 'sell': mt.ORDER_TYPE_SELL}\n",
|
||||
" request = {\n",
|
||||
" \"action\": mt.TRADE_ACTION_DEAL, \"symbol\": symbol, \"volume\": volume,\n",
|
||||
" \"type\": order_type_dict[order_type], \"price\": price_dict[order_type],\n",
|
||||
" \"sl\": stoploss, \"tp\": take_profit, \"deviation\": deviation,\n",
|
||||
" \"magic\": 234000, \"comment\": strategy_name, \"type_time\": mt.ORDER_TIME_GTC,\n",
|
||||
" \"type_filling\": mt.ORDER_FILLING_IOC\n",
|
||||
" }\n",
|
||||
" return mt.order_send(request)\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"Error in market order: {e}\")\n",
|
||||
" return None\n",
|
||||
"\n",
|
||||
"print(\"✅ Helper functions defined\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Market Regime Detection\n",
|
||||
"def detect_market_regime(df, lookback=50):\n",
|
||||
" try:\n",
|
||||
" adx_data = ta.adx(df['high'], df['low'], df['close'], length=14)\n",
|
||||
" adx = adx_data['ADX_14'].iloc[-1] if adx_data is not None and 'ADX_14' in adx_data.columns else 25.0\n",
|
||||
" \n",
|
||||
" try:\n",
|
||||
" bb = ta.bbands(df['close'], length=20)\n",
|
||||
" if bb is not None and len(bb.columns) >= 3:\n",
|
||||
" bb_cols = bb.columns.tolist()\n",
|
||||
" bb_width = ((bb[bb_cols[0]] - bb[bb_cols[2]]) / bb[bb_cols[1]] * 100).iloc[-lookback:].mean()\n",
|
||||
" else: bb_width = 4.0\n",
|
||||
" except: bb_width = 4.0\n",
|
||||
" \n",
|
||||
" price_range = df['high'].iloc[-lookback:].max() - df['low'].iloc[-lookback:].min()\n",
|
||||
" atr_avg = df['atr'].iloc[-lookback:].mean()\n",
|
||||
" range_ratio = price_range / (atr_avg * lookback) if atr_avg > 0 else 1.0\n",
|
||||
" vol_cluster = df['atr'].iloc[-10:].std() / df['atr'].iloc[-50:].mean() if len(df) >= 50 else 1.0\n",
|
||||
" \n",
|
||||
" if adx > 25 and range_ratio > 1.5:\n",
|
||||
" regime, strength = 'trending', min(100, adx * 2)\n",
|
||||
" elif vol_cluster > 1.5:\n",
|
||||
" regime, strength = 'volatile', min(100, vol_cluster * 50)\n",
|
||||
" else:\n",
|
||||
" regime, strength = 'ranging', max(0, 100 - adx * 2)\n",
|
||||
" \n",
|
||||
" return {'regime': regime, 'strength': strength, 'adx': adx, 'bb_width': bb_width, 'range_ratio': range_ratio, 'vol_cluster': vol_cluster}\n",
|
||||
" except Exception as e:\n",
|
||||
" return {'regime': 'ranging', 'strength': 50, 'adx': 20, 'bb_width': 4.0, 'range_ratio': 1.0, 'vol_cluster': 1.0}\n",
|
||||
"\n",
|
||||
"print(\"✅ Market Regime Detection defined\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Adaptive Confidence System\n",
|
||||
"def calculate_adaptive_confidence_threshold(regime_info, base_confidence=70):\n",
|
||||
" regime = regime_info['regime']\n",
|
||||
" adx = regime_info['adx']\n",
|
||||
" \n",
|
||||
" if regime == 'trending':\n",
|
||||
" return max(60, base_confidence - 15) if adx > 30 else base_confidence - 10\n",
|
||||
" elif regime == 'ranging':\n",
|
||||
" return base_confidence + 15\n",
|
||||
" elif regime == 'volatile':\n",
|
||||
" return base_confidence + 20\n",
|
||||
" return base_confidence\n",
|
||||
"\n",
|
||||
"print(\"✅ Adaptive Confidence System defined\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Enhanced Trend Analysis\n",
|
||||
"def get_enhanced_trend(timeframe=\"H4\", lookback=150, symbol=\"XAUUSD\"):\n",
|
||||
" tf_map = {\"D1\": \"d1\", \"H4\": \"h4\", \"H1\": \"h1\", \"M30\": \"m30\", \"M15\": \"m15\", \"M5\": \"m5\"}\n",
|
||||
" tf = tf_map.get(timeframe, timeframe.lower())\n",
|
||||
" \n",
|
||||
" try:\n",
|
||||
" df = get_rates(tf, lookback, symbol)\n",
|
||||
" if df is None or len(df) < 50: return None\n",
|
||||
" \n",
|
||||
" df['close_smooth'] = savgol_filter(df['close'], min(15, len(df)//10), 3)\n",
|
||||
" X = np.arange(len(df)).reshape(-1, 1)\n",
|
||||
" y = df['close_smooth'].values\n",
|
||||
" model = LinearRegression().fit(X, y)\n",
|
||||
" slope = model.coef_[0]\n",
|
||||
" \n",
|
||||
" regime_info = detect_market_regime(df.iloc[-50:])\n",
|
||||
" base_threshold = df['atr'].iloc[-1] * 0.0001\n",
|
||||
" \n",
|
||||
" if regime_info['regime'] == 'trending':\n",
|
||||
" slope_threshold = base_threshold * 0.7\n",
|
||||
" elif regime_info['regime'] == 'ranging':\n",
|
||||
" slope_threshold = base_threshold * 1.5\n",
|
||||
" else:\n",
|
||||
" slope_threshold = base_threshold * 1.2\n",
|
||||
" \n",
|
||||
" trend = \"uptrend\" if slope > slope_threshold else \"downtrend\" if slope < -slope_threshold else \"sideways\"\n",
|
||||
" trend_strength = abs(slope) / slope_threshold if slope_threshold > 0 else 0\n",
|
||||
" \n",
|
||||
" return {\n",
|
||||
" \"trend\": trend, \"slope\": slope, \"slope_threshold\": slope_threshold,\n",
|
||||
" \"trend_strength\": trend_strength, \"atr\": df['atr'].iloc[-1],\n",
|
||||
" \"price\": df['close'].iloc[-1], \"regime_info\": regime_info\n",
|
||||
" }\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"Error in get_enhanced_trend: {e}\")\n",
|
||||
" return None\n",
|
||||
"\n",
|
||||
"print(\"✅ Enhanced Trend Analysis defined\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Extended Top-Down Analysis V2\n",
|
||||
"def extended_top_down_v2(symbol=\"XAUUSD\", lookback=150):\n",
|
||||
" timeframes = [\"D1\", \"H4\", \"H1\", \"M30\", \"M15\", \"M5\"]\n",
|
||||
" trend_info = {}\n",
|
||||
" \n",
|
||||
" for tf in timeframes:\n",
|
||||
" trend_info[tf] = get_enhanced_trend(tf, lookback, symbol)\n",
|
||||
" if trend_info[tf] is None:\n",
|
||||
" print(f\"⚠️ Keine Daten für {tf}\")\n",
|
||||
" return None\n",
|
||||
" \n",
|
||||
" main_regime = trend_info[\"H4\"][\"regime_info\"]\n",
|
||||
" adaptive_confidence_threshold = calculate_adaptive_confidence_threshold(main_regime)\n",
|
||||
" \n",
|
||||
" # Standard-Trend (D1 + H4)\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\n",
|
||||
" fast_timeframes = [\"H1\", \"M30\", \"M15\", \"M5\"]\n",
|
||||
" fast_trends = [trend_info[tf][\"trend\"] for tf in fast_timeframes]\n",
|
||||
" fast_strengths = [trend_info[tf][\"trend_strength\"] for tf in fast_timeframes]\n",
|
||||
" \n",
|
||||
" required_alignment = 2 if main_regime['regime'] == 'trending' else 3\n",
|
||||
" \n",
|
||||
" trend_counts = {'uptrend': 0, 'downtrend': 0, 'sideways': 0}\n",
|
||||
" weighted_strengths = {'uptrend': 0, 'downtrend': 0}\n",
|
||||
" weights = [1.0, 0.8, 0.6, 0.4]\n",
|
||||
" \n",
|
||||
" for i, (trend, strength) in enumerate(zip(fast_trends, fast_strengths)):\n",
|
||||
" trend_counts[trend] += 1\n",
|
||||
" if trend != 'sideways':\n",
|
||||
" weighted_strengths[trend] += strength * weights[i]\n",
|
||||
" \n",
|
||||
" max_count = max(trend_counts['uptrend'], trend_counts['downtrend'])\n",
|
||||
" if max_count >= required_alignment:\n",
|
||||
" if trend_counts['uptrend'] > trend_counts['downtrend']:\n",
|
||||
" fast_trend = \"uptrend\"\n",
|
||||
" elif trend_counts['downtrend'] > trend_counts['uptrend']:\n",
|
||||
" fast_trend = \"downtrend\"\n",
|
||||
" else:\n",
|
||||
" fast_trend = \"uptrend\" if weighted_strengths['uptrend'] > weighted_strengths['downtrend'] else \"downtrend\"\n",
|
||||
" else:\n",
|
||||
" fast_trend = \"sideways\"\n",
|
||||
" \n",
|
||||
" # Top-Down-Trend\n",
|
||||
" if standard_trend == fast_trend and standard_trend != \"sideways\":\n",
|
||||
" top_down_trend = standard_trend\n",
|
||||
" combined_strength = (standard_strength + weighted_strengths.get(fast_trend, 0)) / 2\n",
|
||||
" else:\n",
|
||||
" top_down_trend = \"sideways\"\n",
|
||||
" combined_strength = 0\n",
|
||||
" \n",
|
||||
" # Confidence Calculation\n",
|
||||
" weights = {\"D1\": 2.5, \"H4\": 2.0, \"H1\": 1.5, \"M30\": 1.0, \"M15\": 0.8, \"M5\": 0.6}\n",
|
||||
" \n",
|
||||
" weighted_matching = sum(\n",
|
||||
" weights[tf] * trend_info[tf][\"trend_strength\"] \n",
|
||||
" for tf in timeframes\n",
|
||||
" if trend_info[tf][\"trend\"] == top_down_trend and trend_info[tf][\"trend\"] != \"sideways\"\n",
|
||||
" )\n",
|
||||
" \n",
|
||||
" weighted_total = sum(\n",
|
||||
" weights[tf] * trend_info[tf][\"trend_strength\"]\n",
|
||||
" for tf in timeframes\n",
|
||||
" if trend_info[tf][\"trend\"] != \"sideways\"\n",
|
||||
" )\n",
|
||||
" \n",
|
||||
" confidence = round((weighted_matching / weighted_total) * 100, 2) if weighted_total > 0 else 0.0\n",
|
||||
" \n",
|
||||
" # Risk-Adjusted Signal Strength\n",
|
||||
" atr = trend_info[\"M5\"][\"atr\"]\n",
|
||||
" rrr = 2.5\n",
|
||||
" risk_adjusted_strength = confidence * combined_strength * min(2.0, rrr)\n",
|
||||
" \n",
|
||||
" # Entry Signal\n",
|
||||
" entry_signal = 0\n",
|
||||
" signal_quality = \"none\"\n",
|
||||
" \n",
|
||||
" if (top_down_trend != \"sideways\" and \n",
|
||||
" confidence >= adaptive_confidence_threshold and\n",
|
||||
" risk_adjusted_strength >= 100):\n",
|
||||
" \n",
|
||||
" entry_signal = 1 if top_down_trend == \"uptrend\" else -1\n",
|
||||
" \n",
|
||||
" if confidence >= 85 and risk_adjusted_strength >= 150:\n",
|
||||
" signal_quality = \"excellent\"\n",
|
||||
" elif confidence >= 75 and risk_adjusted_strength >= 120:\n",
|
||||
" signal_quality = \"good\"\n",
|
||||
" else:\n",
|
||||
" signal_quality = \"fair\"\n",
|
||||
" \n",
|
||||
" # Debug Output\n",
|
||||
" debug_data = []\n",
|
||||
" for tf in timeframes:\n",
|
||||
" info = trend_info[tf]\n",
|
||||
" debug_data.append([tf, info[\"trend\"], f\"{info['trend_strength']:.2f}\", \n",
|
||||
" f\"{info['atr']:.4f}\", f\"{info['slope']:.6f}\", f\"{info['price']:.2f}\"])\n",
|
||||
" \n",
|
||||
" print(f\"📊 Enhanced Trend-Analyse für {symbol}\")\n",
|
||||
" print(f\"🎯 Market Regime: {main_regime['regime'].upper()} (Strength: {main_regime['strength']:.0f}%)\")\n",
|
||||
" print(f\"🎚️ Adaptive Confidence Threshold: {adaptive_confidence_threshold}%\")\n",
|
||||
" print(tabulate(debug_data, headers=[\"TF\", \"Trend\", \"Strength\", \"ATR\", \"Slope\", \"Price\"], tablefmt=\"psql\"))\n",
|
||||
" print(f\"➡️ Standard-Trend: {standard_trend} (Strength: {standard_strength:.2f})\")\n",
|
||||
" print(f\"➡️ Fast-Trend: {fast_trend}\")\n",
|
||||
" print(f\"➡️ Top-Down-Trend: {top_down_trend}\")\n",
|
||||
" print(f\"➡️ Confidence: {confidence}% (Threshold: {adaptive_confidence_threshold}%)\")\n",
|
||||
" print(f\"➡️ Risk-Adjusted Strength: {risk_adjusted_strength:.1f}\")\n",
|
||||
" print(f\"➡️ 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_confidence_threshold,\n",
|
||||
" \"risk_adjusted_strength\": risk_adjusted_strength, \"entry_signal\": entry_signal,\n",
|
||||
" \"signal_quality\": signal_quality, \"combined_strength\": combined_strength\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
"print(\"✅ Extended Top-Down V2 defined\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Entry Timing Optimization\n",
|
||||
"def check_pullback_entry(symbol, signal_info, timeframe=\"M5\"):\n",
|
||||
" if signal_info[\"entry_signal\"] == 0:\n",
|
||||
" return False, \"No base signal\"\n",
|
||||
" \n",
|
||||
" try:\n",
|
||||
" df = get_rates(timeframe.lower(), 50, symbol)\n",
|
||||
" if df is None or len(df) < 20:\n",
|
||||
" return False, \"Insufficient data\"\n",
|
||||
" \n",
|
||||
" df['ema21'] = df['close'].ewm(span=21).mean()\n",
|
||||
" df['ema50'] = df['close'].ewm(span=50).mean()\n",
|
||||
" \n",
|
||||
" current_price = df['close'].iloc[-1]\n",
|
||||
" ema21 = df['ema21'].iloc[-1]\n",
|
||||
" ema50 = df['ema50'].iloc[-1]\n",
|
||||
" signal_direction = signal_info[\"entry_signal\"]\n",
|
||||
" \n",
|
||||
" if signal_direction == 1: # Long\n",
|
||||
" if current_price <= ema21 * 1.002 and ema21 > ema50:\n",
|
||||
" return True, \"Pullback to EMA21 for Long\"\n",
|
||||
" elif current_price <= ema21 * 0.998:\n",
|
||||
" return True, \"Below EMA21 - Good Long Entry\"\n",
|
||||
" elif signal_direction == -1: # Short\n",
|
||||
" if current_price >= ema21 * 0.998 and ema21 < ema50:\n",
|
||||
" return True, \"Pullback to EMA21 for Short\"\n",
|
||||
" elif current_price >= ema21 * 1.002:\n",
|
||||
" return True, \"Above EMA21 - Good Short Entry\"\n",
|
||||
" \n",
|
||||
" return False, \"Waiting for better entry timing\"\n",
|
||||
" except Exception as e:\n",
|
||||
" return True, \"Using immediate entry (fallback)\"\n",
|
||||
"\n",
|
||||
"print(\"✅ Entry Timing Optimization defined\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Enhanced Execute Trade Function\n",
|
||||
"def execute_trade_v2(\n",
|
||||
" symbol=\"XAUUSD\",\n",
|
||||
" atr_mult=1.5,\n",
|
||||
" base_confidence=70,\n",
|
||||
" max_risk_per_trade=0.01,\n",
|
||||
" risk_filter=True,\n",
|
||||
" min_atr=0.0010,\n",
|
||||
" use_pullback_entry=True,\n",
|
||||
" debug=True\n",
|
||||
"):\n",
|
||||
" signal_info = extended_top_down_v2(symbol)\n",
|
||||
" if signal_info is None:\n",
|
||||
" print(\"❌ Signal-Analyse fehlgeschlagen\")\n",
|
||||
" return None\n",
|
||||
" \n",
|
||||
" entry_signal = signal_info[\"entry_signal\"]\n",
|
||||
" confidence = signal_info[\"confidence\"]\n",
|
||||
" adaptive_threshold = signal_info[\"adaptive_threshold\"]\n",
|
||||
" signal_quality = signal_info[\"signal_quality\"]\n",
|
||||
" market_regime = signal_info[\"market_regime\"]\n",
|
||||
" \n",
|
||||
" m5_info = signal_info[\"trend_info\"][\"M5\"]\n",
|
||||
" price = m5_info[\"price\"]\n",
|
||||
" atr = m5_info[\"atr\"]\n",
|
||||
" \n",
|
||||
" reason = \"\"\n",
|
||||
" \n",
|
||||
" if confidence < adaptive_threshold:\n",
|
||||
" reason = f\"Confidence {confidence}% < threshold {adaptive_threshold}%\"\n",
|
||||
" elif entry_signal == 0:\n",
|
||||
" reason = f\"No entry signal (Trend: {signal_info['top_down_trend']})\"\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",
|
||||
" elif signal_quality == \"none\":\n",
|
||||
" reason = \"Signal quality insufficient\"\n",
|
||||
" else:\n",
|
||||
" if use_pullback_entry:\n",
|
||||
" pullback_ok, pullback_reason = check_pullback_entry(symbol, signal_info)\n",
|
||||
" if not pullback_ok:\n",
|
||||
" reason = f\"Entry timing: {pullback_reason}\"\n",
|
||||
" \n",
|
||||
" if not reason:\n",
|
||||
" risk_ok = check_risk_limits(symbol, max_risk_per_trade=max_risk_per_trade)\n",
|
||||
" if not risk_ok:\n",
|
||||
" reason = \"Risk limits exceeded\"\n",
|
||||
" \n",
|
||||
" if not reason:\n",
|
||||
" regime_mult = 1.0\n",
|
||||
" if market_regime['regime'] == 'volatile':\n",
|
||||
" regime_mult = 1.3\n",
|
||||
" elif market_regime['regime'] == 'ranging':\n",
|
||||
" regime_mult = 0.8\n",
|
||||
" \n",
|
||||
" adjusted_atr_mult = atr_mult * regime_mult\n",
|
||||
" \n",
|
||||
" if entry_signal == 1:\n",
|
||||
" stop_loss = price - adjusted_atr_mult * atr\n",
|
||||
" take_profit = price + adjusted_atr_mult * atr * 2.5\n",
|
||||
" else:\n",
|
||||
" stop_loss = price + adjusted_atr_mult * atr\n",
|
||||
" take_profit = price - adjusted_atr_mult * atr * 2.5\n",
|
||||
" \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",
|
||||
" else:\n",
|
||||
" volume = 0.01\n",
|
||||
" \n",
|
||||
" print(f\"🚀 ENHANCED TRADE EXECUTION\")\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}\")\n",
|
||||
" print(f\"Stop Loss: {stop_loss:.5f}\")\n",
|
||||
" print(f\"Take Profit: {take_profit:.5f}\")\n",
|
||||
" print(f\"Confidence: {confidence}% (Threshold: {adaptive_threshold}%)\")\n",
|
||||
" print(f\"Signal Quality: {signal_quality.upper()}\")\n",
|
||||
" print(f\"Market Regime: {market_regime['regime'].upper()}\")\n",
|
||||
" \n",
|
||||
" try:\n",
|
||||
" order_result = market_order(\n",
|
||||
" symbol=symbol,\n",
|
||||
" volume=volume,\n",
|
||||
" order_type=\"buy\" if entry_signal == 1 else \"sell\",\n",
|
||||
" stoploss=stop_loss,\n",
|
||||
" take_profit=take_profit\n",
|
||||
" )\n",
|
||||
" return order_result\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"❌ Trade execution failed: {e}\")\n",
|
||||
" return None\n",
|
||||
" else:\n",
|
||||
" if debug:\n",
|
||||
" print(f\"⏸️ TRADE SKIPPED: {reason}\")\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 Execute Trade defined\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Test der optimierten Funktionen\n",
|
||||
"print(\"🔍 Testing Market Regime Detection...\")\n",
|
||||
"df_test = get_rates(\"h4\", 100, symbol)\n",
|
||||
"if df_test is not None:\n",
|
||||
" regime = detect_market_regime(df_test)\n",
|
||||
" print(f\"Regime: {regime['regime'].upper()}\")\n",
|
||||
" print(f\"Strength: {regime['strength']:.1f}%\")\n",
|
||||
" print(f\"ADX: {regime['adx']:.1f}\")\n",
|
||||
" \n",
|
||||
" adaptive_threshold = calculate_adaptive_confidence_threshold(regime)\n",
|
||||
" print(f\"Adaptive Threshold: {adaptive_threshold}% (vs 80% fixed)\")\n",
|
||||
"else:\n",
|
||||
" print(\"❌ Could not get test data\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Test Enhanced Top-Down Analysis\n",
|
||||
"print(\"🔍 Testing Enhanced Top-Down Analysis...\")\n",
|
||||
"signal_result = extended_top_down_v2(symbol)\n",
|
||||
"\n",
|
||||
"if signal_result:\n",
|
||||
" print(f\"🎯 SIGNAL SUMMARY:\")\n",
|
||||
" print(f\"Entry Signal: {signal_result['entry_signal']}\")\n",
|
||||
" print(f\"Confidence: {signal_result['confidence']}%\")\n",
|
||||
" print(f\"Adaptive Threshold: {signal_result['adaptive_threshold']}%\")\n",
|
||||
" print(f\"Signal Quality: {signal_result['signal_quality'].upper()}\")\n",
|
||||
" print(f\"Market Regime: {signal_result['market_regime']['regime'].upper()}\")\n",
|
||||
" print(f\"Risk-Adjusted Strength: {signal_result['risk_adjusted_strength']:.1f}\")\n",
|
||||
" \n",
|
||||
" if signal_result['entry_signal'] != 0:\n",
|
||||
" direction = \"LONG\" if signal_result['entry_signal'] == 1 else \"SHORT\"\n",
|
||||
" print(f\"🚀 TRADING SIGNAL: {direction}\")\n",
|
||||
" else:\n",
|
||||
" print(f\"⏸️ NO TRADING SIGNAL\")\n",
|
||||
"else:\n",
|
||||
" print(\"❌ Signal analysis failed\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Trading Configuration\n",
|
||||
"TRADING_CONFIG = {\n",
|
||||
" 'symbol': symbol,\n",
|
||||
" 'atr_mult': 1.5,\n",
|
||||
" 'base_confidence': 70,\n",
|
||||
" 'max_risk_per_trade': 0.01,\n",
|
||||
" 'risk_filter': True,\n",
|
||||
" 'min_atr': 0.0010,\n",
|
||||
" 'use_pullback_entry': True,\n",
|
||||
" 'debug': True\n",
|
||||
"}\n",
|
||||
"\n",
|
||||
"print(\"⚙️ Trading Configuration:\")\n",
|
||||
"for key, value in TRADING_CONFIG.items():\n",
|
||||
" print(f\" {key}: {value}\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Test Trading Execution\n",
|
||||
"def test_trading():\n",
|
||||
" print(\"🚀 Testing Trade Execution...\")\n",
|
||||
" try:\n",
|
||||
" result = execute_trade_v2(**TRADING_CONFIG)\n",
|
||||
" if result:\n",
|
||||
" print(\"✅ Trade executed successfully!\")\n",
|
||||
" return result\n",
|
||||
" else:\n",
|
||||
" print(\"⏸️ No trade executed\")\n",
|
||||
" return None\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"❌ Error: {e}\")\n",
|
||||
" return None\n",
|
||||
"\n",
|
||||
"test_result = test_trading()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Status Check\n",
|
||||
"def check_bot_status():\n",
|
||||
" print(\"🔍 Trading Bot Status:\")\n",
|
||||
" print(f\" MT5 Connection: {'✅' if mt.terminal_info() else '❌'}\")\n",
|
||||
" \n",
|
||||
" try:\n",
|
||||
" signal_info = extended_top_down_v2(symbol)\n",
|
||||
" if signal_info:\n",
|
||||
" print(f\" Current Signal: {signal_info['entry_signal']}\")\n",
|
||||
" print(f\" Confidence: {signal_info['confidence']}%\")\n",
|
||||
" print(f\" Market Regime: {signal_info['market_regime']['regime'].upper()}\")\n",
|
||||
" print(f\" Signal Quality: {signal_info['signal_quality'].upper()}\")\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\" Signal Check: ❌ Error: {e}\")\n",
|
||||
"\n",
|
||||
"check_bot_status()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 📝 Zusammenfassung\n",
|
||||
"\n",
|
||||
"### ✅ **TradingBot V1.4 Complete ist bereit!**\n",
|
||||
"\n",
|
||||
"**Hauptfunktionen:**\n",
|
||||
"- `extended_top_down_v2()` - Optimierte Signal-Analyse\n",
|
||||
"- `execute_trade_v2()` - Verbesserte Trade-Ausführung\n",
|
||||
"- `detect_market_regime()` - Marktregime-Erkennung\n",
|
||||
"\n",
|
||||
"**Nächste Schritte:**\n",
|
||||
"1. Teste die Funktionen im Demo-Modus\n",
|
||||
"2. Überwache Performance für 1-2 Wochen\n",
|
||||
"3. Optimiere Parameter basierend auf Ergebnissen\n",
|
||||
"4. Bei Erfolg: Live-Trading aktivieren"
|
||||
]
|
||||
}
|
||||
],
|
||||
"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
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,753 @@
|
||||
"""
|
||||
TradingBot V1.4 - Fixed Version
|
||||
Korrigierte Entry Signal Logik ohne externe Abhängigkeiten
|
||||
|
||||
Alle notwendigen Funktionen sind integriert.
|
||||
"""
|
||||
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
import MetaTrader5 as mt
|
||||
import pandas_ta as ta
|
||||
from scipy.signal import savgol_filter, find_peaks
|
||||
from sklearn.linear_model import LinearRegression
|
||||
from tabulate import tabulate
|
||||
from datetime import datetime, timedelta
|
||||
import json
|
||||
|
||||
# =============================================================================
|
||||
# HILFSFUNKTIONEN (aus deiner bestehenden V1.3)
|
||||
# =============================================================================
|
||||
|
||||
def get_rates(timeframe="h4", count=200, symbol="XAUUSD"):
|
||||
"""
|
||||
Holt Kursdaten von MT5
|
||||
"""
|
||||
timeframes_dict = {
|
||||
"m1": mt.TIMEFRAME_M1,
|
||||
"m5": mt.TIMEFRAME_M5,
|
||||
"m15": mt.TIMEFRAME_M15,
|
||||
"m30": mt.TIMEFRAME_M30,
|
||||
"h1": mt.TIMEFRAME_H1,
|
||||
"h4": mt.TIMEFRAME_H4,
|
||||
"d1": mt.TIMEFRAME_D1
|
||||
}
|
||||
|
||||
try:
|
||||
rates = mt.copy_rates_from_pos(symbol, timeframes_dict[timeframe], 0, count)
|
||||
if rates is None:
|
||||
return None
|
||||
|
||||
df = pd.DataFrame(rates)
|
||||
df['time'] = pd.to_datetime(df['time'], unit='s')
|
||||
df.set_index('time', inplace=True)
|
||||
|
||||
# ATR hinzufügen
|
||||
df['atr'] = ta.atr(df['high'], df['low'], df['close'], length=14)
|
||||
|
||||
return df
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error getting rates: {e}")
|
||||
return None
|
||||
|
||||
def check_risk_limits(symbol, volume=None, order_type="buy", max_risk_per_trade=0.01):
|
||||
"""
|
||||
Prüft alle Risikolimits (vereinfachte Version)
|
||||
"""
|
||||
try:
|
||||
account_info = mt.account_info()
|
||||
if not account_info:
|
||||
print("⚠️ Kontodaten nicht verfügbar.")
|
||||
return False
|
||||
|
||||
# Einfache Checks - erweitere nach Bedarf
|
||||
balance = account_info.balance
|
||||
equity = account_info.equity
|
||||
|
||||
# Basis-Risiko-Check
|
||||
if equity < balance * 0.8: # Mehr als 20% Verlust
|
||||
print("⚠️ Drawdown-Limit erreicht")
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error in risk check: {e}")
|
||||
return False
|
||||
|
||||
def market_order(symbol, volume, order_type, stoploss=None, take_profit=None, deviation=20):
|
||||
"""
|
||||
Führt Market Order aus (vereinfachte Version)
|
||||
"""
|
||||
try:
|
||||
price_dict = {
|
||||
'buy': mt.symbol_info_tick(symbol).ask,
|
||||
'sell': mt.symbol_info_tick(symbol).bid
|
||||
}
|
||||
|
||||
order_type_dict = {
|
||||
'buy': mt.ORDER_TYPE_BUY,
|
||||
'sell': mt.ORDER_TYPE_SELL
|
||||
}
|
||||
|
||||
request = {
|
||||
"action": mt.TRADE_ACTION_DEAL,
|
||||
"symbol": symbol,
|
||||
"volume": volume,
|
||||
"type": order_type_dict[order_type],
|
||||
"price": price_dict[order_type],
|
||||
"sl": stoploss,
|
||||
"tp": take_profit,
|
||||
"deviation": deviation,
|
||||
"magic": 234000,
|
||||
"comment": "TradingBot_V1.4_Optimized",
|
||||
"type_time": mt.ORDER_TIME_GTC,
|
||||
"type_filling": mt.ORDER_FILLING_IOC,
|
||||
}
|
||||
|
||||
result = mt.order_send(request)
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error in market order: {e}")
|
||||
return None
|
||||
|
||||
# =============================================================================
|
||||
# 1. MARKET REGIME DETECTION
|
||||
# =============================================================================
|
||||
|
||||
def detect_market_regime(df, lookback=50):
|
||||
"""
|
||||
Erkennt das aktuelle Marktregime (Trending vs. Ranging)
|
||||
"""
|
||||
try:
|
||||
# ADX für Trendstärke
|
||||
adx_data = ta.adx(df['high'], df['low'], df['close'], length=14)
|
||||
if adx_data is None or 'ADX_14' not in adx_data.columns:
|
||||
# Fallback: einfache ADX-Berechnung
|
||||
adx = 25.0 # Standardwert
|
||||
else:
|
||||
adx = adx_data['ADX_14'].iloc[-1] if not pd.isna(adx_data['ADX_14'].iloc[-1]) else 25.0
|
||||
|
||||
# Bollinger Band Squeeze für Ranging Markets
|
||||
try:
|
||||
bb = ta.bbands(df['close'], length=20)
|
||||
if bb is not None and len(bb.columns) >= 3:
|
||||
bb_cols = bb.columns.tolist()
|
||||
bb_upper = bb[bb_cols[0]] # Oberes Band
|
||||
bb_middle = bb[bb_cols[1]] # Mittleres Band
|
||||
bb_lower = bb[bb_cols[2]] # Unteres Band
|
||||
bb_width = ((bb_upper - bb_lower) / bb_middle * 100).iloc[-lookback:].mean()
|
||||
else:
|
||||
bb_width = 4.0 # Standardwert
|
||||
except:
|
||||
bb_width = 4.0
|
||||
|
||||
# Price Action Analysis
|
||||
price_range = (df['high'].iloc[-lookback:].max() - df['low'].iloc[-lookback:].min())
|
||||
atr_avg = df['atr'].iloc[-lookback:].mean()
|
||||
range_ratio = price_range / (atr_avg * lookback) if atr_avg > 0 else 1.0
|
||||
|
||||
# Volatility Cluster Detection
|
||||
vol_cluster = df['atr'].iloc[-10:].std() / df['atr'].iloc[-50:].mean() if len(df) >= 50 else 1.0
|
||||
|
||||
# Regime-Bestimmung
|
||||
if adx > 25 and range_ratio > 1.5:
|
||||
regime = 'trending'
|
||||
strength = min(100, adx * 2)
|
||||
elif vol_cluster > 1.5:
|
||||
regime = 'volatile'
|
||||
strength = min(100, vol_cluster * 50)
|
||||
else:
|
||||
regime = 'ranging'
|
||||
strength = max(0, 100 - adx * 2)
|
||||
|
||||
return {
|
||||
'regime': regime,
|
||||
'strength': strength,
|
||||
'adx': adx,
|
||||
'bb_width': bb_width,
|
||||
'range_ratio': range_ratio,
|
||||
'vol_cluster': vol_cluster
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error in regime detection: {e}")
|
||||
# Fallback
|
||||
return {
|
||||
'regime': 'ranging',
|
||||
'strength': 50,
|
||||
'adx': 20,
|
||||
'bb_width': 4.0,
|
||||
'range_ratio': 1.0,
|
||||
'vol_cluster': 1.0
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# 2. ADAPTIVE CONFIDENCE SYSTEM
|
||||
# =============================================================================
|
||||
|
||||
def calculate_adaptive_confidence_threshold(regime_info, base_confidence=70):
|
||||
"""
|
||||
Berechnet adaptive Confidence-Schwelle basierend auf Marktregime
|
||||
"""
|
||||
regime = regime_info['regime']
|
||||
strength = regime_info['strength']
|
||||
adx = regime_info['adx']
|
||||
|
||||
if regime == 'trending':
|
||||
# In Trending Markets: niedrigere Schwelle bei starken Trends
|
||||
if adx > 30:
|
||||
return max(60, base_confidence - 15)
|
||||
else:
|
||||
return base_confidence - 10
|
||||
|
||||
elif regime == 'ranging':
|
||||
# In Ranging Markets: höhere Schwelle für mehr Selektivität
|
||||
return base_confidence + 15
|
||||
|
||||
elif regime == 'volatile':
|
||||
# In Volatile Markets: deutlich höhere Schwelle
|
||||
return base_confidence + 20
|
||||
|
||||
return base_confidence
|
||||
|
||||
# =============================================================================
|
||||
# 3. ENHANCED TREND ANALYSIS
|
||||
# =============================================================================
|
||||
|
||||
def get_enhanced_trend(timeframe="H4", lookback=150, symbol="XAUUSD"):
|
||||
"""
|
||||
Verbesserte Trend-Analyse mit Regime-Awareness
|
||||
"""
|
||||
# Timeframe mapping
|
||||
tf_map = {"D1": "d1", "H4": "h4", "H1": "h1", "M30": "m30", "M15": "m15", "M5": "m5"}
|
||||
tf = tf_map.get(timeframe, timeframe.lower())
|
||||
|
||||
try:
|
||||
df = get_rates(tf, lookback, symbol)
|
||||
if df is None or len(df) < 50:
|
||||
return None
|
||||
|
||||
# Bestehende Trend-Logik
|
||||
df['close_smooth'] = savgol_filter(df['close'], min(15, len(df)//10), 3)
|
||||
|
||||
# Linear Regression
|
||||
X = np.arange(len(df)).reshape(-1, 1)
|
||||
y = df['close_smooth'].values
|
||||
model = LinearRegression().fit(X, y)
|
||||
slope = model.coef_[0]
|
||||
|
||||
# Market Regime Detection
|
||||
regime_info = detect_market_regime(df.iloc[-50:])
|
||||
|
||||
# Adaptive Slope Threshold basierend auf Regime
|
||||
base_threshold = df['atr'].iloc[-1] * 0.0001
|
||||
|
||||
if regime_info['regime'] == 'trending':
|
||||
slope_threshold = base_threshold * 0.7 # Niedrigere Schwelle in Trends
|
||||
elif regime_info['regime'] == 'ranging':
|
||||
slope_threshold = base_threshold * 1.5 # Höhere Schwelle in Ranges
|
||||
else: # volatile
|
||||
slope_threshold = base_threshold * 1.2
|
||||
|
||||
# Trend bestimmen
|
||||
if slope > slope_threshold:
|
||||
trend = "uptrend"
|
||||
elif slope < -slope_threshold:
|
||||
trend = "downtrend"
|
||||
else:
|
||||
trend = "sideways"
|
||||
|
||||
# Enhanced Trend Strength
|
||||
trend_strength = abs(slope) / slope_threshold if slope_threshold > 0 else 0
|
||||
|
||||
return {
|
||||
"trend": trend,
|
||||
"slope": slope,
|
||||
"slope_threshold": slope_threshold,
|
||||
"trend_strength": trend_strength,
|
||||
"atr": df['atr'].iloc[-1],
|
||||
"price": df['close'].iloc[-1],
|
||||
"regime_info": regime_info
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error in get_enhanced_trend: {e}")
|
||||
return None
|
||||
|
||||
# =============================================================================
|
||||
# 4. OPTIMIZED TOP-DOWN ANALYSIS
|
||||
# =============================================================================
|
||||
|
||||
def extended_top_down_v2(symbol="XAUUSD", lookback=150):
|
||||
"""
|
||||
Optimierte Top-Down-Analyse mit adaptiven Parametern
|
||||
"""
|
||||
|
||||
timeframes = ["D1", "H4", "H1", "M30", "M15", "M5"]
|
||||
trend_info = {}
|
||||
|
||||
# 1. Alle Timeframes analysieren
|
||||
for tf in timeframes:
|
||||
trend_info[tf] = get_enhanced_trend(tf, lookback, symbol)
|
||||
if trend_info[tf] is None:
|
||||
print(f"⚠️ Keine Daten für {tf}")
|
||||
return None
|
||||
|
||||
# 2. Market Regime aus H4 bestimmen (repräsentativ)
|
||||
main_regime = trend_info["H4"]["regime_info"]
|
||||
|
||||
# 3. Adaptive Confidence Threshold
|
||||
adaptive_confidence_threshold = calculate_adaptive_confidence_threshold(main_regime)
|
||||
|
||||
# 4. Enhanced Standard-Trend (D1 + H4 mit Gewichtung)
|
||||
d1_trend = trend_info["D1"]["trend"]
|
||||
h4_trend = trend_info["H4"]["trend"]
|
||||
d1_strength = trend_info["D1"]["trend_strength"]
|
||||
h4_strength = trend_info["H4"]["trend_strength"]
|
||||
|
||||
# Gewichteter Standard-Trend
|
||||
if d1_trend == h4_trend and d1_trend != "sideways":
|
||||
standard_trend = d1_trend
|
||||
standard_strength = (d1_strength * 0.6 + h4_strength * 0.4)
|
||||
elif d1_strength > h4_strength * 1.5: # D1 deutlich stärker
|
||||
standard_trend = d1_trend
|
||||
standard_strength = d1_strength * 0.8
|
||||
elif h4_strength > d1_strength * 1.5: # H4 deutlich stärker
|
||||
standard_trend = h4_trend
|
||||
standard_strength = h4_strength * 0.8
|
||||
else:
|
||||
standard_trend = "sideways"
|
||||
standard_strength = 0
|
||||
|
||||
# 5. Enhanced Fast-Trend mit Regime-Awareness
|
||||
fast_timeframes = ["H1", "M30", "M15", "M5"]
|
||||
fast_trends = [trend_info[tf]["trend"] for tf in fast_timeframes]
|
||||
fast_strengths = [trend_info[tf]["trend_strength"] for tf in fast_timeframes]
|
||||
|
||||
# Regime-abhängige Fast-Trend Logik
|
||||
if main_regime['regime'] == 'trending':
|
||||
# In Trends: 2 von 4 TFs reichen
|
||||
required_alignment = 2
|
||||
else:
|
||||
# In Ranging/Volatile: 3 von 4 TFs erforderlich
|
||||
required_alignment = 3
|
||||
|
||||
trend_counts = {'uptrend': 0, 'downtrend': 0, 'sideways': 0}
|
||||
weighted_strengths = {'uptrend': 0, 'downtrend': 0}
|
||||
|
||||
weights = [1.0, 0.8, 0.6, 0.4] # H1, M30, M15, M5
|
||||
|
||||
for i, (trend, strength) in enumerate(zip(fast_trends, fast_strengths)):
|
||||
trend_counts[trend] += 1
|
||||
if trend != 'sideways':
|
||||
weighted_strengths[trend] += strength * weights[i]
|
||||
|
||||
# Fast-Trend bestimmen
|
||||
max_count = max(trend_counts['uptrend'], trend_counts['downtrend'])
|
||||
if max_count >= required_alignment:
|
||||
if trend_counts['uptrend'] > trend_counts['downtrend']:
|
||||
fast_trend = "uptrend"
|
||||
elif trend_counts['downtrend'] > trend_counts['uptrend']:
|
||||
fast_trend = "downtrend"
|
||||
else:
|
||||
# Bei Gleichstand: Stärke entscheidet
|
||||
if weighted_strengths['uptrend'] > weighted_strengths['downtrend']:
|
||||
fast_trend = "uptrend"
|
||||
else:
|
||||
fast_trend = "downtrend"
|
||||
else:
|
||||
fast_trend = "sideways"
|
||||
|
||||
# 6. Top-Down-Trend Bestimmung
|
||||
if standard_trend == fast_trend and standard_trend != "sideways":
|
||||
top_down_trend = standard_trend
|
||||
combined_strength = (standard_strength + weighted_strengths.get(fast_trend, 0)) / 2
|
||||
else:
|
||||
top_down_trend = "sideways"
|
||||
combined_strength = 0
|
||||
|
||||
# 7. Enhanced Confidence Calculation
|
||||
weights = {"D1": 2.5, "H4": 2.0, "H1": 1.5, "M30": 1.0, "M15": 0.8, "M5": 0.6}
|
||||
|
||||
weighted_matching = sum(
|
||||
weights[tf] * trend_info[tf]["trend_strength"]
|
||||
for tf in timeframes
|
||||
if trend_info[tf]["trend"] == top_down_trend and trend_info[tf]["trend"] != "sideways"
|
||||
)
|
||||
|
||||
weighted_total = sum(
|
||||
weights[tf] * trend_info[tf]["trend_strength"]
|
||||
for tf in timeframes
|
||||
if trend_info[tf]["trend"] != "sideways"
|
||||
)
|
||||
|
||||
confidence = round((weighted_matching / weighted_total) * 100, 2) if weighted_total > 0 else 0.0
|
||||
|
||||
# 8. Risk-Adjusted Signal Strength
|
||||
atr = trend_info["M5"]["atr"]
|
||||
rrr = 2.5 # Risk-Reward Ratio
|
||||
|
||||
risk_adjusted_strength = confidence * combined_strength * min(2.0, rrr)
|
||||
|
||||
# 9. Entry Signal mit adaptiven Kriterien
|
||||
entry_signal = 0
|
||||
signal_quality = "none"
|
||||
|
||||
if (top_down_trend != "sideways" and
|
||||
confidence >= adaptive_confidence_threshold and
|
||||
risk_adjusted_strength >= 100):
|
||||
|
||||
entry_signal = 1 if top_down_trend == "uptrend" else -1
|
||||
|
||||
# Signal Quality Assessment
|
||||
if confidence >= 85 and risk_adjusted_strength >= 150:
|
||||
signal_quality = "excellent"
|
||||
elif confidence >= 75 and risk_adjusted_strength >= 120:
|
||||
signal_quality = "good"
|
||||
else:
|
||||
signal_quality = "fair"
|
||||
|
||||
# 10. Enhanced Debug Output
|
||||
debug_data = []
|
||||
for tf in timeframes:
|
||||
info = trend_info[tf]
|
||||
debug_data.append([
|
||||
tf,
|
||||
info["trend"],
|
||||
f"{info['trend_strength']:.2f}",
|
||||
f"{info['atr']:.4f}",
|
||||
f"{info['slope']:.6f}",
|
||||
f"{info['price']:.2f}"
|
||||
])
|
||||
|
||||
print(f"\n📊 Enhanced Trend-Analyse für {symbol}")
|
||||
print(f"🎯 Market Regime: {main_regime['regime'].upper()} (Strength: {main_regime['strength']:.0f}%)")
|
||||
print(f"🎚️ Adaptive Confidence Threshold: {adaptive_confidence_threshold}%")
|
||||
print()
|
||||
print(tabulate(debug_data, headers=["TF", "Trend", "Strength", "ATR", "Slope", "Price"], tablefmt="psql"))
|
||||
print(f"\n➡️ Standard-Trend: {standard_trend} (Strength: {standard_strength:.2f})")
|
||||
print(f"➡️ Fast-Trend: {fast_trend}")
|
||||
print(f"➡️ Top-Down-Trend: {top_down_trend}")
|
||||
print(f"➡️ Confidence: {confidence}% (Threshold: {adaptive_confidence_threshold}%)")
|
||||
print(f"➡️ Risk-Adjusted Strength: {risk_adjusted_strength:.1f}")
|
||||
print(f"➡️ Signal Quality: {signal_quality.upper()}")
|
||||
|
||||
return {
|
||||
"symbol": symbol,
|
||||
"trend_info": trend_info,
|
||||
"market_regime": main_regime,
|
||||
"standard_trend": standard_trend,
|
||||
"fast_trend": fast_trend,
|
||||
"top_down_trend": top_down_trend,
|
||||
"confidence": confidence,
|
||||
"adaptive_threshold": adaptive_confidence_threshold,
|
||||
"risk_adjusted_strength": risk_adjusted_strength,
|
||||
"entry_signal": entry_signal,
|
||||
"signal_quality": signal_quality,
|
||||
"combined_strength": combined_strength
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# 5. ENTRY TIMING OPTIMIZATION
|
||||
# =============================================================================
|
||||
|
||||
def check_pullback_entry(symbol, signal_info, timeframe="M5"):
|
||||
"""
|
||||
Prüft optimale Entry-Timing durch Pullback-Analyse
|
||||
"""
|
||||
if signal_info["entry_signal"] == 0:
|
||||
return False, "No base signal"
|
||||
|
||||
try:
|
||||
df = get_rates(timeframe.lower(), 50, symbol)
|
||||
|
||||
if df is None or len(df) < 20:
|
||||
return False, "Insufficient data"
|
||||
|
||||
# EMAs für Pullback-Erkennung
|
||||
df['ema21'] = df['close'].ewm(span=21).mean()
|
||||
df['ema50'] = df['close'].ewm(span=50).mean()
|
||||
|
||||
current_price = df['close'].iloc[-1]
|
||||
ema21 = df['ema21'].iloc[-1]
|
||||
ema50 = df['ema50'].iloc[-1]
|
||||
|
||||
signal_direction = signal_info["entry_signal"]
|
||||
|
||||
if signal_direction == 1: # Long Signal
|
||||
# Pullback zu EMA21 oder Support
|
||||
if current_price <= ema21 * 1.002 and ema21 > ema50:
|
||||
return True, "Pullback to EMA21 for Long"
|
||||
elif current_price <= ema21 * 0.998:
|
||||
return True, "Below EMA21 - Good Long Entry"
|
||||
|
||||
elif signal_direction == -1: # Short Signal
|
||||
# Pullback zu EMA21 oder Resistance
|
||||
if current_price >= ema21 * 0.998 and ema21 < ema50:
|
||||
return True, "Pullback to EMA21 for Short"
|
||||
elif current_price >= ema21 * 1.002:
|
||||
return True, "Above EMA21 - Good Short Entry"
|
||||
|
||||
return False, "Waiting for better entry timing"
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error in pullback check: {e}")
|
||||
return True, "Using immediate entry (fallback)"
|
||||
|
||||
# =============================================================================
|
||||
# 6. ENHANCED EXECUTE TRADE FUNCTION
|
||||
# =============================================================================
|
||||
|
||||
def execute_trade_v2(
|
||||
symbol="XAUUSD",
|
||||
atr_mult=1.5,
|
||||
base_confidence=70,
|
||||
max_risk_per_trade=0.01,
|
||||
risk_filter=True,
|
||||
min_atr=0.0010,
|
||||
use_pullback_entry=True,
|
||||
debug=True
|
||||
):
|
||||
"""
|
||||
Optimierte Trade-Ausführung mit allen Verbesserungen
|
||||
"""
|
||||
|
||||
# 1. Enhanced Signal Analysis
|
||||
signal_info = extended_top_down_v2(symbol)
|
||||
if signal_info is None:
|
||||
print("❌ Signal-Analyse fehlgeschlagen")
|
||||
return None
|
||||
|
||||
entry_signal = signal_info["entry_signal"]
|
||||
confidence = signal_info["confidence"]
|
||||
adaptive_threshold = signal_info["adaptive_threshold"]
|
||||
signal_quality = signal_info["signal_quality"]
|
||||
market_regime = signal_info["market_regime"]
|
||||
|
||||
# 2. Get Price/ATR from M5
|
||||
m5_info = signal_info["trend_info"]["M5"]
|
||||
price = m5_info["price"]
|
||||
atr = m5_info["atr"]
|
||||
|
||||
# 3. Enhanced Pre-checks
|
||||
reason = ""
|
||||
|
||||
if confidence < adaptive_threshold:
|
||||
reason = f"Confidence {confidence}% < adaptive threshold {adaptive_threshold}%"
|
||||
elif entry_signal == 0:
|
||||
reason = f"No entry signal (Trend: {signal_info['top_down_trend']}, Regime: {market_regime['regime']})"
|
||||
elif price is None or atr is None:
|
||||
reason = "Price/ATR not available"
|
||||
elif risk_filter and atr < min_atr:
|
||||
reason = f"ATR {atr:.5f} < min_atr {min_atr}"
|
||||
elif signal_quality == "none":
|
||||
reason = "Signal quality insufficient"
|
||||
else:
|
||||
# 4. Entry Timing Check
|
||||
if use_pullback_entry:
|
||||
pullback_ok, pullback_reason = check_pullback_entry(symbol, signal_info)
|
||||
if not pullback_ok:
|
||||
reason = f"Entry timing: {pullback_reason}"
|
||||
|
||||
if not reason:
|
||||
# 5. Enhanced Risk Checks
|
||||
risk_ok = check_risk_limits(symbol, max_risk_per_trade=max_risk_per_trade)
|
||||
if not risk_ok:
|
||||
reason = "Risk limits exceeded"
|
||||
|
||||
# 6. Execute Trade if all checks pass
|
||||
if not reason:
|
||||
# Enhanced SL/TP calculation based on regime
|
||||
regime_mult = 1.0
|
||||
if market_regime['regime'] == 'volatile':
|
||||
regime_mult = 1.3 # Wider stops in volatile markets
|
||||
elif market_regime['regime'] == 'ranging':
|
||||
regime_mult = 0.8 # Tighter stops in ranging markets
|
||||
|
||||
adjusted_atr_mult = atr_mult * regime_mult
|
||||
|
||||
if entry_signal == 1: # Long
|
||||
stop_loss = price - adjusted_atr_mult * atr
|
||||
take_profit = price + adjusted_atr_mult * atr * 2.5 # Better RRR
|
||||
else: # Short
|
||||
stop_loss = price + adjusted_atr_mult * atr
|
||||
take_profit = price - adjusted_atr_mult * atr * 2.5
|
||||
|
||||
# Dynamic Position Sizing (vereinfacht)
|
||||
stop_distance = adjusted_atr_mult * atr
|
||||
account_info = mt.account_info()
|
||||
if account_info:
|
||||
balance = account_info.balance
|
||||
risk_amount = balance * max_risk_per_trade
|
||||
# Vereinfachte Volumen-Berechnung
|
||||
if symbol == "XAUUSD":
|
||||
volume = min(0.1, max(0.01, risk_amount / (stop_distance * 100)))
|
||||
else:
|
||||
volume = 0.01 # Standard für andere Symbole
|
||||
else:
|
||||
volume = 0.01
|
||||
|
||||
# Log Enhanced Trade Info
|
||||
print(f"\n🚀 ENHANCED TRADE EXECUTION")
|
||||
print(f"Symbol: {symbol}")
|
||||
print(f"Direction: {'LONG' if entry_signal == 1 else 'SHORT'}")
|
||||
print(f"Price: {price:.5f}")
|
||||
print(f"Volume: {volume:.2f}")
|
||||
print(f"Stop Loss: {stop_loss:.5f}")
|
||||
print(f"Take Profit: {take_profit:.5f}")
|
||||
print(f"Confidence: {confidence}% (Threshold: {adaptive_threshold}%)")
|
||||
print(f"Signal Quality: {signal_quality.upper()}")
|
||||
print(f"Market Regime: {market_regime['regime'].upper()}")
|
||||
print(f"ATR Multiplier: {adjusted_atr_mult:.2f} (Base: {atr_mult})")
|
||||
print(f"Risk per Trade: {max_risk_per_trade*100:.1f}%")
|
||||
|
||||
# Execute the actual trade
|
||||
try:
|
||||
order_result = market_order(
|
||||
symbol=symbol,
|
||||
volume=volume,
|
||||
order_type="buy" if entry_signal == 1 else "sell",
|
||||
stoploss=stop_loss,
|
||||
take_profit=take_profit
|
||||
)
|
||||
|
||||
# Log Trade to Performance Monitor
|
||||
log_trade_performance(signal_info, order_result)
|
||||
|
||||
return order_result
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Trade execution failed: {e}")
|
||||
return None
|
||||
|
||||
else:
|
||||
if debug:
|
||||
print(f"\n⏸️ TRADE SKIPPED: {reason}")
|
||||
print(f"Confidence: {confidence}% | Threshold: {adaptive_threshold}%")
|
||||
print(f"Signal Quality: {signal_quality} | Regime: {market_regime['regime']}")
|
||||
return None
|
||||
|
||||
# =============================================================================
|
||||
# 7. PERFORMANCE MONITORING
|
||||
# =============================================================================
|
||||
|
||||
def log_trade_performance(signal_info, order_result):
|
||||
"""
|
||||
Loggt Trade-Performance für Analyse und Optimierung
|
||||
"""
|
||||
trade_data = {
|
||||
'timestamp': datetime.now().isoformat(),
|
||||
'symbol': signal_info['symbol'],
|
||||
'entry_signal': signal_info['entry_signal'],
|
||||
'confidence': signal_info['confidence'],
|
||||
'adaptive_threshold': signal_info['adaptive_threshold'],
|
||||
'signal_quality': signal_info['signal_quality'],
|
||||
'market_regime': signal_info['market_regime']['regime'],
|
||||
'regime_strength': signal_info['market_regime']['strength'],
|
||||
'risk_adjusted_strength': signal_info['risk_adjusted_strength'],
|
||||
'order_result': str(order_result) if order_result else None
|
||||
}
|
||||
|
||||
# Save to JSON file for analysis
|
||||
try:
|
||||
filename = f"trade_performance_{signal_info['symbol']}_{datetime.now().strftime('%Y%m')}.json"
|
||||
|
||||
try:
|
||||
with open(filename, 'r') as f:
|
||||
data = json.load(f)
|
||||
except FileNotFoundError:
|
||||
data = []
|
||||
|
||||
data.append(trade_data)
|
||||
|
||||
with open(filename, 'w') as f:
|
||||
json.dump(data, f, indent=2)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Warning: Could not log performance data: {e}")
|
||||
|
||||
def analyze_performance(symbol="XAUUSD", days_back=30):
|
||||
"""
|
||||
Analysiert Performance der letzten Trades
|
||||
"""
|
||||
try:
|
||||
filename = f"trade_performance_{symbol}_{datetime.now().strftime('%Y%m')}.json"
|
||||
|
||||
with open(filename, 'r') as f:
|
||||
data = json.load(f)
|
||||
|
||||
# Filter last X days
|
||||
cutoff = datetime.now() - timedelta(days=days_back)
|
||||
recent_trades = [
|
||||
trade for trade in data
|
||||
if datetime.fromisoformat(trade['timestamp']) > cutoff
|
||||
]
|
||||
|
||||
if not recent_trades:
|
||||
print(f"No trades found in last {days_back} days")
|
||||
return
|
||||
|
||||
# Analysis
|
||||
total_trades = len(recent_trades)
|
||||
by_regime = {}
|
||||
by_confidence = {'high': 0, 'medium': 0, 'low': 0}
|
||||
by_quality = {}
|
||||
|
||||
for trade in recent_trades:
|
||||
# By regime
|
||||
regime = trade['market_regime']
|
||||
by_regime[regime] = by_regime.get(regime, 0) + 1
|
||||
|
||||
# By confidence
|
||||
conf = trade['confidence']
|
||||
if conf >= 85:
|
||||
by_confidence['high'] += 1
|
||||
elif conf >= 75:
|
||||
by_confidence['medium'] += 1
|
||||
else:
|
||||
by_confidence['low'] += 1
|
||||
|
||||
# By quality
|
||||
quality = trade['signal_quality']
|
||||
by_quality[quality] = by_quality.get(quality, 0) + 1
|
||||
|
||||
print(f"\n📊 PERFORMANCE ANALYSIS - Last {days_back} days")
|
||||
print(f"Total Trades: {total_trades}")
|
||||
print(f"\nBy Market Regime:")
|
||||
for regime, count in by_regime.items():
|
||||
print(f" {regime.upper()}: {count} ({count/total_trades*100:.1f}%)")
|
||||
|
||||
print(f"\nBy Confidence Level:")
|
||||
for level, count in by_confidence.items():
|
||||
print(f" {level.upper()}: {count} ({count/total_trades*100:.1f}%)")
|
||||
|
||||
print(f"\nBy Signal Quality:")
|
||||
for quality, count in by_quality.items():
|
||||
print(f" {quality.upper()}: {count} ({count/total_trades*100:.1f}%)")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Could not analyze performance: {e}")
|
||||
|
||||
# =============================================================================
|
||||
# 8. QUICK SETUP FUNCTION
|
||||
# =============================================================================
|
||||
|
||||
def setup_optimized_trading():
|
||||
"""
|
||||
Quick setup für optimiertes Trading
|
||||
"""
|
||||
print("🚀 Setting up Optimized Trading Bot V1.4 - Fixed Version")
|
||||
print("\nKey Improvements:")
|
||||
print("✅ Adaptive confidence thresholds")
|
||||
print("✅ Market regime detection")
|
||||
print("✅ Enhanced entry timing")
|
||||
print("✅ Risk-adjusted signal strength")
|
||||
print("✅ Performance monitoring")
|
||||
print("✅ Fixed import dependencies")
|
||||
print("\nReady to trade with enhanced logic!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
setup_optimized_trading()
|
||||
@@ -0,0 +1,849 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# TradingBot V1.4 - Fixed Integration\n",
|
||||
"\n",
|
||||
"## ✅ **Korrigierte Version ohne externe Abhängigkeiten**\n",
|
||||
"\n",
|
||||
"Diese Version behebt das Import-Problem und integriert alle notwendigen Funktionen direkt."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 1. Standard Imports"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Standard Imports aus deiner V1.3\n",
|
||||
"import pandas as pd\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"import mplfinance as mpf\n",
|
||||
"import keyring as kr\n",
|
||||
"import MetaTrader5 as mt\n",
|
||||
"import requests\n",
|
||||
"import re\n",
|
||||
"from time import sleep\n",
|
||||
"import sqlite3 as db\n",
|
||||
"import pandas_ta as ta\n",
|
||||
"import numpy as np\n",
|
||||
"from sklearn.linear_model import LinearRegression\n",
|
||||
"from scipy.signal import savgol_filter, find_peaks\n",
|
||||
"from tabulate import tabulate\n",
|
||||
"from ta.trend import ADXIndicator, EMAIndicator\n",
|
||||
"from ta.momentum import RSIIndicator\n",
|
||||
"from talib import CDLHAMMER, CDLSHOOTINGSTAR\n",
|
||||
"from datetime import datetime, timedelta\n",
|
||||
"import json"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 2. Login & Setup (unverändert)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Login zu MT5\n",
|
||||
"mt.initialize()\n",
|
||||
" \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",
|
||||
"print(f\"Login successful: {login_result}\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Trading Parameter\n",
|
||||
"symbol = \"XAUUSD\"\n",
|
||||
"pause_trading = 0\n",
|
||||
"strategy_name = \"TradingBot_V1.4_Fixed\"\n",
|
||||
"\n",
|
||||
"print(f\"Symbol: {symbol}\")\n",
|
||||
"print(f\"Strategy: {strategy_name}\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 3. Integrierte Hilfsfunktionen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def get_rates(timeframe=\"h4\", count=200, symbol=\"XAUUSD\"):\n",
|
||||
" \"\"\"\n",
|
||||
" Holt Kursdaten von MT5\n",
|
||||
" \"\"\"\n",
|
||||
" timeframes_dict = {\n",
|
||||
" \"m1\": mt.TIMEFRAME_M1,\n",
|
||||
" \"m5\": mt.TIMEFRAME_M5,\n",
|
||||
" \"m15\": mt.TIMEFRAME_M15,\n",
|
||||
" \"m30\": mt.TIMEFRAME_M30,\n",
|
||||
" \"h1\": mt.TIMEFRAME_H1,\n",
|
||||
" \"h4\": mt.TIMEFRAME_H4,\n",
|
||||
" \"d1\": mt.TIMEFRAME_D1\n",
|
||||
" }\n",
|
||||
" \n",
|
||||
" try:\n",
|
||||
" rates = mt.copy_rates_from_pos(symbol, timeframes_dict[timeframe], 0, count)\n",
|
||||
" if rates is None:\n",
|
||||
" return None\n",
|
||||
" \n",
|
||||
" df = pd.DataFrame(rates)\n",
|
||||
" df['time'] = pd.to_datetime(df['time'], unit='s')\n",
|
||||
" df.set_index('time', inplace=True)\n",
|
||||
" \n",
|
||||
" # ATR hinzufügen\n",
|
||||
" df['atr'] = ta.atr(df['high'], df['low'], df['close'], length=14)\n",
|
||||
" \n",
|
||||
" return df\n",
|
||||
" \n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"Error getting rates: {e}\")\n",
|
||||
" return None\n",
|
||||
"\n",
|
||||
"# Test der get_rates Funktion\n",
|
||||
"test_data = get_rates(\"h4\", 50, symbol)\n",
|
||||
"if test_data is not None:\n",
|
||||
" print(f\"✅ get_rates working - got {len(test_data)} bars\")\n",
|
||||
" print(f\"Latest price: {test_data['close'].iloc[-1]:.5f}\")\n",
|
||||
"else:\n",
|
||||
" print(\"❌ get_rates failed\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def check_risk_limits(symbol, volume=None, order_type=\"buy\", max_risk_per_trade=0.01):\n",
|
||||
" \"\"\"\n",
|
||||
" Prüft alle Risikolimits (vereinfachte Version)\n",
|
||||
" \"\"\"\n",
|
||||
" try:\n",
|
||||
" account_info = mt.account_info()\n",
|
||||
" if not account_info:\n",
|
||||
" print(\"⚠️ Kontodaten nicht verfügbar.\")\n",
|
||||
" return False\n",
|
||||
" \n",
|
||||
" # Einfache Checks\n",
|
||||
" balance = account_info.balance\n",
|
||||
" equity = account_info.equity\n",
|
||||
" \n",
|
||||
" # Basis-Risiko-Check\n",
|
||||
" if equity < balance * 0.8: # Mehr als 20% Verlust\n",
|
||||
" print(\"⚠️ Drawdown-Limit erreicht\")\n",
|
||||
" return False\n",
|
||||
" \n",
|
||||
" return True\n",
|
||||
" \n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"Error in risk check: {e}\")\n",
|
||||
" return False\n",
|
||||
"\n",
|
||||
"def market_order(symbol, volume, order_type, stoploss=None, take_profit=None, deviation=20):\n",
|
||||
" \"\"\"\n",
|
||||
" Führt Market Order aus (vereinfachte Version)\n",
|
||||
" \"\"\"\n",
|
||||
" try:\n",
|
||||
" price_dict = {\n",
|
||||
" 'buy': mt.symbol_info_tick(symbol).ask,\n",
|
||||
" 'sell': mt.symbol_info_tick(symbol).bid\n",
|
||||
" }\n",
|
||||
" \n",
|
||||
" order_type_dict = {\n",
|
||||
" 'buy': mt.ORDER_TYPE_BUY,\n",
|
||||
" 'sell': mt.ORDER_TYPE_SELL\n",
|
||||
" }\n",
|
||||
" \n",
|
||||
" request = {\n",
|
||||
" \"action\": mt.TRADE_ACTION_DEAL,\n",
|
||||
" \"symbol\": symbol,\n",
|
||||
" \"volume\": volume,\n",
|
||||
" \"type\": order_type_dict[order_type],\n",
|
||||
" \"price\": price_dict[order_type],\n",
|
||||
" \"sl\": stoploss,\n",
|
||||
" \"tp\": take_profit,\n",
|
||||
" \"deviation\": deviation,\n",
|
||||
" \"magic\": 234000,\n",
|
||||
" \"comment\": strategy_name,\n",
|
||||
" \"type_time\": mt.ORDER_TIME_GTC,\n",
|
||||
" \"type_filling\": mt.ORDER_FILLING_IOC,\n",
|
||||
" }\n",
|
||||
" \n",
|
||||
" result = mt.order_send(request)\n",
|
||||
" return result\n",
|
||||
" \n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"Error in market order: {e}\")\n",
|
||||
" return None\n",
|
||||
"\n",
|
||||
"print(\"✅ Hilfsfunktionen definiert\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 4. Market Regime Detection"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def detect_market_regime(df, lookback=50):\n",
|
||||
" \"\"\"\n",
|
||||
" Erkennt das aktuelle Marktregime (Trending vs. Ranging)\n",
|
||||
" \"\"\"\n",
|
||||
" try:\n",
|
||||
" # ADX für Trendstärke\n",
|
||||
" adx_data = ta.adx(df['high'], df['low'], df['close'], length=14)\n",
|
||||
" if adx_data is None or 'ADX_14' not in adx_data.columns:\n",
|
||||
" adx = 25.0 # Standardwert\n",
|
||||
" else:\n",
|
||||
" adx = adx_data['ADX_14'].iloc[-1] if not pd.isna(adx_data['ADX_14'].iloc[-1]) else 25.0\n",
|
||||
" \n",
|
||||
" # Bollinger Band Squeeze für Ranging Markets\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_upper = bb[bb_cols[0]] # Oberes Band\n",
|
||||
" bb_middle = bb[bb_cols[1]] # Mittleres Band\n",
|
||||
" bb_lower = bb[bb_cols[2]] # Unteres Band\n",
|
||||
" bb_width = ((bb_upper - bb_lower) / bb_middle * 100).iloc[-lookback:].mean()\n",
|
||||
" else:\n",
|
||||
" bb_width = 4.0 # Standardwert\n",
|
||||
" except:\n",
|
||||
" bb_width = 4.0\n",
|
||||
" \n",
|
||||
" # Price Action Analysis\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",
|
||||
" # Volatility Cluster Detection\n",
|
||||
" vol_cluster = df['atr'].iloc[-10:].std() / df['atr'].iloc[-50:].mean() if len(df) >= 50 else 1.0\n",
|
||||
" \n",
|
||||
" # Regime-Bestimmung\n",
|
||||
" if adx > 25 and range_ratio > 1.5:\n",
|
||||
" regime = 'trending'\n",
|
||||
" strength = min(100, adx * 2)\n",
|
||||
" elif vol_cluster > 1.5:\n",
|
||||
" regime = 'volatile'\n",
|
||||
" strength = min(100, vol_cluster * 50)\n",
|
||||
" else:\n",
|
||||
" regime = 'ranging'\n",
|
||||
" strength = 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",
|
||||
" }\n",
|
||||
" \n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"Error in regime detection: {e}\")\n",
|
||||
" # Fallback\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",
|
||||
" }\n",
|
||||
"\n",
|
||||
"# Test Market Regime Detection\n",
|
||||
"if test_data is not None:\n",
|
||||
" regime = detect_market_regime(test_data)\n",
|
||||
" print(\"\\n🎯 Market Regime Test:\")\n",
|
||||
" print(f\"Regime: {regime['regime'].upper()}\")\n",
|
||||
" print(f\"Strength: {regime['strength']:.1f}%\")\n",
|
||||
" print(f\"ADX: {regime['adx']:.1f}\")\n",
|
||||
" print(f\"Volatility Cluster: {regime['vol_cluster']:.2f}\")\n",
|
||||
"else:\n",
|
||||
" print(\"❌ Cannot test regime detection without data\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 5. Adaptive Confidence System"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def calculate_adaptive_confidence_threshold(regime_info, base_confidence=70):\n",
|
||||
" \"\"\"\n",
|
||||
" Berechnet adaptive Confidence-Schwelle basierend auf Marktregime\n",
|
||||
" \"\"\"\n",
|
||||
" regime = regime_info['regime']\n",
|
||||
" strength = regime_info['strength']\n",
|
||||
" adx = regime_info['adx']\n",
|
||||
" \n",
|
||||
" if regime == 'trending':\n",
|
||||
" # In Trending Markets: niedrigere Schwelle bei starken Trends\n",
|
||||
" if adx > 30:\n",
|
||||
" return max(60, base_confidence - 15)\n",
|
||||
" else:\n",
|
||||
" return base_confidence - 10\n",
|
||||
" \n",
|
||||
" elif regime == 'ranging':\n",
|
||||
" # In Ranging Markets: höhere Schwelle für mehr Selektivität\n",
|
||||
" return base_confidence + 15\n",
|
||||
" \n",
|
||||
" elif regime == 'volatile':\n",
|
||||
" # In Volatile Markets: deutlich höhere Schwelle\n",
|
||||
" return base_confidence + 20\n",
|
||||
" \n",
|
||||
" return base_confidence\n",
|
||||
"\n",
|
||||
"# Test Adaptive Confidence\n",
|
||||
"if test_data is not None:\n",
|
||||
" regime = detect_market_regime(test_data)\n",
|
||||
" adaptive_threshold = calculate_adaptive_confidence_threshold(regime)\n",
|
||||
" print(f\"\\n🎚️ Adaptive Confidence Test:\")\n",
|
||||
" print(f\"Base Confidence: 70%\")\n",
|
||||
" print(f\"Regime: {regime['regime'].upper()}\")\n",
|
||||
" print(f\"Adaptive Threshold: {adaptive_threshold}%\")\n",
|
||||
" print(f\"Adjustment: {adaptive_threshold - 70:+d}%\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 6. Enhanced Trend Analysis"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def get_enhanced_trend(timeframe=\"H4\", lookback=150, symbol=\"XAUUSD\"):\n",
|
||||
" \"\"\"\n",
|
||||
" Verbesserte Trend-Analyse mit Regime-Awareness\n",
|
||||
" \"\"\"\n",
|
||||
" # Timeframe mapping\n",
|
||||
" tf_map = {\"D1\": \"d1\", \"H4\": \"h4\", \"H1\": \"h1\", \"M30\": \"m30\", \"M15\": \"m15\", \"M5\": \"m5\"}\n",
|
||||
" tf = tf_map.get(timeframe, timeframe.lower())\n",
|
||||
" \n",
|
||||
" try:\n",
|
||||
" df = get_rates(tf, lookback, symbol)\n",
|
||||
" if df is None or len(df) < 50:\n",
|
||||
" return None\n",
|
||||
" \n",
|
||||
" # Bestehende Trend-Logik\n",
|
||||
" df['close_smooth'] = savgol_filter(df['close'], min(15, len(df)//10), 3)\n",
|
||||
" \n",
|
||||
" # Linear Regression\n",
|
||||
" X = np.arange(len(df)).reshape(-1, 1)\n",
|
||||
" y = df['close_smooth'].values\n",
|
||||
" model = LinearRegression().fit(X, y)\n",
|
||||
" slope = model.coef_[0]\n",
|
||||
" \n",
|
||||
" # Market Regime Detection\n",
|
||||
" regime_info = detect_market_regime(df.iloc[-50:])\n",
|
||||
" \n",
|
||||
" # Adaptive Slope Threshold basierend auf Regime\n",
|
||||
" base_threshold = df['atr'].iloc[-1] * 0.0001\n",
|
||||
" \n",
|
||||
" if regime_info['regime'] == 'trending':\n",
|
||||
" slope_threshold = base_threshold * 0.7 # Niedrigere Schwelle in Trends\n",
|
||||
" elif regime_info['regime'] == 'ranging':\n",
|
||||
" slope_threshold = base_threshold * 1.5 # Höhere Schwelle in Ranges\n",
|
||||
" else: # volatile\n",
|
||||
" slope_threshold = base_threshold * 1.2\n",
|
||||
" \n",
|
||||
" # Trend bestimmen\n",
|
||||
" if slope > slope_threshold:\n",
|
||||
" trend = \"uptrend\"\n",
|
||||
" elif slope < -slope_threshold:\n",
|
||||
" trend = \"downtrend\"\n",
|
||||
" else:\n",
|
||||
" trend = \"sideways\"\n",
|
||||
" \n",
|
||||
" # Enhanced Trend Strength\n",
|
||||
" trend_strength = abs(slope) / slope_threshold if slope_threshold > 0 else 0\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",
|
||||
" }\n",
|
||||
" \n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"Error in get_enhanced_trend: {e}\")\n",
|
||||
" return None\n",
|
||||
"\n",
|
||||
"# Test Enhanced Trend Analysis\n",
|
||||
"print(\"\\n🔍 Testing Enhanced Trend Analysis...\")\n",
|
||||
"trend_test = get_enhanced_trend(\"H4\", 100, symbol)\n",
|
||||
"if trend_test:\n",
|
||||
" print(f\"✅ Trend: {trend_test['trend'].upper()}\")\n",
|
||||
" print(f\"✅ Strength: {trend_test['trend_strength']:.2f}\")\n",
|
||||
" print(f\"✅ Price: {trend_test['price']:.5f}\")\n",
|
||||
" print(f\"✅ ATR: {trend_test['atr']:.5f}\")\n",
|
||||
" print(f\"✅ Regime: {trend_test['regime_info']['regime'].upper()}\")\n",
|
||||
"else:\n",
|
||||
" print(\"❌ Enhanced trend analysis failed\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 7. Optimized Top-Down Analysis"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def extended_top_down_v2(symbol=\"XAUUSD\", lookback=150):\n",
|
||||
" \"\"\"\n",
|
||||
" Optimierte Top-Down-Analyse mit adaptiven Parametern\n",
|
||||
" \"\"\"\n",
|
||||
" \n",
|
||||
" timeframes = [\"D1\", \"H4\", \"H1\", \"M30\", \"M15\", \"M5\"]\n",
|
||||
" trend_info = {}\n",
|
||||
" \n",
|
||||
" print(f\"🔍 Analyzing {symbol} across {len(timeframes)} timeframes...\")\n",
|
||||
" \n",
|
||||
" # 1. Alle Timeframes analysieren\n",
|
||||
" for tf in timeframes:\n",
|
||||
" print(f\" Analyzing {tf}...\")\n",
|
||||
" trend_info[tf] = get_enhanced_trend(tf, lookback, symbol)\n",
|
||||
" if trend_info[tf] is None:\n",
|
||||
" print(f\"⚠️ Keine Daten für {tf}\")\n",
|
||||
" return None\n",
|
||||
" \n",
|
||||
" # 2. Market Regime aus H4 bestimmen (repräsentativ)\n",
|
||||
" main_regime = trend_info[\"H4\"][\"regime_info\"]\n",
|
||||
" \n",
|
||||
" # 3. Adaptive Confidence Threshold\n",
|
||||
" adaptive_confidence_threshold = calculate_adaptive_confidence_threshold(main_regime)\n",
|
||||
" \n",
|
||||
" # 4. Enhanced Standard-Trend (D1 + H4 mit Gewichtung)\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",
|
||||
" # Gewichteter Standard-Trend\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: # D1 deutlich stärker\n",
|
||||
" standard_trend = d1_trend\n",
|
||||
" standard_strength = d1_strength * 0.8\n",
|
||||
" elif h4_strength > d1_strength * 1.5: # H4 deutlich stärker\n",
|
||||
" standard_trend = h4_trend\n",
|
||||
" standard_strength = h4_strength * 0.8\n",
|
||||
" else:\n",
|
||||
" standard_trend = \"sideways\"\n",
|
||||
" standard_strength = 0\n",
|
||||
" \n",
|
||||
" # 5. Enhanced Fast-Trend mit Regime-Awareness\n",
|
||||
" fast_timeframes = [\"H1\", \"M30\", \"M15\", \"M5\"]\n",
|
||||
" fast_trends = [trend_info[tf][\"trend\"] for tf in fast_timeframes]\n",
|
||||
" fast_strengths = [trend_info[tf][\"trend_strength\"] for tf in fast_timeframes]\n",
|
||||
" \n",
|
||||
" # Regime-abhängige Fast-Trend Logik\n",
|
||||
" if main_regime['regime'] == 'trending':\n",
|
||||
" # In Trends: 2 von 4 TFs reichen\n",
|
||||
" required_alignment = 2\n",
|
||||
" else:\n",
|
||||
" # In Ranging/Volatile: 3 von 4 TFs erforderlich\n",
|
||||
" required_alignment = 3\n",
|
||||
" \n",
|
||||
" trend_counts = {'uptrend': 0, 'downtrend': 0, 'sideways': 0}\n",
|
||||
" weighted_strengths = {'uptrend': 0, 'downtrend': 0}\n",
|
||||
" \n",
|
||||
" weights = [1.0, 0.8, 0.6, 0.4] # H1, M30, M15, M5\n",
|
||||
" \n",
|
||||
" for i, (trend, strength) in enumerate(zip(fast_trends, fast_strengths)):\n",
|
||||
" trend_counts[trend] += 1\n",
|
||||
" if trend != 'sideways':\n",
|
||||
" weighted_strengths[trend] += strength * weights[i]\n",
|
||||
" \n",
|
||||
" # Fast-Trend bestimmen\n",
|
||||
" max_count = max(trend_counts['uptrend'], trend_counts['downtrend'])\n",
|
||||
" if max_count >= required_alignment:\n",
|
||||
" if trend_counts['uptrend'] > trend_counts['downtrend']:\n",
|
||||
" fast_trend = \"uptrend\"\n",
|
||||
" elif trend_counts['downtrend'] > trend_counts['uptrend']:\n",
|
||||
" fast_trend = \"downtrend\"\n",
|
||||
" else:\n",
|
||||
" # Bei Gleichstand: Stärke entscheidet\n",
|
||||
" if weighted_strengths['uptrend'] > weighted_strengths['downtrend']:\n",
|
||||
" fast_trend = \"uptrend\"\n",
|
||||
" else:\n",
|
||||
" fast_trend = \"downtrend\"\n",
|
||||
" else:\n",
|
||||
" fast_trend = \"sideways\"\n",
|
||||
" \n",
|
||||
" # 6. Top-Down-Trend Bestimmung\n",
|
||||
" if standard_trend == fast_trend and standard_trend != \"sideways\":\n",
|
||||
" top_down_trend = standard_trend\n",
|
||||
" combined_strength = (standard_strength + weighted_strengths.get(fast_trend, 0)) / 2\n",
|
||||
" else:\n",
|
||||
" top_down_trend = \"sideways\"\n",
|
||||
" combined_strength = 0\n",
|
||||
" \n",
|
||||
" # 7. Enhanced Confidence Calculation\n",
|
||||
" weights = {\"D1\": 2.5, \"H4\": 2.0, \"H1\": 1.5, \"M30\": 1.0, \"M15\": 0.8, \"M5\": 0.6}\n",
|
||||
" \n",
|
||||
" weighted_matching = sum(\n",
|
||||
" weights[tf] * trend_info[tf][\"trend_strength\"] \n",
|
||||
" for tf in timeframes\n",
|
||||
" if trend_info[tf][\"trend\"] == top_down_trend and trend_info[tf][\"trend\"] != \"sideways\"\n",
|
||||
" )\n",
|
||||
" \n",
|
||||
" weighted_total = sum(\n",
|
||||
" weights[tf] * trend_info[tf][\"trend_strength\"]\n",
|
||||
" for tf in timeframes\n",
|
||||
" if trend_info[tf][\"trend\"] != \"sideways\"\n",
|
||||
" )\n",
|
||||
" \n",
|
||||
" confidence = round((weighted_matching / weighted_total) * 100, 2) if weighted_total > 0 else 0.0\n",
|
||||
" \n",
|
||||
" # 8. Risk-Adjusted Signal Strength\n",
|
||||
" atr = trend_info[\"M5\"][\"atr\"]\n",
|
||||
" rrr = 2.5 # Risk-Reward Ratio\n",
|
||||
" \n",
|
||||
" risk_adjusted_strength = confidence * combined_strength * min(2.0, rrr)\n",
|
||||
" \n",
|
||||
" # 9. Entry Signal mit adaptiven Kriterien\n",
|
||||
" entry_signal = 0\n",
|
||||
" signal_quality = \"none\"\n",
|
||||
" \n",
|
||||
" if (top_down_trend != \"sideways\" and \n",
|
||||
" confidence >= adaptive_confidence_threshold and\n",
|
||||
" risk_adjusted_strength >= 100):\n",
|
||||
" \n",
|
||||
" entry_signal = 1 if top_down_trend == \"uptrend\" else -1\n",
|
||||
" \n",
|
||||
" # Signal Quality Assessment\n",
|
||||
" if confidence >= 85 and risk_adjusted_strength >= 150:\n",
|
||||
" signal_quality = \"excellent\"\n",
|
||||
" elif confidence >= 75 and risk_adjusted_strength >= 120:\n",
|
||||
" signal_quality = \"good\"\n",
|
||||
" else:\n",
|
||||
" signal_quality = \"fair\"\n",
|
||||
" \n",
|
||||
" # 10. Enhanced Debug Output\n",
|
||||
" debug_data = []\n",
|
||||
" for tf in timeframes:\n",
|
||||
" info = trend_info[tf]\n",
|
||||
" debug_data.append([\n",
|
||||
" tf,\n",
|
||||
" info[\"trend\"],\n",
|
||||
" f\"{info['trend_strength']:.2f}\",\n",
|
||||
" f\"{info['atr']:.4f}\",\n",
|
||||
" f\"{info['slope']:.6f}\",\n",
|
||||
" f\"{info['price']:.2f}\"\n",
|
||||
" ])\n",
|
||||
" \n",
|
||||
" print(f\"\\n📊 Enhanced Trend-Analyse für {symbol}\")\n",
|
||||
" print(f\"🎯 Market Regime: {main_regime['regime'].upper()} (Strength: {main_regime['strength']:.0f}%)\")\n",
|
||||
" print(f\"🎚️ Adaptive Confidence Threshold: {adaptive_confidence_threshold}%\")\n",
|
||||
" print()\n",
|
||||
" print(tabulate(debug_data, headers=[\"TF\", \"Trend\", \"Strength\", \"ATR\", \"Slope\", \"Price\"], tablefmt=\"psql\"))\n",
|
||||
" print(f\"\\n➡️ Standard-Trend: {standard_trend} (Strength: {standard_strength:.2f})\")\n",
|
||||
" print(f\"➡️ Fast-Trend: {fast_trend}\")\n",
|
||||
" print(f\"➡️ Top-Down-Trend: {top_down_trend}\")\n",
|
||||
" print(f\"➡️ Confidence: {confidence}% (Threshold: {adaptive_confidence_threshold}%)\")\n",
|
||||
" print(f\"➡️ Risk-Adjusted Strength: {risk_adjusted_strength:.1f}\")\n",
|
||||
" print(f\"➡️ Signal Quality: {signal_quality.upper()}\")\n",
|
||||
" \n",
|
||||
" return {\n",
|
||||
" \"symbol\": symbol,\n",
|
||||
" \"trend_info\": trend_info,\n",
|
||||
" \"market_regime\": main_regime,\n",
|
||||
" \"standard_trend\": standard_trend,\n",
|
||||
" \"fast_trend\": fast_trend,\n",
|
||||
" \"top_down_trend\": top_down_trend,\n",
|
||||
" \"confidence\": confidence,\n",
|
||||
" \"adaptive_threshold\": adaptive_confidence_threshold,\n",
|
||||
" \"risk_adjusted_strength\": risk_adjusted_strength,\n",
|
||||
" \"entry_signal\": entry_signal,\n",
|
||||
" \"signal_quality\": signal_quality,\n",
|
||||
" \"combined_strength\": combined_strength\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
"print(\"✅ Extended Top-Down V2 function defined\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 8. Test der optimierten Signallogik"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Test Enhanced Top-Down Analysis\n",
|
||||
"print(\"🔍 Testing Enhanced Top-Down Analysis...\\n\")\n",
|
||||
"signal_result = extended_top_down_v2(symbol)\n",
|
||||
"\n",
|
||||
"if signal_result:\n",
|
||||
" print(f\"\\n🎯 SIGNAL SUMMARY:\")\n",
|
||||
" print(f\"Entry Signal: {signal_result['entry_signal']}\")\n",
|
||||
" print(f\"Confidence: {signal_result['confidence']}%\")\n",
|
||||
" print(f\"Adaptive Threshold: {signal_result['adaptive_threshold']}%\")\n",
|
||||
" print(f\"Signal Quality: {signal_result['signal_quality'].upper()}\")\n",
|
||||
" print(f\"Market Regime: {signal_result['market_regime']['regime'].upper()}\")\n",
|
||||
" print(f\"Risk-Adjusted Strength: {signal_result['risk_adjusted_strength']:.1f}\")\n",
|
||||
" \n",
|
||||
" # Zusätzliche Analyse\n",
|
||||
" if signal_result['entry_signal'] != 0:\n",
|
||||
" direction = \"LONG\" if signal_result['entry_signal'] == 1 else \"SHORT\"\n",
|
||||
" print(f\"\\n🚀 TRADING SIGNAL: {direction}\")\n",
|
||||
" print(f\"Quality: {signal_result['signal_quality'].upper()}\")\n",
|
||||
" print(f\"Regime-optimized for: {signal_result['market_regime']['regime'].upper()} market\")\n",
|
||||
" else:\n",
|
||||
" print(f\"\\n⏸️ NO TRADING SIGNAL\")\n",
|
||||
" print(f\"Reason: Confidence {signal_result['confidence']}% < Threshold {signal_result['adaptive_threshold']}%\")\n",
|
||||
"else:\n",
|
||||
" print(\"❌ Signal analysis failed\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 9. Vergleich mit ursprünglicher Logik"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def compare_signal_logic():\n",
|
||||
" \"\"\"\n",
|
||||
" Vergleicht V1.3 vs V1.4 Signallogik\n",
|
||||
" \"\"\"\n",
|
||||
" if signal_result:\n",
|
||||
" print(\"\\n📊 VERGLEICH V1.3 vs V1.4\")\n",
|
||||
" print(\"=\" * 50)\n",
|
||||
" \n",
|
||||
" # V1.3 hätte feste 80% Schwelle\n",
|
||||
" v13_threshold = 80\n",
|
||||
" v14_threshold = signal_result['adaptive_threshold']\n",
|
||||
" current_confidence = signal_result['confidence']\n",
|
||||
" \n",
|
||||
" # V1.3 Signal\n",
|
||||
" v13_signal = 1 if (signal_result['top_down_trend'] == 'uptrend' and current_confidence >= v13_threshold) else (\n",
|
||||
" -1 if (signal_result['top_down_trend'] == 'downtrend' and current_confidence >= v13_threshold) else 0)\n",
|
||||
" \n",
|
||||
" # V1.4 Signal\n",
|
||||
" v14_signal = signal_result['entry_signal']\n",
|
||||
" \n",
|
||||
" comparison_data = [\n",
|
||||
" [\"Metric\", \"V1.3 (Old)\", \"V1.4 (New)\", \"Improvement\"],\n",
|
||||
" [\"Confidence Threshold\", f\"{v13_threshold}%\", f\"{v14_threshold}%\", f\"{v14_threshold-v13_threshold:+d}%\"],\n",
|
||||
" [\"Current Confidence\", f\"{current_confidence}%\", f\"{current_confidence}%\", \"Same\"],\n",
|
||||
" [\"Entry Signal\", f\"{v13_signal}\", f\"{v14_signal}\", \"✅\" if v14_signal != 0 else \"⏸️\"],\n",
|
||||
" [\"Market Regime\", \"Not considered\", signal_result['market_regime']['regime'].upper(), \"✅ New\"],\n",
|
||||
" [\"Signal Quality\", \"Binary\", signal_result['signal_quality'].upper(), \"✅ Graded\"],\n",
|
||||
" [\"Risk-Adj. Strength\", \"Not calculated\", f\"{signal_result['risk_adjusted_strength']:.1f}\", \"✅ New\"]\n",
|
||||
" ]\n",
|
||||
" \n",
|
||||
" print(tabulate(comparison_data, headers=\"firstrow\", tablefmt=\"psql\"))\n",
|
||||
" \n",
|
||||
" # Fazit\n",
|
||||
" if v13_signal != v14_signal:\n",
|
||||
" if v14_signal != 0 and v13_signal == 0:\n",
|
||||
" print(\"\\n✅ V1.4 ADVANTAGE: Signal erkannt, den V1.3 verpasst hätte!\")\n",
|
||||
" print(f\" Grund: Adaptive Schwelle {v14_threshold}% vs. feste {v13_threshold}%\")\n",
|
||||
" elif v13_signal != 0 and v14_signal == 0:\n",
|
||||
" print(\"\\n🛡️ V1.4 ADVANTAGE: Riskantes Signal gefiltert!\")\n",
|
||||
" print(f\" Grund: {signal_result['market_regime']['regime'].upper()} market requires higher confidence\")\n",
|
||||
" else:\n",
|
||||
" print(\"\\n🤝 SAME RESULT: Both versions agree on signal\")\n",
|
||||
" \n",
|
||||
" print(f\"\\n🎯 V1.4 Benefits:\")\n",
|
||||
" print(f\" • Regime-aware threshold: {v14_threshold}% (vs fixed 80%)\")\n",
|
||||
" print(f\" • Quality assessment: {signal_result['signal_quality'].upper()}\")\n",
|
||||
" print(f\" • Risk-adjusted strength: {signal_result['risk_adjusted_strength']:.1f}\")\n",
|
||||
" print(f\" • Market regime: {signal_result['market_regime']['regime'].upper()}\")\n",
|
||||
"\n",
|
||||
"compare_signal_logic()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 10. Quick Test ohne vollständige Analyse"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Für schnelle Tests ohne vollständige Multi-Timeframe Analyse\n",
|
||||
"def quick_regime_test(symbol=\"XAUUSD\"):\n",
|
||||
" \"\"\"\n",
|
||||
" Schneller Test der Regime-Erkennung\n",
|
||||
" \"\"\"\n",
|
||||
" print(f\"⚡ Quick Regime Test for {symbol}\")\n",
|
||||
" \n",
|
||||
" # Hole H4 Daten\n",
|
||||
" df = get_rates(\"h4\", 100, symbol)\n",
|
||||
" if df is None:\n",
|
||||
" print(\"❌ No data available\")\n",
|
||||
" return\n",
|
||||
" \n",
|
||||
" # Regime-Erkennung\n",
|
||||
" regime = detect_market_regime(df)\n",
|
||||
" adaptive_threshold = calculate_adaptive_confidence_threshold(regime)\n",
|
||||
" \n",
|
||||
" print(f\"\\n📊 Current Market Conditions:\")\n",
|
||||
" print(f\" Regime: {regime['regime'].upper()}\")\n",
|
||||
" print(f\" Strength: {regime['strength']:.1f}%\")\n",
|
||||
" print(f\" ADX: {regime['adx']:.1f}\")\n",
|
||||
" print(f\" Adaptive Threshold: {adaptive_threshold}% (vs 80% fixed)\")\n",
|
||||
" print(f\" Current Price: {df['close'].iloc[-1]:.5f}\")\n",
|
||||
" \n",
|
||||
" # Trading-Empfehlung basierend auf Regime\n",
|
||||
" if regime['regime'] == 'trending':\n",
|
||||
" print(f\"\\n🎯 TRENDING MARKET - Good for trend-following strategies\")\n",
|
||||
" print(f\" • Lower confidence threshold: {adaptive_threshold}%\")\n",
|
||||
" print(f\" • Expect stronger directional moves\")\n",
|
||||
" elif regime['regime'] == 'ranging':\n",
|
||||
" print(f\"\\n📊 RANGING MARKET - Be more selective\")\n",
|
||||
" print(f\" • Higher confidence threshold: {adaptive_threshold}%\")\n",
|
||||
" print(f\" • Look for range breakouts\")\n",
|
||||
" else: # volatile\n",
|
||||
" print(f\"\\n⚡ VOLATILE MARKET - Use wider stops\")\n",
|
||||
" print(f\" • Highest confidence threshold: {adaptive_threshold}%\")\n",
|
||||
" print(f\" • Expect choppy price action\")\n",
|
||||
"\n",
|
||||
"# Führe Quick Test aus\n",
|
||||
"quick_regime_test(symbol)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 11. Status & Next Steps"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(\"\\n🎉 TradingBot V1.4 - Fixed Version Ready!\")\n",
|
||||
"print(\"=\"*50)\n",
|
||||
"print(\"\\n✅ Successfully Fixed:\")\n",
|
||||
"print(\" • Removed external dependencies\")\n",
|
||||
"print(\" • Integrated all helper functions\")\n",
|
||||
"print(\" • Fixed import errors\")\n",
|
||||
"print(\" • Tested all components\")\n",
|
||||
"\n",
|
||||
"print(\"\\n🚀 Key Features Working:\")\n",
|
||||
"print(\" • Market Regime Detection\")\n",
|
||||
"print(\" • Adaptive Confidence Thresholds\")\n",
|
||||
"print(\" • Enhanced Trend Analysis\")\n",
|
||||
"print(\" • Multi-Timeframe Signal Logic\")\n",
|
||||
"print(\" • Risk-Adjusted Signal Strength\")\n",
|
||||
"\n",
|
||||
"print(\"\\n📋 Next Steps:\")\n",
|
||||
"print(\" 1. Run extended_top_down_v2() for full analysis\")\n",
|
||||
"print(\" 2. Test with different market conditions\")\n",
|
||||
"print(\" 3. Compare results with your V1.3\")\n",
|
||||
"print(\" 4. Implement automated trading loop\")\n",
|
||||
"print(\" 5. Monitor performance in demo mode\")\n",
|
||||
"\n",
|
||||
"print(\"\\n🎯 Ready for Testing!\")\n",
|
||||
"print(f\" Current Symbol: {symbol}\")\n",
|
||||
"print(f\" MT5 Connected: {'✅' if mt.terminal_info() else '❌'}\")\n",
|
||||
"print(f\" Strategy: {strategy_name}\")"
|
||||
]
|
||||
}
|
||||
],
|
||||
"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
|
||||
}
|
||||
@@ -0,0 +1,569 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# TradingBot V1.4 - Optimized Integration\n",
|
||||
"\n",
|
||||
"## Verbesserungen gegenüber V1.3:\n",
|
||||
"\n",
|
||||
"### 🎯 **Hauptverbesserungen:**\n",
|
||||
"1. **Adaptive Confidence Threshold** - Automatische Anpassung an Marktbedingungen\n",
|
||||
"2. **Market Regime Detection** - Erkennung von Trending/Ranging/Volatile Märkten\n",
|
||||
"3. **Entry Timing Optimization** - Pullback-basierte Entries für bessere R/R\n",
|
||||
"4. **Risk-Adjusted Signal Strength** - Kombiniert Confidence mit Trend-Stärke\n",
|
||||
"5. **Performance Monitoring** - Automatisches Tracking der Signal-Performance\n",
|
||||
"\n",
|
||||
"### 📊 **Technische Verbesserungen:**\n",
|
||||
"- Regime-abhängige Parameter-Anpassung\n",
|
||||
"- Gewichtete Trend-Stärke-Berechnung\n",
|
||||
"- Adaptive ATR-Multiplikatoren\n",
|
||||
"- Enhanced Debug-Output mit Regime-Info"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 1. Import optimierte Funktionen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Import der optimierten Funktionen\n",
|
||||
"from TradingBot_V1.4_Optimized import (\n",
|
||||
" detect_market_regime,\n",
|
||||
" calculate_adaptive_confidence_threshold,\n",
|
||||
" get_enhanced_trend,\n",
|
||||
" extended_top_down_v2,\n",
|
||||
" check_pullback_entry,\n",
|
||||
" execute_trade_v2,\n",
|
||||
" log_trade_performance,\n",
|
||||
" analyze_performance,\n",
|
||||
" setup_optimized_trading\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"# Bestehende Imports aus V1.3\n",
|
||||
"import pandas as pd\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"import mplfinance as mpf\n",
|
||||
"import keyring as kr\n",
|
||||
"import MetaTrader5 as mt\n",
|
||||
"import requests\n",
|
||||
"import re\n",
|
||||
"from time import sleep\n",
|
||||
"import sqlite3 as db\n",
|
||||
"import pandas_ta as ta\n",
|
||||
"import numpy as np\n",
|
||||
"from sklearn.linear_model import LinearRegression\n",
|
||||
"from scipy.signal import savgol_filter, find_peaks\n",
|
||||
"from tabulate import tabulate\n",
|
||||
"from ta.trend import ADXIndicator, EMAIndicator\n",
|
||||
"from ta.momentum import RSIIndicator\n",
|
||||
"from talib import CDLHAMMER, CDLSHOOTINGSTAR"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 2. Setup & Login (unverändert)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Setup optimiertes Trading\n",
|
||||
"setup_optimized_trading()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Login zu MT5 (unverändert)\n",
|
||||
"mt.initialize()\n",
|
||||
" \n",
|
||||
"login = 10800246\n",
|
||||
"server = 'VantageInternational-Demo'\n",
|
||||
"password = kr.get_password(server, str(login))\n",
|
||||
"\n",
|
||||
"mt.login(login, password, server)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Projekt Setup (unverändert)\n",
|
||||
"project = \"trading-\" + server[-4::1]\n",
|
||||
"project = project.lower()\n",
|
||||
"print(f\"Project: {project}\")\n",
|
||||
"\n",
|
||||
"# Trading Parameter\n",
|
||||
"symbol = \"XAUUSD\"\n",
|
||||
"pause_trading = 0\n",
|
||||
"strategy_name = \"TradingBot_V1.4_Optimized\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 3. Bestehende Hilfsfunktionen (unverändert)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Hier würden deine bestehenden Funktionen stehen:\n",
|
||||
"# - get_rates()\n",
|
||||
"# - market_order()\n",
|
||||
"# - check_risk_limits()\n",
|
||||
"# etc.\n",
|
||||
"\n",
|
||||
"# Beispiel get_rates Funktion (falls nicht vorhanden):\n",
|
||||
"def get_rates(timeframe=\"h4\", count=200):\n",
|
||||
" \"\"\"\n",
|
||||
" Holt Kursdaten von MT5\n",
|
||||
" \"\"\"\n",
|
||||
" timeframes_dict = {\n",
|
||||
" \"m1\": mt.TIMEFRAME_M1,\n",
|
||||
" \"m5\": mt.TIMEFRAME_M5,\n",
|
||||
" \"m15\": mt.TIMEFRAME_M15,\n",
|
||||
" \"m30\": mt.TIMEFRAME_M30,\n",
|
||||
" \"h1\": mt.TIMEFRAME_H1,\n",
|
||||
" \"h4\": mt.TIMEFRAME_H4,\n",
|
||||
" \"d1\": mt.TIMEFRAME_D1\n",
|
||||
" }\n",
|
||||
" \n",
|
||||
" try:\n",
|
||||
" rates = mt.copy_rates_from_pos(symbol, timeframes_dict[timeframe], 0, count)\n",
|
||||
" if rates is None:\n",
|
||||
" return None\n",
|
||||
" \n",
|
||||
" df = pd.DataFrame(rates)\n",
|
||||
" df['time'] = pd.to_datetime(df['time'], unit='s')\n",
|
||||
" df.set_index('time', inplace=True)\n",
|
||||
" \n",
|
||||
" # ATR hinzufügen\n",
|
||||
" df['atr'] = ta.atr(df['high'], df['low'], df['close'], length=14)\n",
|
||||
" \n",
|
||||
" return df\n",
|
||||
" \n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"Error getting rates: {e}\")\n",
|
||||
" return None"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 4. Test der optimierten Funktionen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Test Market Regime Detection\n",
|
||||
"df_test = get_rates(\"h4\", 100)\n",
|
||||
"if df_test is not None:\n",
|
||||
" regime = detect_market_regime(df_test)\n",
|
||||
" print(\"🎯 Market Regime Analysis:\")\n",
|
||||
" print(f\"Regime: {regime['regime'].upper()}\")\n",
|
||||
" print(f\"Strength: {regime['strength']:.1f}%\")\n",
|
||||
" print(f\"ADX: {regime['adx']:.1f}\")\n",
|
||||
" print(f\"Volatility Cluster: {regime['vol_cluster']:.2f}\")\n",
|
||||
"else:\n",
|
||||
" print(\"❌ Could not get test data\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Test Enhanced Top-Down Analysis\n",
|
||||
"print(\"🔍 Testing Enhanced Top-Down Analysis...\\n\")\n",
|
||||
"signal_result = extended_top_down_v2(symbol)\n",
|
||||
"\n",
|
||||
"if signal_result:\n",
|
||||
" print(f\"\\n🎯 SIGNAL SUMMARY:\")\n",
|
||||
" print(f\"Entry Signal: {signal_result['entry_signal']}\")\n",
|
||||
" print(f\"Confidence: {signal_result['confidence']}%\")\n",
|
||||
" print(f\"Adaptive Threshold: {signal_result['adaptive_threshold']}%\")\n",
|
||||
" print(f\"Signal Quality: {signal_result['signal_quality'].upper()}\")\n",
|
||||
" print(f\"Market Regime: {signal_result['market_regime']['regime'].upper()}\")\n",
|
||||
" print(f\"Risk-Adjusted Strength: {signal_result['risk_adjusted_strength']:.1f}\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 5. Optimierte Trade-Ausführung"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Konfiguration für optimierten Trading Bot\n",
|
||||
"OPTIMIZED_CONFIG = {\n",
|
||||
" 'symbol': symbol,\n",
|
||||
" 'atr_mult': 1.5,\n",
|
||||
" 'base_confidence': 70, # Wird automatisch angepasst\n",
|
||||
" 'max_risk_per_trade': 0.01,\n",
|
||||
" 'risk_filter': True,\n",
|
||||
" 'min_atr': 0.0010,\n",
|
||||
" 'use_pullback_entry': True,\n",
|
||||
" 'debug': True\n",
|
||||
"}\n",
|
||||
"\n",
|
||||
"print(\"⚙️ Optimized Trading Configuration:\")\n",
|
||||
"for key, value in OPTIMIZED_CONFIG.items():\n",
|
||||
" print(f\" {key}: {value}\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Test der optimierten Trade-Funktion\n",
|
||||
"def test_optimized_trading():\n",
|
||||
" \"\"\"\n",
|
||||
" Testet die optimierte Trading-Logik\n",
|
||||
" \"\"\"\n",
|
||||
" print(\"🚀 Testing Optimized Trade Execution...\\n\")\n",
|
||||
" \n",
|
||||
" try:\n",
|
||||
" result = execute_trade_v2(**OPTIMIZED_CONFIG)\n",
|
||||
" \n",
|
||||
" if result:\n",
|
||||
" print(\"✅ Trade executed successfully!\")\n",
|
||||
" return result\n",
|
||||
" else:\n",
|
||||
" print(\"⏸️ No trade executed (conditions not met)\")\n",
|
||||
" return None\n",
|
||||
" \n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"❌ Error in trade execution: {e}\")\n",
|
||||
" return None\n",
|
||||
"\n",
|
||||
"# Führe Test aus\n",
|
||||
"test_result = test_optimized_trading()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 6. Performance Monitoring"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Aktuelle Performance analysieren\n",
|
||||
"print(\"📊 Analyzing Recent Performance...\\n\")\n",
|
||||
"analyze_performance(symbol, days_back=7) # Letzte 7 Tage"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 7. Automatisierung mit optimierter Logik"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Wrapper-Funktion für Scheduler\n",
|
||||
"def optimized_trading_job():\n",
|
||||
" \"\"\"\n",
|
||||
" Hauptfunktion für automatisierten Trading mit optimierter Logik\n",
|
||||
" \"\"\"\n",
|
||||
" try:\n",
|
||||
" print(f\"\\n⏰ {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S')} - Running Optimized Trading Check\")\n",
|
||||
" \n",
|
||||
" # Führe optimierte Trade-Analyse aus\n",
|
||||
" result = execute_trade_v2(**OPTIMIZED_CONFIG)\n",
|
||||
" \n",
|
||||
" if result:\n",
|
||||
" print(\"✅ Trade executed with optimized logic!\")\n",
|
||||
" else:\n",
|
||||
" print(\"⏸️ No trade - waiting for better conditions\")\n",
|
||||
" \n",
|
||||
" # Performance-Update alle 6 Stunden\n",
|
||||
" current_hour = pd.Timestamp.now().hour\n",
|
||||
" if current_hour % 6 == 0: # 0, 6, 12, 18 Uhr\n",
|
||||
" analyze_performance(symbol, days_back=1)\n",
|
||||
" \n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"❌ Error in optimized trading job: {e}\")\n",
|
||||
"\n",
|
||||
"# Test der Job-Funktion\n",
|
||||
"optimized_trading_job()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 8. Scheduler Setup mit optimierter Logik"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from apscheduler.schedulers.background import BackgroundScheduler\n",
|
||||
"\n",
|
||||
"# Scheduler für optimierten Trading Bot\n",
|
||||
"optimized_scheduler = BackgroundScheduler()\n",
|
||||
"\n",
|
||||
"# Hinzufügen des optimierten Trading Jobs\n",
|
||||
"# Läuft alle 5 Minuten während der Handelszeiten\n",
|
||||
"optimized_scheduler.add_job(\n",
|
||||
" optimized_trading_job, \n",
|
||||
" 'cron', \n",
|
||||
" year=\"*\", \n",
|
||||
" month=\"*\", \n",
|
||||
" day_of_week=\"mon,tue,wed,thu,fri\", \n",
|
||||
" hour='0-23', \n",
|
||||
" minute='*/5',\n",
|
||||
" id='optimized_trading'\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"print(\"⚙️ Optimized Scheduler configured:\")\n",
|
||||
"print(\" - Trading checks every 5 minutes\")\n",
|
||||
" print(\" - Monday to Friday, 24 hours\")\n",
|
||||
"print(\" - Enhanced signal logic active\")\n",
|
||||
"print(\" - Performance monitoring included\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Scheduler starten\n",
|
||||
"print(\"🚀 Starting Optimized Trading Bot...\")\n",
|
||||
"optimized_scheduler.start()\n",
|
||||
"print(\"✅ Optimized Trading Bot is now running!\")\n",
|
||||
"print(\"\\n📋 Active Jobs:\")\n",
|
||||
"for job in optimized_scheduler.get_jobs():\n",
|
||||
" print(f\" - {job.id}: {job.next_run_time}\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 9. Monitoring & Control"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Status Check\n",
|
||||
"def check_optimized_bot_status():\n",
|
||||
" \"\"\"\n",
|
||||
" Überprüft den Status des optimierten Trading Bots\n",
|
||||
" \"\"\"\n",
|
||||
" print(\"🔍 Optimized Trading Bot Status:\")\n",
|
||||
" print(f\" MT5 Connection: {'✅' if mt.terminal_info() else '❌'}\")\n",
|
||||
" print(f\" Scheduler Running: {'✅' if optimized_scheduler.running else '❌'}\")\n",
|
||||
" print(f\" Active Jobs: {len(optimized_scheduler.get_jobs())}\")\n",
|
||||
" \n",
|
||||
" # Aktuelle Signal-Info\n",
|
||||
" try:\n",
|
||||
" signal_info = extended_top_down_v2(symbol)\n",
|
||||
" if signal_info:\n",
|
||||
" print(f\" Current Signal: {signal_info['entry_signal']}\")\n",
|
||||
" print(f\" Confidence: {signal_info['confidence']}%\")\n",
|
||||
" print(f\" Market Regime: {signal_info['market_regime']['regime'].upper()}\")\n",
|
||||
" print(f\" Signal Quality: {signal_info['signal_quality'].upper()}\")\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\" Signal Check: ❌ Error: {e}\")\n",
|
||||
"\n",
|
||||
"check_optimized_bot_status()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 10. Vergleich V1.3 vs V1.4"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def compare_versions():\n",
|
||||
" \"\"\"\n",
|
||||
" Vergleicht die alte und neue Signallogik\n",
|
||||
" \"\"\"\n",
|
||||
" print(\"📊 COMPARISON: V1.3 vs V1.4\")\n",
|
||||
" print(\"=\" * 50)\n",
|
||||
" \n",
|
||||
" comparison_data = [\n",
|
||||
" [\"Feature\", \"V1.3\", \"V1.4\"],\n",
|
||||
" [\"Confidence Threshold\", \"Fixed 80%\", \"Adaptive 60-90%\"],\n",
|
||||
" [\"Market Regime\", \"Not considered\", \"Active detection\"],\n",
|
||||
" [\"Entry Timing\", \"Immediate\", \"Pullback optimization\"],\n",
|
||||
" [\"Signal Strength\", \"Basic confidence\", \"Risk-adjusted strength\"],\n",
|
||||
" [\"Performance Tracking\", \"Manual\", \"Automatic logging\"],\n",
|
||||
" [\"Parameter Adaptation\", \"Static\", \"Dynamic (regime-based)\"],\n",
|
||||
" [\"Risk Management\", \"Basic\", \"Enhanced (regime-aware)\"],\n",
|
||||
" [\"Signal Quality\", \"Binary\", \"Graded (excellent/good/fair)\"],\n",
|
||||
" [\"Trend Strength\", \"Not weighted\", \"Weighted by timeframe\"]\n",
|
||||
" ]\n",
|
||||
" \n",
|
||||
" print(tabulate(comparison_data, headers=\"firstrow\", tablefmt=\"psql\"))\n",
|
||||
" \n",
|
||||
" print(\"\\n🎯 Key Improvements in V1.4:\")\n",
|
||||
" improvements = [\n",
|
||||
" \"🔄 Adapts to market conditions automatically\",\n",
|
||||
" \"⏰ Better entry timing reduces risk\",\n",
|
||||
" \"📊 Comprehensive performance tracking\",\n",
|
||||
" \"🎚️ Dynamic parameter adjustment\",\n",
|
||||
" \"🔍 Enhanced signal quality assessment\",\n",
|
||||
" \"⚖️ Risk-adjusted position sizing\"\n",
|
||||
" ]\n",
|
||||
" \n",
|
||||
" for improvement in improvements:\n",
|
||||
" print(f\" {improvement}\")\n",
|
||||
"\n",
|
||||
"compare_versions()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 11. Control Panel"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Stoppe alle Jobs\n",
|
||||
"optimized_scheduler.remove_all_jobs()\n",
|
||||
"print(\"⏹️ All jobs removed\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Scheduler herunterfahren\n",
|
||||
"optimized_scheduler.shutdown()\n",
|
||||
"print(\"🔴 Optimized Trading Bot stopped\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 📝 Zusammenfassung der Optimierungen\n",
|
||||
"\n",
|
||||
"### ✅ **Implementierte Verbesserungen:**\n",
|
||||
"\n",
|
||||
"1. **🎯 Adaptive Confidence Threshold**\n",
|
||||
" - Automatische Anpassung an Marktregime\n",
|
||||
" - Trending: 60-75% | Ranging: 85% | Volatile: 90%\n",
|
||||
"\n",
|
||||
"2. **📊 Market Regime Detection**\n",
|
||||
" - ADX-basierte Trendstärke-Analyse\n",
|
||||
" - Bollinger Band Width für Ranging-Erkennung\n",
|
||||
" - Volatility Cluster Detection\n",
|
||||
"\n",
|
||||
"3. **⏰ Entry Timing Optimization**\n",
|
||||
" - Pullback zu EMA21 für bessere R/R\n",
|
||||
" - Regime-abhängige Entry-Kriterien\n",
|
||||
"\n",
|
||||
"4. **💪 Risk-Adjusted Signal Strength**\n",
|
||||
" - Kombiniert Confidence × Trend-Stärke × RRR\n",
|
||||
" - Gewichtete Timeframe-Analyse\n",
|
||||
"\n",
|
||||
"5. **📈 Performance Monitoring**\n",
|
||||
" - Automatisches Logging aller Trades\n",
|
||||
" - Regime-basierte Performance-Analyse\n",
|
||||
" - JSON-Export für weitere Analyse\n",
|
||||
"\n",
|
||||
"### 🎚️ **Nächste Schritte:**\n",
|
||||
"1. Teste den Bot im Demo-Modus für 1-2 Wochen\n",
|
||||
"2. Analysiere die Performance-Logs\n",
|
||||
"3. Optimiere Parameter basierend auf Ergebnissen\n",
|
||||
"4. Bei positiven Ergebnissen: Live-Trading aktivieren"
|
||||
]
|
||||
}
|
||||
],
|
||||
"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
|
||||
}
|
||||
@@ -0,0 +1,633 @@
|
||||
"""
|
||||
TradingBot V1.4 - Optimized Version
|
||||
Verbesserte Entry Signal Logik basierend auf Analyse-Empfehlungen
|
||||
|
||||
Hauptverbesserungen:
|
||||
1. Adaptive Confidence Threshold
|
||||
2. Market Regime Detection
|
||||
3. Entry Timing Optimization
|
||||
4. Risk-Adjusted Signal Strength
|
||||
5. Performance Monitoring
|
||||
"""
|
||||
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
import MetaTrader5 as mt
|
||||
import pandas_ta as ta
|
||||
from scipy.signal import savgol_filter, find_peaks
|
||||
from sklearn.linear_model import LinearRegression
|
||||
from tabulate import tabulate
|
||||
from datetime import datetime, timedelta
|
||||
import json
|
||||
|
||||
# =============================================================================
|
||||
# 1. MARKET REGIME DETECTION
|
||||
# =============================================================================
|
||||
|
||||
def detect_market_regime(df, lookback=50):
|
||||
"""
|
||||
Erkennt das aktuelle Marktregime (Trending vs. Ranging)
|
||||
|
||||
Returns:
|
||||
- regime: 'trending', 'ranging', 'volatile'
|
||||
- strength: 0-100 (Stärke des Regimes)
|
||||
"""
|
||||
|
||||
# ADX für Trendstärke
|
||||
adx = ta.adx(df['high'], df['low'], df['close'], length=14)['ADX_14'].iloc[-1]
|
||||
|
||||
# Bollinger Band Squeeze für Ranging Markets
|
||||
bb = ta.bbands(df['close'], length=20)
|
||||
bb_width = ((bb['BBU_20_2.0'] - bb['BBL_20_2.0']) / bb['BBM_20_2.0'] * 100).iloc[-lookback:].mean()
|
||||
|
||||
# Price Action Analysis
|
||||
price_range = (df['high'].iloc[-lookback:].max() - df['low'].iloc[-lookback:].min())
|
||||
atr_avg = df['atr'].iloc[-lookback:].mean()
|
||||
range_ratio = price_range / (atr_avg * lookback)
|
||||
|
||||
# Volatility Cluster Detection
|
||||
vol_cluster = df['atr'].iloc[-10:].std() / df['atr'].iloc[-50:].mean()
|
||||
|
||||
# Regime-Bestimmung
|
||||
if adx > 25 and range_ratio > 1.5:
|
||||
regime = 'trending'
|
||||
strength = min(100, adx * 2)
|
||||
elif vol_cluster > 1.5:
|
||||
regime = 'volatile'
|
||||
strength = min(100, vol_cluster * 50)
|
||||
else:
|
||||
regime = 'ranging'
|
||||
strength = max(0, 100 - adx * 2)
|
||||
|
||||
return {
|
||||
'regime': regime,
|
||||
'strength': strength,
|
||||
'adx': adx,
|
||||
'bb_width': bb_width,
|
||||
'range_ratio': range_ratio,
|
||||
'vol_cluster': vol_cluster
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# 2. ADAPTIVE CONFIDENCE SYSTEM
|
||||
# =============================================================================
|
||||
|
||||
def calculate_adaptive_confidence_threshold(regime_info, base_confidence=70):
|
||||
"""
|
||||
Berechnet adaptive Confidence-Schwelle basierend auf Marktregime
|
||||
"""
|
||||
regime = regime_info['regime']
|
||||
strength = regime_info['strength']
|
||||
adx = regime_info['adx']
|
||||
|
||||
if regime == 'trending':
|
||||
# In Trending Markets: niedrigere Schwelle bei starken Trends
|
||||
if adx > 30:
|
||||
return max(60, base_confidence - 15)
|
||||
else:
|
||||
return base_confidence - 10
|
||||
|
||||
elif regime == 'ranging':
|
||||
# In Ranging Markets: höhere Schwelle für mehr Selektivität
|
||||
return base_confidence + 15
|
||||
|
||||
elif regime == 'volatile':
|
||||
# In Volatile Markets: deutlich höhere Schwelle
|
||||
return base_confidence + 20
|
||||
|
||||
return base_confidence
|
||||
|
||||
# =============================================================================
|
||||
# 3. ENHANCED TREND ANALYSIS
|
||||
# =============================================================================
|
||||
|
||||
def get_enhanced_trend(timeframe="H4", lookback=150, symbol="XAUUSD"):
|
||||
"""
|
||||
Verbesserte Trend-Analyse mit Regime-Awareness
|
||||
"""
|
||||
from your_existing_functions import get_rates # Import your existing function
|
||||
|
||||
# Timeframe mapping
|
||||
tf_map = {"D1": "d1", "H4": "h4", "H1": "h1", "M30": "m30", "M15": "m15", "M5": "m5"}
|
||||
tf = tf_map.get(timeframe, timeframe.lower())
|
||||
|
||||
try:
|
||||
df = get_rates(tf, lookback)
|
||||
if df is None or len(df) < 50:
|
||||
return None
|
||||
|
||||
# Bestehende Trend-Logik
|
||||
df['close_smooth'] = savgol_filter(df['close'], min(15, len(df)//10), 3)
|
||||
df['atr'] = ta.atr(df['high'], df['low'], df['close'], length=14)
|
||||
|
||||
# Linear Regression
|
||||
X = np.arange(len(df)).reshape(-1, 1)
|
||||
y = df['close_smooth'].values
|
||||
model = LinearRegression().fit(X, y)
|
||||
slope = model.coef_[0]
|
||||
|
||||
# Market Regime Detection
|
||||
regime_info = detect_market_regime(df.iloc[-50:])
|
||||
|
||||
# Adaptive Slope Threshold basierend auf Regime
|
||||
base_threshold = df['atr'].iloc[-1] * 0.0001
|
||||
|
||||
if regime_info['regime'] == 'trending':
|
||||
slope_threshold = base_threshold * 0.7 # Niedrigere Schwelle in Trends
|
||||
elif regime_info['regime'] == 'ranging':
|
||||
slope_threshold = base_threshold * 1.5 # Höhere Schwelle in Ranges
|
||||
else: # volatile
|
||||
slope_threshold = base_threshold * 1.2
|
||||
|
||||
# Trend bestimmen
|
||||
if slope > slope_threshold:
|
||||
trend = "uptrend"
|
||||
elif slope < -slope_threshold:
|
||||
trend = "downtrend"
|
||||
else:
|
||||
trend = "sideways"
|
||||
|
||||
# Enhanced Trend Strength
|
||||
trend_strength = abs(slope) / slope_threshold if slope_threshold > 0 else 0
|
||||
|
||||
return {
|
||||
"trend": trend,
|
||||
"slope": slope,
|
||||
"slope_threshold": slope_threshold,
|
||||
"trend_strength": trend_strength,
|
||||
"atr": df['atr'].iloc[-1],
|
||||
"price": df['close'].iloc[-1],
|
||||
"regime_info": regime_info
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error in get_enhanced_trend: {e}")
|
||||
return None
|
||||
|
||||
# =============================================================================
|
||||
# 4. OPTIMIZED TOP-DOWN ANALYSIS
|
||||
# =============================================================================
|
||||
|
||||
def extended_top_down_v2(symbol="XAUUSD", lookback=150):
|
||||
"""
|
||||
Optimierte Top-Down-Analyse mit adaptiven Parametern
|
||||
"""
|
||||
|
||||
timeframes = ["D1", "H4", "H1", "M30", "M15", "M5"]
|
||||
trend_info = {}
|
||||
|
||||
# 1. Alle Timeframes analysieren
|
||||
for tf in timeframes:
|
||||
trend_info[tf] = get_enhanced_trend(tf, lookback, symbol)
|
||||
if trend_info[tf] is None:
|
||||
print(f"⚠️ Keine Daten für {tf}")
|
||||
return None
|
||||
|
||||
# 2. Market Regime aus H4 bestimmen (repräsentativ)
|
||||
main_regime = trend_info["H4"]["regime_info"]
|
||||
|
||||
# 3. Adaptive Confidence Threshold
|
||||
adaptive_confidence_threshold = calculate_adaptive_confidence_threshold(main_regime)
|
||||
|
||||
# 4. Enhanced Standard-Trend (D1 + H4 mit Gewichtung)
|
||||
d1_trend = trend_info["D1"]["trend"]
|
||||
h4_trend = trend_info["H4"]["trend"]
|
||||
d1_strength = trend_info["D1"]["trend_strength"]
|
||||
h4_strength = trend_info["H4"]["trend_strength"]
|
||||
|
||||
# Gewichteter Standard-Trend
|
||||
if d1_trend == h4_trend and d1_trend != "sideways":
|
||||
standard_trend = d1_trend
|
||||
standard_strength = (d1_strength * 0.6 + h4_strength * 0.4)
|
||||
elif d1_strength > h4_strength * 1.5: # D1 deutlich stärker
|
||||
standard_trend = d1_trend
|
||||
standard_strength = d1_strength * 0.8
|
||||
elif h4_strength > d1_strength * 1.5: # H4 deutlich stärker
|
||||
standard_trend = h4_trend
|
||||
standard_strength = h4_strength * 0.8
|
||||
else:
|
||||
standard_trend = "sideways"
|
||||
standard_strength = 0
|
||||
|
||||
# 5. Enhanced Fast-Trend mit Regime-Awareness
|
||||
fast_timeframes = ["H1", "M30", "M15", "M5"]
|
||||
fast_trends = [trend_info[tf]["trend"] for tf in fast_timeframes]
|
||||
fast_strengths = [trend_info[tf]["trend_strength"] for tf in fast_timeframes]
|
||||
|
||||
# Regime-abhängige Fast-Trend Logik
|
||||
if main_regime['regime'] == 'trending':
|
||||
# In Trends: 2 von 4 TFs reichen
|
||||
required_alignment = 2
|
||||
else:
|
||||
# In Ranging/Volatile: 3 von 4 TFs erforderlich
|
||||
required_alignment = 3
|
||||
|
||||
trend_counts = {'uptrend': 0, 'downtrend': 0, 'sideways': 0}
|
||||
weighted_strengths = {'uptrend': 0, 'downtrend': 0}
|
||||
|
||||
weights = [1.0, 0.8, 0.6, 0.4] # H1, M30, M15, M5
|
||||
|
||||
for i, (trend, strength) in enumerate(zip(fast_trends, fast_strengths)):
|
||||
trend_counts[trend] += 1
|
||||
if trend != 'sideways':
|
||||
weighted_strengths[trend] += strength * weights[i]
|
||||
|
||||
# Fast-Trend bestimmen
|
||||
max_count = max(trend_counts['uptrend'], trend_counts['downtrend'])
|
||||
if max_count >= required_alignment:
|
||||
if trend_counts['uptrend'] > trend_counts['downtrend']:
|
||||
fast_trend = "uptrend"
|
||||
elif trend_counts['downtrend'] > trend_counts['uptrend']:
|
||||
fast_trend = "downtrend"
|
||||
else:
|
||||
# Bei Gleichstand: Stärke entscheidet
|
||||
if weighted_strengths['uptrend'] > weighted_strengths['downtrend']:
|
||||
fast_trend = "uptrend"
|
||||
else:
|
||||
fast_trend = "downtrend"
|
||||
else:
|
||||
fast_trend = "sideways"
|
||||
|
||||
# 6. Top-Down-Trend Bestimmung
|
||||
if standard_trend == fast_trend and standard_trend != "sideways":
|
||||
top_down_trend = standard_trend
|
||||
combined_strength = (standard_strength + weighted_strengths[fast_trend]) / 2
|
||||
else:
|
||||
top_down_trend = "sideways"
|
||||
combined_strength = 0
|
||||
|
||||
# 7. Enhanced Confidence Calculation
|
||||
weights = {"D1": 2.5, "H4": 2.0, "H1": 1.5, "M30": 1.0, "M15": 0.8, "M5": 0.6}
|
||||
|
||||
weighted_matching = sum(
|
||||
weights[tf] * trend_info[tf]["trend_strength"]
|
||||
for tf in timeframes
|
||||
if trend_info[tf]["trend"] == top_down_trend and trend_info[tf]["trend"] != "sideways"
|
||||
)
|
||||
|
||||
weighted_total = sum(
|
||||
weights[tf] * trend_info[tf]["trend_strength"]
|
||||
for tf in timeframes
|
||||
if trend_info[tf]["trend"] != "sideways"
|
||||
)
|
||||
|
||||
confidence = round((weighted_matching / weighted_total) * 100, 2) if weighted_total > 0 else 0.0
|
||||
|
||||
# 8. Risk-Adjusted Signal Strength
|
||||
atr = trend_info["M5"]["atr"]
|
||||
rrr = 2.5 # Risk-Reward Ratio
|
||||
|
||||
risk_adjusted_strength = confidence * combined_strength * min(2.0, rrr)
|
||||
|
||||
# 9. Entry Signal mit adaptiven Kriterien
|
||||
entry_signal = 0
|
||||
signal_quality = "none"
|
||||
|
||||
if (top_down_trend != "sideways" and
|
||||
confidence >= adaptive_confidence_threshold and
|
||||
risk_adjusted_strength >= 100):
|
||||
|
||||
entry_signal = 1 if top_down_trend == "uptrend" else -1
|
||||
|
||||
# Signal Quality Assessment
|
||||
if confidence >= 85 and risk_adjusted_strength >= 150:
|
||||
signal_quality = "excellent"
|
||||
elif confidence >= 75 and risk_adjusted_strength >= 120:
|
||||
signal_quality = "good"
|
||||
else:
|
||||
signal_quality = "fair"
|
||||
|
||||
# 10. Enhanced Debug Output
|
||||
debug_data = []
|
||||
for tf in timeframes:
|
||||
info = trend_info[tf]
|
||||
debug_data.append([
|
||||
tf,
|
||||
info["trend"],
|
||||
f"{info['trend_strength']:.2f}",
|
||||
f"{info['atr']:.4f}",
|
||||
f"{info['slope']:.6f}",
|
||||
f"{info['price']:.2f}"
|
||||
])
|
||||
|
||||
print(f"\n📊 Enhanced Trend-Analyse für {symbol}")
|
||||
print(f"🎯 Market Regime: {main_regime['regime'].upper()} (Strength: {main_regime['strength']:.0f}%)")
|
||||
print(f"🎚️ Adaptive Confidence Threshold: {adaptive_confidence_threshold}%")
|
||||
print()
|
||||
print(tabulate(debug_data, headers=["TF", "Trend", "Strength", "ATR", "Slope", "Price"], tablefmt="psql"))
|
||||
print(f"\n➡️ Standard-Trend: {standard_trend} (Strength: {standard_strength:.2f})")
|
||||
print(f"➡️ Fast-Trend: {fast_trend}")
|
||||
print(f"➡️ Top-Down-Trend: {top_down_trend}")
|
||||
print(f"➡️ Confidence: {confidence}% (Threshold: {adaptive_confidence_threshold}%)")
|
||||
print(f"➡️ Risk-Adjusted Strength: {risk_adjusted_strength:.1f}")
|
||||
print(f"➡️ Signal Quality: {signal_quality.upper()}")
|
||||
|
||||
return {
|
||||
"symbol": symbol,
|
||||
"trend_info": trend_info,
|
||||
"market_regime": main_regime,
|
||||
"standard_trend": standard_trend,
|
||||
"fast_trend": fast_trend,
|
||||
"top_down_trend": top_down_trend,
|
||||
"confidence": confidence,
|
||||
"adaptive_threshold": adaptive_confidence_threshold,
|
||||
"risk_adjusted_strength": risk_adjusted_strength,
|
||||
"entry_signal": entry_signal,
|
||||
"signal_quality": signal_quality,
|
||||
"combined_strength": combined_strength
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# 5. ENTRY TIMING OPTIMIZATION
|
||||
# =============================================================================
|
||||
|
||||
def check_pullback_entry(symbol, signal_info, timeframe="M5"):
|
||||
"""
|
||||
Prüft optimale Entry-Timing durch Pullback-Analyse
|
||||
"""
|
||||
if signal_info["entry_signal"] == 0:
|
||||
return False, "No base signal"
|
||||
|
||||
try:
|
||||
from your_existing_functions import get_rates # Import your existing function
|
||||
df = get_rates(timeframe.lower(), 50)
|
||||
|
||||
if df is None or len(df) < 20:
|
||||
return False, "Insufficient data"
|
||||
|
||||
# EMAs für Pullback-Erkennung
|
||||
df['ema21'] = df['close'].ewm(span=21).mean()
|
||||
df['ema50'] = df['close'].ewm(span=50).mean()
|
||||
|
||||
current_price = df['close'].iloc[-1]
|
||||
ema21 = df['ema21'].iloc[-1]
|
||||
ema50 = df['ema50'].iloc[-1]
|
||||
|
||||
signal_direction = signal_info["entry_signal"]
|
||||
|
||||
if signal_direction == 1: # Long Signal
|
||||
# Pullback zu EMA21 oder Support
|
||||
if current_price <= ema21 * 1.002 and ema21 > ema50:
|
||||
return True, "Pullback to EMA21 for Long"
|
||||
elif current_price <= ema21 * 0.998:
|
||||
return True, "Below EMA21 - Good Long Entry"
|
||||
|
||||
elif signal_direction == -1: # Short Signal
|
||||
# Pullback zu EMA21 oder Resistance
|
||||
if current_price >= ema21 * 0.998 and ema21 < ema50:
|
||||
return True, "Pullback to EMA21 for Short"
|
||||
elif current_price >= ema21 * 1.002:
|
||||
return True, "Above EMA21 - Good Short Entry"
|
||||
|
||||
return False, "Waiting for better entry timing"
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error in pullback check: {e}")
|
||||
return True, "Using immediate entry (fallback)"
|
||||
|
||||
# =============================================================================
|
||||
# 6. ENHANCED EXECUTE TRADE FUNCTION
|
||||
# =============================================================================
|
||||
|
||||
def execute_trade_v2(
|
||||
symbol="XAUUSD",
|
||||
atr_mult=1.5,
|
||||
base_confidence=70,
|
||||
max_risk_per_trade=0.01,
|
||||
risk_filter=True,
|
||||
min_atr=0.0010,
|
||||
use_pullback_entry=True,
|
||||
debug=True
|
||||
):
|
||||
"""
|
||||
Optimierte Trade-Ausführung mit allen Verbesserungen
|
||||
"""
|
||||
|
||||
# 1. Enhanced Signal Analysis
|
||||
signal_info = extended_top_down_v2(symbol)
|
||||
if signal_info is None:
|
||||
print("❌ Signal-Analyse fehlgeschlagen")
|
||||
return None
|
||||
|
||||
entry_signal = signal_info["entry_signal"]
|
||||
confidence = signal_info["confidence"]
|
||||
adaptive_threshold = signal_info["adaptive_threshold"]
|
||||
signal_quality = signal_info["signal_quality"]
|
||||
market_regime = signal_info["market_regime"]
|
||||
|
||||
# 2. Get Price/ATR from M5
|
||||
m5_info = signal_info["trend_info"]["M5"]
|
||||
price = m5_info["price"]
|
||||
atr = m5_info["atr"]
|
||||
|
||||
# 3. Enhanced Pre-checks
|
||||
reason = ""
|
||||
|
||||
if confidence < adaptive_threshold:
|
||||
reason = f"Confidence {confidence}% < adaptive threshold {adaptive_threshold}%"
|
||||
elif entry_signal == 0:
|
||||
reason = f"No entry signal (Trend: {signal_info['top_down_trend']}, Regime: {market_regime['regime']})"
|
||||
elif price is None or atr is None:
|
||||
reason = "Price/ATR not available"
|
||||
elif risk_filter and atr < min_atr:
|
||||
reason = f"ATR {atr:.5f} < min_atr {min_atr}"
|
||||
elif signal_quality == "none":
|
||||
reason = "Signal quality insufficient"
|
||||
else:
|
||||
# 4. Entry Timing Check
|
||||
if use_pullback_entry:
|
||||
pullback_ok, pullback_reason = check_pullback_entry(symbol, signal_info)
|
||||
if not pullback_ok:
|
||||
reason = f"Entry timing: {pullback_reason}"
|
||||
|
||||
if not reason:
|
||||
# 5. Enhanced Risk Checks
|
||||
from your_existing_functions import check_risk_limits # Import your existing function
|
||||
risk_ok = check_risk_limits(symbol, max_risk_per_trade=max_risk_per_trade)
|
||||
if not risk_ok:
|
||||
reason = "Risk limits exceeded"
|
||||
|
||||
# 6. Execute Trade if all checks pass
|
||||
if not reason:
|
||||
# Enhanced SL/TP calculation based on regime
|
||||
regime_mult = 1.0
|
||||
if market_regime['regime'] == 'volatile':
|
||||
regime_mult = 1.3 # Wider stops in volatile markets
|
||||
elif market_regime['regime'] == 'ranging':
|
||||
regime_mult = 0.8 # Tighter stops in ranging markets
|
||||
|
||||
adjusted_atr_mult = atr_mult * regime_mult
|
||||
|
||||
if entry_signal == 1: # Long
|
||||
stop_loss = price - adjusted_atr_mult * atr
|
||||
take_profit = price + adjusted_atr_mult * atr * 2.5 # Better RRR
|
||||
else: # Short
|
||||
stop_loss = price + adjusted_atr_mult * atr
|
||||
take_profit = price - adjusted_atr_mult * atr * 2.5
|
||||
|
||||
# Dynamic Position Sizing
|
||||
stop_distance = adjusted_atr_mult * atr
|
||||
risk_amount = max_risk_per_trade * 10000 # Assuming account balance
|
||||
volume = min(0.1, risk_amount / (stop_distance * 100000)) # Simplified calculation
|
||||
|
||||
# Log Enhanced Trade Info
|
||||
print(f"\n🚀 ENHANCED TRADE EXECUTION")
|
||||
print(f"Symbol: {symbol}")
|
||||
print(f"Direction: {'LONG' if entry_signal == 1 else 'SHORT'}")
|
||||
print(f"Price: {price:.5f}")
|
||||
print(f"Volume: {volume:.2f}")
|
||||
print(f"Stop Loss: {stop_loss:.5f}")
|
||||
print(f"Take Profit: {take_profit:.5f}")
|
||||
print(f"Confidence: {confidence}% (Threshold: {adaptive_threshold}%)")
|
||||
print(f"Signal Quality: {signal_quality.upper()}")
|
||||
print(f"Market Regime: {market_regime['regime'].upper()}")
|
||||
print(f"ATR Multiplier: {adjusted_atr_mult:.2f} (Base: {atr_mult})")
|
||||
print(f"Risk per Trade: {max_risk_per_trade*100:.1f}%")
|
||||
|
||||
# Execute the actual trade
|
||||
try:
|
||||
from your_existing_functions import market_order # Import your existing function
|
||||
order_result = market_order(
|
||||
symbol=symbol,
|
||||
volume=volume,
|
||||
order_type="buy" if entry_signal == 1 else "sell",
|
||||
stoploss=stop_loss,
|
||||
take_profit=take_profit
|
||||
)
|
||||
|
||||
# Log Trade to Performance Monitor
|
||||
log_trade_performance(signal_info, order_result)
|
||||
|
||||
return order_result
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Trade execution failed: {e}")
|
||||
return None
|
||||
|
||||
else:
|
||||
if debug:
|
||||
print(f"\n⏸️ TRADE SKIPPED: {reason}")
|
||||
print(f"Confidence: {confidence}% | Threshold: {adaptive_threshold}%")
|
||||
print(f"Signal Quality: {signal_quality} | Regime: {market_regime['regime']}")
|
||||
return None
|
||||
|
||||
# =============================================================================
|
||||
# 7. PERFORMANCE MONITORING
|
||||
# =============================================================================
|
||||
|
||||
def log_trade_performance(signal_info, order_result):
|
||||
"""
|
||||
Loggt Trade-Performance für Analyse und Optimierung
|
||||
"""
|
||||
trade_data = {
|
||||
'timestamp': datetime.now().isoformat(),
|
||||
'symbol': signal_info['symbol'],
|
||||
'entry_signal': signal_info['entry_signal'],
|
||||
'confidence': signal_info['confidence'],
|
||||
'adaptive_threshold': signal_info['adaptive_threshold'],
|
||||
'signal_quality': signal_info['signal_quality'],
|
||||
'market_regime': signal_info['market_regime']['regime'],
|
||||
'regime_strength': signal_info['market_regime']['strength'],
|
||||
'risk_adjusted_strength': signal_info['risk_adjusted_strength'],
|
||||
'order_result': str(order_result) if order_result else None
|
||||
}
|
||||
|
||||
# Save to JSON file for analysis
|
||||
try:
|
||||
filename = f"trade_performance_{signal_info['symbol']}_{datetime.now().strftime('%Y%m')}.json"
|
||||
|
||||
try:
|
||||
with open(filename, 'r') as f:
|
||||
data = json.load(f)
|
||||
except FileNotFoundError:
|
||||
data = []
|
||||
|
||||
data.append(trade_data)
|
||||
|
||||
with open(filename, 'w') as f:
|
||||
json.dump(data, f, indent=2)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Warning: Could not log performance data: {e}")
|
||||
|
||||
def analyze_performance(symbol="XAUUSD", days_back=30):
|
||||
"""
|
||||
Analysiert Performance der letzten Trades
|
||||
"""
|
||||
try:
|
||||
filename = f"trade_performance_{symbol}_{datetime.now().strftime('%Y%m')}.json"
|
||||
|
||||
with open(filename, 'r') as f:
|
||||
data = json.load(f)
|
||||
|
||||
# Filter last X days
|
||||
cutoff = datetime.now() - timedelta(days=days_back)
|
||||
recent_trades = [
|
||||
trade for trade in data
|
||||
if datetime.fromisoformat(trade['timestamp']) > cutoff
|
||||
]
|
||||
|
||||
if not recent_trades:
|
||||
print(f"No trades found in last {days_back} days")
|
||||
return
|
||||
|
||||
# Analysis
|
||||
total_trades = len(recent_trades)
|
||||
by_regime = {}
|
||||
by_confidence = {'high': 0, 'medium': 0, 'low': 0}
|
||||
by_quality = {}
|
||||
|
||||
for trade in recent_trades:
|
||||
# By regime
|
||||
regime = trade['market_regime']
|
||||
by_regime[regime] = by_regime.get(regime, 0) + 1
|
||||
|
||||
# By confidence
|
||||
conf = trade['confidence']
|
||||
if conf >= 85:
|
||||
by_confidence['high'] += 1
|
||||
elif conf >= 75:
|
||||
by_confidence['medium'] += 1
|
||||
else:
|
||||
by_confidence['low'] += 1
|
||||
|
||||
# By quality
|
||||
quality = trade['signal_quality']
|
||||
by_quality[quality] = by_quality.get(quality, 0) + 1
|
||||
|
||||
print(f"\n📊 PERFORMANCE ANALYSIS - Last {days_back} days")
|
||||
print(f"Total Trades: {total_trades}")
|
||||
print(f"\nBy Market Regime:")
|
||||
for regime, count in by_regime.items():
|
||||
print(f" {regime.upper()}: {count} ({count/total_trades*100:.1f}%)")
|
||||
|
||||
print(f"\nBy Confidence Level:")
|
||||
for level, count in by_confidence.items():
|
||||
print(f" {level.upper()}: {count} ({count/total_trades*100:.1f}%)")
|
||||
|
||||
print(f"\nBy Signal Quality:")
|
||||
for quality, count in by_quality.items():
|
||||
print(f" {quality.upper()}: {count} ({count/total_trades*100:.1f}%)")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Could not analyze performance: {e}")
|
||||
|
||||
# =============================================================================
|
||||
# 8. QUICK SETUP FUNCTION
|
||||
# =============================================================================
|
||||
|
||||
def setup_optimized_trading():
|
||||
"""
|
||||
Quick setup für optimiertes Trading
|
||||
"""
|
||||
print("🚀 Setting up Optimized Trading Bot V1.4")
|
||||
print("\nKey Improvements:")
|
||||
print("✅ Adaptive confidence thresholds")
|
||||
print("✅ Market regime detection")
|
||||
print("✅ Enhanced entry timing")
|
||||
print("✅ Risk-adjusted signal strength")
|
||||
print("✅ Performance monitoring")
|
||||
print("\nReady to trade with enhanced logic!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
setup_optimized_trading()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,394 @@
|
||||
"""
|
||||
TradingBot V1.4 - Relaxed Version
|
||||
Weniger restriktive Parameter für mehr Trading-Signale
|
||||
|
||||
Hauptänderungen:
|
||||
- Niedrigere Confidence-Schwellen
|
||||
- Weniger strenge Signal-Quality-Filter
|
||||
- Relaxed Risk-Adjusted Strength
|
||||
"""
|
||||
|
||||
# Import der Fixed Version als Basis
|
||||
from TradingBot_V1.4_Fixed import *
|
||||
|
||||
def calculate_adaptive_confidence_threshold_relaxed(regime_info, base_confidence=60):
|
||||
"""
|
||||
Relaxed Version: Niedrigere Schwellen für mehr Signale
|
||||
"""
|
||||
regime = regime_info['regime']
|
||||
strength = regime_info['strength']
|
||||
adx = regime_info['adx']
|
||||
|
||||
if regime == 'trending':
|
||||
# In Trending Markets: noch niedrigere Schwelle
|
||||
if adx > 30:
|
||||
return max(50, base_confidence - 20) # War -15
|
||||
else:
|
||||
return base_confidence - 15 # War -10
|
||||
|
||||
elif regime == 'ranging':
|
||||
# In Ranging Markets: weniger streng
|
||||
return base_confidence + 10 # War +15
|
||||
|
||||
elif regime == 'volatile':
|
||||
# In Volatile Markets: weniger restriktiv
|
||||
return base_confidence + 15 # War +20
|
||||
|
||||
return base_confidence
|
||||
|
||||
def extended_top_down_v2_relaxed(symbol="XAUUSD", lookback=150):
|
||||
"""
|
||||
Relaxed Version der Top-Down-Analyse für mehr Trading-Signale
|
||||
"""
|
||||
|
||||
timeframes = ["D1", "H4", "H1", "M30", "M15", "M5"]
|
||||
trend_info = {}
|
||||
|
||||
print(f"🔍 Analyzing {symbol} with RELAXED parameters...")
|
||||
|
||||
# 1. Alle Timeframes analysieren
|
||||
for tf in timeframes:
|
||||
trend_info[tf] = get_enhanced_trend(tf, lookback, symbol)
|
||||
if trend_info[tf] is None:
|
||||
print(f"⚠️ Keine Daten für {tf}")
|
||||
return None
|
||||
|
||||
# 2. Market Regime aus H4 bestimmen
|
||||
main_regime = trend_info["H4"]["regime_info"]
|
||||
|
||||
# 3. RELAXED Adaptive Confidence Threshold
|
||||
adaptive_confidence_threshold = calculate_adaptive_confidence_threshold_relaxed(main_regime)
|
||||
|
||||
# 4. Standard-Trend (gleich wie vorher)
|
||||
d1_trend = trend_info["D1"]["trend"]
|
||||
h4_trend = trend_info["H4"]["trend"]
|
||||
d1_strength = trend_info["D1"]["trend_strength"]
|
||||
h4_strength = trend_info["H4"]["trend_strength"]
|
||||
|
||||
if d1_trend == h4_trend and d1_trend != "sideways":
|
||||
standard_trend = d1_trend
|
||||
standard_strength = (d1_strength * 0.6 + h4_strength * 0.4)
|
||||
elif d1_strength > h4_strength * 1.5:
|
||||
standard_trend = d1_trend
|
||||
standard_strength = d1_strength * 0.8
|
||||
elif h4_strength > d1_strength * 1.5:
|
||||
standard_trend = h4_trend
|
||||
standard_strength = h4_strength * 0.8
|
||||
else:
|
||||
standard_trend = "sideways"
|
||||
standard_strength = 0
|
||||
|
||||
# 5. RELAXED Fast-Trend (weniger TFs erforderlich)
|
||||
fast_timeframes = ["H1", "M30", "M15", "M5"]
|
||||
fast_trends = [trend_info[tf]["trend"] for tf in fast_timeframes]
|
||||
fast_strengths = [trend_info[tf]["trend_strength"] for tf in fast_timeframes]
|
||||
|
||||
# RELAXED: Immer nur 2 von 4 TFs erforderlich (statt regime-abhängig)
|
||||
required_alignment = 2
|
||||
|
||||
trend_counts = {'uptrend': 0, 'downtrend': 0, 'sideways': 0}
|
||||
weighted_strengths = {'uptrend': 0, 'downtrend': 0}
|
||||
|
||||
weights = [1.0, 0.8, 0.6, 0.4]
|
||||
|
||||
for i, (trend, strength) in enumerate(zip(fast_trends, fast_strengths)):
|
||||
trend_counts[trend] += 1
|
||||
if trend != 'sideways':
|
||||
weighted_strengths[trend] += strength * weights[i]
|
||||
|
||||
max_count = max(trend_counts['uptrend'], trend_counts['downtrend'])
|
||||
if max_count >= required_alignment:
|
||||
if trend_counts['uptrend'] > trend_counts['downtrend']:
|
||||
fast_trend = "uptrend"
|
||||
elif trend_counts['downtrend'] > trend_counts['uptrend']:
|
||||
fast_trend = "downtrend"
|
||||
else:
|
||||
if weighted_strengths['uptrend'] > weighted_strengths['downtrend']:
|
||||
fast_trend = "uptrend"
|
||||
else:
|
||||
fast_trend = "downtrend"
|
||||
else:
|
||||
fast_trend = "sideways"
|
||||
|
||||
# 6. Top-Down-Trend Bestimmung
|
||||
if standard_trend == fast_trend and standard_trend != "sideways":
|
||||
top_down_trend = standard_trend
|
||||
combined_strength = (standard_strength + weighted_strengths.get(fast_trend, 0)) / 2
|
||||
else:
|
||||
top_down_trend = "sideways"
|
||||
combined_strength = 0
|
||||
|
||||
# 7. Enhanced Confidence Calculation (gleich)
|
||||
weights = {"D1": 2.5, "H4": 2.0, "H1": 1.5, "M30": 1.0, "M15": 0.8, "M5": 0.6}
|
||||
|
||||
weighted_matching = sum(
|
||||
weights[tf] * trend_info[tf]["trend_strength"]
|
||||
for tf in timeframes
|
||||
if trend_info[tf]["trend"] == top_down_trend and trend_info[tf]["trend"] != "sideways"
|
||||
)
|
||||
|
||||
weighted_total = sum(
|
||||
weights[tf] * trend_info[tf]["trend_strength"]
|
||||
for tf in timeframes
|
||||
if trend_info[tf]["trend"] != "sideways"
|
||||
)
|
||||
|
||||
confidence = round((weighted_matching / weighted_total) * 100, 2) if weighted_total > 0 else 0.0
|
||||
|
||||
# 8. RELAXED Risk-Adjusted Signal Strength
|
||||
atr = trend_info["M5"]["atr"]
|
||||
rrr = 2.5
|
||||
|
||||
risk_adjusted_strength = confidence * combined_strength * min(2.0, rrr)
|
||||
|
||||
# 9. RELAXED Entry Signal (niedrigere Schwelle)
|
||||
entry_signal = 0
|
||||
signal_quality = "none"
|
||||
|
||||
# RELAXED: Niedrigere Schwelle für risk_adjusted_strength
|
||||
min_strength = 80 # War 100
|
||||
|
||||
if (top_down_trend != "sideways" and
|
||||
confidence >= adaptive_confidence_threshold and
|
||||
risk_adjusted_strength >= min_strength):
|
||||
|
||||
entry_signal = 1 if top_down_trend == "uptrend" else -1
|
||||
|
||||
# RELAXED Signal Quality (niedrigere Schwellen)
|
||||
if confidence >= 80 and risk_adjusted_strength >= 130: # War 85/150
|
||||
signal_quality = "excellent"
|
||||
elif confidence >= 70 and risk_adjusted_strength >= 100: # War 75/120
|
||||
signal_quality = "good"
|
||||
else:
|
||||
signal_quality = "fair"
|
||||
|
||||
# 10. Debug Output
|
||||
debug_data = []
|
||||
for tf in timeframes:
|
||||
info = trend_info[tf]
|
||||
debug_data.append([
|
||||
tf,
|
||||
info["trend"],
|
||||
f"{info['trend_strength']:.2f}",
|
||||
f"{info['atr']:.4f}",
|
||||
f"{info['slope']:.6f}",
|
||||
f"{info['price']:.2f}"
|
||||
])
|
||||
|
||||
print(f"\n📊 RELAXED Trend-Analyse für {symbol}")
|
||||
print(f"🎯 Market Regime: {main_regime['regime'].upper()} (Strength: {main_regime['strength']:.0f}%)")
|
||||
print(f"🎚️ RELAXED Adaptive Threshold: {adaptive_confidence_threshold}% (vs standard V1.4)")
|
||||
print()
|
||||
print(tabulate(debug_data, headers=["TF", "Trend", "Strength", "ATR", "Slope", "Price"], tablefmt="psql"))
|
||||
print(f"\n➡️ Standard-Trend: {standard_trend} (Strength: {standard_strength:.2f})")
|
||||
print(f"➡️ Fast-Trend: {fast_trend}")
|
||||
print(f"➡️ Top-Down-Trend: {top_down_trend}")
|
||||
print(f"➡️ Confidence: {confidence}% (RELAXED Threshold: {adaptive_confidence_threshold}%)")
|
||||
print(f"➡️ Risk-Adjusted Strength: {risk_adjusted_strength:.1f} (Min: {min_strength})")
|
||||
print(f"➡️ Signal Quality: {signal_quality.upper()}")
|
||||
|
||||
# Vergleich mit Standard V1.4
|
||||
standard_threshold = calculate_adaptive_confidence_threshold(main_regime)
|
||||
print(f"\n🔄 RELAXED vs STANDARD V1.4:")
|
||||
print(f" Standard V1.4 threshold: {standard_threshold}%")
|
||||
print(f" Relaxed V1.4 threshold: {adaptive_confidence_threshold}%")
|
||||
print(f" Difference: {adaptive_confidence_threshold - standard_threshold:+d}% (more lenient)")
|
||||
|
||||
return {
|
||||
"symbol": symbol,
|
||||
"trend_info": trend_info,
|
||||
"market_regime": main_regime,
|
||||
"standard_trend": standard_trend,
|
||||
"fast_trend": fast_trend,
|
||||
"top_down_trend": top_down_trend,
|
||||
"confidence": confidence,
|
||||
"adaptive_threshold": adaptive_confidence_threshold,
|
||||
"risk_adjusted_strength": risk_adjusted_strength,
|
||||
"entry_signal": entry_signal,
|
||||
"signal_quality": signal_quality,
|
||||
"combined_strength": combined_strength,
|
||||
"min_strength_used": min_strength
|
||||
}
|
||||
|
||||
def execute_trade_v2_relaxed(
|
||||
symbol="XAUUSD",
|
||||
atr_mult=1.5,
|
||||
base_confidence=60, # Niedriger als 70
|
||||
max_risk_per_trade=0.01,
|
||||
risk_filter=True,
|
||||
min_atr=0.0008, # Niedriger als 0.0010
|
||||
use_pullback_entry=False, # DISABLED für mehr Signale
|
||||
debug=True
|
||||
):
|
||||
"""
|
||||
RELAXED Trade-Ausführung mit weniger restriktiven Parametern
|
||||
"""
|
||||
|
||||
# 1. RELAXED Signal Analysis
|
||||
signal_info = extended_top_down_v2_relaxed(symbol)
|
||||
if signal_info is None:
|
||||
print("❌ Signal-Analyse fehlgeschlagen")
|
||||
return None
|
||||
|
||||
entry_signal = signal_info["entry_signal"]
|
||||
confidence = signal_info["confidence"]
|
||||
adaptive_threshold = signal_info["adaptive_threshold"]
|
||||
signal_quality = signal_info["signal_quality"]
|
||||
market_regime = signal_info["market_regime"]
|
||||
|
||||
# 2. Get Price/ATR from M5
|
||||
m5_info = signal_info["trend_info"]["M5"]
|
||||
price = m5_info["price"]
|
||||
atr = m5_info["atr"]
|
||||
|
||||
# 3. RELAXED Pre-checks
|
||||
reason = ""
|
||||
|
||||
if confidence < adaptive_threshold:
|
||||
reason = f"Confidence {confidence}% < relaxed threshold {adaptive_threshold}%"
|
||||
elif entry_signal == 0:
|
||||
reason = f"No entry signal (Trend: {signal_info['top_down_trend']}, Regime: {market_regime['regime']})"
|
||||
elif price is None or atr is None:
|
||||
reason = "Price/ATR not available"
|
||||
elif risk_filter and atr < min_atr:
|
||||
reason = f"ATR {atr:.5f} < min_atr {min_atr}"
|
||||
else:
|
||||
# 4. SKIP Entry Timing Check (use_pullback_entry=False)
|
||||
|
||||
# 5. RELAXED Risk Checks
|
||||
risk_ok = check_risk_limits(symbol, max_risk_per_trade=max_risk_per_trade)
|
||||
if not risk_ok:
|
||||
reason = "Risk limits exceeded"
|
||||
|
||||
# 6. Execute Trade if all checks pass
|
||||
if not reason:
|
||||
# Standard SL/TP calculation
|
||||
regime_mult = 1.0
|
||||
if market_regime['regime'] == 'volatile':
|
||||
regime_mult = 1.2 # Weniger drastisch als 1.3
|
||||
elif market_regime['regime'] == 'ranging':
|
||||
regime_mult = 0.9 # Weniger drastisch als 0.8
|
||||
|
||||
adjusted_atr_mult = atr_mult * regime_mult
|
||||
|
||||
if entry_signal == 1: # Long
|
||||
stop_loss = price - adjusted_atr_mult * atr
|
||||
take_profit = price + adjusted_atr_mult * atr * 2.5
|
||||
else: # Short
|
||||
stop_loss = price + adjusted_atr_mult * atr
|
||||
take_profit = price - adjusted_atr_mult * atr * 2.5
|
||||
|
||||
# Position Sizing
|
||||
account_info = mt.account_info()
|
||||
if account_info:
|
||||
balance = account_info.balance
|
||||
risk_amount = balance * max_risk_per_trade
|
||||
if symbol == "XAUUSD":
|
||||
volume = min(0.1, max(0.01, risk_amount / (adjusted_atr_mult * atr * 100)))
|
||||
else:
|
||||
volume = 0.01
|
||||
else:
|
||||
volume = 0.01
|
||||
|
||||
# Log Enhanced Trade Info
|
||||
print(f"\n🚀 RELAXED TRADE EXECUTION")
|
||||
print(f"Symbol: {symbol}")
|
||||
print(f"Direction: {'LONG' if entry_signal == 1 else 'SHORT'}")
|
||||
print(f"Price: {price:.5f}")
|
||||
print(f"Volume: {volume:.2f}")
|
||||
print(f"Stop Loss: {stop_loss:.5f}")
|
||||
print(f"Take Profit: {take_profit:.5f}")
|
||||
print(f"Confidence: {confidence}% (RELAXED Threshold: {adaptive_threshold}%)")
|
||||
print(f"Signal Quality: {signal_quality.upper()}")
|
||||
print(f"Market Regime: {market_regime['regime'].upper()}")
|
||||
print(f"Pullback Entry: DISABLED (immediate entry)")
|
||||
print(f"Risk per Trade: {max_risk_per_trade*100:.1f}%")
|
||||
|
||||
# Execute trade
|
||||
try:
|
||||
order_result = market_order(
|
||||
symbol=symbol,
|
||||
volume=volume,
|
||||
order_type="buy" if entry_signal == 1 else "sell",
|
||||
stoploss=stop_loss,
|
||||
take_profit=take_profit
|
||||
)
|
||||
|
||||
log_trade_performance(signal_info, order_result)
|
||||
return order_result
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Trade execution failed: {e}")
|
||||
return None
|
||||
|
||||
else:
|
||||
if debug:
|
||||
print(f"\n⏸️ RELAXED TRADE SKIPPED: {reason}")
|
||||
print(f"Confidence: {confidence}% | Relaxed Threshold: {adaptive_threshold}%")
|
||||
print(f"Signal Quality: {signal_quality} | Regime: {market_regime['regime']}")
|
||||
return None
|
||||
|
||||
def compare_all_versions(symbol="XAUUSD"):
|
||||
"""
|
||||
Vergleicht alle Versionen: V1.3, V1.4 Standard, V1.4 Relaxed
|
||||
"""
|
||||
print("🔄 COMPARING ALL VERSIONS")
|
||||
print("=" * 40)
|
||||
|
||||
try:
|
||||
# V1.4 Standard
|
||||
signal_std = extended_top_down_v2(symbol, lookback=100)
|
||||
|
||||
# V1.4 Relaxed
|
||||
signal_rel = extended_top_down_v2_relaxed(symbol, lookback=100)
|
||||
|
||||
if signal_std and signal_rel:
|
||||
comparison_data = [
|
||||
["Version", "Confidence", "Threshold", "Signal", "Quality", "Would Trade"],
|
||||
["V1.3 (simulated)", f"{signal_std['confidence']:.1f}%", "80%",
|
||||
"1" if signal_std['confidence'] >= 80 and signal_std['top_down_trend'] != 'sideways' else "0",
|
||||
"N/A", "✅" if signal_std['confidence'] >= 80 and signal_std['top_down_trend'] != 'sideways' else "❌"],
|
||||
["V1.4 Standard", f"{signal_std['confidence']:.1f}%", f"{signal_std['adaptive_threshold']}%",
|
||||
str(signal_std['entry_signal']), signal_std['signal_quality'],
|
||||
"✅" if signal_std['entry_signal'] != 0 else "❌"],
|
||||
["V1.4 Relaxed", f"{signal_rel['confidence']:.1f}%", f"{signal_rel['adaptive_threshold']}%",
|
||||
str(signal_rel['entry_signal']), signal_rel['signal_quality'],
|
||||
"✅" if signal_rel['entry_signal'] != 0 else "❌"]
|
||||
]
|
||||
|
||||
print(tabulate(comparison_data, headers="firstrow", tablefmt="psql"))
|
||||
|
||||
# Empfehlung
|
||||
trading_count = sum([
|
||||
1 if signal_std['confidence'] >= 80 and signal_std['top_down_trend'] != 'sideways' else 0,
|
||||
1 if signal_std['entry_signal'] != 0 else 0,
|
||||
1 if signal_rel['entry_signal'] != 0 else 0
|
||||
])
|
||||
|
||||
print(f"\n📊 TRADING SIGNALS: {trading_count}/3 versions would trade")
|
||||
|
||||
if trading_count == 0:
|
||||
print("🛑 NO VERSION would trade - market conditions not suitable")
|
||||
elif trading_count == 1:
|
||||
print("⚡ Only one version trades - high selectivity")
|
||||
elif trading_count == 2:
|
||||
print("🎯 Two versions agree - moderate confidence")
|
||||
else:
|
||||
print("🚀 All versions agree - strong signal!")
|
||||
|
||||
return signal_rel
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error in comparison: {e}")
|
||||
return None
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("🚀 TradingBot V1.4 - RELAXED Version Ready!")
|
||||
print("Less restrictive parameters for more trading signals")
|
||||
print("\nKey changes:")
|
||||
print("• Lower confidence thresholds")
|
||||
print("• Disabled pullback entry timing")
|
||||
print("• Lower risk-adjusted strength requirement")
|
||||
print("• More lenient signal quality assessment")
|
||||
print("\nUse: extended_top_down_v2_relaxed() for analysis")
|
||||
print("Use: execute_trade_v2_relaxed() for trading")
|
||||
@@ -0,0 +1,498 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# 🚨 Trading Bot Fix - Warum handelt er nicht mehr?\n",
|
||||
"\n",
|
||||
"## Systematische Diagnose und Lösungen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Imports\n",
|
||||
"import pandas as pd\n",
|
||||
"import numpy as np\n",
|
||||
"import MetaTrader5 as mt\n",
|
||||
"import pandas_ta as ta\n",
|
||||
"from scipy.signal import savgol_filter\n",
|
||||
"from sklearn.linear_model import LinearRegression\n",
|
||||
"from tabulate import tabulate\n",
|
||||
"from datetime import datetime\n",
|
||||
"\n",
|
||||
"# Deine bestehenden Funktionen\n",
|
||||
"try:\n",
|
||||
" from TradingBot_V1.4_Fixed import extended_top_down_v2, get_rates, detect_market_regime\n",
|
||||
" print(\"✅ V1.4 functions imported successfully\")\n",
|
||||
"except ImportError as e:\n",
|
||||
" print(f\"❌ Import error: {e}\")\n",
|
||||
" print(\"Continuing with basic diagnosis...\")\n",
|
||||
"\n",
|
||||
"symbol = \"XAUUSD\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 1. 🔍 Grundlegende Diagnose"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(\"🔍 TRADING BOT DIAGNOSIS\")\n",
|
||||
"print(\"=\" * 50)\n",
|
||||
"\n",
|
||||
"issues_found = []\n",
|
||||
"\n",
|
||||
"# MT5 Connection Check\n",
|
||||
"print(\"\\n1️⃣ MT5 Connection Check:\")\n",
|
||||
"terminal_info = mt.terminal_info()\n",
|
||||
"if terminal_info:\n",
|
||||
" print(\" ✅ MT5 connected\")\n",
|
||||
" print(f\" Company: {terminal_info.company}\")\n",
|
||||
" print(f\" Connected: {terminal_info.connected}\")\n",
|
||||
" print(f\" Trade allowed: {terminal_info.trade_allowed}\")\n",
|
||||
" if not terminal_info.trade_allowed:\n",
|
||||
" issues_found.append(\"Trading not allowed in terminal\")\n",
|
||||
"else:\n",
|
||||
" print(\" ❌ MT5 not connected\")\n",
|
||||
" issues_found.append(\"MT5 connection failed\")\n",
|
||||
"\n",
|
||||
"# Account Info Check\n",
|
||||
"print(\"\\n2️⃣ Account Info Check:\")\n",
|
||||
"account_info = mt.account_info()\n",
|
||||
"if account_info:\n",
|
||||
" print(f\" ✅ Account: {account_info.login}\")\n",
|
||||
" print(f\" Balance: {account_info.balance}\")\n",
|
||||
" print(f\" Equity: {account_info.equity}\")\n",
|
||||
" print(f\" Trade allowed: {account_info.trade_allowed}\")\n",
|
||||
" if not account_info.trade_allowed:\n",
|
||||
" issues_found.append(\"Trading not allowed on account\")\n",
|
||||
"else:\n",
|
||||
" print(\" ❌ Cannot get account info\")\n",
|
||||
" issues_found.append(\"Account info unavailable\")\n",
|
||||
"\n",
|
||||
"# Symbol Info Check\n",
|
||||
"print(f\"\\n3️⃣ Symbol Info Check ({symbol}):\")\n",
|
||||
"symbol_info = mt.symbol_info(symbol)\n",
|
||||
"if symbol_info:\n",
|
||||
" print(f\" ✅ Symbol exists: {symbol_info.name}\")\n",
|
||||
" print(f\" Trade mode: {symbol_info.trade_mode}\")\n",
|
||||
" print(f\" Min volume: {symbol_info.volume_min}\")\n",
|
||||
" if symbol_info.trade_mode == 0:\n",
|
||||
" issues_found.append(f\"Trading disabled for {symbol}\")\n",
|
||||
"else:\n",
|
||||
" print(f\" ❌ Symbol {symbol} not found\")\n",
|
||||
" issues_found.append(f\"Symbol {symbol} not available\")\n",
|
||||
"\n",
|
||||
"# Current Price Check\n",
|
||||
"print(\"\\n4️⃣ Price Data Check:\")\n",
|
||||
"tick = mt.symbol_info_tick(symbol)\n",
|
||||
"if tick:\n",
|
||||
" print(f\" ✅ Current price: Bid={tick.bid}, Ask={tick.ask}\")\n",
|
||||
" spread = tick.ask - tick.bid\n",
|
||||
" print(f\" Spread: {spread:.5f}\")\n",
|
||||
" if spread > 0.01:\n",
|
||||
" issues_found.append(f\"High spread: {spread:.5f}\")\n",
|
||||
"else:\n",
|
||||
" print(\" ❌ No current price data\")\n",
|
||||
" issues_found.append(\"No price data available\")\n",
|
||||
"\n",
|
||||
"print(f\"\\n📋 Issues Found: {len(issues_found)}\")\n",
|
||||
"for i, issue in enumerate(issues_found, 1):\n",
|
||||
" print(f\" {i}. {issue}\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 2. 📊 Signal-Analyse: Warum kein Trade?"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Teste deine optimierte V1.4 Logik\n",
|
||||
"print(\"🔍 SIGNAL ANALYSIS - Why no trading?\")\n",
|
||||
"print(\"=\" * 50)\n",
|
||||
"\n",
|
||||
"try:\n",
|
||||
" # Hole Signal-Info\n",
|
||||
" signal_info = extended_top_down_v2(symbol, lookback=100)\n",
|
||||
" \n",
|
||||
" if signal_info:\n",
|
||||
" print(f\"\\n📊 CURRENT SIGNAL STATUS:\")\n",
|
||||
" print(f\"Entry Signal: {signal_info['entry_signal']}\")\n",
|
||||
" print(f\"Confidence: {signal_info['confidence']:.1f}%\")\n",
|
||||
" print(f\"Adaptive Threshold: {signal_info['adaptive_threshold']:.1f}%\")\n",
|
||||
" print(f\"Signal Quality: {signal_info['signal_quality'].upper()}\")\n",
|
||||
" print(f\"Market Regime: {signal_info['market_regime']['regime'].upper()}\")\n",
|
||||
" print(f\"Top-Down Trend: {signal_info['top_down_trend'].upper()}\")\n",
|
||||
" print(f\"Risk-Adjusted Strength: {signal_info['risk_adjusted_strength']:.1f}\")\n",
|
||||
" \n",
|
||||
" # Analyse warum kein Signal\n",
|
||||
" print(f\"\\n🔍 WHY NO TRADING SIGNAL:\")\n",
|
||||
" \n",
|
||||
" reasons = []\n",
|
||||
" \n",
|
||||
" if signal_info['top_down_trend'] == 'sideways':\n",
|
||||
" reasons.append(\"❌ No clear trend direction (sideways market)\")\n",
|
||||
" \n",
|
||||
" if signal_info['confidence'] < signal_info['adaptive_threshold']:\n",
|
||||
" deficit = signal_info['adaptive_threshold'] - signal_info['confidence']\n",
|
||||
" reasons.append(f\"❌ Confidence too low: {signal_info['confidence']:.1f}% < {signal_info['adaptive_threshold']:.1f}% (need {deficit:.1f}% more)\")\n",
|
||||
" \n",
|
||||
" if signal_info['risk_adjusted_strength'] < 100:\n",
|
||||
" reasons.append(f\"❌ Risk-adjusted strength too low: {signal_info['risk_adjusted_strength']:.1f} < 100\")\n",
|
||||
" \n",
|
||||
" if signal_info['signal_quality'] == 'none':\n",
|
||||
" reasons.append(\"❌ Signal quality insufficient\")\n",
|
||||
" \n",
|
||||
" if reasons:\n",
|
||||
" for reason in reasons:\n",
|
||||
" print(f\" {reason}\")\n",
|
||||
" else:\n",
|
||||
" print(\" ✅ All signal criteria met - check other filters\")\n",
|
||||
" \n",
|
||||
" # Vergleich mit V1.3\n",
|
||||
" print(f\"\\n🔄 V1.3 vs V1.4 COMPARISON:\")\n",
|
||||
" v13_threshold = 80\n",
|
||||
" v13_would_trade = (\n",
|
||||
" signal_info['top_down_trend'] != 'sideways' and \n",
|
||||
" signal_info['confidence'] >= v13_threshold\n",
|
||||
" )\n",
|
||||
" v14_trades = signal_info['entry_signal'] != 0\n",
|
||||
" \n",
|
||||
" print(f\" V1.3 would trade: {'✅' if v13_would_trade else '❌'} (fixed 80% threshold)\")\n",
|
||||
" print(f\" V1.4 trades: {'✅' if v14_trades else '❌'} (adaptive {signal_info['adaptive_threshold']:.1f}% threshold)\")\n",
|
||||
" \n",
|
||||
" if v13_would_trade and not v14_trades:\n",
|
||||
" print(f\" 🛡️ V1.4 is MORE SELECTIVE in {signal_info['market_regime']['regime'].upper()} market\")\n",
|
||||
" elif not v13_would_trade and v14_trades:\n",
|
||||
" print(f\" 🚀 V1.4 found opportunity V1.3 missed!\")\n",
|
||||
" \n",
|
||||
" else:\n",
|
||||
" print(\"❌ Could not get signal info\")\n",
|
||||
" \n",
|
||||
"except Exception as e:\n",
|
||||
" print(f\"❌ Error in signal analysis: {e}\")\n",
|
||||
" print(\"Will try simplified analysis...\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 3. 🔧 Quick Fixes"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(\"🔧 QUICK FIXES TO TRY\")\n",
|
||||
"print(\"=\" * 30)\n",
|
||||
"\n",
|
||||
"# Fix 1: Temporär niedrigere Schwelle\n",
|
||||
"print(\"\\n1️⃣ LOWER THRESHOLD TEMPORARILY:\")\n",
|
||||
"print(\" Copy this code to make V1.4 less selective:\")\n",
|
||||
"print(\"\")\n",
|
||||
"quick_fix_1 = '''def quick_fix_lower_threshold(signal_info):\n",
|
||||
" # Reduziere adaptive Schwelle um 15%\n",
|
||||
" original_threshold = signal_info['adaptive_threshold']\n",
|
||||
" new_threshold = max(60, original_threshold - 15)\n",
|
||||
" \n",
|
||||
" print(f\"Original threshold: {original_threshold}%\")\n",
|
||||
" print(f\"New threshold: {new_threshold}%\")\n",
|
||||
" \n",
|
||||
" if signal_info['confidence'] >= new_threshold:\n",
|
||||
" print(\"✅ Would trade with lower threshold!\")\n",
|
||||
" return True\n",
|
||||
" else:\n",
|
||||
" print(f\"❌ Still need {new_threshold - signal_info['confidence']:.1f}% more confidence\")\n",
|
||||
" return False'''\n",
|
||||
"\n",
|
||||
"print(quick_fix_1)\n",
|
||||
"\n",
|
||||
"# Fix 2: Bypass Pullback Entry\n",
|
||||
"print(\"\\n\\n2️⃣ BYPASS PULLBACK ENTRY:\")\n",
|
||||
"print(\" Set: use_pullback_entry = False\")\n",
|
||||
"print(\" This allows immediate entries instead of waiting for pullbacks\")\n",
|
||||
"\n",
|
||||
"# Fix 3: Allow Fair Quality\n",
|
||||
"print(\"\\n3️⃣ ALLOW 'FAIR' SIGNAL QUALITY:\")\n",
|
||||
"print(\" Modify signal quality check to accept 'fair' signals\")\n",
|
||||
"\n",
|
||||
"# Fix 4: Emergency V1.3 Mode\n",
|
||||
"print(\"\\n4️⃣ EMERGENCY V1.3 MODE:\")\n",
|
||||
"print(\" Use simplified logic similar to your original bot\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 4. 🚨 Emergency V1.3-Style Trading"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def emergency_trading_signal(symbol=\"XAUUSD\"):\n",
|
||||
" \"\"\"\n",
|
||||
" Vereinfachte V1.3-ähnliche Logik als Fallback\n",
|
||||
" \"\"\"\n",
|
||||
" print(\"🚨 EMERGENCY V1.3-STYLE TRADING\")\n",
|
||||
" print(\"=\" * 40)\n",
|
||||
" \n",
|
||||
" try:\n",
|
||||
" # Einfache get_rates Funktion\n",
|
||||
" def simple_get_rates(tf, count):\n",
|
||||
" tf_map = {\"h4\": mt.TIMEFRAME_H4, \"m5\": mt.TIMEFRAME_M5}\n",
|
||||
" rates = mt.copy_rates_from_pos(symbol, tf_map[tf], 0, count)\n",
|
||||
" if rates is None:\n",
|
||||
" return None\n",
|
||||
" df = pd.DataFrame(rates)\n",
|
||||
" df['atr'] = ta.atr(df['high'], df['low'], df['close'], length=14)\n",
|
||||
" return df\n",
|
||||
" \n",
|
||||
" # Hole H4 und M5 Daten\n",
|
||||
" h4_df = simple_get_rates(\"h4\", 150)\n",
|
||||
" m5_df = simple_get_rates(\"m5\", 100)\n",
|
||||
" \n",
|
||||
" if h4_df is None or m5_df is None:\n",
|
||||
" return 0, \"No data available\"\n",
|
||||
" \n",
|
||||
" print(f\"Got H4 data: {len(h4_df)} bars\")\n",
|
||||
" print(f\"Got M5 data: {len(m5_df)} bars\")\n",
|
||||
" \n",
|
||||
" # Vereinfachte Trend-Analyse H4\n",
|
||||
" h4_df['close_smooth'] = savgol_filter(h4_df['close'], 15, 3)\n",
|
||||
" X = np.arange(len(h4_df)).reshape(-1, 1)\n",
|
||||
" y = h4_df['close_smooth'].values\n",
|
||||
" model = LinearRegression().fit(X, y)\n",
|
||||
" slope_h4 = model.coef_[0]\n",
|
||||
" \n",
|
||||
" atr_h4 = h4_df['atr'].iloc[-1]\n",
|
||||
" threshold_h4 = atr_h4 * 0.0001\n",
|
||||
" \n",
|
||||
" if slope_h4 > threshold_h4:\n",
|
||||
" h4_trend = \"uptrend\"\n",
|
||||
" elif slope_h4 < -threshold_h4:\n",
|
||||
" h4_trend = \"downtrend\"\n",
|
||||
" else:\n",
|
||||
" h4_trend = \"sideways\"\n",
|
||||
" \n",
|
||||
" print(f\"H4 Trend: {h4_trend} (slope: {slope_h4:.6f})\")\n",
|
||||
" \n",
|
||||
" # Vereinfachte Trend-Analyse M5\n",
|
||||
" m5_df['close_smooth'] = savgol_filter(m5_df['close'], 15, 3)\n",
|
||||
" X_m5 = np.arange(len(m5_df)).reshape(-1, 1)\n",
|
||||
" y_m5 = m5_df['close_smooth'].values\n",
|
||||
" model_m5 = LinearRegression().fit(X_m5, y_m5)\n",
|
||||
" slope_m5 = model_m5.coef_[0]\n",
|
||||
" \n",
|
||||
" atr_m5 = m5_df['atr'].iloc[-1]\n",
|
||||
" threshold_m5 = atr_m5 * 0.0001\n",
|
||||
" \n",
|
||||
" if slope_m5 > threshold_m5:\n",
|
||||
" m5_trend = \"uptrend\"\n",
|
||||
" elif slope_m5 < -threshold_m5:\n",
|
||||
" m5_trend = \"downtrend\"\n",
|
||||
" else:\n",
|
||||
" m5_trend = \"sideways\"\n",
|
||||
" \n",
|
||||
" print(f\"M5 Trend: {m5_trend} (slope: {slope_m5:.6f})\")\n",
|
||||
" \n",
|
||||
" # Vereinfachte Confidence\n",
|
||||
" if h4_trend == m5_trend and h4_trend != \"sideways\":\n",
|
||||
" confidence = 85 # Hoch wenn aligned\n",
|
||||
" signal = 1 if h4_trend == \"uptrend\" else -1\n",
|
||||
" trend_agreement = \"✅ ALIGNED\"\n",
|
||||
" else:\n",
|
||||
" confidence = 45 # Niedrig wenn nicht aligned\n",
|
||||
" signal = 0\n",
|
||||
" trend_agreement = \"❌ NOT ALIGNED\"\n",
|
||||
" \n",
|
||||
" print(f\"Trend Agreement: {trend_agreement}\")\n",
|
||||
" print(f\"Confidence: {confidence}%\")\n",
|
||||
" \n",
|
||||
" # V1.3-ähnliche niedrige Schwelle\n",
|
||||
" emergency_threshold = 70\n",
|
||||
" \n",
|
||||
" print(f\"Emergency Threshold: {emergency_threshold}%\")\n",
|
||||
" \n",
|
||||
" if confidence >= emergency_threshold and signal != 0:\n",
|
||||
" direction = \"LONG\" if signal == 1 else \"SHORT\"\n",
|
||||
" return signal, f\"🚀 EMERGENCY {direction} SIGNAL! Confidence: {confidence}%\"\n",
|
||||
" else:\n",
|
||||
" return 0, f\"❌ No emergency signal: confidence {confidence}% < {emergency_threshold}%\"\n",
|
||||
" \n",
|
||||
" except Exception as e:\n",
|
||||
" return 0, f\"Error in emergency analysis: {e}\"\n",
|
||||
"\n",
|
||||
"# Test Emergency Signal\n",
|
||||
"emergency_signal, emergency_reason = emergency_trading_signal(symbol)\n",
|
||||
"print(f\"\\n🎯 EMERGENCY RESULT:\")\n",
|
||||
"print(f\"Signal: {emergency_signal}\")\n",
|
||||
"print(f\"Reason: {emergency_reason}\")\n",
|
||||
"\n",
|
||||
"if emergency_signal != 0:\n",
|
||||
" print(\"\\n🚀 EMERGENCY SIGNAL DETECTED!\")\n",
|
||||
" print(\"You could use this as a fallback trading signal.\")\n",
|
||||
"else:\n",
|
||||
" print(\"\\n⏸️ Even emergency logic shows no signal\")\n",
|
||||
" print(\"Market conditions may genuinely not be suitable for trading.\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 5. 🔄 Test mit deiner ursprünglichen V1.3 Funktion"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(\"🔄 TESTING YOUR ORIGINAL V1.3 LOGIC\")\n",
|
||||
"print(\"=\" * 40)\n",
|
||||
"\n",
|
||||
"# Hier würdest du deine ursprüngliche extended_top_down() Funktion aus V1.3 aufrufen\n",
|
||||
"print(\"To test your original logic, run:\")\n",
|
||||
"print(\"\")\n",
|
||||
"print(\"# Copy your original extended_top_down() function here\")\n",
|
||||
"print(\"# Then run:\")\n",
|
||||
"print(\"original_result = extended_top_down(symbol)\")\n",
|
||||
"print(\"print(f'Original V1.3 result: {original_result}')\")\n",
|
||||
"print(\"\")\n",
|
||||
"print(\"This will show you if your V1.3 logic would still trade.\")\n",
|
||||
"print(\"If V1.3 trades but V1.4 doesn't, we know V1.4 is too restrictive.\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 6. 🎯 Immediate Solutions"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(\"🎯 IMMEDIATE SOLUTIONS TO GET TRADING AGAIN\")\n",
|
||||
"print(\"=\" * 50)\n",
|
||||
"\n",
|
||||
"solutions = [\n",
|
||||
" \"1️⃣ QUICK FIX - Lower Adaptive Threshold:\",\n",
|
||||
" \" In execute_trade_v2(), change:\",\n",
|
||||
" \" adaptive_threshold = signal_info['adaptive_threshold'] - 15\",\n",
|
||||
" \"\",\n",
|
||||
" \"2️⃣ DISABLE PULLBACK ENTRY:\",\n",
|
||||
" \" Set: use_pullback_entry = False\",\n",
|
||||
" \" This removes the timing filter\",\n",
|
||||
" \"\",\n",
|
||||
" \"3️⃣ ACCEPT FAIR SIGNALS:\",\n",
|
||||
" \" Allow signal_quality = 'fair' to trade\",\n",
|
||||
" \"\",\n",
|
||||
" \"4️⃣ EMERGENCY MODE:\",\n",
|
||||
" \" Use the emergency_trading_signal() function above\",\n",
|
||||
" \" as your main trading logic temporarily\",\n",
|
||||
" \"\",\n",
|
||||
" \"5️⃣ HYBRID APPROACH:\",\n",
|
||||
" \" If V1.4 says no trade, check emergency signal\",\n",
|
||||
" \" If emergency signal exists, trade with smaller volume\",\n",
|
||||
" \"\",\n",
|
||||
" \"6️⃣ REVERT TO V1.3:\",\n",
|
||||
" \" Temporarily go back to your original bot\",\n",
|
||||
" \" while we fine-tune V1.4 parameters\"\n",
|
||||
"]\n",
|
||||
"\n",
|
||||
"for solution in solutions:\n",
|
||||
" print(solution)\n",
|
||||
"\n",
|
||||
"print(\"\\n\" + \"=\" * 50)\n",
|
||||
"print(\"🚨 MOST LIKELY ISSUE: V1.4 is TOO SELECTIVE\")\n",
|
||||
"print(\"V1.4 was designed to be more careful, which means fewer trades.\")\n",
|
||||
"print(\"This is actually GOOD for avoiding bad trades, but may feel like 'not working'.\")\n",
|
||||
"print(\"\")\n",
|
||||
"print(\"💡 RECOMMENDATION:\")\n",
|
||||
"print(\"1. Try the emergency signal above\")\n",
|
||||
"print(\"2. If it works, gradually tune V1.4 to be less restrictive\")\n",
|
||||
"print(\"3. Compare results over 1-2 weeks to see which performs better\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 7. 📊 Parameter Tuning"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Zeige aktuelle Parameter und Tuning-Optionen\n",
|
||||
"print(\"📊 PARAMETER TUNING OPTIONS\")\n",
|
||||
"print(\"=\" * 35)\n",
|
||||
"\n",
|
||||
"tuning_options = [\n",
|
||||
" \"Current V1.4 Parameters (too restrictive?):\",\n",
|
||||
" \"• Base confidence: 70%\",\n",
|
||||
" \"• Trending adjustment: -10 to -15%\",\n",
|
||||
" \"• Ranging adjustment: +15%\",\n",
|
||||
" \"• Volatile adjustment: +20%\",\n",
|
||||
" \"• Min risk-adjusted strength: 100\",\n",
|
||||
" \"\",\n",
|
||||
" \"Suggested Relaxed Parameters:\",\n",
|
||||
" \"• Base confidence: 60%\",\n",
|
||||
" \"• Trending adjustment: -15 to -20%\",\n",
|
||||
" \"• Ranging adjustment: +10%\",\n",
|
||||
" \"• Volatile adjustment: +15%\",\n",
|
||||
" \"• Min risk-adjusted strength: 80\",\n",
|
||||
" \"\",\n",
|
||||
" \"Very Relaxed (V1.3-like):\",\n",
|
||||
" \"• Fixed confidence: 75%\",\n",
|
||||
" \"• No regime adjustments\",\n",
|
||||
" \"• No signal quality filter\",\n",
|
||||
" \"• No pullback entry timing\"\n",
|
||||
"]\n",
|
||||
"\n",
|
||||
"for option in tuning_options:\n",
|
||||
" print(option)"
|
||||
]
|
||||
}\n",
|
||||
],\n",
|
||||
"metadata": {\n",
|
||||
"kernelspec": {\n",
|
||||
\"display_name\": \"Python 3\",\n",
|
||||
\"language\": \"python\",\n",
|
||||
\"name\": \"python3\"\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": 3\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n \"version\": \"3.11.5\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}
|
||||
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"trading_config": {
|
||||
"symbol": "XAUUSD",
|
||||
"base_confidence": 70,
|
||||
"atr_multiplier": 1.5,
|
||||
"max_risk_per_trade": 0.01,
|
||||
"min_atr": 0.0010,
|
||||
"use_pullback_entry": true,
|
||||
"strategy_name": "TradingBot_V1.4_Optimized"
|
||||
},
|
||||
|
||||
"regime_thresholds": {
|
||||
"trending": {
|
||||
"min_adx": 25,
|
||||
"confidence_adjustment": -10,
|
||||
"atr_mult_adjustment": 0.0
|
||||
},
|
||||
"ranging": {
|
||||
"max_adx": 20,
|
||||
"confidence_adjustment": 15,
|
||||
"atr_mult_adjustment": -0.2
|
||||
},
|
||||
"volatile": {
|
||||
"vol_cluster_threshold": 1.5,
|
||||
"confidence_adjustment": 20,
|
||||
"atr_mult_adjustment": 0.3
|
||||
}
|
||||
},
|
||||
|
||||
"timeframe_weights": {
|
||||
"D1": 2.5,
|
||||
"H4": 2.0,
|
||||
"H1": 1.5,
|
||||
"M30": 1.0,
|
||||
"M15": 0.8,
|
||||
"M5": 0.6
|
||||
},
|
||||
|
||||
"signal_quality_thresholds": {
|
||||
"excellent": {
|
||||
"min_confidence": 85,
|
||||
"min_risk_adjusted_strength": 150
|
||||
},
|
||||
"good": {
|
||||
"min_confidence": 75,
|
||||
"min_risk_adjusted_strength": 120
|
||||
},
|
||||
"fair": {
|
||||
"min_confidence": 60,
|
||||
"min_risk_adjusted_strength": 100
|
||||
}
|
||||
},
|
||||
|
||||
"risk_management": {
|
||||
"max_daily_loss": 0.05,
|
||||
"max_drawdown": 0.10,
|
||||
"max_positions": 3,
|
||||
"spread_filter": true,
|
||||
"max_spread": 3.0
|
||||
},
|
||||
|
||||
"schedule_settings": {
|
||||
"check_interval_minutes": 5,
|
||||
"trading_days": ["mon", "tue", "wed", "thu", "fri"],
|
||||
"trading_hours": "0-23",
|
||||
"performance_analysis_hours": [0, 6, 12, 18]
|
||||
},
|
||||
|
||||
"debug_settings": {
|
||||
"verbose_logging": true,
|
||||
"save_performance_logs": true,
|
||||
"print_regime_info": true,
|
||||
"log_skipped_trades": true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user