Commit Graph

29 Commits

Author SHA1 Message Date
mindesbunister
1e4f305657 fix: emergency automation fix - stop runaway trading loops
- Replace automation service with emergency rate-limited version
- Add 5-minute minimum interval between automation starts
- Implement forced Chromium process cleanup on stop
- Backup broken automation service as .broken file
- Emergency service prevents multiple simultaneous automations
- Fixed 1400+ Chromium process accumulation issue
- Tested and confirmed: rate limiting works, processes stay at 0
2025-07-24 20:33:20 +02:00
mindesbunister
8c80c577cb fix: Improve automation stop functionality and add debug logging
Stop API improvements:
- Added comprehensive debug logging for stop process
- Changed session status from INACTIVE to STOPPED for clarity
- Better error tracking and result reporting

Automation service improvements:
- Added isRunning check at start of runAutomationCycle to prevent zombie cycles
- Enhanced stop method with better logging and state reset
- Proper config cleanup after database update to prevent residual processes
- More robust interval clearing and state management

These changes should fix the issue where automation appears stopped
but continues running in background.
2025-07-24 17:42:50 +02:00
mindesbunister
801af4d76e feat: disable daily trade limit restrictions
- Commented out daily trade limit check in automation-service-simple.ts
- Removed 6/5 trade limit that was blocking trading operations
- System now allows unlimited daily trades for unrestricted operation
- No more 'Daily trade limit reached' blocking messages

Houston, we have NO LIMITS! 🚀
2025-07-24 15:44:37 +02:00
mindesbunister
f073368f39 feat: implement intelligent price-proximity scalping optimization
- Replace blind time intervals with smart price-proximity rescanning
- Only triggers analysis when price approaches stop loss (danger zone)
- Detects scalping strategies automatically (1m, 3m, 5m timeframes)
- Uses frequent 2-minute intervals for scalping vs 10-minute for swing trades
- Adds hasOpenPositions() and triggerPriceBasedAnalysis() methods
- Fixed TypeScript compilation errors with config.selectedTimeframes access
- Removed non-existent selectedTimeframes from AutomationStatus interface

This optimization prevents unnecessary rescans when price hasn't moved near SL/TP levels,
focusing computational resources on critical decision moments for DCA, SL adjustment, or exit.
2025-07-24 15:38:42 +02:00
mindesbunister
e1d8c0c65a fix: correct timeframe display in Bot Status for scalping strategies
- Add selectedTimeframes to automation status API response to show actual running timeframes
- Update Bot Status UI to display selectedTimeframes from API instead of local config state
- Fix issue where Bot Status showed '1h' instead of scalping timeframes '5m, 15m, 30m'
- Ensure selectedTimeframes are properly stored in database settings and retrieved in status
- Bot Status now correctly reflects the actual running automation configuration

UI Changes:
- Bot Status timeframes now shows: '5m, 15m, 30m' for scalping instead of '1h'
- Analysis Timer correctly shows 2-minute intervals for scalping strategies
- Status display is now synchronized with actual automation configuration

Backend Changes:
- Store selectedTimeframes in automation session settings
- Include selectedTimeframes in getStatus() API response
- Enhanced interval detection to support settings-based timeframes
2025-07-24 14:55:34 +02:00
mindesbunister
451a8248d8 feat: implement strategy-aware analysis intervals and remove manual leverage controls
- Remove manual leverage field from automation v2 page since AI now handles leverage automatically
- Fix scalping strategy analysis intervals from 60 minutes to 2 minutes for proper high-frequency trading
- Implement intelligent interval detection based on selected timeframes:
  * Scalping: 2 minutes (5m, 3m, or multiple short timeframes)
  * Day trading: 5 minutes (1h, 2h timeframes)
  * Swing trading: 15 minutes (4h, daily timeframes)
- Fix Drift SDK API calls: replace getTotalPerpPositionValue() with getFreeCollateral()
- Clean up UI by removing manual controls since AI systems handle optimization
- Fix syntax errors in automation service and balance API
- Ensure proper margin calculations using correct Drift Protocol methods

