- Set signalSource='manual' for Telegram trades, 'tradingview' for TradingView
- Updated analytics queries to exclude manual trades from indicator analysis
- getTradingStats() filters manual trades (TradingView performance only)
- Version comparison endpoint filters manual trades
- Created comprehensive filtering guide: docs/MANUAL_TRADE_FILTERING.md
- Ensures clean data for indicator optimization without contamination
- Changed 'pricePosition' to 'pricePositionAtEntry' in extreme positions query
- Fixed database error: column "pricePosition" does not exist
Context:
- API was failing with Error 42703 (column not found)
- Database schema uses 'pricePositionAtEntry', not 'pricePosition'
- Version comparison section now loads correctly in analytics dashboard
- Fixed extremePositionStats type to match actual SQL query fields
- Changed .count to .trades (query returns 'trades' column, not 'count')
- Simplified extreme positions metrics (removed missing avg_adx and weak_adx_count)
- Fixed version comparison fallback from 'v1' to 'unknown'
Technical:
- SQL query only returns: version, trades, wins, total_pnl, avg_quality_score
- Code was trying to access non-existent fields causing TypeScript errors
- Build now succeeds, container deployed
- Changed SQL queries to use indicatorVersion (TradingView strategy versions)
- Updated version descriptions to only show v5/v6/unknown
- v5 = Buy/Sell Signal strategy (pre-Nov 12)
- v6 = HalfTrend + BarColor strategy (Nov 12+)
- unknown = Pre-version-tracking trades
Context:
- User clarified: 'v4 is v6. the version reflects the moneyline version'
- Dashboard should show indicator strategy versions, not scoring logic versions
- Added dynamicATRAnalysis section to /api/analytics/tp-sl-optimization
- Analyzes v6 trades with ATR data to compare fixed vs dynamic targets
- Dynamic targets: TP2=2x ATR, SL=1.5x ATR (from config)
- Shows +39.8% advantage with 14 trades (.72 improvement)
- Includes data sufficiency check (need 30+ trades)
- Recommendation logic: WAIT/IMPLEMENT/CONSIDER/NEUTRAL based on sample size and advantage
- Returns detailed metrics: sample size, avg ATR, hit rates, P&L comparison
- Integrates seamlessly with existing MAE/MFE analysis
Current status: 14/30 trades collected, insufficient for implementation
Expected: Frontend will display this data to track progress toward 30-trade threshold
Improved flip-flop penalty logic to distinguish between:
- Chop (bad): <2% price move from opposite signal → -25 penalty
- Reversal (good): ≥2% price move from opposite signal → allowed
Changes:
- lib/database/trades.ts: getRecentSignals() now returns oppositeDirectionPrice
- lib/trading/signal-quality.ts: Added currentPrice parameter, price movement check
- app/api/trading/check-risk/route.ts: Added currentPrice to RiskCheckRequest interface
- app/api/trading/execute/route.ts: Pass openResult.fillPrice as currentPrice
- app/api/analytics/reentry-check/route.ts: Pass currentPrice from metrics
Example scenarios:
- ETH $170 SHORT → $153 LONG (10% move) = reversal allowed ✅
- ETH $154.50 SHORT → $154.30 LONG (0.13% move) = chop blocked ⚠️
Deployed: 09:18 CET Nov 14, 2025
Container: trading-bot-v4
PHASE 1 IMPLEMENTATION:
Signal quality scoring now checks database for recent trading patterns
and applies penalties to prevent overtrading and flip-flop losses.
NEW PENALTIES:
1. Overtrading: 3+ signals in 30min → -20 points
- Detects consolidation zones where system generates excessive signals
- Counts both executed trades AND blocked signals
2. Flip-flop: Opposite direction in last 15min → -25 points
- Prevents rapid long→short→long whipsaws
- Example: SHORT at 10:00, LONG at 10:12 = blocked
3. Alternating pattern: Last 3 trades flip directions → -30 points
- Detects choppy market conditions
- Pattern like long→short→long = system getting chopped
DATABASE INTEGRATION:
- New function: getRecentSignals() in lib/database/trades.ts
- Queries last 30min of trades + blocked signals
- Checks last 3 executed trades for alternating pattern
- Zero performance impact (fast indexed queries)
ARCHITECTURE:
- scoreSignalQuality() now async (requires database access)
- All callers updated: check-risk, execute, reentry-check
- skipFrequencyCheck flag available for special cases
- Frequency penalties included in qualityResult breakdown
EXPECTED IMPACT:
- Eliminate overnight flip-flop losses (like SOL $141-145 chop)
- Reduce overtrading during sideways consolidation
- Better capital preservation in non-trending markets
- Should improve win rate by 5-10% by avoiding worst setups
TESTING:
- Deploy and monitor next 5 signals in choppy markets
- Check logs for frequency penalty messages
- Analyze if blocked signals would have been losers
Files changed:
- lib/database/trades.ts: Added getRecentSignals()
- lib/trading/signal-quality.ts: Made async, added frequency checks
- app/api/trading/check-risk/route.ts: await + symbol parameter
- app/api/trading/execute/route.ts: await + symbol parameter
- app/api/analytics/reentry-check/route.ts: await + skipFrequencyCheck
- Add market data cache service (5min expiry) for storing TradingView metrics
- Create /api/trading/market-data webhook endpoint for continuous data updates
- Add /api/analytics/reentry-check endpoint for validating manual trades
- Update execute endpoint to auto-cache metrics from incoming signals
- Enhance Telegram bot with pre-execution analytics validation
- Support --force flag to override analytics blocks
- Use fresh ADX/ATR/RSI data when available, fallback to historical
- Apply performance modifiers: -20 for losing streaks, +10 for winning
- Minimum re-entry score 55 (vs 60 for new signals)
- Fail-open design: proceeds if analytics unavailable
- Show data freshness and source in Telegram responses
- Add comprehensive setup guide in docs/guides/REENTRY_ANALYTICS_QUICKSTART.md
Phase 1 implementation for smart manual trade validation.
- Changed numeric fields from typed as number to 'any' in raw query results
- Properly convert Prisma Decimal/BigInt types to JavaScript numbers
- Fixes TypeError: e.totalPnL.toFixed is not a function
- All numeric values (totalPnL, avgPnL, avgADX, etc.) now converted with Number()
Issue: Prisma returns Decimal objects from aggregation queries which don't have
toFixed() method. Frontend expects plain numbers for .toFixed(2) formatting.
- Add getLastTrade() function to database service
- Create /api/analytics/last-trade endpoint
- Display last trade with full details on analytics page
- Show entry/exit prices, P&L, position size, targets
- Visual indicators for trade direction and exit reason
- Helps quickly diagnose where trades went (TP1, TP2, or SL)
- Created /api/analytics/tp-sl-optimization endpoint
- Analyzes historical trades using MAE/MFE data
- Calculates optimal TP1/TP2/SL levels based on percentiles
- Provides win rate, profit factor, and hit rate analysis
- Shows money left on table (MFE - realized P&L)
- Projects impact of optimal levels on future performance
Analytics calculated:
- MAE analysis: avg, median, percentiles, worst
- MFE analysis: avg, median, percentiles, best
- Current level performance: TP1/TP2/SL hit rates
- Optimal recommendations: TP1=50% of avg MFE, TP2=80%, SL=70% of avg MAE
- Projected improvements: win rate change, profit factor, total P&L
Requires 10+ closed trades with MAE/MFE data to generate recommendations
Test script: scripts/test-analytics.sh
Next: Phase 4 (visual dashboard) or wait for trades with MAE/MFE data
- Fixed Prisma client not being available in Docker container
- Added isTestTrade flag to exclude test trades from analytics
- Created analytics views for net positions (matches Drift UI netting)
- Added API endpoints: /api/analytics/positions and /api/analytics/stats
- Added test trade endpoint: /api/trading/test-db
- Updated Dockerfile to properly copy Prisma client from builder stage
- Database now successfully stores all trades with full details
- Supports position netting calculations to match Drift perpetuals behavior