Commit Graph

735 Commits

Author SHA1 Message Date
mindesbunister
23db02de72 docs: Update leverage settings - 10x SOL, 5x ETH (Jan 2, 2026)
- Updated Adaptive Leverage System section to reflect current .env
- LEVERAGE=10 (global), SOLANA_LEVERAGE=10, ETHEREUM_LEVERAGE=5
- Rationale: 82% WR, 2.18 PF, 6.19% max DD justifies 10x
- Previous: Was 5x fixed (Dec 26, 2025)
2026-01-02 22:29:53 +01:00
mindesbunister
cb40cf22d7 fix: Convert Format Success to Code node for reliable Telegram formatting (Jan 3, 2026)
- Changed Format Success from Set node (n8n-nodes-base.set) to Code node (n8n-nodes-base.code)
- Set nodes with complex inline JS expressions often fail to evaluate, returning raw template code
- Code node typeVersion 2 properly executes JavaScript with template literals
- Fixes Telegram receiving raw ${resp.symbol} instead of actual values

Affects:
- Smart Entry queue messages
- Trade opened messages
- Signal processed messages

IMPORTANT: User must import updated workflow to n8n via:
1. Open https://flow.egonetix.de
2. Money Machine workflow → Settings → Export
4. Import workflows/trading/Money_Machine.json
2026-01-02 21:57:57 +01:00
mindesbunister
1fd13c1729 fix: Restore Direction Mode to optimized indicator (Jan 2, 2026)
- Optimized indicator was missing Direction Mode feature (Long Only)
- Copied working moneyline_v11_2_indicator.pinescript over broken optimized version
- Direction Mode defaults to 'Long Only' (disables SHORT signals)
- Key feature: allowLong/allowShort gates final signals based on direction setting
- Green supertrend line now properly sticks to candles with plot.style_linebr
- Added Monte Carlo simulation notebook for v11.2 projections

Files changed:
- workflows/trading/moneyline_v11_2_optimized_indicator.pinescript (restored)
- docs/analysis/v11_compounding_simulation.ipynb (new)
2026-01-02 21:48:38 +01:00
mindesbunister
919cb7a64c config: Update leverage from 5x to 10x
Justified by validated Long-only backtest (Nov 24 - Jan 3):
- Win Rate: 82.14% (required >65%)
- Profit Factor: 2.18 (required >1.5)
- Max Drawdown: 6.19% (required <15%)
- Sample Size: 28 trades (required >20)

Risk Management Rules:
- Position cap: 80% max of free collateral
- Stop rule: If -25% account (75), drop to 5x
- Review: After 14 trades (2 weeks), evaluate live vs backtest
2026-01-02 20:16:53 +01:00
mindesbunister
7f86364fb1 docs: Add Direction Mode documentation (Jan 2, 2026)
- Updated CURRENT ACTIVE SYSTEM section with Direction Mode feature
- Default: 'Long Only' (84% win rate on LONGs, SHORTs disabled until optimized)
- Added allowLong/allowShort filter logic documentation
- Updated Last Updated date to Jan 2, 2026 with commit reference
2026-01-02 19:41:58 +01:00
mindesbunister
c89aa10f16 feat: Add Direction Mode to v11.2 INDICATOR for LONG-only trading
- Added 'Trade Direction' dropdown (Both/Long Only/Short Only)
- Default set to 'Long Only' to disable SHORT signals
- Signals filtered by allowLong/allowShort before alerts fire
- Debug table shows current direction mode setting
- User discovered 84% win rate on LONGs - shorts need optimization
- Production ready for LONG-only live trading
2026-01-02 19:37:49 +01:00
mindesbunister
1f8630862c fix: Filter plotshape signals by direction mode (visual bug fix) 2026-01-02 19:29:36 +01:00
mindesbunister
fa6f0a80bc fix: Make strategy backtest LONG and SHORT independently (not reversals)
CRITICAL BUG FIXED (Jan 2, 2026):
- Old backtest treated SHORT signal as 'exit LONG only' (reversal system)
- Live trading opens actual SHORT position = different outcome
- Backtest showed profit but live trading lost money due to mismatch

