Commit Graph

9 Commits

Author SHA1 Message Date
mindesbunister
b4bcde942a critical: Fix entry AND exit prices to use actual Drift fills (Bug #89)
- Extended getActualFillPriceFromTx() to also extract entry fill prices
- openPosition() now uses actual fill from tx logs (was using oracle price)
- closePosition() already fixed to use actual exit fills
- Both prices now extracted via Drift SDK LogParser OrderActionRecord events
- Eliminates ~0.08% entry and exit price discrepancies vs Drift UI
- P&L calculations now 100% accurate to actual execution prices

Files changed:
- lib/drift/orders.ts (entry extraction in openPosition)
- docs/COMMON_PITFALLS.md (updated Pitfall #89)

Expected impact: Entry AND exit prices match Drift exactly on all future trades
2026-01-12 08:32:48 +01:00
mindesbunister
2af13eaa88 docs: Add pitfall #94 - P&L using oracle price instead of actual fill price
- Documented 5.7% P&L over-reporting bug (Drift $133.03 vs Database $140.56)
- Root cause: closePosition() used oracle price instead of actual fill price
- Fix: getActualFillPriceFromTx() helper extracts real fills from transaction logs
- WrappedEvent has properties directly on object, NOT nested under .data
- References commit c1bff0d (Jan 11, 2026)
2026-01-11 21:10:09 +01:00
mindesbunister
f57aa925b8 critical: Bug #93 - Three-layer entry price validation with oracle fallback
Root Cause: quoteAssetAmount/baseAssetAmount division producing garbage entry prices
- Found 6 autosync records with impossible prices (.18, 6.30, 7.11, 116.24 for SOL)
- Drift SDK values can be corrupted during state transitions

Fix Layer 1 (lib/drift/client.ts):
- Added per-asset price range validation (SOL: 0-000, BTC: 0k-00k, ETH: 00-0k)
- Returns null for invalid prices

Fix Layer 2 (lib/trading/sync-helper.ts):
- Added validatedEntryPrice calculation with oracle fallback
- Falls back to Pyth oracle when calculated price is garbage

Fix Layer 3 (lib/trading/sync-helper.ts):
- Trade creation uses validatedEntryPrice in all 4 price fields
- entryPrice, peakPrice, maxFavorablePrice, maxAdversePrice

Documentation:
- Full Bug #93 added to COMMON_PITFALLS.md with code examples
- Quick Reference table updated

Cleaned: 6 garbage autosync records deleted from database
2026-01-08 19:29:58 +01:00
mindesbunister
bb2432f3bf docs: Add Bug #92 - Exit order token sizing mismatch to Common Pitfalls
- Added comprehensive documentation for TP/SL size mismatch bug
- Root cause: usdToBase() recalculated tokens at each exit price
- Fix: Pass positionSizeTokens from position fill, use tokensToBase()
- Updated Quick Reference Table (now 74 pitfalls)
- Updated last modified date to January 6, 2026
2026-01-07 10:02:10 +01:00
mindesbunister
26ddd177b3 docs: Add Bug #91 to COMMON_PITFALLS.md and copilot-instructions.md
Bug #91: Math.floor truncation leaves fractional position remnants
- Root cause: new BN(Math.floor(sizeToClose * 1e9)) truncates position sizes
- Solution: SDK's closePosition() uses exact BN arithmetic (baseAssetAmount.abs())
- Added to Quick Reference Table in COMMON_PITFALLS.md
- Added full documentation entry (~70 lines)
- Updated Top 10 Critical Pitfalls in copilot-instructions.md
- Replaced #75 (Wrong Year) with #91 (more impactful to trading operations)
2026-01-01 13:58:29 +01:00
mindesbunister
465f6bdb82 critical: Bug #90 - Use placeAndTakePerpOrder for immediate MARKET order fills
ROOT CAUSE: placePerpOrder() only places orders on Drift order book, doesn't fill.
SOLUTION: placeAndTakePerpOrder() places AND matches against makers atomically.

Real Incident (Dec 31, 2025):
- Dec 30 18:17: SHORT opened at $124.36
- Dec 31 00:30: LONG signal received - should flip position
- Transaction confirmed but Solscan showed 'Place' not 'Fill'
- Position remained open, eventually hit SL twice
- Total loss: ~$40.21

Files changed:
- lib/drift/orders.ts (line 662): placePerpOrder → placeAndTakePerpOrder
- docs/COMMON_PITFALLS.md: Added Bug #90 documentation

Deployment: Dec 31, 2025 11:38 CET (container trading-bot-v4)
2025-12-31 11:45:21 +01:00
mindesbunister
b11da009eb critical: Bug #89 - Detect and handle Drift fractional position remnants (3-part fix)
- Part 1: Position Manager fractional remnant detection after close attempts
  * Check if position < 1.5× minOrderSize after close transaction
  * Log to persistent logger with FRACTIONAL_REMNANT_DETECTED
  * Track closeAttempts, limit to 3 maximum
  * Mark exitReason='FRACTIONAL_REMNANT' in database
  * Remove from monitoring after 3 failed attempts

- Part 2: Pre-close validation in closePosition()
  * Check if position viable before attempting close
  * Reject positions < 1.5× minOrderSize with specific error
  * Prevent wasted transaction attempts on too-small positions
  * Return POSITION_TOO_SMALL_TO_CLOSE error with manual instructions

- Part 3: Health monitor detection for fractional remnants
  * Query Trade table for FRACTIONAL_REMNANT exits in last 24h
  * Alert operators with position details and manual cleanup instructions
  * Provide trade IDs, symbols, and Drift UI link

- Database schema: Added closeAttempts Int? field to Track attempts

Root cause: Drift protocol exchange constraints can leave fractional positions
Evidence: 3 close transactions confirmed but 0.15 SOL remnant persisted
Financial impact: ,000+ risk from unprotected fractional positions
Status: Fix implemented, awaiting deployment verification

See: docs/COMMON_PITFALLS.md Bug #89 for complete incident details
2025-12-16 22:05:12 +01:00
copilot-swe-agent[bot]
e06650d055 docs: Fix pitfall count to 72 in COMMON_PITFALLS.md header
Co-authored-by: mindesbunister <32161838+mindesbunister@users.noreply.github.com>
2025-12-05 00:20:51 +00:00
copilot-swe-agent[bot]
0c76bca1cc docs: Extract Common Pitfalls to dedicated documentation
- Created docs/COMMON_PITFALLS.md with all 72 pitfalls
- Organized by severity and category for better navigation
- Added quick reference table and cross-reference index
- Reduced copilot-instructions.md from 6,575 to 3,608 lines (45%)
- Kept Top 10 critical pitfalls in main instructions
- Preserved all git commits, dates, code examples
- Updated docs/README.md with references to new doc

Benefits:
- Faster AI agent context loading
- Easier maintenance and updates
- Better searchability by category
- Clear pattern recognition for similar issues
- Maintains comprehensive knowledge base

Co-authored-by: mindesbunister <32161838+mindesbunister@users.noreply.github.com>
2025-12-05 00:19:16 +00:00