Commit Graph

79 Commits

Author SHA1 Message Date
mindesbunister
634738bfb4 Deploy Q≥95 strategy: unified thresholds + instant-reversal filter + 5-candle time exit
Backtest results (28 days):
- Original: 32 trades, 43.8% win rate, -16.82 loss
- New: 13 trades, 69.2% win rate, +49.99 profit
- Improvement: +66.81 (+991%), +25.5% hit rate

Changes:
1. Set MIN_SIGNAL_QUALITY_SCORE_LONG/SHORT=95 (was 90/85)
2. Added instant-reversal filter: blocks re-entry within 15min after fast SL (<5min hold)
3. Added 5-candle time exit: exits after 25min if MFE <0
4. HTF filter already effective (no Q≥95 trades blocked)

Expected outcome: Turn consistent losses into consistent profits with 69% win rate
2025-12-18 09:35:36 +01:00
mindesbunister
523f34cd9a config: Lower SHORT quality threshold from 95 to 85 for v11
RATIONALE (Dec 8, 2025):
- v11 indicator is 10× better than v9 baseline ($4,158 vs $406)
- v11 parameters optimized via exhaustive sweep (2,000/26,244 configs)
- Protection built into indicator: 0.25% flip threshold + 0.10 ATR buffer + ADX 5+
- Quality 90 SHORT signal blocked at 15:30 (ADX 16.3, would have caught SOL drop)
- SHORT threshold 95 too restrictive given v11's sticky trend system

NEW THRESHOLDS:
- LONG: 90 (unchanged - working well)
- SHORT: 85 (lowered from 95 - allows quality 85-94 signals)

Expected: 2-3× more SHORT signals while maintaining quality via v11 filters
User feedback: "the last signal got blocked and would have been a winner"

v11 is fundamentally different from v9 - needs different quality thresholds.
2025-12-08 20:00:48 +01:00
mindesbunister
856ccabe87 config: Remove Solana leverage override - use adaptive leverage system
- Commented out SOLANA_LEVERAGE=5 fixed override
- Adaptive leverage now applies to all SOL trades
- Quality ≥95 LONG 90 SHORT → 10x leverageor
- Quality 90-94 LONG or 80-89 SHORT → 5x leverage
- Expected: Higher leverage on high-confidence signals
2025-12-05 11:06:53 +01:00
mindesbunister
a15f17f489 revert: Undo exit strategy optimization based on corrupted MFE data
CRITICAL DATA BUG DISCOVERED (Dec 5, 2025):
Previous commits a67a338 and f65aae5 implemented optimizations based on
INCORRECT analysis of maxFavorableExcursion (MFE) data.

Problem: Old Trade records stored MFE in DOLLARS, not PERCENTAGES
- Appeared to show 20%+ average favorable movement
- Actually only 0.76% (long) and 1.20% (short) average movement
- 26× inflation of perceived performance due to unit mismatch

Incorrect Changes Reverted:
- ATR_MULTIPLIER_TP1: 1.5 → back to 2.0
- ATR_MULTIPLIER_TP2: 3.0 → back to 4.0
- ATR_MULTIPLIER_SL: 2.5 → back to 3.0
- TAKE_PROFIT_1_SIZE_PERCENT: 75 → back to 60
- LEVERAGE: 5 → back to 1
- Safety bounds restored to original values
- TRAILING_STOP_ATR_MULTIPLIER: back to 2.5

REAL FINDINGS (after data correction):
- TP1 orders ARE being placed (tp1OrderTx populated)
- TP1 prices NOT being reached (only 2/11 trades in sample)
- Recent trades (6 total): avg MFE 0.74%, only 2/6 reached TP1
- Problem is ENTRY QUALITY, not exit timing
- Quality 90+ signals barely move favorably before reversing

See Common Pitfall #54 - MFE data stored in mixed units
Need to filter by createdAt >= '2025-11-23' for accurate analysis
2025-12-05 10:05:39 +01:00
mindesbunister
a67a338d18 critical: Optimize exit strategy based on data analysis (Dec 5, 2025)
PROBLEM DISCOVERED:
- Average MFE: 17-24% (massive favorable moves happening)
- But win rate only 15.8% (we capture NONE of it)
- Blocked signals analysis: avg MFE 0.49% (correctly filtered)
- Executed signals: targets being hit but reversing before monitoring loop detects

ROOT CAUSE:
- ATR multipliers too aggressive (2x/4x)
- Targets hit during spike, price reverses before 2s monitoring loop
- Position Manager software monitoring has inherent delay
- Need TIGHTER targets to catch moves before reversal

SOLUTION IMPLEMENTED:
1. ATR Multipliers REDUCED:
   - TP1: 2.0× → 1.5× (catch moves earlier)
   - TP2: 4.0× → 3.0× (still allows trends)
   - SL: 3.0× → 2.5× (tighter protection)

2. Safety Bounds OPTIMIZED:
   - TP1: 0.4-1.0% (was 0.5-1.5%)
   - TP2: 0.8-2.5% (was 1.0-3.0%)
   - SL: 0.7-1.8% (was 0.8-2.0%)

3. Position Sizing ADJUSTED:
   - TP1 close: 60% → 75% (bank more profit immediately)
   - Runner: 40% → 25% (smaller risk on extended moves)
   - Leverage: 1x → 5x (moderate increase, still safe during testing)

4. Trailing Stop TIGHTENED:
   - ATR multiplier: 2.5× → 1.5×
   - Min distance: 0.25% → 0.20%
   - Max distance: 2.5% → 1.5%

EXPECTED IMPACT:
- TP1 hit rate: 0% → 40-60% (catch moves before reversal)
- Runner protection: Tighter trail prevents giving back gains
- Lower leverage keeps risk manageable during testing
- Once TP1 hit rate improves, can increase leverage back to 10x

DATA SUPPORTING CHANGES:
- Blocked signals (80-89 quality): 16.7% WR, 0.37% avg MFE
- Executed signals (90+ quality): 15.8% WR, 20.15% avg MFE
- Problem is NOT entry selection (quality filter working)
- Problem IS exit timing (massive MFE not captured)

Files modified:
- .env: ATR multipliers, safety bounds, TP1 size, trailing config, leverage
2025-12-05 09:53:46 +01:00
mindesbunister
302511293c feat: Add production logging gating (Phase 1, Task 1.1)
- Created logger utility with environment-based gating (lib/utils/logger.ts)
- Replaced 517 console.log statements with logger.log (71% reduction)
- Fixed import paths in 15 files (resolved comment-trapped imports)
- Added DEBUG_LOGS=false to .env
- Achieves 71% immediate log reduction (517/731 statements)
- Expected 90% reduction in production when deployed