Changes:
- Added close_entries_rule='ANY' to strategy declaration
- Opposite signal now CLOSES current position first, then opens NEW
- Added 'Direction Mode' dropdown: Both / Long Only / Short Only
- Comments document the fix for future reference

This allows honest evaluation:
1. Run 'Both' mode to see true combined performance
2. Run 'Long Only' to see LONG-only results
3. Run 'Short Only' to see SHORT-only results (likely the problem area)
2026-01-02 19:18:55 +01:00
mindesbunister
184b8f8a5b docs: Update n8n MCP token + Add comprehensive workflow documentation
- Updated MCP Bearer token in copilot-instructions.md (new token ending ...SQbRcoBo)
- Created docs/N8N_WORKFLOW_DOCUMENTATION.md with complete Money Machine workflow docs
- Smart Entry bypass for v11.2+ signals with indicatorScore >= 90
- Money_Machine.json formatting cleanup

Files changed:
- .github/copilot-instructions.md: MCP token update
- docs/N8N_WORKFLOW_DOCUMENTATION.md: NEW comprehensive n8n docs
- app/api/trading/execute/route.ts: Smart Entry bypass for high-quality signals
- workflows/trading/Money_Machine.json: Telegram message formatting fixes
2026-01-01 15:47:33 +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
4bf5761ec0 critical: Bug #91 - Use SDK closePosition() for exact BN (no Math.floor truncation)
Root Cause: Math.floor(sizeToClose * 1e9) truncated position sizes, leaving tiny fractional remnants (e.g., 0.00000008 SOL) that prevented full position closure.

Discovery: Drift UI 'Close All Positions' failed with 'not enough collateral' but clicking 'Market' order worked - because Market uses exact position size.

Solution: SDK's driftClient.closePosition() uses exact BN arithmetic internally (baseAssetAmount.abs()), avoiding any floating point truncation.

Changes:
- lib/drift/orders.ts lines 647-690
- For 100% closes: Now uses driftClient.closePosition(marketIndex)
- For partial closes: Continues using placeAndTakePerpOrder

Expected Impact: Flip operations will now fully close positions without leaving fractional remnants that cause 'position still open' failures.

Financial Impact: Prevents flip failures that caused user 000+ losses from multiple bugs in position closing logic.
2026-01-01 13:50:45 +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
d0323fddd7 docs: Update Q95 section - mark as ARCHIVED, document 5-candle exit removal
- Q95 strategy section marked as ARCHIVED (superseded by v11.2)
- 5-Candle Time Exit marked as REMOVED (commit 9036252)
- Updated 'Filters Applied' to note 5-candle removal
- Added references to v11.2 as current production system
- v11.2 backtest (+53.80% return, PF 2.617) did NOT include 5-candle rule
2025-12-27 21:39:59 +01:00
mindesbunister
90362526c4 fix: Remove 5-candle time exit rule for v11.2 strategy
- Removed TIME_EXIT_5_CANDLE logic from position-manager.ts
- v11.2 backtest (+53.80%) didn't include this exit rule
- Trades will now be allowed to reach TP1 (+1.1%) instead of early exit
- Previous behavior: Exit after 25min if MFE < $30 (force-exited -0.20% trade)
- New behavior: Let trades run to configured TP1/SL levels

Rationale: The 5-candle rule was from an older Q>=95 strategy optimization.
v11.2 indicator already filters to PF 2.617 profitable setups, additional
time-based filtering was counter-productive and introduced untested behavior.
2025-12-27 20:21:37 +01:00
mindesbunister
9781eba6d9 docs: Update v11.2 backtest numbers to verified values (+53.80% return, PF 2.617, 202 trades) 2025-12-26 16:57:14 +01:00
mindesbunister
87c7b81b99 docs: Update v11.2 with verified backtest results (+53.80%, PF 2.617)
- Corrected comment from +50%/2.507 to actual verified +53.80%/2.617
- 202 trades, 8.35% max drawdown confirmed via user screenshot
- At 5x leverage: ~269% monthly return potential, 00 → 00-,100
2025-12-26 16:42:29 +01:00
mindesbunister
0b6f1f7a7d feat: v11.2 Indicator Score Bypass System (SCORE:100)
- Added indicatorScore bypass in check-risk endpoint (lines 91-104)
  * When indicatorScore >= 90, bypasses quality threshold check
  * Logs: '🎯 INDICATOR SCORE BYPASS: Score X >= 90, bypassing quality check'