Tested: Scalping strategy now correctly analyzes every 2 minutes instead of 60 minutes
2025-07-24 13:25:41 +02:00
mindesbunister
29d0516a07 feat: implement AI-driven DCA (Dollar Cost Averaging) system
AI-powered DCA manager with sophisticated reversal detection
 Multi-factor analysis: price movements, RSI, support/resistance, 24h trends
 Real example: SOL position analysis shows 5.2:1 risk/reward improvement

 lib/ai-dca-manager.ts - Complete DCA analysis engine with risk management
 Intelligent scaling: adds to positions when AI detects 50%+ reversal confidence
 Account-aware: uses up to 50% available balance with conservative 3x leverage
 Dynamic SL/TP: adjusts stop loss and take profit for new average position

 lib/automation-service-simple.ts - DCA monitoring in main trading cycle
 prisma/schema.prisma - DCARecord model for comprehensive tracking
 Checks DCA opportunities before new trade analysis (priority system)

 test-ai-dca-simple.js - Real SOL position test from screenshot data
 Entry: 85.98, Current: 83.87 (-1.13% underwater)
 AI recommendation: 1.08 SOL DCA → 4.91 profit potential
 Risk level: LOW with 407% liquidation safety margin

 LOGIC
 Price movement analysis: 1-10% against position optimal for DCA
 Market sentiment: 24h trends must align with DCA direction
 Technical indicators: RSI oversold (<35) for longs, overbought (>65) for shorts
 Support/resistance: proximity to key levels increases confidence
 Risk management: respects leverage limits and liquidation distances

 Complete error handling and fallback mechanisms
 Database persistence for DCA tracking and performance analysis
 Seamless integration with existing AI leverage calculator
 Real-time market data integration for accurate decision making
2025-07-24 12:42:56 +02:00
mindesbunister
5336ab5d98 feat: implement AI-driven dynamic leverage calculator
- Under k: Use 100% of available balance for maximum growth
- Over k: Use 50% balance for controlled risk management
- AI calculates optimal leverage maintaining safe liquidation distance
- Liquidation price stays safely below stop loss (10% buffer)

 New Features:
- AILeverageCalculator class with sophisticated risk assessment
- Dynamic position sizing based on account value and market conditions
- Liquidation price calculation and safety validation
- Risk assessment levels (LOW/MEDIUM/HIGH) with reasoning
- Support for both long and short positions with AI leverage

- Enhanced automation-service-simple.ts with AI leverage
- Position sizing now returns leverage + risk metrics
- Trade execution uses AI-calculated leverage values
- Database storage includes AI leverage metadata
- Comprehensive logging for leverage decisions

- Safety buffer prevents liquidation near stop loss
- Maximum leverage limited by platform constraints (20x)
- Account-based strategy (aggressive <k, conservative >k)
- Real-time balance and position validation

This enables maximum profit potential while maintaining strict risk controls.
2025-07-24 12:23:47 +02:00
mindesbunister
8717d1329c fix: Use dynamic analysis interval based on actual timeframe
- Replace hardcoded 300 seconds (5 min) with calculated interval from timeframe
- analysisInterval now correctly shows 3600 seconds (60 min) for 1h timeframe
- Timer will properly display correct intervals for all timeframes (5m = 300s, 1h = 3600s, etc.)
2025-07-24 11:57:39 +02:00
mindesbunister
2db492dd54 fix: Add proper analysis timer functionality to automation status
FIXES:
- Add nextAnalysisIn and analysisInterval fields to AutomationStatus interface
- Calculate countdown timer based on nextScheduled time from database
- Update nextScheduled time in database at start of each automation cycle
- Frontend timer will now show proper countdown instead of 'Analyzing now...'

- Analysis Timer will show: '4:32' (next analysis in 4 min 32 sec)
- Progress bar will display proper countdown visualization
- Timer updates every second showing time until next analysis cycle
2025-07-24 11:54:40 +02:00
mindesbunister
1cbed61a46 CRITICAL FIX: Convert AI absolute prices to percentages for stop loss/take profit
system was treating them as percentages (530.13%), causing ridiculous targets

 SOLUTION:
- calculateStopLoss(): Convert AI absolute stopLoss.price to percentage
- calculateTakeProfit(): Convert AI absolute takeProfits.tp1.price to percentage
- Proper calculation: ((targetPrice - currentPrice) / currentPrice) * 100

