#!/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)