Files

186 lines
5.9 KiB
Python
Raw Permalink Normal View History

2025-12-16 22:02:15 +01:00
#!/usr/bin/env python3
"""
🔍 Position Monitor Diagnose
Prüft warum geschlossene Positionen nicht in der DB landen
"""
import MetaTrader5 as mt
import sqlite3
from datetime import datetime
print("=" * 60)
print("🔍 POSITION MONITOR DIAGNOSE")
print("=" * 60)
# ==========================================
# 1. MT5 CONNECTION CHECK
# ==========================================
print("\n1️⃣ MT5 Connection Check...")
if not mt.initialize():
print("❌ MT5 nicht verbunden!")
print(f" Fehler: {mt.last_error()}")
exit(1)
else:
print("✅ MT5 verbunden")
# Account Info
account_info = mt.account_info()
if account_info:
print(f" Account: {account_info.login}")
print(f" Balance: ${account_info.balance:.2f}")
# ==========================================
# 2. DATABASE CHECK
# ==========================================
print("\n2️⃣ Database Check...")
conn = sqlite3.connect("trading_bot.db")
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
# Get open trades from DB
cursor.execute("""
SELECT ticket, symbol, type, entry_time, status
FROM trades
WHERE status = 'open'
ORDER BY entry_time DESC
""")
db_open_trades = cursor.fetchall()
print(f"✅ Offene Trades in DB: {len(db_open_trades)}")
if db_open_trades:
print("\n DB Open Trades:")
for trade in db_open_trades:
print(f" • Ticket {trade['ticket']}: {trade['type']} {trade['symbol']} @ {trade['entry_time']}")
# ==========================================
# 3. MT5 POSITIONS CHECK
# ==========================================
print("\n3️⃣ MT5 Current Positions...")
mt5_positions = mt.positions_get()
print(f"✅ Offene Positionen in MT5: {len(mt5_positions) if mt5_positions else 0}")
mt5_tickets = set()
if mt5_positions:
print("\n MT5 Open Positions:")
for pos in mt5_positions:
mt5_tickets.add(pos.ticket)
print(f" • Ticket {pos.ticket}: {pos.type} {pos.symbol} @ {pos.price_open}")
# ==========================================
# 4. COMPARE DB vs MT5
# ==========================================
print("\n4️⃣ Vergleich DB vs MT5...")
closed_positions = []
for trade in db_open_trades:
ticket = trade['ticket']
if ticket not in mt5_tickets:
closed_positions.append(ticket)
print(f"❗ Ticket {ticket} in DB als 'open', aber NICHT in MT5 → GESCHLOSSEN!")
if not closed_positions:
print("✅ Alle DB-Trades sind in MT5 noch offen (korrekt)")
else:
print(f"\n🎯 Gefunden: {len(closed_positions)} geschlossene Positionen in DB!")
# ==========================================
# 5. CHECK HISTORY FOR CLOSED POSITIONS
# ==========================================
if closed_positions:
print("\n5️⃣ Prüfe History für geschlossene Positionen...")
for ticket in closed_positions:
print(f"\n Ticket {ticket}:")
# Get deals history
deals = mt.history_deals_get(ticket=ticket)
if not deals:
print(f" ❌ Keine History gefunden!")
print(f" → Mögliche Ursache: History nicht weit genug zurück geladen")
continue
print(f" ✅ {len(deals)} Deals gefunden")
# Find close deal
close_deal = None
for deal in deals:
print(f" Deal {deal.ticket}: entry={deal.entry}, type={deal.type}, price={deal.price}, time={datetime.fromtimestamp(deal.time)}")
if deal.entry == 1: # Entry out = Close
close_deal = deal
if close_deal:
print(f" ✅ CLOSE DEAL gefunden:")
print(f" Exit Price: {close_deal.price}")
print(f" Exit Time: {datetime.fromtimestamp(close_deal.time)}")
print(f" Profit: {close_deal.profit}")
print(f" Commission: {close_deal.commission}")
print(f" Swap: {close_deal.swap}")
print(f" Net Profit: {close_deal.profit + close_deal.commission + close_deal.swap}")
else:
print(f" ❌ Kein Close Deal gefunden (entry=1)")
# ==========================================
# 6. CHECK HISTORY TIME RANGE
# ==========================================
print("\n6️⃣ MT5 History Time Range Check...")
# Get history from last 7 days
from datetime import timedelta
now = datetime.now()
week_ago = now - timedelta(days=7)
deals = mt.history_deals_get(week_ago, now)
if deals:
print(f"✅ History verfügbar: {len(deals)} Deals in letzten 7 Tagen")
oldest = min(deals, key=lambda d: d.time)
newest = max(deals, key=lambda d: d.time)
print(f" Oldest: {datetime.fromtimestamp(oldest.time)}")
print(f" Newest: {datetime.fromtimestamp(newest.time)}")
else:
print("❌ Keine History verfügbar!")
# ==========================================
# 7. RECOMMENDATIONS
# ==========================================
print("\n" + "=" * 60)
print("📋 ZUSAMMENFASSUNG & EMPFEHLUNGEN")
print("=" * 60)
print(f"\n• DB Open Trades: {len(db_open_trades)}")
print(f"• MT5 Open Positions: {len(mt5_positions) if mt5_positions else 0}")
print(f"• Geschlossene (nicht updated): {len(closed_positions)}")
if closed_positions:
print("\n⚠️ PROBLEM IDENTIFIZIERT:")
print(f" {len(closed_positions)} Positionen sind geschlossen, aber DB wurde nicht updated!")
print("\n💡 LÖSUNG:")
print(" 1. Position Monitor läuft bereits")
print(" 2. Führe manuell aus: position_monitor.check_open_positions()")
print(" 3. Prüfe Logs auf Fehler")
elif len(db_open_trades) == len(mt5_positions if mt5_positions else []):
print("\n✅ ALLES OK:")
print(" Alle DB-Trades sind korrekt als 'open' markiert")
print(" Position Monitor wartet auf nächsten Close")
else:
print("\n❓ UNKLAR:")
print(" DB und MT5 nicht synchron, aber keine offensichtlichen Closes")
mt.shutdown()
conn.close()
print("\n" + "=" * 60)
print("✅ Diagnose abgeschlossen")
print("=" * 60)