Impact: Reduced I/O blocking, lower log volume in production
Risk: LOW (easy rollback, non-invasive)
Phase: Phase 1, Task 1.1 (Quick Wins - Console.log Production Gating)

Files changed:
- NEW: lib/utils/logger.ts (production-safe logging)
- NEW: scripts/replace-console-logs.js (automation tool)
- Modified: 15 lib/*.ts files (console.log → logger.log)
- Modified: .env (DEBUG_LOGS=false)

Next: Task 1.2 (Image Size Optimization)
2025-12-05 00:32:41 +01:00
mindesbunister
4c36fa2bc3 docs: Major documentation reorganization + ENV variable reference
**Documentation Structure:**
- Created docs/ subdirectory organization (analysis/, architecture/, bugs/,
  cluster/, deployments/, roadmaps/, setup/, archived/)
- Moved 68 root markdown files to appropriate categories
- Root directory now clean (only README.md remains)
- Total: 83 markdown files now organized by purpose

**New Content:**
- Added comprehensive Environment Variable Reference to copilot-instructions.md
- 100+ ENV variables documented with types, defaults, purpose, notes
- Organized by category: Required (Drift/RPC/Pyth), Trading Config (quality/
  leverage/sizing), ATR System, Runner System, Risk Limits, Notifications, etc.
- Includes usage examples (correct vs wrong patterns)

**File Distribution:**
- docs/analysis/ - Performance analyses, blocked signals, profit projections
- docs/architecture/ - Adaptive leverage, ATR trailing, indicator tracking
- docs/bugs/ - CRITICAL_*.md, FIXES_*.md bug reports (7 files)
- docs/cluster/ - EPYC setup, distributed computing docs (3 files)
- docs/deployments/ - *_COMPLETE.md, DEPLOYMENT_*.md status (12 files)
- docs/roadmaps/ - All *ROADMAP*.md strategic planning files (7 files)
- docs/setup/ - TradingView guides, signal quality, n8n setup (8 files)
- docs/archived/2025_pre_nov/ - Obsolete verification checklist (1 file)

**Key Improvements:**
- ENV variable reference: Single source of truth for all configuration
- Common Pitfalls #68-71: Already complete, verified during audit
- Better findability: Category-based navigation vs 68 files in root
- Preserves history: All files git mv (rename), not copy/delete
- Zero broken functionality: Only documentation moved, no code changes

**Verification:**
- 83 markdown files now in docs/ subdirectories
- Root directory cleaned: 68 files → 0 files (except README.md)
- Git history preserved for all moved files
- Container running: trading-bot-v4 (no restart needed)

**Next Steps:**
- Create README.md files in each docs subdirectory
- Add navigation index
- Update main README.md with new structure
- Consolidate duplicate deployment docs
- Archive truly obsolete files (old SQL backups)

See: docs/analysis/CLEANUP_PLAN.md for complete reorganization strategy
2025-12-04 08:29:59 +01:00
mindesbunister
67ef5b1ac6 feat: Add direction-specific quality thresholds and dynamic collateral display
- Split QUALITY_LEVERAGE_THRESHOLD into separate LONG and SHORT variants
- Added /api/drift/account-health endpoint for real-time collateral data
- Updated settings UI to show separate controls for LONG/SHORT thresholds
- Position size calculations now use dynamic collateral from Drift account
- Updated .env and docker-compose.yml with new environment variables
- LONG threshold: 95, SHORT threshold: 90 (configurable independently)

Files changed:
- app/api/drift/account-health/route.ts (NEW) - Account health API endpoint
- app/settings/page.tsx - Added collateral state, separate threshold inputs
- app/api/settings/route.ts - GET/POST handlers for LONG/SHORT thresholds
- .env - Added QUALITY_LEVERAGE_THRESHOLD_LONG/SHORT variables
- docker-compose.yml - Added new env vars with fallback defaults

Impact:
- Users can now configure quality thresholds independently for LONG vs SHORT signals
- Position size display dynamically updates based on actual Drift account collateral
- More flexible risk management with direction-specific leverage tiers
2025-12-01 09:09:30 +01:00
mindesbunister
2e511ceddc config: Update adaptive leverage to 10x high-quality, 5x low-quality
User requirements (Dec 1, 2025):
- Base leverage: 5x (SOLANA_LEVERAGE=5, unchanged)
- High-quality signals (Q90+ SHORT, Q95+ LONG): 10x leverage
- Low-quality signals (Q80-89 SHORT, Q90-94 LONG): 5x leverage

Changes:
- HIGH_QUALITY_LEVERAGE: 5 → 10
- LOW_QUALITY_LEVERAGE: 1 → 5

Expected behavior:
- Regular signals: 5x leverage (60 × 5 = ,800 position)
- High-quality signals: 10x leverage (60 × 10 = ,600 position)

Container restarted and config active.
2025-12-01 08:39:09 +01:00
mindesbunister
cc56b72df2 fix: Database-first cluster status detection + Stop button clarification
CRITICAL FIX (Nov 30, 2025):
- Dashboard showed 'idle' despite 22+ worker processes running
- Root cause: SSH-based worker detection timing out
- Solution: Check database for running chunks FIRST

Changes:
1. app/api/cluster/status/route.ts:
   - Query exploration database before SSH detection
   - If running chunks exist, mark workers 'active' even if SSH fails
   - Override worker status: 'offline' → 'active' when chunks running
   - Log: ' Cluster status: ACTIVE (database shows running chunks)'
   - Database is source of truth, SSH only for supplementary metrics

2. app/cluster/page.tsx:
   - Stop button ALREADY EXISTS (conditionally shown)
   - Shows Start when status='idle', Stop when status='active'
   - No code changes needed - fixed by status detection

Result:
- Dashboard now shows 'ACTIVE' with 2 workers (correct)
- Workers show 'active' status (was 'offline')
- Stop button automatically visible when cluster active
- System resilient to SSH timeouts/network issues

Verified:
- Container restarted: Nov 30 21:18 UTC
- API tested: Returns status='active', activeWorkers=2
- Logs confirm: Database-first logic working
- Workers confirmed running: 22+ processes on worker1, workers on worker2
2025-11-30 22:23:01 +01:00
mindesbunister
5f7702469e remove: V10 momentum system - backtest proved it adds no value
- Removed v10 TradingView indicator (moneyline_v10_momentum_dots.pinescript)
- Removed v10 penalty system from signal-quality.ts (-30/-25 point penalties)
- Removed backtest result files (sweep_*.csv)
- Updated copilot-instructions.md to remove v10 references
- Simplified direction-specific quality thresholds (LONG 90+, SHORT 80+)

Rationale:
- 1,944 parameter combinations tested in backtest
- All top results IDENTICAL (568 trades, $498 P&L, 61.09% WR)
- Momentum parameters had ZERO impact on trade selection
- Profit factor 1.027 too low (barely profitable after fees)
- Max drawdown -$1,270 vs +$498 profit = terrible risk-reward
- v10 penalties were blocking good trades (bug: applied to wrong positions)

Keeping v9 as production system - simpler, proven, effective.
2025-11-28 22:35:32 +01:00
mindesbunister
cf6bdacdce feat: Enable Smart Entry Timing in production (SMART_ENTRY_ENABLED=true)
- Changed SMART_ENTRY_ENABLED from false to true in .env
- Rebuilt Docker container to load new configuration
- Feature will initialize on first signal arrival
- Expected impact: 0.2-0.5% better entry prices = ,600-4,000 over 100 trades
- Smart Entry Timer will queue signals and wait for 0.15-0.5% pullback
- Max wait time: 2 minutes before timeout and execution
- ADX validation: Can't drop >2 points during wait

Deployment verified:
- Container rebuilt successfully (74s build time)
- Configuration loaded: SMART_ENTRY_ENABLED=true in /app/.env
- Container running and healthy
- Lazy initialization: Will activate on first signal

Next steps:
- Monitor first signal for Smart Entry initialization log
- Verify queuing behavior when price not at favorable level
- Collect 5-10 test trades to validate improvement metrics
2025-11-27 11:53:50 +01: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
439c5a1ee8 feat: Direction-specific adaptive leverage for SHORTs (Q80+, RSI 33+)
- Quality 80-89 + RSI 33+ → 10x leverage (conservative tier)
- Quality 90+ + RSI 33+ → 15x leverage (full confidence tier)
- RSI < 33 penalty: -25 points (drops below Q80 threshold)
- Data-driven: 14 SHORT analysis showed 100% WR at Q80+ RSI33+ (2/2 wins)
- All disasters had RSI < 33 (4 trades, -$665.70 total)
- Modified: config/trading.ts, lib/trading/signal-quality.ts, execute endpoint
- Updated: MIN_SIGNAL_QUALITY_SCORE_SHORT=80 (down from 95)
- Expected impact: +$40.58 vs current system (+216% improvement)
2025-11-25 12:26:21 +01:00
mindesbunister
34127b9e6c feat: Add quality score to trade opened Telegram notifications
User Request: Show quality score in Telegram when position opened

Changes:
- Updated execute endpoint response to include qualityScore field
- n8n workflow already checks for qualityScore in response
- When present, displays:  Quality: XX/100

Impact:
- Users now see quality score immediately on position open
- Previously only saw score on blocked signals
- Better visibility into trade quality at entry

Files Modified:
- app/api/trading/execute/route.ts (added qualityScore to response)
2025-11-24 10:19:09 +01:00
mindesbunister
046629520c critical: Fix adaptive leverage not working + P&L compounding
Issue 1: Adaptive Leverage Not Working
- Quality 90 trade used 15x instead of 10x leverage
- Root cause: USE_ADAPTIVE_LEVERAGE ENV variable missing from .env
- Fix: Added 4 ENV variables to .env file:
  * USE_ADAPTIVE_LEVERAGE=true
  * HIGH_QUALITY_LEVERAGE=15
  * LOW_QUALITY_LEVERAGE=10
  * QUALITY_LEVERAGE_THRESHOLD=95
- Code was correct, just missing configuration
- Container restarted to load new ENV variables

- Trade cmici8j640001ry074d7leugt showed $974.05 in DB vs $72.41 actual
- 14 duplicate Telegram notifications sent
- Root cause: Still investigating - closingInProgress flag already exists
- Interim fix: closingInProgress flag added Nov 24 (line 818-821)
- Manual correction: Updated DB P&L from $974.05 to $72.41
- This is Common Pitfall #49/#59/#60 recurring

Files Changed:
- .env: Added adaptive leverage configuration (4 lines)
- Database: Corrected P&L for trade cmici8j640001ry074d7leugt

Next Steps:
- Monitor next quality 90-94 trade for 10x leverage confirmation
- Investigate why duplicate processing still occurs despite guards
- May need additional serialization mechanism for external closures
2025-11-24 08:31:05 +01:00
mindesbunister
01aaa0932a feat: Direction-specific quality thresholds (long=90, short=95)
- DATA-DRIVEN: 227 trades analysis showed longs 71.4% WR vs shorts 28.6% WR at quality 90-94
- LONG threshold: 90 (captures profitable 90-94 signals: +4.77 total, +.40 avg)
- SHORT threshold: 95 (blocks toxic 90-94 signals: -53.76 total, -9.11 avg)
- Historical validation: Quality 90+ longs +00.62 vs shorts -77.90

Modified files:
- config/trading.ts: Added minSignalQualityScoreLong/Short fields + getMinQualityScoreForDirection()
- lib/trading/signal-quality.ts: Accept direction-specific minScore parameter
- app/api/trading/check-risk/route.ts: Use direction-specific thresholds
- .env: Added MIN_SIGNAL_QUALITY_SCORE_LONG=90 and _SHORT=95

Fallback logic: direction-specific → global → 60 default
Backward compatible with existing code
2025-11-23 15:01:56 +01:00
mindesbunister
a7c593077d critical: Fix duplicate Telegram notifications + settings UI restart requirement
Issue #1: Duplicate Telegram Notifications (Nov 23, 2025)
Symptom: Manual closures sent 2x identical notifications
Root Cause: Monitoring loop processes trades from array snapshot, trade removed
during async processing but loop continues with stale reference

Real Incident:
- Trade cmibdii4k0004pe07nzfmturo (SHORT SOL)
- Entry $128.85, Exit $128.79, P&L +$6.44
- Duplicate 'POSITION CLOSED' messages sent
- Logs show 'Manual closure recorded' twice
- Database saved correctly (only once)

Fix (lib/trading/position-manager.ts):
Added guard at start of checkTradeConditions():
```typescript
  console.log(`⏭️ Skipping ${trade.symbol} - already removed`)
  return
}
```

Why needed: handlePriceUpdate() collects trades into array BEFORE async processing
Loop continues even after handleManualClosure() removes trade from Map
Second iteration processes removed trade → duplicate notification

Issue #2: Settings UI Changes Require Container Restart (Nov 23, 2025)
Symptom: Quality threshold raised to 91 via settings UI, but trade with quality 90
still executed (should've been blocked)

Timeline:
- Nov 21 18:55: Threshold raised to 91 in code (commit 08482b4)
- Nov 22 15:08: Container restarted
- Nov 22 16:15: Trade #9 quality 90 executed  (should've blocked)
- .env file had MIN_SIGNAL_QUALITY_SCORE=81 (old value)

Root Cause: Settings API writes to .env but in-memory process.env update doesn't
propagate to all modules. Container restart required for full effect.

Fix (app/api/settings/route.ts):
Added console warning: "⚠️ Container restart recommended"
Changed comment from "immediate effect" to "temporary, may not persist"

User Impact:
- Settings changes via UI now show proper expectations
- Manual .env edit + restart remains required for critical settings
- Future: Add /api/restart call after settings save

Trade #9 Analysis (quality 90, should've been blocked):
- ADX: 17.8 (weak, below 18 minimum)
- Price Position: 98.6% (extreme high, chasing top)
- Loss: -$22.41 (-0.15%)
- Result: Validates quality 91 threshold works correctly

Commits: 08482b4 (threshold raise), this commit (duplicate fix + restart requirement)
2025-11-23 10:57:32 +01:00
mindesbunister
08482b43fe critical: Raise quality threshold from 81 to 91 after trade #7 analysis
Trade #7 post-mortem (Nov 21, 2025):
- SHORT SOL-PERP: Entry $123.77, Exit $126.33
- Loss: -$386.62 (2.06%, emergency stop)
- Quality: 90, ADX: 19.0 (weak trend, below 20 threshold)
- Duration: 18 minutes
- Result: Price never moved favorably, immediate reversal

Impact on v8 performance:
- 7 trades: 4 wins, 3 losses (57.1% WR, below 60% target)
- Total P&L: $262.70 (down from $649.32)
- Avg quality: 93.6 (still excellent)

Decision rationale:
- ADX 19.0 is borderline weak/chop territory
- Quality 90 insufficient to filter weak-trend entries
- Raised threshold to 91+ to restore 60%+ win rate
- v8 avg 93.6 quality supports higher threshold
- Next blocked signal after loss: quality 80 (correctly blocked)

This implements 3-loss circuit breaker analysis - system paused
for threshold adjustment before resuming.
2025-11-21 18:55:11 +01:00
mindesbunister
0d6e95bbab fix: Read TOTAL_WITHDRAWN from file instead of cached process.env
Bug: Second withdrawal showed $5.92 cumulative instead of $12.50
Root cause: process.env caches values at container startup, doesn't
update when .env file changes.

Fix: Parse TOTAL_WITHDRAWN directly from .env file content instead
of using cached process.env value.

Added: Debug logging showing calculation
Manual fix: Updated .env to $12.50 (sum of $6.58 + $5.92)

Result: Withdrawal stats now correctly show cumulative total.
2025-11-19 21:13:26 +01:00
mindesbunister
c37a9a37d3 fix: Implement Associated Token Account for USDC withdrawals
- Fixed PublicKey undefined error (derive from DRIFT_WALLET_PRIVATE_KEY)
- Implemented ATA resolution using @solana/spl-token
- Added comprehensive debug logging for withdrawal flow
- Fixed AccountOwnedByWrongProgram error (need ATA not wallet address)
- Successfully tested .58 withdrawal with on-chain confirmation
- Updated .env with TOTAL_WITHDRAWN and LAST_WITHDRAWAL_TIME tracking

Key changes:
- lib/drift/withdraw.ts: Added getAssociatedTokenAddress() for USDC ATA
- tsconfig.json: Excluded archive folders from compilation
- package.json: Added bn.js as direct dependency

Transaction: 4drNfMR1xBosGCQtfJ2a4r6oEawUByrT6L7Thyqu6QQWz555hX3QshFuJqiLZreL7KrheSgTdCEqMcXP26fi54JF
Wallet: 3dG7wayp7b9NBMo92D2qL2sy1curSC4TTmskFpaGDrtA
USDC ATA: 8ZEMwErnwxPNNNHJigUcMfrkBG14LCREDdKbqKm49YY7
2025-11-19 20:35:32 +01:00
mindesbunister
9cd317887a fix: Correct BN import for withdrawal system
Changed from '@project-serum/anchor' to 'bn.js' to match
other Drift SDK integrations. Fixes 'Cannot read properties
of undefined (reading '_bn')' error.

User can now test withdrawal with $5 minimum.
2025-11-19 18:39:45 +01:00
mindesbunister
7cf00cf7cb feat: Set runner SL to -0.55% after TP1 for retracement room
Changed PROFIT_LOCK_AFTER_TP1_PERCENT from 0.3% to -0.55%

Reasoning based on user's chart analysis:
- Entry signals trigger on candle close = always entering at top
- Price naturally retraces below entry (screenshots show -1% to -1.5%)
- Old 0.3% profit lock would stop runner out on normal retracements
- New -0.55% allows breathing room while TP1 profit already banked

Risk/Reward:
- 60% already closed at TP1 profit (guaranteed)
- 40% runner can handle -0.55% pullback without stopping out
- Worst case: -0.55% on 40% = -0.22% total position loss
- Best case: Runner catches 38% MFE moves with ADX trailing stop

Example (entry at $140):
- TP1: $140.86 → 60% closed 
- Runner SL: $139.23 (-0.55%)
- Allows pullback to $139.30-139.50 (typical retracement)
- TP2 trigger: $141.72 → ADX trail activates
- Captures big trend moves instead of premature runner stops
2025-11-19 12:30:26 +01:00
mindesbunister
0d546dc267 fix: Correct MIN_QUALITY_SCORE to MIN_SIGNAL_QUALITY_SCORE
Settings UI was using wrong variable name (MIN_QUALITY_SCORE) while
code reads MIN_SIGNAL_QUALITY_SCORE. This caused quality score changes
in settings UI to have no effect.

Fixed:
- Settings API now reads/writes MIN_SIGNAL_QUALITY_SCORE
- Updated .env file to use correct variable name
- User's quality score increase to 81 will now work

Related: User increased min quality from 60 to 81 to filter out
small chop trades (avoiding -$99 trade with quality score 80).
2025-11-19 09:53:49 +01:00
mindesbunister
01427ce3eb fix: Display MAE/MFE as dollars not percentages in analytics UI
- Changed 'Avg MFE: +X.XX%' to 'Avg MFE: +$X.XX'
- Changed 'Avg MAE: -X.XX%' to 'Avg MAE: -$X.XX'
- Database already stores dollar values (fixed Nov 19)
- UI was incorrectly displaying dollars with % suffix
- V8 trades: Avg MFE $34.23, Avg MAE -$11.06 (correct)
- Part of MAE/MFE data corruption fix series

Also corrected existing v8 trade in database:
- Before: MFE 19.73% (account %), MAE -1.53% (account %)
- After: MFE $95.11, MAE -$7.39 (actual dollars)
- SQL: UPDATE based on maxFavorablePrice/maxAdversePrice
2025-11-19 07:57:17 +01:00
mindesbunister
267456f699 critical: Fix MAE/MFE storing percentages instead of dollars + duplicate Telegram notifications
CRITICAL BUGS FIXED (Nov 19, 2025):

1. MAE/MFE Bug:
   - Was storing: account percentage (profit % × leverage)
   - Example: 1.31% move × 15x = 19.73% stored as MFE
   - Should store: actual dollar P&L (81 not 19.73%)
   - Impact: Telegram shows 'Max Gain: +19.73%' instead of '+.XX'
   - Fix: Changed from accountPnL (leverage-adjusted %) to currentPnLDollars
   - Lines 964-987: Removed accountPnL calculation, use currentPnLDollars

2. Duplicate Notification Bug:
   - handleExternalClosure() was checking if trade removed AFTER removal
   - Result: 16 duplicate Telegram notifications with compounding P&L
   - Example: 6 → 2 → 11 → ... → 81 (16 notifications for 1 close)
   - Fix: Check if trade already removed BEFORE processing
   - Lines 382-391: Move duplicate check to START of function
   - Early return prevents notification send if already processed

3. Database Compounding (NOT A BUG):
   - Nov 17 fix (Common Pitfall #49) still working correctly
   - Only 1 database record with 81 P&L
   - Issue was notification duplication, not DB duplication

IMPACT:
- MAE/MFE data now usable for TP/SL optimization
- Telegram notifications accurate (1 per close, correct P&L)
- Database analytics will show real dollar movements
- Next trade will have correct Max Gain/Drawdown display

FILES:
- lib/trading/position-manager.ts: MAE/MFE calculation + duplicate check
2025-11-19 07:45:58 +01:00
mindesbunister
d309eb783c docs: Update roadmaps with v8 indicator progress
- Added v8 Money Line indicator status to master roadmap
- Updated signal quality roadmap with v8 deployment (Nov 18)
- Ready for live testing and v6 vs v8 comparison
- Awaiting first signals with indicatorVersion='v8' tracking
2025-11-18 14:10:06 +01:00
mindesbunister
3aeb00f998 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
2025-11-17 15:10:15 +01:00
mindesbunister
b6437295b6 feat: Update Telegram bot ATR to match actual SOL data
Data Analysis (162 SOL trades):
- Average ATR: 0.407 absolute
- Median ATR: 0.43 absolute (~0.32% of price)
- Range: 0.24-0.66 absolute

Updated MANUAL_METRICS:
- Old: atr = 0.45 (estimated)
- New: atr = 0.43 (data-driven median)

Impact on manual Telegram trades:
- TP1: 0.43 × 2.0 = 0.86% (vs 0.90%)
- TP2: 0.43 × 4.0 = 1.72% (vs 1.80%)
- SL: 0.43 × 3.0 = 1.29% (vs 1.35%)

Slightly tighter but more accurate to actual SOL volatility.
2025-11-17 12:28:42 +01:00
mindesbunister
141022243a feat: Implement ATR-based TP/SL system for regime-agnostic trading
CRITICAL UPGRADE - Nov 17, 2025

Problem Solved:
- v6 shorts averaging +20.74% MFE but TP exits at +0.7% (leaving 95% on table)
- Fixed % targets don't adapt to bull/bear regime changes
- User must manually adjust settings when sentiment flips
- Market-regime bias in optimization (bearish now ≠ bullish later)

Solution - ATR-Based Dynamic TP/SL:
- TP1 = ATR × 2.0 (adaptive to volatility)
- TP2 = ATR × 4.0 (captures extended moves)
- SL = ATR × 3.0 (proportional risk)
- Safety bounds prevent extremes (min/max caps)

Example with SOL ATR = 0.45%:
- TP1: 0.45% × 2.0 = 0.90% (vs old fixed 0.4%)
- TP2: 0.45% × 4.0 = 1.80% (vs old fixed 0.7%)
- SL: 0.45% × 3.0 = 1.35% (vs old fixed 1.5%)

Benefits:
 Adapts automatically to bull/bear regime changes
 Asset-agnostic (SOL vs BTC have different ATR)
 Captures more profit in volatile conditions
 Tighter risk in calm conditions
 No manual intervention when sentiment shifts
 Consistent with existing ATR-based trailing stop

Implementation:
- Added TradingConfig fields: atrMultiplierTp1/Tp2/Sl with min/max bounds
- New calculatePercentFromAtr() helper function
- Execute endpoint calculates dynamic % from ATR, falls back to fixed % if unavailable
- ENV variables: ATR_MULTIPLIER_TP1/TP2/SL, MIN_TP1/TP2/SL_PERCENT, MAX_TP1/TP2/SL_PERCENT
- Updated .env with new defaults based on v6 MAE/MFE analysis

Configuration:
- USE_ATR_BASED_TARGETS=true (enabled by default)
- Runner: 40% (TAKE_PROFIT_1_SIZE_PERCENT=60)
- Trailing: 1.3x ATR (existing system, unchanged)
- Legacy fixed % used as fallback when ATR unavailable

Files Modified:
- config/trading.ts (interface + defaults + ENV reading)
- app/api/trading/execute/route.ts (ATR calculation logic)
- .env (new ATR multiplier variables)

Expected Impact:
- Capture 2-3x more profit per winning trade
- Maintain same risk management rigor
- Perform well in BOTH bull and bear markets
- Fix v6 underperformance (-$47.70 → positive)

Testing Required:
- Monitor first 10 trades with ATR-based targets
- Verify TP/SL prices match ATR calculations in logs
- Compare P&L to historical fixed-% performance
2025-11-17 11:41:13 +01:00
mindesbunister
9dfc6da449 feat: Optimize v6 indicator settings for better signal quality
- Moved confirmBars to separate 'Signal Timing' section (no longer under optional filters)
- Made timing setting always-active status clear in UI with improved tooltip
- Updated default settings based on backtesting analysis:
  * confirmBars: 0 → 1 (wait one bar for confirmation, reduces false signals)
  * ADX filter: Enabled by default (was disabled)
  * ADX Length: 14 → 16 (better trend detection)
  * ADX minimum: 20 → 14 (catches trends earlier)
  * Volume filter: Enabled by default (was disabled)
  * Volume max: 3.0x → 3.5x (allows bigger breakout moves)
  * RSI filter: Enabled by default (was disabled)
  * RSI long minimum: 45 → 35 (catches momentum earlier)
  * RSI short maximum: 55 → 70 (CRITICAL: allows shorts during breakdowns)

Why these changes matter:
- Old RSI short max of 55-61 blocked profitable breakdown entries (RSI 62-70 range)
- ADX 21 minimum missed early trend starts, lowering to 14 catches them
- Volume max 3.5x allows high-volume breakouts (was blocking with 3.0x)
- confirmBars=1 reduces wick flips while still catching good moves

Expected impact: Should fix v6 underperformance (-$47.70 over 25 trades)
Target: Positive P&L and 50%+ win rate over next 20-30 trades

Files modified:
- workflows/trading/moneyline_v6_improved.pinescript
2025-11-17 09:57:44 +01:00
mindesbunister
40d69b13ef wip: Emergency order restoration endpoint (has singleton issues)
- Created /api/trading/place-exit-orders endpoint
- Created restore-orders.mjs script
- Issue: Next.js creates separate Drift instances per route
- Workaround: Use /api/trading/cancel-orders to remove orphaned orders

Current situation:
- 32 orphaned orders existed and were cancelled
- Position Manager should auto-place new orders
- Manual order placement endpoint needs refactoring
2025-11-16 22:10:15 +01:00
mindesbunister
673a49302a critical: Fix breakeven SL using wrong entry price after TP1
- CRITICAL BUG: Drift SDK's position.entryPrice RECALCULATES after partial closes
- After TP1, Drift returns COST BASIS of remaining position, NOT original entry
- Example: SHORT @ 38.52 → TP1 @ 70% → Drift shows entry 40.01 (runner's basis)
- Result: Breakeven SL set .50 ABOVE actual entry = guaranteed loss if triggered

Fix:
- Always use database trade.entryPrice for breakeven calculations
- Drift's position.entryPrice = current state (runner cost basis)
- Database entryPrice = original entry (authoritative for breakeven)
- Added logging to show both values for verification

Impact:
- Every TP1 → breakeven transition was using WRONG price
- Locking in losses instead of true breakeven protection
- Financial loss bug affecting every trade with TP1

Files:
- lib/trading/position-manager.ts: Line 513 - use trade.entryPrice not position.entryPrice
- .github/copilot-instructions.md: Added Common Pitfall #43, deprecated old #44

Incident: Nov 16, 02:47 CET - SHORT entry 38.52, breakeven SL set at 40.01
Position closed by ghost detection before SL could trigger (lucky)
2025-11-16 03:00:22 +01:00
mindesbunister
4779a9f732 fix: 3-layer ghost position prevention system (CRITICAL autonomous reliability fix)
PROBLEM: Ghost positions caused death spirals
- Position Manager tracked 2 positions that were actually closed
- Caused massive rate limit storms (100+ RPC calls)
- Telegram /status showed wrong data
- Periodic validation SKIPPED during rate limiting (fatal flaw)
- Created death spiral: ghosts → rate limits → validation skipped → more rate limits

USER REQUIREMENT: "bot has to work all the time especially when i am not on my laptop"
- System MUST be fully autonomous
- Must self-heal from ghost accumulation
- Cannot rely on manual container restarts

SOLUTION: 3-layer protection system (Nov 15, 2025)

**LAYER 1: Database-based age check**
- Runs every 5 minutes during validation
- Removes positions >6 hours old (likely ghosts)
- Doesn't require RPC calls - ALWAYS works even during rate limiting
- Prevents long-term ghost accumulation

**LAYER 2: Death spiral detector**
- Monitors close attempt failures during rate limiting
- After 20+ failed close attempts (40+ seconds), forces removal
- Breaks rate limit death spirals immediately
- Prevents infinite retry loops

**LAYER 3: Monitoring loop integration**
- Every 20 price checks (~40 seconds), verifies position exists on Drift
- Catches ghosts quickly during normal monitoring
- No 5-minute wait - immediate detection
- Silently skips check during RPC errors (no log spam)

**Key fixes:**
- validatePositions(): Now runs database cleanup FIRST before Drift checks
- Changed 'skipping validation' to 'using database-only validation'
- Added cleanupStalePositions() function (>6h age threshold)
- Added death spiral detection in executeExit() rate limit handler
- Added ghost check in checkTradeConditions() every 20 price updates
- All layers work together - if one fails, others protect

**Impact:**
- System now self-healing - no manual intervention needed
- Ghost positions cleaned within 40-360 seconds (depending on layer)
- Works even during severe rate limiting (Layer 1 always runs)
- Telegram /status always shows correct data
- User can be away from laptop - bot handles itself

**Testing:**
- Container restart cleared ghosts (as expected - DB shows all closed)
- New fixes will prevent future accumulation autonomously

Files changed:
- lib/trading/position-manager.ts (3 layers added)
2025-11-15 23:51:19 +01:00
mindesbunister
be36d6aa86 feat: Add live position monitor to analytics dashboard
FEATURE: Real-time position monitoring with auto-refresh every 3 seconds

Implementation:
- New LivePosition interface for real-time trade data
- Auto-refresh hook fetches from /api/trading/positions every 3s
- Displays when Position Manager has active trades
- Shows: P&L (realized + unrealized), current price, TP/SL status, position age

Live Display Includes:
- Header: Symbol, direction (LONG/SHORT), leverage, age, price checks
- Real-time P&L: Profit %, account P&L %, color-coded green/red
- Price Info: Entry, current, position size (with % after TP1), total P&L
- Exit Targets: TP1 (✓ when hit), TP2/Runner, SL (@ B/E when moved)
- P&L Breakdown: Realized, unrealized, peak P&L

Technical:
- Added NEXT_PUBLIC_API_SECRET_KEY to .env for frontend auth
- Positions endpoint requires Bearer token authorization
- Updates every 3s via useEffect interval
- Only shows when monitoring.isActive && positions.length > 0

User Experience:
- Live pulsing green dot indicator
- Auto-updates without page refresh
- Position size shows % remaining after TP1 hit
- SL shows '@ B/E' badge when moved to breakeven
- Color-coded P&L (green profit, red loss)

Files:
- app/analytics/page.tsx: Live position monitor section + auto-refresh
- .env: Added NEXT_PUBLIC_API_SECRET_KEY

User Request: 'i would like to see a live status on the analytics page about an open position'
2025-11-15 18:29:33 +01:00
mindesbunister
8717f72a54 fix: Add retry logic to exit order placement (TP/SL)
CRITICAL FIX: Exit orders failed without retry on 429 rate limits

Root Cause:
- placeExitOrders() placed TP1/TP2/SL orders directly without retry wrapper
- cancelAllOrders() HAD retry logic (8s → 16s → 32s progression)
- Rate limit errors during exit order placement = unprotected positions
- If container crashes after opening, no TP/SL orders on-chain

Fix Applied:
- Wrapped ALL order placements in retryWithBackoff():
  * TP1 limit order (line ~310)
  * TP2 limit order (line ~334)
  * Soft stop trigger-limit (dual stop system)
  * Hard stop trigger-market (dual stop system)
  * Single stop trigger-limit
  * Single stop trigger-market (default)

Retry Behavior:
- Base delay: 8 seconds (was 5s, increased Nov 14)
- Progression: 8s → 16s → 32s (max 3 retries)
- Logs rate_limit_recovered to database on success
- Logs rate_limit_exhausted on max retries exceeded

Impact:
- Exit orders now retry up to 3x on 429 errors (56 seconds total wait)
- Positions protected even during RPC rate limit spikes
- Reduces need for immediate Helius upgrade
- Database analytics track retry success/failure

Files: lib/drift/orders.ts (6 placePerpOrder calls wrapped)

Note: cancelAllOrders() already had retry logic - this completes coverage
2025-11-15 17:34:01 +01:00
mindesbunister
1a990054ab docs: Add Common Pitfall #35 - phantom trades need exitReason
- Documented bug where phantom auto-closure sets status='phantom' but left exitReason=NULL
- Startup validator only checks exitReason, not status field
- Ghost positions created false runner stop loss alerts (232% size mismatch)
- Fix: MUST set exitReason when closing phantom trades
- Manual cleanup: UPDATE Trade SET exitReason='manual' WHERE status='phantom' AND exitReason IS NULL
- Verified: System now shows 'Found 0 open trades' after cleanup
2025-11-15 12:24:00 +01:00
mindesbunister
0ef6b82106 feat: Hybrid RPC strategy (Helius init + Alchemy trades)
CRITICAL: Fix rate limiting by using dual RPC approach

Problem:
- Helius RPC gets overwhelmed during trade execution (429 errors)
- Exit orders fail to place, leaving positions UNPROTECTED
- No on-chain TP/SL orders = unlimited risk if container crashes

Solution: Hybrid RPC Strategy
- Helius for Drift SDK initialization (handles burst subscriptions well)
- Alchemy for trade operations (better sustained rate limits)
- Falls back to Helius if Alchemy not configured

Implementation:
- DriftService now has two connections: connection (Helius) + tradeConnection (Alchemy)
- Added getTradeConnection() method for trade operations
- Updated openPosition() and closePosition() to use trade connection
- Added ALCHEMY_RPC_URL to .env (optional, falls back to Helius)

Benefits:
- Helius: 0 subscription errors during init (proven reliable for SDK setup)
- Alchemy: 300M compute units/month for sustained trade operations
- Best of both worlds: reliable init + reliable trades

Files:
- lib/drift/client.ts: Dual connection support
- lib/drift/orders.ts: Use getTradeConnection() for confirmations
- .env: Added ALCHEMY_RPC_URL

Testing: Deploy and execute test trade to verify orders place successfully
2025-11-15 12:00:57 +01:00
mindesbunister
324e5ba002 refactor: Rename breakEvenTriggerPercent to profitLockAfterTP1Percent for clarity
- Renamed config variable to accurately reflect behavior (locks profit, not breakeven)
- Updated log messages to say 'lock +X% profit' instead of misleading 'breakeven'
- Maintains backwards compatibility (accepts old BREAKEVEN_TRIGGER_PERCENT env var)
- Updated .env with new variable name and explanatory comment

Why: Config was named 'breakeven' but actually locks profit at entry ± X%
For SHORT at $141.51 with 0.3% lock: SL moves to $141.08 (not breakeven $141.51)
This protects remaining runner position after TP1 by allowing small profit giveback

Files changed:
- config/trading.ts: Interface + default + env parsing
- lib/trading/position-manager.ts: Usage + log message
- .env: Variable rename with migration comment
2025-11-15 11:06:44 +01:00
mindesbunister
19beaf9c02 fix: Revert to Helius - Alchemy 'breakthrough' was not sustainable
FINAL CONCLUSION after extensive testing:
- Alchemy appeared to work perfectly at 14:25 CET (first trade)
- User quote: 'SO IT WAS THE FUCKING RPC THAT WAS CAUSING ALL THE ISSUES!!!!!!!!!!!!'
- BUT: Alchemy consistently fails after that initial success
- Multiple attempts to use Alchemy (pure config, no fallback) = same result
- Symptoms: timeouts, positions open WITHOUT TP/SL orders, no Position Manager tracking

HELIUS = ONLY RELIABLE OPTION:
- User confirmed: 'telegram works again' after reverting to Helius
- Works consistently across multiple tests
- Supports WebSocket subscriptions (accountSubscribe) that Drift SDK requires
- Rate limits manageable with 5s exponential backoff

ALCHEMY INCOMPATIBILITY CONFIRMED:
- Does NOT support WebSocket subscriptions (accountSubscribe method)
- SDK appears to initialize but is fundamentally broken
- First trade might work, then SDK gets into bad state
- Cannot be used reliably for Drift Protocol trading

Files restored from working Helius state.
This is the definitive answer: Helius only, no alternatives work.
2025-11-14 21:07:58 +01:00
mindesbunister
f30a2c4ed4 fix: CRITICAL - Revert to Helius RPC (Alchemy breaks Drift SDK)
ISSUE CONFIRMED:
- Alchemy RPC does NOT support WebSocket subscriptions (accountSubscribe method)
- Drift SDK REQUIRES WebSocket support to function properly
- When using Alchemy:
  * SDK initializes with 100+ accountSubscribe errors
  * Claims 'initialized successfully' but is actually broken
  * First API call (openPosition) sometimes works
  * Subsequent calls hang indefinitely OR
  * Positions open without TP/SL orders (NO RISK MANAGEMENT)
  * Position Manager doesn't track positions

SOLUTION:
- Use Helius as primary RPC (supports all Solana methods + WebSocket)
- Helius free tier: 10 req/sec sustained, 100 burst
- Rate limits manageable with retry logic (5s exponential backoff)
- System fully operational with Helius

ALCHEMY INCOMPATIBILITY:
- Alchemy Growth (10,000 CU/s) excellent for raw transaction throughput
- But completely incompatible with Drift SDK architecture
- Cannot be used as primary RPC for Drift Protocol trading

User confirmed: 'after changing back the settings it started to act up again'
This is Common Pitfall #1 - NEVER use RPC without WebSocket support
2025-11-14 20:53:16 +01:00
mindesbunister
78ab9e1a94 fix: Increase transaction confirmation timeout to 60s for Alchemy Growth
- Alchemy Growth (10,000 CU/s) can handle longer confirmation waits
- Increased timeout from 30s to 60s in both openPosition() and closePosition()
- Added debug logging to execute endpoint to trace hang points
- Configured dual RPC: Alchemy primary (transactions), Helius fallback (subscriptions)
- Previous 30s timeout was causing premature failures during Solana congestion
- This should resolve 'Transaction was not confirmed in 30.00 seconds' errors

Related: User reported n8n webhook returning 500 with timeout error
2025-11-14 20:42:59 +01:00
mindesbunister
6dccea5d91 revert: Back to last known working state (27eb5d4)
- Restored Drift client, orders, and .env from commit 27eb5d4
- Updated to current Helius API key
- ISSUE: Execute/check-risk endpoints still hang
- Root cause appears to be Drift SDK initialization hanging at runtime
- Bot initializes successfully at startup but hangs on subsequent Drift calls
- Non-Drift endpoints work fine (settings, positions query)
- Needs investigation: Drift SDK behavior or RPC interaction issue
2025-11-14 20:17:50 +01:00
mindesbunister
6445a135a8 feat: Helius primary + Alchemy fallback for trade execution
- Helius HTTPS: Primary RPC for Drift SDK initialization and subscriptions
- Alchemy HTTPS (10K CU/s): Fallback RPC for transaction confirmations
- Added getFallbackConnection() method to DriftService
- openPosition() and closePosition() now use Alchemy for tx confirmations
- accountSubscribe errors are non-fatal warnings (SDK falls back gracefully)
- System fully operational: Drift initialized, Position Manager ready
- Trade execution will use high-throughput Alchemy for confirmations
2025-11-14 16:51:14 +01:00
mindesbunister
1cf5c9aba1 feat: Smart startup RPC strategy (Helius → Alchemy)
Strategy:
1. Start with Helius (handles startup burst better - 10 req/sec sustained)
2. After successful init, switch to Alchemy (more stable for trading)
3. On 429 errors during operations, fall back to Helius, then return to Alchemy

Implementation:
- lib/drift/client.ts: Smart constructor checks for fallback, uses it for startup
- After initialize() completes, automatically switches to primary RPC
- Swaps connections and reinitializes Drift SDK with Alchemy
- Falls back to Helius on rate limits, switches back after recovery

Benefits:
- Helius absorbs SDK subscribe() burst (many concurrent calls)
- Alchemy provides stability for normal trading operations
- Best of both worlds: burst tolerance + operational stability

Status:
- Code complete and tested
- Helius API key needs updating (current key returns 401)
- Fallback temporarily disabled in .env until key fixed
- Position Manager working perfectly (trade monitored via Alchemy)

To enable:
1. Get fresh Helius API key from helius.dev
2. Set SOLANA_FALLBACK_RPC_URL in .env
3. Restart bot - will use Helius for startup automatically
2025-11-14 15:41:52 +01:00
mindesbunister
7ff78ee0bd feat: Hybrid RPC fallback system (Alchemy → Helius)
- Automatic fallback after 2 consecutive rate limits
- Primary: Alchemy (300M CU/month, stable for normal ops)
- Fallback: Helius (10 req/sec, backup for startup bursts)
- Reduced startup validation: 6h window, 5 trades (was 24h, 20 trades)
- Multi-position safety check (prevents order cancellation conflicts)
- Rate limit-aware retry logic with exponential backoff

Implementation:
- lib/drift/client.ts: Added fallbackConnection, switchToFallbackRpc()
- .env: SOLANA_FALLBACK_RPC_URL configuration
- lib/startup/init-position-manager.ts: Reduced validation scope
- lib/trading/position-manager.ts: Multi-position order protection

Tested: System switched to fallback on startup, Position Manager active
Result: 1 active trade being monitored after automatic RPC switch
2025-11-14 15:28:07 +01:00
mindesbunister
7afd7d5aa1 feat: switch from Helius to Alchemy RPC provider
Changes:
- Updated SOLANA_RPC_URL to use Alchemy (https://solana-mainnet.g.alchemy.com/v2/...)
- Migrated from Helius free tier to Alchemy free tier
- Includes previous rate limit fixes (8s backoff, 2s operation delays)

Context:
- Helius free tier: 10 req/sec sustained, 100 req/sec burst
- Alchemy free tier: 300M compute units/month (more generous)
- User hit 239 rate limit errors in 10 minutes on Helius
- User registered Alchemy account and provided API key

Impact:
- Should significantly reduce 429 rate limit errors
- Better free tier limits for trading bot operations
- Combined with delay fixes for optimal RPC usage
2025-11-14 14:01:52 +01:00
mindesbunister
28c1110a85 feat: Integrate dynamic ATR analysis into TP/SL optimization endpoint
- 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
2025-11-14 09:03:15 +01:00
mindesbunister
6590f4fb1e feat: phantom trade auto-closure system
- Auto-close phantom positions immediately via market order
- Return HTTP 200 (not 500) to allow n8n workflow continuation
- Save phantom trades to database with full P&L tracking
- Exit reason: 'manual' category for phantom auto-closes
- Protects user during unavailable hours (sleeping, no phone)
- Add Docker build best practices to instructions (background + tail)
- Document phantom system as Critical Component #1
- Add Common Pitfall #30: Phantom notification workflow

Why auto-close:
- User can't always respond to phantom alerts
- Unmonitored position = unlimited risk exposure
- Better to exit with small loss/gain than leave exposed
- Re-entry possible if setup actually good

Files changed:
- app/api/trading/execute/route.ts: Auto-close logic
- .github/copilot-instructions.md: Documentation + build pattern
2025-11-14 05:37:51 +01:00
mindesbunister
a21ae6d622 Add v7-momentum indicator (experimental, disabled)
- Created momentum scalper indicator for catching rapid price acceleration
- ROC-based detection: 2.0% threshold over 5 bars
- Volume confirmation: 2.0x spike (checks last 3 bars)
- ADX filter: Requires 12+ minimum directional movement
- Anti-chop filter: Blocks signals in dead markets
- Debug table: Real-time metric display for troubleshooting

Status: Functional but signal quality inferior to v6 HalfTrend
Decision: Shelved for now, continue with proven v6 strategy
File: docs/guides/MOMENTUM_INDICATOR_V1.pine (239 lines)

Lessons learned:
- Momentum indicators inherently noisy (40-50% WR expected)
- Signals either too early (false breakouts) or too late (miss move)
- Volume spike timing issue: Often lags price move by 1-2 bars
- Better to optimize proven strategy than add complexity

Related: Position Manager duplicate update bug fixed (awaiting verification)
2025-11-12 19:55:19 +01:00