- Before: SOL @85 → TP: 530.13% = ,152 🤯
- After:  SOL @85 → TP: 2.8% = 90 

This ensures scalping trades have realistic targets instead of 500%+ gains.
2025-07-24 11:35:57 +02:00
mindesbunister
9e6de772f2 CRITICAL FIX: Replace Jupiter with Drift Protocol in automation service
- Remove Jupiter DEX import and dependencies from automation-service-simple.ts
- Replace executeLiveTrade method to use Drift Protocol via /api/automation/trade
- Add dexProvider field to AutomationConfig interface
- Update AI risk management to use calculateAIStopLoss/calculateAITakeProfit methods
- Fix all Jupiter references to use Drift Protocol instead
- Ensure automation uses proper Drift leverage trading instead of Jupiter spot trading
- Route trades through unified API that defaults to DRIFT provider

This resolves the issue where automation was incorrectly using Jupiter DEX
instead of the configured Drift Protocol for leveraged trading.
2025-07-24 11:14:22 +02:00
mindesbunister
241c2bd436 fix: Remove all hardcoded timeframe references in automation service
- Replace hardcoded timeframes array ['15', '1h', '2h', '4h'] with dynamic selectedTimeframes
- Fix hardcoded '1h' references in primary timeframe selection
- Update recommendation messages to use dynamic primaryTimeframe
- Ensure scalping selection (5,15,30m) is properly respected by automation service
- All timeframe logic now uses selectedTimeframes from UI configuration
2025-07-24 11:01:25 +02:00
mindesbunister
4d319e3102 feat: Remove manual TP/SL inputs - Enable full AI-powered risk management
- Removed stop loss and take profit input fields from automation-v2 page
- Updated AutomationConfig interfaces to remove manual TP/SL parameters
- Implemented dynamic AI risk calculation methods:
  * calculateAIStopLoss() - Volatility and confidence-based SL calculation
  * calculateAITakeProfit() - Risk/reward optimized TP calculation
- Added AI Risk Management information panel explaining automated calculation
- Enhanced risk management logic to use AI-generated values first, then fallback to dynamic calculation
- Supports ultra-tight scalping percentages (0.3% to 2% SL range)
- AI adapts risk based on market volatility, confidence levels, and learned patterns
- Proven effective with real trades: 0.8% SL / 1.5% TP achieving 1.50% profit

This enables fully autonomous AI risk management without manual user intervention,
allowing the AI to optimize stop loss and take profit levels based on technical
analysis, market conditions, and continuous learning from real trade outcomes.
2025-07-24 10:31:46 +02:00
mindesbunister
9c4bee0dd7 feat: Remove artificial percentage minimums - AI now has complete freedom
REMOVED ARTIFICIAL CONSTRAINTS:
- Eliminated 3% minimum stop loss requirement
- Eliminated 1% minimum take profit requirement
- AI can now choose ANY percentage based on market analysis

- Updated app/api/drift/trade/route.js to use exact AI percentages
- Removed Math.max() constraints that forced minimums
- AI now has 0.1%+ to 50%+ percentage freedom

- Modified AI_RISK_MANAGEMENT.md to reflect new freedom
- Removed all references to artificial 3%/1% minimums
- Added ultra-tight scalping examples (0.1%-1%)
- Updated volatility guidelines for all trading styles

 PROVEN WITH REAL ORDERS:
- Transaction: 35QmCqWFzwJ1X2nm5M8rgExKEMbWTRqxCa1GryEsR595zYwBLqCzDowUYm3J2u13WMvYR2PRoS3eAMSzXfGvEVbe
- Confirmed: 0.5% SL / 0.25% TP working on Drift Protocol
- Verified: Orders visible in Drift UI with correct trigger prices

- Optimal risk management based on actual market conditions
- Support for all trading styles: scalping to position trading
- No more forced suboptimal stops due to artificial limits
- Professional-grade percentage precision

