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

84 lines
2.3 KiB
Python
Raw Normal View History

2025-12-16 22:02:15 +01:00
#!/usr/bin/env python3
"""
🧹 Cleanup Stale Open Positions
Changes status from 'open' to 'historical' for old positions
"""
import sqlite3
from datetime import datetime, timedelta
DB_PATH = "trading_bot.db"
def cleanup_stale_positions():
"""Clean up old open positions"""
print("=" * 70)
print("🧹 CLEANING UP STALE OPEN POSITIONS")
print("=" * 70)
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
try:
# 1. Check current state
print("\n📊 CURRENT STATE:")
cursor.execute("SELECT status, COUNT(*) FROM trades GROUP BY status")
for row in cursor.fetchall():
print(f" {row[0]}: {row[1]}")
# 2. Find stale open positions (older than 24h)
cutoff = (datetime.now() - timedelta(hours=24)).isoformat()
cursor.execute("""
SELECT COUNT(*)
FROM trades
WHERE status = 'open'
AND entry_time < ?
""", (cutoff,))
stale_count = cursor.fetchone()[0]
print(f"\n🔍 Found {stale_count} stale 'open' positions (older than 24h)")
if stale_count == 0:
print("✅ Nothing to clean up!")
return True
# 3. Update stale positions to historical
cursor.execute("""
UPDATE trades
SET status = 'historical'
WHERE status = 'open'
AND entry_time < ?
""", (cutoff,))
conn.commit()
print(f"✅ Updated {stale_count} positions: 'open' → 'historical'")
# 4. Verify
print("\n📊 AFTER CLEANUP:")
cursor.execute("SELECT status, COUNT(*) FROM trades GROUP BY status")
for row in cursor.fetchall():
print(f" {row[0]}: {row[1]}")
print("\n✅ CLEANUP COMPLETE!")
print("\n💡 RESULT:")
print(" - Old 'open' trades moved to 'historical'")
print(" - New trades will use 'closed' status")
print(" - Consecutive loss counter will work correctly")
return True
except Exception as e:
print(f"\n❌ ERROR: {e}")
import traceback
traceback.print_exc()
return False
finally:
conn.close()
if __name__ == "__main__":
import sys
success = cleanup_stale_positions()
sys.exit(0 if success else 1)