critical: Fix ghost detection P&L compounding - delete from Map BEFORE check

Bug: Multiple monitoring loops detect ghost simultaneously
- Loop 1: has(tradeId) → true → proceeds
- Loop 2: has(tradeId) → true → ALSO proceeds (race condition)
- Both send Telegram notifications with compounding P&L

Real incident (Dec 2, 2025):
- Manual SHORT at $138.84
- 23 duplicate notifications
- P&L compounded: -$47.96 → -$1,129.24 (23× accumulation)
- Database shows single trade with final compounded value

Fix: Map.delete() returns true if key existed, false if already removed
- Call delete() FIRST
- Check return value
 proceeds
- All other loops get false → skip immediately
- Atomic operation prevents race condition

Pattern: This is variant of Common Pitfalls #48, #49, #59, #60, #61
- All had "check then delete" pattern
- All vulnerable to async timing issues
- Solution: "delete then check" pattern
- Map.delete() is synchronous and atomic

Files changed:
- lib/trading/position-manager.ts lines 390-410

Related: DUPLICATE PREVENTED message was working but too late
This commit is contained in:
mindesbunister
2025-12-02 18:25:56 +01:00
parent d156abc976
commit 93dd950821
7 changed files with 893 additions and 6 deletions

View File

@@ -501,6 +501,71 @@ Documentation is not bureaucracy - it's **protecting future profitability** by p
---
## 🎯 BlockedSignal Minute-Precision Tracking (Dec 2, 2025 - OPTIMIZED)
**Purpose:** Track exact minute-by-minute price movements for blocked signals to determine EXACTLY when TP1/TP2 would have been hit
**Critical Optimization (Dec 2, 2025):**
- **Original Threshold:** 30 minutes (arbitrary, inefficient)
- **User Insight:** "we have 1 minute data, so use it"
- **Optimized Threshold:** 1 minute (matches data granularity)
- **Performance Impact:** 30× faster processing (96.7% reduction in wait time)
- **Result:** 0 signals → 15 signals immediately eligible for analysis
**System Architecture:**
```
Data Collection: Every 1 minute (MarketData table) ✓
Processing Wait: 1 minute (OPTIMIZED from 30 min) ✓
Analysis Detail: Every 1 minute (480 points/8h) ✓
Result Storage: Exact minute timestamps ✓
Perfect alignment - all components at 1-minute granularity
```
**Validation Results (Dec 2, 2025):**
- **Batch Processing:** 15 signals analyzed immediately after optimization
- **Win Rate (recent 25):** 48% TP1 hits, 0 SL losses
- **Historical Baseline:** 15.8% TP1 win rate (7,427 total signals)
- **Recent Performance:** 3× better than historical baseline
- **Exact Timestamps:**
- Signal cmiolsiaq005: Created 13:18:02, TP1 13:26:04 (8.0 min exactly)
- Signal cmiolv2hw005: Created 13:20:01, TP1 13:26:04 (6.0 min exactly)
**Code Location:**
```typescript
// File: lib/analysis/blocked-signal-tracker.ts, Line 528
// CRITICAL FIX (Dec 2, 2025): Changed from 30min to 1min
// Rationale: We collect 1-minute data, so use it! No reason to wait longer.
// Impact: 30× faster processing eligibility (0 → 15 signals immediately qualified)
const oneMinuteAgo = new Date(Date.now() - 1 * 60 * 1000)
```
**Why This Matters:**
- **Matches Data Granularity:** 1-minute data collection = 1-minute processing threshold
- **Eliminates Arbitrary Delays:** No reason to wait 30 minutes when data is available
- **Immediate Analysis:** Signals qualify for batch processing within 1 minute of creation
- **Exact Precision:** Database stores exact minute timestamps (6-8 min resolution typical)
- **User Philosophy:** "we have 1 minute data, so use it" - use available precision fully
**Database Fields (Minute Precision):**
- `signalCreatedTime` - Exact timestamp when signal generated (YYYY-MM-DD HH:MM:SS)
- `tp1HitTime` - Exact minute when TP1 target reached
- `tp2HitTime` - Exact minute when TP2 target reached
- `slHitTime` - Exact minute when SL triggered
- `minutesToTP1` - Decimal minutes from signal to TP1 (e.g., 6.0, 8.0)
- `minutesToTP2` - Decimal minutes from signal to TP2
- `minutesToSL` - Decimal minutes from signal to SL
**Git Commits:**
- d156abc "docs: Add mandatory git workflow and critical feedback requirements" (Dec 2, 2025)
- [Next] "perf: Optimize BlockedSignal processing threshold from 30min to 1min"
**Lesson Learned:**
When you have high-resolution data (1 minute), use it immediately. Arbitrary delays (30 minutes) waste processing time without providing value. Match all system components to the same granularity for consistency and efficiency.
---
## <20>📊 1-Minute Data Collection System (Nov 27, 2025)
**Purpose:** Real-time market data collection via TradingView 1-minute alerts for Phase 7.1/7.2/7.3 enhancements