Commit Graph

8 Commits

Author SHA1 Message Date
mindesbunister
6990f20d6f feat: Orderbook shadow logging system - Phase 1 complete
Implementation:
- Added 7 orderbook fields to Trade model (spreadBps, imbalanceRatio, depths, impact, walls)
- Oracle-based estimates with 2bps spread assumption
- ENV flag: ENABLE_ORDERBOOK_LOGGING (defaults true)
- Execute wrapper lines 1037-1053 guards orderbook logic

Database:
- Direct SQL ALTER TABLE (avoided migration drift issues)
- All columns nullable DOUBLE PRECISION
- Prisma schema synced via db pull + generate

Deployment:
- Container rebuilt and deployed successfully
- All 7 columns verified accessible
- System operational, ready for live trade validation

Files changed:
- config/trading.ts (enableOrderbookLogging flag, line 127)
- types/trading.ts (orderbook interfaces)
- lib/database/trades.ts (createTrade saves orderbook data)
- app/api/trading/execute/route.ts (ENV wrapper lines 1037-1053)
- prisma/schema.prisma (7 orderbook fields)
- docs/ORDERBOOK_SHADOW_LOGGING.md (complete documentation)

Status:  PRODUCTION READY - awaiting first trade for validation
2025-12-19 08:51:36 +01:00
mindesbunister
bfb73150ab Disable smart validation queue - not active with Q≥95 strategy 2025-12-18 11:24:08 +01:00
mindesbunister
3bba68637c docs: Comprehensive v11 analysis - 000 loss root cause documented
- Complete breakdown of 7 v11 trades performance
- Root cause: Indicator filters never applied (Bug #84)
- Quality threshold analysis (LONG 60-70 RSI optimal)
- All parameters documented with data evidence
- Emergency fix deployed (v11.1 with working filters)
2025-12-17 15:40:59 +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
mindesbunister
aa16daffa2 critical: Fix Bug #87 - Add 3-tier SL verification with circuit breaker
CRITICAL FIX: Prevents silent stop-loss placement failures that caused $1,000+ losses

Created lib/safety/sl-verification.ts (334 lines):
 60s → 90s delays
- Queries Drift protocol directly via user.getOpenOrders()
- Filters SL orders: marketIndex + reduceOnly + TRIGGER_MARKET/LIMIT
- Circuit breaker: haltTrading() blocks new trades on verification failure
- Emergency shutdown: Force-closes position after 3 failed attempts
- Event-driven architecture: Triggered once post-open (not polling)
- Reduces Drift API calls by ~95% vs continuous polling

Integrated in app/api/trading/execute/route.ts:
- Line 54: Import shouldAcceptNewTrade for pre-execution check
- Lines 215-221: Circuit breaker validates trading allowed (HTTP 503 if halted)
- Lines 583-592: Triggers SL verification post-open (fire-and-forget)

Root Cause - Bug #76: Silent SL placement failure
Database Evidence: Trade cmj8abpjo00w8o407m3fndmx0
- tp1OrderTx: 'DsRv7E8vtAS4dKFmoQoTZMdiLTUju9cfmr9DPCgquP3V...'  EXISTS
- tp2OrderTx: '3cmYgGE828hZAhpepShXmpxqCTACFvXijqEjEzoed5PG...'  EXISTS
- slOrderTx: NULL 
- softStopOrderTx: NULL 
- hardStopOrderTx: NULL 

User Report: 'RISK MANAGEMENT WAS REMOVED WHEN PRICE WENT TO SL!!!!! POSITION STILL OPEN'
Reality: SL orders never placed from start (not cancelled later)

Solution Philosophy: 'better safe than sorry' - user's words
Safety: Query on-chain state directly, don't trust internal success flags

Deployed: 2025-12-16 13:50:18 UTC
Docker Image: SHA256:80fd45004e71fa490fc4f472b252ecb25db91c6d90948de1516646b12a00446f
Container: trading-bot-v4 restarted successfully
2025-12-16 14:50:18 +01:00
copilot-swe-agent[bot]
0dedfecde5 docs: Final summary - All bugs fixed with comprehensive tests and documentation
Co-authored-by: mindesbunister <32161838+mindesbunister@users.noreply.github.com>
2025-12-09 22:32:18 +00:00
mindesbunister
a8c1b2ca06 feat: Phase 2 Smart Entry Timing - COMPLETE
Implementation of 1-minute data enhancements Phase 2:
- Queue signals when price not at favorable pullback level
- Monitor every 15s for 0.15-0.5% pullback (LONG=dip, SHORT=bounce)
- Validate ADX hasn't dropped >2 points (trend still strong)
- Timeout at 2 minutes → execute at current price
- Expected improvement: 0.2-0.5% per trade = ,600-4,000 over 100 trades

Files:
- lib/trading/smart-entry-timer.ts (616 lines, zero TS errors)
- app/api/trading/execute/route.ts (integrated smart entry check)
- .env (SMART_ENTRY_* configuration, disabled by default)

Next steps:
- Test with SMART_ENTRY_ENABLED=true in development
- Monitor first 5-10 trades for improvement verification
- Enable in production after successful testing
2025-11-27 11:40:23 +01:00
mindesbunister
bfdb0ba779 feat: Implement adaptive leverage based on signal quality score
- Quality-based risk adjustment: 95+ = 15x, 90-94 = 10x, <90 = blocked
- Data-driven decision: v8 quality 95+ = 100% WR (4/4 wins)
- Config fields: useAdaptiveLeverage, highQualityLeverage, lowQualityLeverage, qualityLeverageThreshold
- Helper function: getLeverageForQualityScore() returns appropriate leverage tier
- Position sizing: Modified getActualPositionSizeForSymbol() to accept optional qualityScore param
- Execute endpoint: Calculate quality score early (before sizing) for leverage determination
- Test endpoint: Uses quality 100 for maximum leverage on manual test trades
- ENV variables: USE_ADAPTIVE_LEVERAGE, HIGH_QUALITY_LEVERAGE, LOW_QUALITY_LEVERAGE, QUALITY_LEVERAGE_THRESHOLD
- Impact: 33% less exposure on borderline quality signals (90-94)
- Example: $540 × 10x = $5,400 vs $8,100 (saves $2,700 exposure on volatile signals)
- Files changed:
  * config/trading.ts (interface, config, ENV, helper function, position sizing)
  * app/api/trading/execute/route.ts (early quality calculation, pass to sizing)
  * app/api/trading/test/route.ts (quality 100 for test trades)
2025-11-24 00:47:09 +01:00