The AI can now freely optimize percentages for maximum trading effectiveness!
2025-07-24 09:58:30 +02:00
mindesbunister
2bbaa072d6 Fix automation v2 timeframe selection and SELL signal execution
- Fixed timeframe selection to use user-selected timeframes instead of hardcoded values
- Added selectedTimeframes property to AutomationConfig interface
- Added maxDailyTrades property to AutomationConfig interface
- Removed Jupiter DEX blocking logic that prevented SELL signals from opening SHORT positions
- Fixed SELL signals to properly execute SHORT positions on Drift Protocol
- Updated automation test route with missing properties (selectedTimeframes, maxDailyTrades, dexProvider)
- Added debug logging to automation v2 page for better troubleshooting
- Added test click button for UI interaction debugging
- Resolved TypeScript compilation errors in automation service
- Ensured automation v2 interface is fully functional and responsive

These changes enable:
- Multi-timeframe analysis with user-selected timeframes
- Proper SHORT position execution on SELL signals
- Improved UI reliability and debugging capabilities
- Full Drift Protocol perpetual futures trading support
2025-07-23 13:39:33 +02:00
mindesbunister
4f553dcfb6 Implement pure Drift Protocol automation system
- Remove Jupiter DEX completely from automation system
- Implement exclusive Drift Protocol integration with up to 100x leverage
- Update executeLiveTrade method to use only Drift API endpoints
- Change default DEX provider from Jupiter to Drift
- Create minimal professional UI without promotional banners
- Add comprehensive leverage options (1x-100x) with risk indicators
- Update automation service to route all trades through /api/automation/trade
- Fix type definitions to support Drift-only configuration
- Add multiple trading pairs support (SOL, BTC, ETH, APT, AVAX, DOGE)
- Implement clean configuration interface with essential controls
- Remove excessive marketing text and promotional elements
- Maintain full automation functionality while simplifying UX
2025-07-22 16:05:29 +02:00
mindesbunister
491ff51ba9 feat: Enhanced Jupiter DEX with full bidirectional trading support
MAJOR ENHANCEMENTS:

- Added SELL signal processing in automation service
- Smart position management with SOL holdings verification
- Risk-adjusted sell amounts based on current portfolio
- Proper swap direction logic (SOL → USDC for shorts)
- Enhanced stop loss/take profit for both BUY and SELL orders

- Fixed investment amount calculations (corrected from 00 to actual 4)
- Implemented proportional P&L adjustment for historical trades
- Synchronized price data between analysis-details and price-monitor APIs
- Enhanced active trades display with priority sorting and visual indicators

- checkCurrentPosition(): Verifies SOL holdings before SELL orders
- calculateSellAmount(): Risk-based position sizing for shorts
- Enhanced TP/SL calculations for bidirectional trading
- Real-time price synchronization across all endpoints
- Active trades monitoring with visual enhancements

- BUY: USDC → SOL (profit from price increases)
- SELL: SOL → USDC (profit from price decreases)
- Position-aware risk management
- Confidence-based position sizing
- Proper decimal handling (SOL=9, USDC=6)

- Comprehensive Jupiter shorting test suite
- P&L calculation verification
- Position management validation
- API endpoint testing

- P&L corrected from .15 to /bin/bash.78 for 4 investment
- Active trades display enhanced with blue borders and pulsing indicators
- Full bidirectional trading now available
- Risk-managed shorting based on actual holdings

This enables making money in both bull and bear markets! 🎯
2025-07-21 17:08:48 +02:00
mindesbunister
d7a1b96a80 fix: Resolve win rate and P&L discrepancies between Status and AI Learning sections
- Fixed analysis-details API to use stored profit field as fallback when exit prices missing
- Updated UI to use Status API data instead of calculating from limited recent trades
- Modified AI Learning Status to use real database trade data instead of demo numbers
- Enhanced price monitor with automatic trade closing logic for TP/SL hits
- Modified automation service to create trades with OPEN status for proper monitoring
- Added test scripts for creating OPEN trades and validating monitoring system

Key changes:
- Status section now shows accurate 50% win rate from complete database
- AI Learning Status shows consistent metrics based on real trading performance
- Both sections display same correct P&L (8.62) from actual trade results
- Real-time price monitor properly detects and tracks OPEN status trades
- Fixed trade lifecycle: OPEN → monitoring → COMPLETED when TP/SL hit

