critical: Fix P&L calculation and TP1 false detection bugs

- Add originalPositionSize tracking to prevent stale size usage
- Add price validation to TP1 detection (prevents manual closes misidentified as TP1)
- Fix external closure P&L to use originalPositionSize not currentSize
- Add handleManualClosure method for proper exit reason detection
- Add isPriceAtTarget helper for TP/SL price validation (0.2% tolerance)
- Update all ActiveTrade creation points (execute, test, sync-positions, test-db)

Bug fixes:
- Manual close at 42.34 was detected as TP1 (target 40.71) - FIXED
- P&L showed -$1.71 instead of actual -$2.92 - FIXED
- Exit reason showed SL instead of manual - FIXED

Root cause: Position Manager detected size reduction without validating
price was actually at TP1 level. Used stale currentSize for P&L calculation.

Files modified:
- lib/trading/position-manager.ts (core fixes)
- app/api/trading/execute/route.ts
- app/api/trading/test/route.ts
- app/api/trading/sync-positions/route.ts
- app/api/trading/test-db/route.ts
This commit is contained in:
mindesbunister
2025-11-17 15:10:15 +01:00
parent 84bd2e27f0
commit 3aeb00f998
6 changed files with 133 additions and 11 deletions

4
.env
View File

@@ -388,7 +388,7 @@ NEW_RELIC_LICENSE_KEY=
# - PHASE_2_COMPLETE_REPORT.md - Feature summary
USE_TRAILING_STOP=true
TRAILING_STOP_PERCENT=0.3
TRAILING_STOP_PERCENT=0.5
TRAILING_STOP_ACTIVATION=0.4
MIN_QUALITY_SCORE=60
SOLANA_ENABLED=true
@@ -411,5 +411,5 @@ TRAILING_STOP_MIN_PERCENT=0.25
TRAILING_STOP_MAX_PERCENT=0.9
USE_PERCENTAGE_SIZE=false
BREAKEVEN_TRIGGER_PERCENT=0
BREAKEVEN_TRIGGER_PERCENT=0.4
ATR_MULTIPLIER_FOR_TP2=2