/** * Integration patch for main trading system * Adds automated Drift order cleanup to trading workflow */ const { driftOrderCleanupService } = require('./lib/drift-order-cleanup-service.js') class TradingSystemIntegration { static initialized = false /** * Initialize the cleanup service with the trading system */ static async initializeCleanupService() { if (this.initialized) { console.log('๐Ÿ”„ Drift cleanup service already initialized') return } console.log('๐Ÿš€ Initializing Drift order cleanup service...') try { // Start the automated monitoring driftOrderCleanupService.start(45000) // Check every 45 seconds // Set up cleanup triggers for position changes this.setupPositionMonitoring() this.initialized = true console.log('โœ… Drift order cleanup service initialized successfully') } catch (error) { console.error('โŒ Failed to initialize cleanup service:', error) throw error } } /** * Set up monitoring for position changes that might require cleanup */ static setupPositionMonitoring() { // Monitor for position closures that might leave orphaned orders const originalMonitorPosition = global.monitorPosition || (() => {}) global.monitorPosition = async (...args) => { const result = await originalMonitorPosition(...args) // Trigger cleanup after position monitoring setTimeout(async () => { try { console.log('๐Ÿงน Triggering cleanup after position monitoring...') await driftOrderCleanupService.checkAndCleanupOrders() } catch (error) { console.error('โŒ Cleanup after position monitoring failed:', error) } }, 5000) // Wait 5 seconds after position monitoring return result } console.log('๐Ÿ“Š Position monitoring integration set up') } /** * Cleanup orders after a specific trade action */ static async cleanupAfterTrade(tradeInfo = {}) { console.log('๐Ÿงน Cleaning up orders after trade action:', tradeInfo) try { // Wait a moment for the trade to settle await new Promise(resolve => setTimeout(resolve, 3000)) // Force cleanup const result = await driftOrderCleanupService.forceCleanup() console.log(`โœ… Post-trade cleanup completed: ${result.summary.totalCanceled} orders canceled`) return result } catch (error) { console.error('โŒ Post-trade cleanup failed:', error) return { success: false, error: error.message } } } /** * Enhanced position monitoring with automatic cleanup */ static async monitorPositionWithCleanup(marketSymbol, maxChecks = 30) { console.log(`๐Ÿ“Š Monitoring position for ${marketSymbol} with automatic cleanup...`) let lastPositionState = null for (let i = 0; i < maxChecks; i++) { try { // Check current position const response = await fetch('http://localhost:9001/api/drift/positions') if (response.ok) { const data = await response.json() const position = data.positions?.find(p => p.symbol === marketSymbol) // Detect position closure if (lastPositionState && lastPositionState.size !== 0 && (!position || position.size === 0)) { console.log(`๐ŸŽฏ Position closure detected for ${marketSymbol} - triggering cleanup`) // Wait a moment then cleanup setTimeout(async () => { try { await this.cleanupAfterTrade({ symbol: marketSymbol, action: 'position_closed' }) } catch (error) { console.error('โŒ Cleanup after position closure failed:', error) } }, 5000) } lastPositionState = position } // Wait before next check await new Promise(resolve => setTimeout(resolve, 10000)) } catch (error) { console.error(`โŒ Error monitoring position ${marketSymbol}:`, error) } } console.log(`๐Ÿ“Š Position monitoring completed for ${marketSymbol}`) } /** * Get cleanup service status */ static getCleanupStatus() { return { initialized: this.initialized, serviceStatus: driftOrderCleanupService.getStatus() } } /** * Stop the cleanup service */ static stopCleanupService() { if (!this.initialized) { console.log('โš ๏ธ Cleanup service not initialized') return } driftOrderCleanupService.stop() this.initialized = false console.log('๐Ÿ›‘ Drift order cleanup service stopped') } } // Auto-initialize if running in main trading environment if (typeof global !== 'undefined' && global.process?.title?.includes('node')) { // Wait a moment to let other systems initialize setTimeout(() => { TradingSystemIntegration.initializeCleanupService().catch(error => { console.error('โŒ Auto-initialization failed:', error) }) }, 10000) // Wait 10 seconds } module.exports = { TradingSystemIntegration, driftOrderCleanupService }