- Added indicatorScore to ExecuteTradeRequest interface
  * Optional field: indicatorScore?: number

- n8n workflow updated (via API):
  * Parse Signal Enhanced: Regex extracts SCORE:(\d+) from alert
  * Check Risk1: Passes indicatorScore in request body
  * Execute Trade1: Passes indicatorScore to bot

- v11.2 Indicator sends SCORE:100 in all alerts
  * Indicator already filters to PF 2.507 profitable setups
  * Bot quality scoring is redundant for pre-validated signals

Signal Flow:
TradingView v11.2 (SCORE:100) → Webhook → Parse Signal → Check Risk1 (bypass) → Execute Trade1 → Trade Executed

Verified: Dec 26, 2025 - Full webhook test successful
- Execution 70758 completed
- SOL-PERP LONG opened at $124.01
- Drift and DB positions match (12.86 SOL, $1,597)
2025-12-26 14:35:48 +01:00
mindesbunister
a8dcee612a docs: Document indicator score bypass system (SCORE:100)
- Updated CURRENT ACTIVE SYSTEM section to Dec 26, 2025
- Added new 'Indicator Score Bypass System' section
- v11.2 sends SCORE:100 to bypass bot quality scoring
- n8n Money Machine workflow updated via API (Dec 26, 2025 10:58 UTC)
- Signal flow: Indicator (PF 2.507) → n8n (parse+pass) → Bot (bypass) → Execute
- Rationale: Two-layer filtering was counterproductive
- Files: pinescript, parse_signal_enhanced.json, Money_Machine.json, execute/route.ts
2025-12-26 12:03:20 +01:00
mindesbunister
ba1fe4433e feat: Indicator score bypass - v11.2 sends SCORE:100 to bypass bot quality scoring
Changes:
- moneyline_v11_2_indicator.pinescript: Alert format now includes SCORE:100
- parse_signal_enhanced.json: Added indicatorScore parsing (SCORE:X regex)
- execute/route.ts: Added hasIndicatorScore bypass (score >= 90 bypasses quality check)
- Money_Machine.json: Both Execute Trade nodes now pass indicatorScore to API

Rationale: v11.2 indicator filters already optimized (2.544 PF, +51.80% return).
Bot-side quality scoring was blocking proven profitable signals (e.g., quality 75).
Now indicator passes SCORE:100, bot respects it and executes immediately.

This completes the signal chain:
Indicator (SCORE:100) → n8n parser (indicatorScore) → workflow → bot endpoint (bypass)
2025-12-26 11:40:12 +01:00
mindesbunister
91f8abed19 docs: Update documentation for Dec 26 config changes
- Updated Active System section: v11.2 INDICATOR now production
- Documented v11.2 optimized parameters (ATR 12, Mult 3.8, ADX 15, RSI 56-69)
- Updated Adaptive Leverage: NOW DISABLED, fixed 5x leverage
- Removed 10x tier references, consistent 5x across all symbols
2025-12-26 10:19:48 +01:00
mindesbunister
5d8fa78d85 config: Set TP1=1.1%, SL=2.8%, leverage=5x (no 10x tier)
- Updated STOP_LOSS_PERCENT from -1.5 to -2.8
- Updated TAKE_PROFIT_1_PERCENT from 0.8 to 1.1
- Clamped ATR bounds: MIN/MAX_TP1_PERCENT=1.1, MIN/MAX_SL_PERCENT=2.8
- Set LEVERAGE=5 (was 1)
- Disabled adaptive leverage (USE_ADAPTIVE_LEVERAGE=false)
- Set HIGH/LOW_QUALITY_LEVERAGE both to 5 (removed 10x tier)
- Set SOLANA_LEVERAGE=5, ETHEREUM_LEVERAGE=5

