Files
Place-Order-Trading-Bot/setup_automated_backup.py
T
cbazza 23f0a4c800 Add database cleanup and backup automation
Created comprehensive database maintenance tools:

1. database_cleanup.py ( EXECUTED)
   - Fixed 102 unknown sessions → assigned to correct sessions
   - Revealed true win rate: 67.8% (not 18.5%!)
   - Created automatic backup before changes

2. cleanup_historical_trades.py
   - Handles 240 'historical' trades with NULL profit
   - 3 options: Delete / Mark / Set to breakeven
   - Interactive selection with backup

3. setup_automated_backup.py
   - Daily automated backups
   - Windows Task Scheduler integration
   - 7-day backup rotation
   - Manual backup option

Results after cleanup:
-  Unknown sessions: 0 (was 102)
-  Session distribution: asian 132, ny 64, overlap 75, london 58
-  Win rate: 67.8% (61 wins / 90 trades)
-  Backup created: trading_bot_before_cleanup_20251226_162438.db
-  240 historical trades pending decision (recommend delete)

Next steps:
1. Run cleanup_historical_trades.py (option 1: delete)
2. Setup automated backups via Task Scheduler
3. Re-analyze performance with correct session data
2025-12-26 16:28:07 +01:00

187 lines
5.1 KiB
Python

#!/usr/bin/env python3
"""
💾 Automated Backup Setup
Erstellt tägliche automatische Backups via Windows Task Scheduler
"""
import os
import shutil
from datetime import datetime
import subprocess
BACKUP_DIR = "backups"
DB_PATH = "trading_bot.db"
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
# ==========================================
# BACKUP SCRIPT
# ==========================================
def create_daily_backup():
"""Erstellt tägliches Backup mit Rotation"""
if not os.path.exists(BACKUP_DIR):
os.makedirs(BACKUP_DIR)
# Create backup
timestamp = datetime.now().strftime('%Y%m%d')
backup_path = f"{BACKUP_DIR}/trading_bot_daily_{timestamp}.db"
shutil.copy(DB_PATH, backup_path)
print(f"✅ Backup erstellt: {backup_path}")
# Cleanup old backups (keep last 7 days)
cleanup_old_backups(7)
def cleanup_old_backups(keep_days=7):
"""Löscht Backups älter als X Tage"""
if not os.path.exists(BACKUP_DIR):
return
backups = [f for f in os.listdir(BACKUP_DIR) if f.startswith("trading_bot_daily_")]
backups.sort(reverse=True) # Neueste zuerst
# Keep only last N backups
to_delete = backups[keep_days:]
for backup in to_delete:
backup_path = os.path.join(BACKUP_DIR, backup)
os.remove(backup_path)
print(f"🗑️ Gelöscht: {backup}")
print(f"💾 Behalten: {min(len(backups), keep_days)} Backups")
# ==========================================
# WINDOWS TASK SCHEDULER SETUP
# ==========================================
def create_backup_bat():
"""Erstellt .bat Datei für Task Scheduler"""
bat_content = f"""@echo off
REM Daily Database Backup
cd /d "{SCRIPT_DIR}"
python setup_automated_backup.py --run
"""
bat_path = os.path.join(SCRIPT_DIR, "daily_backup.bat")
with open(bat_path, 'w') as f:
f.write(bat_content)
print(f"✅ Backup Script erstellt: {bat_path}")
return bat_path
def create_task_scheduler_command(bat_path):
"""Erstellt Windows Task Scheduler Befehl"""
task_name = "TradingBotDailyBackup"
# schtasks command
cmd = f"""schtasks /Create /TN "{task_name}" /TR "{bat_path}" /SC DAILY /ST 00:00 /F"""
print("\n" + "="*80)
print("📋 WINDOWS TASK SCHEDULER SETUP")
print("="*80)
print("\nFührenden Sie folgenden Befehl in CMD (als Administrator) aus:")
print()
print(cmd)
print()
print("Oder manuell:")
print("1. Windows-Taste + R")
print("2. taskschd.msc eingeben")
print("3. 'Aufgabe erstellen'")
print(f"4. Name: {task_name}")
print("5. Trigger: Täglich um 00:00")
print(f"6. Aktion: {bat_path}")
print()
# Try to create automatically
try:
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if result.returncode == 0:
print("✅ Task Scheduler automatisch erstellt!")
else:
print(f"⚠️ Automatische Erstellung fehlgeschlagen: {result.stderr}")
print("Bitte manuell erstellen (siehe oben)")
except Exception as e:
print(f"⚠️ Konnte nicht automatisch erstellen: {e}")
print("Bitte manuell erstellen (siehe oben)")
# ==========================================
# PYTHON SCHEDULER (Alternative)
# ==========================================
def setup_python_scheduler():
"""Info für Python-basierte Scheduler Alternative"""
print("\n" + "="*80)
print("🐍 ALTERNATIVE: Python Scheduler")
print("="*80)
print("\nFalls Windows Task Scheduler nicht funktioniert:")
print()
print("pip install schedule")
print()
print("Dann in Ihrem trading_bot Notebook/Script:")
print("""
import schedule
import time
from setup_automated_backup import create_daily_backup
# Schedule backup daily at midnight
schedule.every().day.at("00:00").do(create_daily_backup)
# In Scheduler-Loop (läuft bereits):
while True:
schedule.run_pending()
time.sleep(60)
""")
# ==========================================
# MAIN
# ==========================================
def main():
import sys
print("="*80)
print("💾 AUTOMATED BACKUP SETUP")
print("="*80)
print()
# Check if --run flag (called by task scheduler)
if "--run" in sys.argv:
print("🔄 Running scheduled backup...")
create_daily_backup()
return
# Setup mode
print("Optionen:")
print()
print("1️⃣ Windows Task Scheduler Setup (Empfohlen)")
print("2️⃣ Python Scheduler Info")
print("3️⃣ Manuelles Backup JETZT ausführen")
print("4️⃣ Backup-Verzeichnis aufräumen")
print()
choice = input("Ihre Wahl (1-4): ").strip()
if choice == "1":
bat_path = create_backup_bat()
create_task_scheduler_command(bat_path)
elif choice == "2":
setup_python_scheduler()
elif choice == "3":
print("\n🔄 Erstelle Backup...")
create_daily_backup()
elif choice == "4":
days = input("Wie viele Tage behalten? (Standard: 7): ").strip()
days = int(days) if days else 7
cleanup_old_backups(days)
else:
print(f"❌ Ungültige Wahl: {choice}")
print("\n✅ Fertig!")
if __name__ == "__main__":
main()