Files
Place-Order-Trading-Bot/TradingBot_Diagnosis.py
T

355 lines
12 KiB
Python

"""
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)