User request: consistent 5x leverage, fixed TP1/SL targets
2025-12-26 10:18:49 +01:00
mindesbunister
358085d4f6 docs: Exit strategy analysis - losers 42x bigger than winners, dynamic thresholds rejected
- Created comprehensive exit strategy analysis from 30-day backtest
- Key finding: Average loss -1.84 vs average win /bin/bash.76 (42 asymmetry)
- Root cause: Position management not working, not entry quality
- Dynamic thresholds tested: only +.21/month improvement (rejected)
- Backtesting infrastructure: 487-line Python script with regime analysis
- Database: PostgreSQL integration for 78 real trades Nov 23 - Dec 23
- Next steps: Fix exit strategy, not thresholds (exits are the problem)
2025-12-23 18:01:24 +01:00
mindesbunister
9c65124743 docs: Complete exit strategy analysis - ,400 loss root cause identified
- Root cause: Exit strategy, NOT entry timing
- Smoking gun: Identical entry conditions (+83 winner AND -,129 loser)
- Key problems: SL too wide (ATR 3.0), no catastrophic cap, trailing too tight
- Phase 1 fixes: Tighten SL to ATR 2.0, add -2 avg winner cap, block extreme longs
- Phase 2 fixes: Widen trailing to ATR 2.5, earlier profit acceleration
- Expected impact: -,400 → +4 over 78 trades
- Validation: 10/30/50 trade milestones
- Files: Full analysis, implementation plan, executive summary
2025-12-23 17:25:54 +01:00
mindesbunister
4b0b9faa20 fix: Add skipNotification gate to prevent disabled symbol notifications
- Insert 'Check Skip Notification' IF node between Format Risk and Telegram Risk
- Route TRUE branch (skipNotification === true) to workflow end (no notification)
- Route FALSE branch to Telegram Risk for notification
- Fixes unwanted FARTCOIN-PERP notifications while preserving SOL-PERP notifications
- API at /api/trading/check-risk returns skipNotification: true for disabled symbols
2025-12-21 19:28:12 +01:00
mindesbunister
e60e6d4030 fix: Block disabled symbols (FARTCOIN) from risk check to prevent unwanted Telegram notifications 2025-12-21 14:27:33 +01:00
mindesbunister
aafc4ce506 docs: Add orderbook shadow logging to copilot instructions
- Added comprehensive section to Critical Components (#2)
- Ensures all future AI agents aware of orderbook feature
- Documents implementation, scope (trade-time only), status
- Cross-references ORDERBOOK_SHADOW_LOGGING.md for details
- Status: Deployed Dec 19, 2025, Phase 1 complete
- Awaiting validation with first 50-100 trades
2025-12-19 09:32:21 +01:00
mindesbunister
67dde80679 docs: Clarify orderbook shadow logging scope for next agent
Key clarifications in ORDERBOOK_SHADOW_LOGGING.md:

1. Trade execution only (NOT periodic):
   - Orderbook captured in /api/trading/execute (lines 1037-1053)
   - NOT captured in /api/trading/market-data (1-minute feed)
   - Frequency: 3-5 orderbook snapshots per day (when trades execute)
   - vs. 1,440 market data updates per day (price/ATR/ADX/RSI)

2. Phase 1.5 declined (Dec 19, 2025):
   - User asked about 1-minute periodic orderbook capture
   - Agent explained tradeoffs: 1,440 API calls/day, more storage
   - User confirmed trade-time capture sufficient for now
   - Periodic monitoring not needed for Phase 1 validation

3. Scope clarity for resumption:
   - Phase 1 complete and deployed
   - Goal: Collect 50-100 trades with orderbook data
   - Phase 2: Real orderbook API integration (Hyperliquid/Jupiter)
   - Next agent: Monitor trade data collection, analyze patterns

Status:  All Phase 1 tasks complete, awaiting first trade validation
2025-12-19 09:07:46 +01:00
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
bf52a44b31 Fix instant-reversal filter: Use direct Prisma query instead of incorrect array filter 2025-12-18 09:56:42 +01:00
mindesbunister
f1c4548dca Update copilot-instructions: Mark Q≥95 strategy as DEPLOYED with backtest validation 2025-12-18 09:40:25 +01:00
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
de2e6bf2e5 docs: Correct CURRENT ACTIVE SYSTEM - v11.2 IMPROVED (not v11)
User clarification: 'i thought it is the v11 v2'
- Updated to show v11.2 IMPROVED as active version
- Documented both available indicators (v11.2 improved and v11 all filters)
- Added parameters for both versions for comparison
- Note: Database shows 'v11' but user has v11.2 loaded in TradingView
2025-12-17 15:50:54 +01:00
mindesbunister
f4695da802 docs: Add CURRENT ACTIVE SYSTEM section to copilot-instructions.md
MANDATORY section for all AI agents to check first:
- Current TradingView indicator: v11 All Filters (filters NOW working)
- Signal quality scoring: v9 with direction-specific thresholds
- Position management: TP2-as-runner with ATR-based dynamic targets
- Adaptive leverage: 10x/5x with LONG 95+, SHORT 90+ thresholds
- Verification commands to check what's actually deployed

This prevents confusion when multiple implementations exist.
User mandate: 'i want this to be a mandatory thing to document'
2025-12-17 15:48:17 +01:00
mindesbunister
f372485e3b docs: Update copilot-instructions.md with v11 analysis commit reference 2025-12-17 15:44:13 +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
826e4f7dbe docs: Document Docker build optimization (914MB → 27KB)
Added Docker build context optimization details to Architecture Overview:
- 33,389× smaller build context (914.39MB → 27.39KB)
- 89% faster context transfer (14.3s → 1.6s)
- 36% faster total builds (267.6s → 170.8s)
- Key exclusion patterns documented
- Commit reference for future context
2025-12-17 15:38:21 +01:00
mindesbunister
ce56a540c6 perf: Optimize Docker build context from 914MB to 27KB
- Add explicit node_modules exclusion patterns (**/node_modules, node_modules/)
- Exclude Python virtual environments (.venv/, .backtester/, cluster/.venv/)
- Exclude cluster data files (chunks/, data/, CSV files - 143MB)
- Exclude backtester data and CSV files (~7MB)

Impact:
- Build context: 914.39MB → 27.39KB (33,389× smaller)
- Context transfer: 14.3s → 1.6s (89% faster)
- Total build time: 267.6s → 170.8s (36% faster)

With layer caching, typical rebuilds now ~60-90s instead of ~267s.
2025-12-17 15:37:08 +01:00
mindesbunister
cf4178251a docs: Add Bug #87 to Common Pitfalls + create state persistence test suite
- Added Bug #87 (Position Manager state lost on restart) to TOP 10 Critical Pitfalls
- Comprehensive documentation with incident details, root cause, fix implementation
- Created state-persistence.test.ts to validate all 18 critical state fields
- Test suite validates tp2Hit, trailingStopActive, peakPrice (critical for runner recovery)
- Testing notes: TypeScript , npm test ⏱ timeout (120s), Docker deployment 
- Real-world validation pending: Next trade with container restart

Bug #87 Impact:
- Financial: ~$18.56 runner profit lost
- Root Cause: Race condition in nested Prisma query
- Fix: 4-step bulletproof atomic persistence with verification
- Status:  DEPLOYED Dec 17, 2025 15:14 UTC (commit 341341d)
2025-12-17 15:25:16 +01:00
mindesbunister
341341d8b1 critical: Bulletproof Position Manager state persistence (Bug #87)
PROBLEM: Container restart caused Position Manager to lose tracking of runner
system state, resulting in on-chain TP1 order closing entire position (100%)
instead of partial close (60%).

ROOT CAUSE: updateTradeState() had race condition in configSnapshot merge logic
- nested Prisma query inside update caused non-atomic read-modify-write
- positionManagerState was NULL in database despite saveTradeState() calls
- Missing critical state fields: tp2Hit, trailingStopActive, peakPrice

THE FIX (3-Layer Protection):
1. Atomic state persistence with verification
   - Separate read → merge → write → verify steps
   - Bulletproof verification after save (catches silent failures)
   - Persistent logger for save failures (investigation trail)

2. Complete state tracking
   - Added tp2Hit (runner system activation)
   - Added trailingStopActive (trailing stop recovery)
   - Added peakPrice (trailing stop calculations)
   - All MAE/MFE fields preserved

3. Bulletproof recovery on restart
   - initialize() restores ALL state from configSnapshot
   - Runner system can continue after TP1 partial close
   - Trailing stop resumes with correct peak price
   - No on-chain order conflicts

FILES CHANGED:
- lib/database/trades.ts (lines 66-90, 282-362)
  * UpdateTradeStateParams: Added tp2Hit, trailingStopActive, peakPrice
  * updateTradeState(): 4-step atomic save with verification
  * Persistent logging for save failures

- lib/trading/position-manager.ts (lines 2233-2258)
  * saveTradeState(): Now saves ALL critical runner system state
  * Includes tp2Hit, trailingStopActive, peakPrice
  * Complete MAE/MFE tracking

EXPECTED BEHAVIOR AFTER FIX:
- Container restart: PM restores full state from database
- TP1 partial close: 60% closed, 40% runner continues
- TP2 activation: Runner exits with trailing stop
- No on-chain order conflicts (PM controls partial closes)

USER IMPACT:
- No more missed runner profits due to restarts
- Complete position tracking through container lifecycle
- Bulletproof verification catches save failures early

INCIDENT REFERENCE:
- Trade ID: cmja0z6r00006t907qh24jfyk
- Date: Dec 17, 2025
- Loss: ~$18.56 potential runner profit missed
- User quote: "we have missed out here despite being a winner"

See Bug #87 in Common Pitfalls for full incident details
2025-12-17 15:06:05 +01:00
mindesbunister
8fdcf06d4b docs: Add Docker cache bug to Common Pitfalls (Bug #86)
- Documents critical incident where --force-recreate didn't deploy code
- Telegram showed 0.15% instead of 0.3% despite commits and rebuild
- Root cause: Docker cached build layers, only container recreated
- Solution: docker compose build --no-cache trading-bot required
- Adds when to use --no-cache vs --force-recreate guidelines
- Includes verification steps and prevention rules
- 2 hours debugging time, now documented for future reference
2025-12-17 14:55:08 +01:00
mindesbunister
0310b14f24 fix: Enable BlockedSignalTracker for SMART_VALIDATION_QUEUED signals
- Added 'SMART_VALIDATION_QUEUED' to blockReason filter (line 115)
- Enables price tracking and outcome analysis for validation queue
- Will track MFE/MAE, TP1/TP2/SL hits for queued signals
- Purpose: Collect data to justify adaptive threshold calculations
- Affects 10 existing + all future validation queue signals
2025-12-17 14:00:11 +01:00
mindesbunister
6ac2647565 feat: Make Smart Validation Queue thresholds adaptive in Telegram notifications
CHANGES:
- Extended sendValidationNotification interface with confirmationThreshold, maxDrawdown, entryWindowMinutes
- Updated telegram.ts to display actual queued signal thresholds instead of hardcoded values
- Modified smart-validation-queue.ts to pass dynamic threshold values to Telegram
- Messages now show exact thresholds used for each signal (not fixed 0.3%/1.0%/90min)

PURPOSE:
- User requested adaptive display instead of hardcoded values
- Enables future per-signal threshold customization
- Each signal can have different thresholds based on characteristics

EXAMPLE:
  Before: 'Will enter if +0.3% confirms' (all signals)
  After:  'Will enter if +0.25% confirms' (high ADX signal)
          'Will enter if +0.4% confirms'  (low ADX signal)

STATUS: Ready for deployment - will show actual threshold per signal
2025-12-17 13:39:54 +01:00
mindesbunister
dd9e5bd650 fix: Correct Smart Validation Queue confirmation threshold in Telegram notification (0.15% → 0.3%) 2025-12-17 13:26:50 +01:00
mindesbunister
a155a55cfc docs: Document v11 restoration and v11.2 creation (Bug #85)
CRITICAL DOCUMENTATION: Parameter drift incident Dec 17, 2025

PROBLEM DISCOVERED:
- Both v11_all_filters and v11_2_emergency_fix were IDENTICAL
- Emergency fix (ADX 18, RSI 58-68) had replaced optimal values
- Original v11 optimal (ADX 5, RSI 55-70) from 26,244 config sweep lost
- User reported: "filters creating scattered signals without clear quality"

RESOLUTION:
- v11_all_filters.pinescript: Restored to optimal (ADX 5, RSI 55-70)
- v11_2_improved.pinescript: Created with balanced improvements (ADX 12, RSI 56-69)
- v11_2_emergency_fix.pinescript: Archived for reference (too restrictive)

EXHAUSTIVE SWEEP DATA:
- 2,000/26,244 configurations tested
- Best: $4,158 PnL, 72.5% WR, 1.755 PF, $95 max DD

LESSON LEARNED:
- Emergency fixes under pressure overcompensate
- Exhaustive sweep data > reactive parameter changes after losses
- Always preserve proven baselines before experimenting
- Separate experimental file prevents production breakage

NEW COMMON PITFALL #85:
- Title: v11 Parameter Drift - Emergency Fix Replaced Optimal Values
- Severity: CRITICAL ($1,000+ loss series contributor)
- Prevention: Never overwrite optimal without data proving new values better
- Files: moneyline_v11_all_filters.pinescript, moneyline_v11_2_improved.pinescript

Dec 17, 2025
2025-12-17 11:02:21 +01:00
mindesbunister
178348d269 fix: Restore v11 to optimal parameters + create v11.2 IMPROVED
V11 RESTORATION (moneyline_v11_all_filters.pinescript):
- ADX minimum: 18 → 5 (exhaustive sweep optimal from 26,244 configs)
- RSI LONG: 58-68 → 55-70 (data-driven range captures momentum)
- Flip threshold: 0.15% (unchanged - user validated)
- Version: v11.2 → v11 (correct indicator version)
- Rationale: v11.2 emergency fix was too restrictive, created scattered signals

V11.2 IMPROVED CREATION (moneyline_v11_2_improved.pinescript):
- Flip threshold: 0.15 → 0.20% (tighter trend confirmation)
- ADX minimum: 5 → 12 (moderate between v11 permissive and emergency 18)
- RSI LONG: 55-70 → 56-69 (balanced quality improvement)
- RSI SHORT: 30-70 (unchanged - working well)
- Version: v11.2
- Goal: Quality signals without being overly restrictive

CONTEXT:
- User reported v11.2 emergency fix creating scattered low-quality signals
- Both files were identical (v11.2 parameters), lost v11 optimal values
- Exhaustive sweep: $4,158 PnL (72.5% WR, 1.755 PF) with ADX=5
- Real money system: $540 USDC capital, parameter changes affect profitability

FILES:
- v11_all_filters: Production indicator (restored to proven parameters)
- v11_2_improved: Experimental version (balanced improvements)
- v11_2_emergency_fix: Backup (preserved for reference)

Dec 17, 2025
2025-12-17 10:59:04 +01:00
mindesbunister
2234bbc171 fix: Add getPrismaClient import for Bug #89 fractional remnant detection
- Fixed import in health monitor to include getPrismaClient
- Required for Bug #89 FRACTIONAL_REMNANT database queries
- Resolved Build 2 module resolution error (../database/client)
- Corrected import path to ../database/trades

Also includes v11.2 PineScript emergency parameter fix
2025-12-17 08:43:14 +01:00
mindesbunister
bafaf699ec feat: v11.2 subversion - Emergency fix for ADX/RSI parameters
- New file: moneyline_v11_2_emergency_fix.pinescript
- ADX minimum: 5 → 18 (blocks weak chop)
- RSI LONG: 55-70 → 58-68 (tighter momentum)
- Fixed ADX boundary check (> to >=)
- Indicator version: v11.2 for tracking
- Original v11 file remains unchanged
2025-12-16 22:06:43 +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
7c8f1688aa critical: v11.2 EMERGENCY FIX - ADX 18 min (was 5), RSI 58-68 LONG (was 55-70)
- ADX minimum: 5 → 18 (all ADX <18 trades were losses)
- RSI LONG range: 55-70 → 58-68 (tighter momentum window)
- Fixed ADX filter: > to >= for proper boundary check
- Reason: 4 consecutive SL losses, quality 95-100 signals failing
- Evidence: ADX 13.2 = -0.55, ADX 15.8 = -.18, RSI 59.5 = -0.03
2025-12-16 22:02:39 +01:00