@@ -602,9 +602,10 @@ async def confirmation_expiry_task():
602602 rehydrated_count = rehydrate_paper_trades ()
603603 if rehydrated_count > 0 :
604604 logger .info (f"Rehydrated { rehydrated_count } active paper trades into PositionManager" )
605- cleaned_file_orphans = cleanup_orphan_paper_trades ()
606- if cleaned_file_orphans > 0 :
607- logger .warning (f"ORPHAN FILE CLEANUP: Closed { cleaned_file_orphans } trades on startup" )
605+ # NOTE: cleanup_orphan_paper_trades is NOT called here on purpose.
606+ # The orphan_file_cleanup_task background task will handle file-only orphans
607+ # after a delay, giving pending confirmations time to complete.
608+ # This prevents trades in confirmation-delay from being immediately closed on startup.
608609
609610 # Orphan Cleanup Task (closes old open trades)
610611 async def orphan_cleanup_task ():
@@ -738,17 +739,27 @@ async def orphan_file_cleanup_task():
738739 logger .debug ("Orphan file cleanup task disabled" )
739740 return
740741
742+ # Initial delay to allow pending confirmations to complete after startup
743+ # This prevents trades in confirmation-delay from being closed immediately
744+ initial_delay = getattr (settings , "CONFIRMATION_DELAY_SECONDS" , 60 ) + 30 # confirmation delay + buffer
745+ logger .info (f"Orphan file cleanup task: waiting { initial_delay } s for initial delay before first cleanup" )
746+ await asyncio .sleep (initial_delay )
747+
741748 poll_interval = 120.0 # Check every 2 minutes
742749 while True :
743750 try :
744- await asyncio .sleep (poll_interval )
745751 if not is_paper_trading ():
752+ await asyncio .sleep (poll_interval )
746753 continue
747- cleanup_orphan_paper_trades ()
754+ cleaned = cleanup_orphan_paper_trades ()
755+ if cleaned > 0 :
756+ logger .warning (f"ORPHAN FILE CLEANUP: Closed { cleaned } file-only orphan trades" )
757+ await asyncio .sleep (poll_interval )
748758 except asyncio .CancelledError :
749759 break
750760 except Exception as e :
751761 logger .error (f"Orphan file cleanup task error: { e } " )
762+ await asyncio .sleep (poll_interval )
752763
753764 # Start orphan cleanup task
754765 if settings .ORPHAN_CLEANUP_ENABLED :
0 commit comments