fix: add null checks to prevent 'Cannot read properties of null' error on automation page

- Added proper null checks for status object before accessing selectedTimeframes
- Fixed timeframes display to handle null status gracefully
- Fixed analysis interval calculation with optional chaining
- Resolved 500 internal server error on /automation-v2 page
This commit is contained in:
mindesbunister
2025-07-24 15:04:25 +02:00
parent e1d8c0c65a
commit 1505bc04cd
6 changed files with 2381 additions and 249 deletions

View File

@@ -15,35 +15,11 @@ This is a Next.js 15 App Router application with TypeScript, Tailwind CSS, and A
- TradingView automation with session persistence in `lib/tradingview-automation.ts`
- Session data stored in `.tradingview-session/` volume mount to avoid captchas
### AI-Driven Dynamic Leverage System ✅
**Complete AI leverage calculator with intelligent position sizing:**
- `lib/ai-leverage-calculator.ts` - Core AI leverage calculation engine with risk management
- Account-based strategies: <$1k uses 100% balance (aggressive), >$1k uses 50% balance (conservative)
- Safety mechanisms: 10% buffer between liquidation price and stop loss
- Platform integration: Drift Protocol with maximum 20x leverage constraints
- **Integration**: Enhanced `lib/automation-service-simple.ts` uses AI-calculated leverage for all positions
### AI-Driven DCA (Dollar Cost Averaging) System ✅
**Revolutionary position scaling that maximizes profits while managing risk:**
- `lib/ai-dca-manager.ts` - AI-powered DCA analysis engine with reversal detection
- **Multi-factor Analysis**: Price movements, 24h trends, RSI levels, support/resistance
- **Smart Scaling**: Adds to positions when AI detects reversal potential (50%+ confidence threshold)
- **Risk Management**: Respects leverage limits, adjusts stop loss/take profit for new average price
- **Account Integration**: Uses available balance strategically (up to 50% for DCA operations)
- **Real Example**: SOL position at $185.98 entry, $183.87 current → AI recommends 1.08 SOL DCA for 5.2:1 R/R improvement
**DCA Decision Factors:**
- Price movement against position (1-10% optimal range)
- 24h market sentiment alignment with DCA direction
- Technical indicators (RSI oversold/overbought zones)
- Proximity to support/resistance levels
- Available balance and current leverage headroom
- Liquidation distance and safety buffers
**Integration Points:**
- `lib/automation-service-simple.ts` - Automated DCA monitoring in main trading cycle
- `prisma/schema.prisma` - DCARecord model for tracking all scaling operations
- Database tracking of DCA count, total amount, and performance metrics
### AI Analysis Pipeline
- OpenAI GPT-4o mini for cost-effective chart analysis (~$0.006 per analysis)
- Multi-layout comparison and consensus detection in `lib/ai-analysis.ts`
- Professional trading setups with exact entry/exit levels and risk management
- Layout-specific indicator analysis (RSI vs Stochastic RSI, MACD vs OBV)
### Trading Integration
- **Drift Protocol**: Perpetual futures trading via `@drift-labs/sdk`
@@ -53,43 +29,6 @@ This is a Next.js 15 App Router application with TypeScript, Tailwind CSS, and A
## Critical Development Patterns
### Automation System Development Wisdom
**Key lessons from building and debugging the automation system:**
#### AI Risk Management vs Manual Controls
- **NEVER mix manual TP/SL inputs with AI automation** - causes conflicts and unpredictable behavior
- When implementing AI-driven automation, remove all manual percentage inputs from the UI
- AI should calculate dynamic stop losses and take profits based on market conditions, not user-defined percentages
- Always validate that UI selections (timeframes, strategies) are properly passed to backend services
#### Balance and P&L Calculation Critical Rules
- **ALWAYS use Drift SDK's built-in calculation methods** instead of manual calculations
- Use `driftClient.getUser().getTotalCollateral()` for accurate collateral values
- Use `driftClient.getUser().getUnrealizedPNL()` for accurate P&L calculations
- **NEVER use hardcoded prices** (like $195 for SOL) - always get current market data
- **NEVER use empirical precision factors** - use official SDK precision handling
- Test balance calculations against actual Drift interface values for validation
- Unrealized P&L should match position-level P&L calculations
#### Timeframe Handling Best Practices
- **Always use minute values first** in timeframe mapping to avoid TradingView confusion
- Example: `'4h': ['240', '240m', '4h', '4H']` - 240 minutes FIRST, then alternatives
- Validate that UI timeframe selections reach the automation service correctly
- Log timeframe values at every step to catch hardcoded overrides
#### System Integration Debugging
- **Always validate data flow** from UI → API → Service → Trading execution
- Check for hardcoded values that override user selections (especially timeframes)
- Verify correct protocol usage (Drift vs Jupiter) in trading execution
- Test cleanup systems regularly - memory leaks kill automation reliability
- Implement comprehensive logging for multi-step processes
#### Analysis Timer Implementation
- Store `nextScheduled` timestamps in database for persistence across restarts
- Calculate countdown dynamically based on current time vs scheduled time
- Update timer fields in automation status responses for real-time UI updates
- Format countdown as "XhYm" or "Xm Ys" for better user experience
### Docker Container Development (Required)
**All development happens inside Docker containers** using Docker Compose v2. Browser automation requires specific system dependencies that are only available in the containerized environment:
@@ -618,39 +557,6 @@ When working with this codebase, prioritize Docker consistency, understand the d
4. Commit restoration: `git add . && git commit -m "fix: restore automation-v2 functionality" && git push`
5. Rebuild container to persist restoration
### Testing and Validation Patterns (Critical)
**Essential validation steps learned from complex automation debugging:**
#### API Response Validation
- **Always test API responses directly** with curl before debugging UI issues
- Compare calculated values against actual trading platform values
- Example: `curl -s http://localhost:9001/api/drift/balance | jq '.unrealizedPnl'`
- Validate that API returns realistic values (2-5% targets, not 500% gains)
#### Multi-Component System Testing
- **Test data flow end-to-end**: UI selection → API endpoint → Service logic → Database storage
- Use browser dev tools to verify API calls match expected parameters
- Check database updates after automation cycles complete
- Validate that timer calculations match expected intervals
#### Trading Integration Validation
- **Never assume trading calculations are correct** - always validate against platform
- Test with small amounts first when implementing new trading logic
- Compare bot-calculated P&L with actual platform P&L values
- Verify protocol selection (Drift vs Jupiter) matches intended trading method
#### AI Analysis Output Validation
- **Always check AI responses for realistic values** before using in trading
- AI can return absolute prices when percentages are expected - validate data types
- Log AI analysis results to catch unrealistic take profit targets (>50% gains)
- Implement bounds checking on AI-generated trading parameters
#### Cleanup System Monitoring
- **Test cleanup functionality after every automation cycle**
- Monitor memory usage patterns to catch cleanup failures early
- Verify that cleanup triggers properly after analysis completion
- Check for zombie browser processes that indicate cleanup issues
### Successful Implementation Workflow
**After completing any feature or fix:**
```bash