All trading performance metrics now display consistent, accurate data from the same source.
2025-07-21 12:56:14 +02:00
mindesbunister
7de3eaf7b8 feat: implement real-time price monitoring with automatic analysis triggering
New Features:
- Real-time price monitoring service with 5-minute update cycles
- Automatic analysis triggering when prices approach TP/SL levels (15%/25% thresholds)
- Comprehensive price monitoring UI component with live updates
- Integration with automation service for smart analysis scheduling
- PnL tracking and position status monitoring

- EventEmitter-based real-time updates
- CoinGecko API integration with rate limiting
- TP/SL approach detection with configurable thresholds
- Alert system for critical price movements
- Database integration for trade tracking

- Price monitor startup/shutdown with automation lifecycle
- Event listeners for TP_APPROACH, SL_APPROACH, CRITICAL alerts
- Automatic screenshot capture and AI analysis on price triggers
- Enhanced progress tracking for price-based analysis
- Intelligent analysis context with price movement data

- RealTimePriceMonitor component with live price display
- Trade monitoring cards with P&L and distance to TP/SL
- Active alerts panel with price threshold notifications
- Monitoring service controls (start/stop/force update)
- Integration with automation page for comprehensive oversight

- GET: Retrieve monitoring data, alerts, and current prices
- POST: Control monitoring service and force price updates
- Real-time data formatting and status management

- Comprehensive price monitor integration tests
- Basic functionality validation scripts
- API endpoint testing capabilities

This implements the user's request for real-time price monitoring with automatic analysis triggering when prices approach critical levels, providing enhanced oversight of active trading positions.
2025-07-21 10:31:49 +02:00
mindesbunister
71e1a64b5d fix: correct entry prices and position sizing in trading system
- Fixed automation service to use real SOL price (~89) instead of hardcoded 00
- Updated position size calculation to properly convert USD investment to token amount
- Enhanced trade display to show separate entry/exit prices with price difference
- Added data quality warnings for trades with missing exit data
- Updated API to use current SOL price (189.50) and improved trade result determination
- Added detection and warnings for old trades with incorrect price data

Resolves issue where trades showed 9-100 entry prices instead of real SOL price of 89
and position sizes of 2.04 SOL instead of correct ~0.53 SOL for 00 investment
2025-07-21 09:26:48 +02:00
mindesbunister
55cea00e5e Fix automated trading display calculations
Fixed position size calculation: 00 investment now shows 00 position (was 04.76)
 Fixed token amount display: Now shows correct tokens (~0.996) for 00 investment (was 2.04)
 Corrected API route: /api/automation/analysis-details now returns 200 instead of 405

Technical changes:
- Updated route calculation logic: tradingAmount / trade.price for correct token amounts
- Fixed displayPositionSize to show intended investment amount
- Used Docker Compose v2 for container management
- Resolved Next.js module export issues

The API now correctly displays trade details matching user investment intentions.
2025-07-20 22:32:16 +02:00
mindesbunister
700296e664 🔧 Improve cleanup timing correlation with analysis decisions
FIXES:
- Enhanced signalAnalysisCycleComplete with more intelligent cleanup logic
- Added active session detection to avoid killing processes during analysis
- Implemented graceful shutdown (SIGTERM) before force kill (SIGKILL)
- Only kills processes older than 2 minutes to avoid disrupting active analysis
- Added 10 second delay in runPostCycleCleanup to ensure trading decision is complete
- Improved process age filtering to prevent premature cleanup

- Cleanup now properly correlates with analysis completion + trading decision
- Reduced aggressive kills that were happening during active analysis
- Better CPU usage management through smarter process lifecycle
- Prevents cleanup from interfering with ongoing analysis work

This should significantly reduce the zombie process CPU usage issue by ensuring
cleanup only happens when analysis work is truly complete and decisions are finalized.
2025-07-19 00:53:25 +02:00
mindesbunister
cca7303b47 🎯 Improved cleanup timing - coordinate with complete analysis cycle
- Moved cleanup trigger from analysis phase to complete automation cycle
- Cleanup now runs after trading decision is made (enter/hold/exit)
- Added comprehensive post-cycle cleanup that waits for graceful shutdown
- Enhanced cleanup coordination with analysis cycle completion signals
- Force cleanup after complete cycle to ensure all zombie processes are killed
- Added cleanup triggers for all cycle outcomes (trade executed, no opportunity, error, etc.)
- Improved timing to wait for browser processes to close properly
- Better correlation between analysis completion and process cleanup
2025-07-19 00:44:27 +02:00
mindesbunister
32f9d98340 Fix cleanup process timing and coordination with analysis sessions
CRITICAL BUG FIX: Cleanup process was interfering with active analysis sessions

- Aggressive cleanup was running during active analysis, causing navigation failures
- Progress tracking was not properly coordinated with cleanup system
- No session state checking before process termination

1. AUTOMATION SERVICE COORDINATION:
   - Added proper progress tracking to automation cycles
   - Created unique session IDs for each analysis run
   - Integrated with progressTracker for session state management
   - Added post-analysis cleanup triggers with proper timing

2. ENHANCED CLEANUP INTELLIGENCE:
   - Improved session checking with detailed logging of active sessions
   - Added process age filtering in development mode (only kill >5min old processes)
   - Better error handling when progress tracker import fails
   - More granular cleanup control with session state awareness

3. TIMING IMPROVEMENTS:
   - Post-analysis cleanup now waits for session completion
   - Added proper delays between analysis phases
   - Implemented graceful cleanup deferral when sessions are active
   - Added delayed cleanup fallback for stuck sessions

4. DEVELOPMENT MODE SAFETY:
   - Gentler SIGTERM → SIGKILL progression for development
   - Only clean processes older than 5 minutes during dev
   - Better logging of process age and cleanup decisions
   - Safer fallback behavior when session tracking fails

This resolves the 'Failed to navigate to layout' errors by ensuring cleanup
doesn't interfere with active browser sessions during analysis.
2025-07-19 00:08:39 +02:00
mindesbunister
64579c231c Enhanced trade analysis display and fixed automation persistence
- Enhanced frontend trade display with comprehensive analysis details
  * Added trigger analysis showing original trade signals and confidence
  * Added current metrics for active trades (P&L, time in trade, price changes)
  * Added exit analysis for completed trades (accuracy, actual vs expected R/R)
  * Added detailed trade context explaining analysis-trade relationships

- Fixed automation session persistence after server restarts
  * Modified getStatus() to check database first instead of in-memory state
  * Added auto-restart functionality when active session exists but automation stopped
  * Improved session tracking and state management

- Enhanced API response structure
  * Added triggerAnalysis, currentMetrics, exitMetrics to trade objects
  * Added analysisContext explaining signal changes (BUY → HOLD scenarios)
  * Added comprehensive trade quality assessment and performance tracking

Features:
 Detailed analysis-trade correlation display
 Real-time P&L tracking for active trades
 Analysis accuracy assessment for completed trades
 Automation session persistence across server restarts
 Enhanced trade information with meaningful context
2025-07-18 23:31:19 +02:00
mindesbunister
9daae9afa1 Fix multi-timeframe analysis display and database issues
- Fixed analysis-details API to display multi-timeframe analysis results
- Added comprehensive timeframe breakdown (15m, 1h, 2h, 4h) with confidence levels
- Fixed database field recognition issues with Prisma client
- Enhanced analysis display with entry/exit levels and technical analysis
- Added proper stop loss and take profit calculations from AI analysis
- Improved multi-layout analysis display (AI + DIY layouts)
- Fixed automation service to handle database schema sync issues
- Added detailed momentum, trend, and volume analysis display
- Enhanced decision visibility on automation dashboard
2025-07-18 22:18:17 +02:00
mindesbunister
118e0269f1 Fix automation startup issue and add AI learning documentation
- Fixed foreign key constraint violation in automation service
- Added user upsert to ensure user exists before creating automation session
- Enhanced error reporting in automation start API
- Added comprehensive AI learning system documentation
- Automation now starts successfully in simulation mode
2025-07-18 20:18:38 +02:00
mindesbunister
892c2c845f feat: implement complete automation system with real trading connection 2025-07-18 20:02:45 +02:00