Commit Graph

184 Commits

Author SHA1 Message Date
mindesbunister
31ef8b01f2 docs: Add Common Pitfall #54 - Telegram webhook vs polling conflict 2025-12-04 17:19:08 +01:00
mindesbunister
14f28bf464 docs: Add mandatory rule #5 - CHECK DOCUMENTATION FIRST before suggestions
- New IRON-CLAD RULE: Always search docs before making suggestions or asking questions
- Purpose: Prevent wasting user time with already-answered questions
- Examples: TradingView rate limits, roadmap features, known bugs, configuration
- Workflow: Read request → Search docs → Check if answered → THEN respond
- Applies to: Features, bugs, config, architecture, deployment, troubleshooting
- Red flags: User says 'we already documented this' or 'check docs first'
- Why: User spent months documenting comprehensively, 'NOTHING gets lost' principle
- Impact: Respect user's documentation effort, save time = save money in financial system

Files modified:
- .github/copilot-instructions.md (line ~103-150, added Rule #5 with examples and workflow)
2025-12-04 17:05:32 +01:00
mindesbunister
76040fa82b docs: Add New Agent Quick Start section to copilot instructions
- Added explicit onboarding workflow at top of file
- 4-step sequence: copilot-instructions → docs/README → README → explore
- Lists all 8 documentation subdirectories with descriptions
- Emphasizes 'NOTHING gets lost' principle
- Ensures new agents have clear entry point without manual explanation
2025-12-04 14:06:05 +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
e48332e347 docs: Add verification status for Common Pitfall #53 fixes (Dec 3, 2025) 2025-12-03 23:03:40 +01:00
mindesbunister
835fe176da docs: Add Common Pitfalls #70 & #71 - Bug 5 & Bug 1 fixes
Pitfall #70: Smart Validation Queue rejected by execute endpoint
- Fixed execute endpoint to accept validatedEntry=true bypass flag
- Allows quality 50-89 signals validated by price action
- Smart Validation Queue now works end-to-end

Pitfall #71: Revenge system missing external closure integration
- Fixed external closure handler to trigger revenge for quality 85+ SL
- 30-minute revenge window activates for external stop-outs
- Completes revenge system coverage for all exit scenarios

Both fixes deployed in commit 785b09e (Dec 3, 2025)
Container restart required to activate fixes
2025-12-03 20:23:21 +01:00
mindesbunister
0f88d88dd3 docs: Add Common Pitfalls #68-69 (Dec 3, 2025 bug fixes)
- Pitfall #68: Smart Entry using webhook percentage as signal price
  * Root cause: TradingView webhook price field contained percentage (70.80) instead of market price (42.50)
  * Impact: 97% pullback calculations made Smart Entry impossible to trigger
  * Fix: Use Pyth current price instead of webhook price
  * Commit: 7d0d38a

- Pitfall #69: Direction-specific leverage thresholds not explicit
  * Made LONG/SHORT leverage assignment explicit even though values same
  * Improves code clarity and maintainability
  * Commit: 58f812f

Both fixes deployed Dec 3, 2025, 09:02:45 CET (timestamp verified)
2025-12-03 10:27:07 +01:00
mindesbunister
702ef7953b docs: Add Common Pitfall #67 - Ghost detection race condition
Bug: 23 duplicate Telegram notifications with P&L compounding (-7.96 to -,129.24)
Cause: Multiple monitoring loops passed has() check before any deleted from Map
Fix: Use Map.delete() atomic return value as deduplication lock
Result: First caller deletes and proceeds, subsequent callers return immediately

Related: #48-49 (TP1 P&L compound), #59-61 (external closure duplicates)
Deployed: Dec 2, 2025 17:32:52 UTC (commit 93dd950)
2025-12-02 18:43:24 +01:00
mindesbunister
93dd950821 critical: Fix ghost detection P&L compounding - delete from Map BEFORE check
Bug: Multiple monitoring loops detect ghost simultaneously
- Loop 1: has(tradeId) → true → proceeds
- Loop 2: has(tradeId) → true → ALSO proceeds (race condition)
- Both send Telegram notifications with compounding P&L

Real incident (Dec 2, 2025):
- Manual SHORT at $138.84
- 23 duplicate notifications
- P&L compounded: -$47.96 → -$1,129.24 (23× accumulation)
- Database shows single trade with final compounded value

Fix: Map.delete() returns true if key existed, false if already removed
- Call delete() FIRST
- Check return value
 proceeds
- All other loops get false → skip immediately
- Atomic operation prevents race condition

Pattern: This is variant of Common Pitfalls #48, #49, #59, #60, #61
- All had "check then delete" pattern
- All vulnerable to async timing issues
- Solution: "delete then check" pattern
- Map.delete() is synchronous and atomic

Files changed:
- lib/trading/position-manager.ts lines 390-410

Related: DUPLICATE PREVENTED message was working but too late
2025-12-02 18:25:56 +01:00
mindesbunister
d156abc976 docs: Add mandatory git workflow and critical feedback requirements
CRITICAL UPDATES to AI assistant instructions:

1. MANDATORY GIT WORKFLOW (DO NOT SKIP):
   - Added explicit requirement: implement → test → verify → document → commit → push
   - Made git commits NON-OPTIONAL for all significant changes
   - Added to both general prompt and copilot-instructions.md
   - Rationale: Agent has pattern of skipping documentation/commits

2. CHALLENGE USER IDEAS:
   - Added requirement to think critically about user requests
   - Instruction: "Think freely and don't hold back"
   - Goal: Find BEST solution, not just A solution
   - Push back on ideas that don't make sense
   - Ask "is there a simpler/faster/safer way?"

3. COMPREHENSIVE DOCUMENTATION SECTION:
   - Replaced brief documentation note with full workflow guide
   - Added 80+ lines of detailed documentation requirements
   - Includes examples, red flags, mindset principles
   - Emphasizes: "Git commit + Documentation = Complete work"

Files modified:
- .github/prompts/general prompt.prompt.md (added sections 5a, 6, updated 7-8)
- .github/copilot-instructions.md (comprehensive documentation workflow)

User mandate: "I am sick and tired of reminding you" - this makes it automatic.

Impact: Future implementations will ALWAYS include documentation and git commits as part of standard workflow, not as afterthoughts.
2025-12-02 15:23:20 +01:00
mindesbunister
5773d7d36d feat: Extend 1-minute data retention from 4 weeks to 1 year
- Updated lib/maintenance/data-cleanup.ts retention period: 28 days → 365 days
- Storage requirements validated: 251 MB/year (negligible)
- Rationale: 13× more historical data for better pattern analysis
- Benefits: 260-390 blocked signals/year vs 20-30/month
- Cleanup cutoff: Now Dec 2, 2024 (vs Nov 4, 2025 previously)
- Deployment verified: Container restarted, cleanup scheduled for 3 AM daily
2025-12-02 11:55:36 +01:00
mindesbunister
4239c99057 docs: Add Common Pitfall #66 - Smart Entry Validation Queue symbol normalization bug
- Symptom: Abandonment notifications showing impossible prices (26 → 8.18 in 30s)
- Root cause: Symbol format mismatch (TradingView 'SOLUSDT' vs cache 'SOL-PERP')
- Fix: Added normalizeTradingViewSymbol() in check-risk endpoint before validation queue
- Impact: Cache lookup now succeeds, Telegram shows correct abandonment prices
- Files: check-risk/route.ts line 9 (import), lines 432-444 (normalization)
- Commit: 6cec2e8 deployed Dec 1, 2025
- Lesson: Always normalize symbols at integration boundaries, cache key mismatches fail silently
2025-12-01 23:51:40 +01:00
mindesbunister
e748cf709d fix: Correct SSH hop for EPYC worker2 connectivity
- ProxyJump (-J) doesn't work from Docker container
- Changed to nested SSH: hop -> target
- Proper command escaping for nested SSH
- Worker2 (srv-bd-host01) only accessible via worker1 (pve-nu-monitor01)
2025-12-01 19:42:08 +01:00
mindesbunister
f050372d7a docs: Add Common Pitfall #65 - distributed worker quality_filter bug 2025-12-01 15:21:27 +01:00
mindesbunister
1f83a7d7c4 feat: Add coordinator log viewer to cluster UI
- Created /api/cluster/logs endpoint to read coordinator.log
- Added real-time log display in cluster UI (updates every 3s)
- Shows last 100 lines of coordinator.log in terminal-style display
- Includes manual refresh button
- Improves debugging experience - no need to SSH for logs

User feedback: 'why dont we add the output of the log at the bottom of the page so i know whats going on'

This addresses poor visibility into coordinator errors and failures.
Next step: Fix SSH timeout issue blocking worker execution.
2025-12-01 11:49:23 +01:00
mindesbunister
c343daeb44 docs: Document EPYC cluster SSH timeout fix in Common Pitfalls
- Added Common Pitfall #64: SSH timeout for nested hop scenarios
- Documented 30s→60s timeout increase rationale
- Explained SSH options: StrictHostKeyChecking, ConnectTimeout, ServerAliveInterval
- Included verification data: 23-24 processes per worker at 99% CPU
- Provided formula for calculating minimum timeouts for multi-hop SSH
- Cross-referenced commit ef371a1 (the actual code fix)
- Added future prevention guidance (timeout formulas, SSH multiplexing)

This documentation update accompanies the cluster fix deployed earlier.
2025-12-01 09:46:17 +01:00
mindesbunister
549fe8e077 docs: CRITICAL - Make documentation + git commit hand-in-hand #1 PRIORITY
USER MANDATE (Dec 1, 2025): Documentation MUST go hand-in-hand with EVERY git commit.
This is NOT optional. This is NOT a suggestion. This is MANDATORY.

Changes:
- Elevated documentation section to #1 PRIORITY status
- Added user's direct quote: 'this HAS to go hand in hand'
- Expanded from 15 lines to 100+ lines with comprehensive guidelines
- Added 'Why This is #1 Priority' section with user's frustration quote
- Added explicit 'When Documentation is MANDATORY' checklist
- Added 'The Correct Mindset' section emphasizing it's part of the work
- Added 4 scenario examples showing what MUST be documented
- Added 'Red Flags' section to catch missing documentation
- Added 'Integration with Existing Sections' guide
- Made it crystal clear: Code without documentation = INCOMPLETE WORK

This addresses user's repeated reminders about documentation being mandatory.
Future AI agents will now see this as the #1 priority it is.

NO MORE PUSHING CODE WITHOUT DOCUMENTATION UPDATES.
2025-12-01 09:17:51 +01:00
mindesbunister
b1a41733b8 docs: Document Dec 1 adaptive leverage UI enhancements
- Updated adaptive leverage configuration section with current values (10x/5x)
- Added Settings UI documentation with 5 configurable fields
- Documented direction-specific thresholds (LONG/SHORT split)
- Added dynamic collateral display implementation details
- Documented new /api/drift/account-health endpoint
- Added commit history for Dec 1 changes (2e511ce, 21c13b9, a294f44, 67ef5b1)
- Updated API endpoints section with account-health route

Changes reflect full UI implementation completed Dec 1, 2025:
- Independent LONG (95) and SHORT (90) quality threshold controls
- Real-time collateral fetching from Drift Protocol
- Position size calculator with dynamic balance updates
- Complete production-ready adaptive leverage system
2025-12-01 09:15:03 +01:00
mindesbunister
d4ecbcd168 docs: Add Smart Validation threshold optimization findings (n=200 backtest)
- Backtested 200 random DATA_COLLECTION_ONLY signals
- Validated initial n=11 finding at scale
- CURRENT (±0.3%): +0.169% avg, 67.9% WR, 14% entry rate (WINNER)
- OPTION 1 (±0.2%): -0.363% avg, 43.1% WR, 26% entry rate
- OPTION 2 (±0.15%): -0.524% avg, 35.6% WR, 36% entry rate
- Key insight: Lower thresholds catch more losers than winners
- Decision: Keep current ±0.3% thresholds (statistically validated)
2025-12-01 00:42:58 +01:00
mindesbunister
9d2055e59c docs: Add mandatory documentation workflow - git commit must go hand-in-hand with documentation 2025-12-01 00:12:28 +01:00
mindesbunister
56feef723b docs: Add Smart Entry Validation System to Common Pitfall #63 2025-12-01 00:07:21 +01:00
mindesbunister
887ae3b924 docs: Add comprehensive cluster status detection to copilot instructions
- Document database-first architecture pattern
- Include problem, root cause, and solution details
- Add verification methodology with before/after examples
- Document cluster control system (Start/Stop buttons)
- Include database schema and operational state
- Add lessons learned about infrastructure vs business logic
- Reference STATUS_DETECTION_FIX_COMPLETE.md for full details
- Current state: 2 workers active, processing 4000 combinations
2025-11-30 22:38:06 +01:00
mindesbunister
2d14f2d5c5 docs: Complete v9 parameter optimization & backtesting documentation
- v10 removal background (Nov 28, 2025)
- v9 baseline performance (05.88, 569 trades, 60.98% WR)
- Adaptive leverage implementation (5x high quality, 1x borderline)
- Parameter sweep strategy (8 parameters, 65,536 combinations)
- EPYC exhaustive sweep status (24 workers, ~17h remaining)
- Backtesting infrastructure details
- Expected outcomes and analysis plan
- Key lessons learned from v10 failure
2025-11-29 00:04:48 +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
4fb6a45fab docs: Update SHORT threshold to 80 with v10 penalty system explanation
- SHORT threshold now 80 (works WITH v10 penalties, not standalone)
- v10 applies -30 to -55 point penalties for weak setups (ADX < 23, mid-range)
- Documented penalty calculation examples (bad/trap/good setups)
- Removed outdated Nov 23 data analysis (pre-v10 system)
- Added RSI filter evolution context (removed because RSI 50+ = best 68.2% WR)
- Updated quality threshold references throughout docs (95 → 80 for SHORTs)
2025-11-28 00:39:43 +01:00
mindesbunister
3cd292d90d docs: Add Common Pitfall #62 - Missing quality threshold validation
- Bug: Execute endpoint calculated quality but never validated it
- Three trades executed at quality 30/50/50 (threshold: 90/95)
- All three stopped out, confirming low quality = losing trades
- Root cause: TradingView sent incomplete data (metrics=0, old v5) + missing validation after timeframe check
- Fix: Added validation block lines 193-213 in execute/route.ts
- Returns HTTP 400 if quality < minQualityScore
- Deployed: Nov 27, 2025 23:16 UTC (commit cefa3e6)
- Lesson: Calculate ≠ Validate - minQualityScore must be enforced at ALL execution pathways

This documents the CRITICAL FIX from commit cefa3e6.
Per Nov 27 mandatory documentation rules, work is INCOMPLETE without copilot-instructions.md updates.
2025-11-27 23:28:26 +01:00
mindesbunister
2749c08d15 docs: MANDATORY copilot-instructions.md updates + 1-min data direction field
CRITICAL: Added iron-clad rule that copilot-instructions.md MUST be updated
for every significant change. User is 'sick and tired' of reminding.

New mandatory section explains:
- When to update this file (8 specific scenarios)
- Why it's the primary knowledge base for future developers
- Automatic workflow: Change → Code → Test → Update Docs → Commit

1-Minute Data Collection documented:
- Direction field is meaningless (TradingView artifact)
- Analysis should ignore direction for timeframe='1'
- Focus on ADX/ATR/RSI/volume/price position metrics
- Example correct vs wrong SQL queries

This is NON-NEGOTIABLE going forward.
2025-11-27 19:32:22 +01:00
mindesbunister
b13a0f1b6b docs: Update copilot-instructions.md with Phase 7.3 Adaptive Trailing Stop
- Position Manager section: Complete Phase 7.3 documentation with real-time ADX queries
- Documented adaptive multiplier logic: acceleration bonus, deceleration penalty, combined 3.16× max
- Added example calculation showing 2.15× wider trail vs old static system
- When Making Changes section: Added Phase 7.3 verification steps and log monitoring
- Trailing stop changes: Updated with new adaptive system details and testing procedures
- References: PHASE_7.3_ADAPTIVE_TRAILING_DEPLOYED.md and 1MIN_DATA_ENHANCEMENTS_ROADMAP.md
2025-11-27 17:02:59 +01:00
mindesbunister
56e9522740 docs: Add MA crossover detection to copilot instructions 2025-11-27 16:31:05 +01:00
mindesbunister
2cf3deb551 docs: CRITICAL - Fix roadmap Phase 7.1/7.2 status + add MANDATORY update requirements
PROBLEM DISCOVERED (Nov 27, 2025):
User: "whats next on our roadmap with the biggest impact?"
Agent: "Phase 3 Smart Entry Timing - NOT STARTED"
User: "i thought that was already implemented?" ← USER WAS RIGHT!
Reality: Phase 3 = Phase 7.1 (smart-entry-timer.ts, 718 lines, DEPLOYED)

ROOT CAUSE:
- Roadmap said "Phase 3: NOT STARTED"
- Code reality: Phase 7.1 Smart Entry Timer fully operational
- Phase 7.2 Signal Quality Validation also deployed Nov 27
- Documentation completely out of sync with deployed code

IMPACT:
- User confusion justified (roadmap misleading)
- Wasted time investigating "next feature" already deployed
- Agent suggested implementing feature that exists
- Phase numbering confusion (Phase 2/3/7.1/7.2 mixed)

FIXES APPLIED:

1. 1MIN_DATA_ENHANCEMENTS_ROADMAP.md:
   - Phase 7.1: Smart Entry Timer →  COMPLETE (DEPLOYED)
   - Added complete documentation of deployed system
   - Explained timeout protection (NO MISSED TRADES)
   - Showed ENV config (SMART_ENTRY_ENABLED=true)
   - Phase 7.2: Already marked complete (Nov 27)

2. .github/copilot-instructions.md:
   - NEW SECTION: "📋 MANDATORY: ROADMAP MAINTENANCE"
   - 6 iron-clad rules for roadmap updates
   - Update immediately after deployment (same session)
   - Verify roadmap accuracy BEFORE recommending features
   - Never suggest features based only on roadmap status
   - ALWAYS grep codebase to verify implementation
   - Checklist for roadmap updates
   - Before recommending "next feature" verification steps

MANDATORY WORKFLOW (ALL FUTURE AGENTS):
. Complete feature/phase
. Update roadmap status → COMPLETE with date
. Document actual impact (after data collection)
. Consolidate phase numbering if inconsistencies
. Commit roadmap changes SAME SESSION
. VERIFY feature exists before recommending

LESSON LEARNED:
Roadmap documentation is CRITICAL in real money system.
Wrong roadmap = wrong priorities = wasted time = lost profits.
User time is valuable - outdated docs waste it.

FILES CHANGED:
- 1MIN_DATA_ENHANCEMENTS_ROADMAP.md (Phase 7.1 marked COMPLETE)
- .github/copilot-instructions.md (MANDATORY section added)

STATUS: Documentation now reflects deployed reality 
2025-11-27 14:26:15 +01:00
mindesbunister
a676eb4753 docs: Add zero-downtime changes guide - stop unnecessary rebuilds
PROBLEM: Rebuilding container 4-6 times per session when most changes don't need it
- Every rebuild: 40-70 seconds downtime
- Recent session: 200 seconds downtime that could've been 50 seconds
- Rebuilding for documentation (should be git only)
- Rebuilding for n8n workflows (should be manual import)
- Rebuilding for ENV changes (should be restart only)

SOLUTION: Created comprehensive guide on what actually needs rebuilds

ZERO DOWNTIME (just commit):
- Documentation (.md files)
- Workflows (.json, .pinescript)
- Hot-reload endpoints (roadmap reload)

RESTART ONLY (5-10 seconds):
- ENV variable changes (.env)
- Database schema (prisma migrate + generate)

REBUILD REQUIRED (40-70 seconds):
- Code changes (.ts, .tsx, .js)
- Dependencies (package.json)
- Dockerfile changes

SMART BATCHING:
- Group multiple code changes into ONE rebuild
- Example: 6 fixes → 1 rebuild = 50s total (not 6× rebuilds = 300s)

CREATED FILES:
- docs/ZERO_DOWNTIME_CHANGES.md (comprehensive guide with examples)
- Updated copilot-instructions.md (quick decision matrix)

EXPECTED IMPACT:
- 60-80% reduction in rebuild frequency
- 60-80% reduction in downtime per session
- Better workflow: batch changes, test together, deploy once

User was right: We were rebuilding WAY too often unnecessarily 
2025-11-27 14:08:42 +01:00
mindesbunister
ceb84c3bc1 feat: Revenge system enhancements #4 and #10 - IMPLEMENTED
Enhancement #4: Failed Revenge Tracking
- Added 3 database fields: revengeOutcome, revengePnL, revengeFailedReason
- Added updateRevengeOutcome() method in stop-hunt-tracker.ts
- Position Manager hooks revenge trade closes, records outcome
- Enables data-driven analysis of revenge success rate

Enhancement #10: Metadata Persistence
- Added 4 database fields: firstCrossTime, lowestInZone, highestInZone, zoneResetCount
- Migrated 90-second zone tracking from in-memory to database
- Rewrote shouldExecuteRevenge() with database persistence
- Container restarts now preserve exact zone tracking state

Technical Details:
- Prisma schema updated with 7 new StopHunt fields
- Added signalSource field to ActiveTrade interface
- All zone metadata persisted in real-time to database
- Build verified successful (no TypeScript errors)

Files Changed:
- prisma/schema.prisma (StopHunt model + index)
- lib/trading/stop-hunt-tracker.ts (DB persistence + outcome tracking)
- lib/trading/position-manager.ts (revenge hook + interface)
- docs/REVENGE_ENHANCEMENTS_EXPLAINED.md (comprehensive guide)

Pending User Decision:
- Enhancement #1: ADX confirmation (3 options explained in docs)
- Enhancement #6: SL distance validation (2× ATR recommended)

Status: Ready for deployment after Prisma migration
Date: Nov 27, 2025
2025-11-27 08:08:37 +01:00
mindesbunister
2238261dfe docs: Add Docker Optimization & Build Cache Management section
DOCUMENTATION UPDATE (Nov 26, 2025):
User quote: "ok. dont forget the documentation"

Added comprehensive Docker Optimization section covering:

1. MULTI-STAGE BUILDS (already implemented):
   - Verified Dockerfile uses builder → runner pattern
   - Benefits: Smaller images, faster builds, better layer reuse

2. BUILDKIT AUTO-CLEANUP (just configured):
   - Updated /etc/docker/daemon.json with 20GB threshold
   - Auto garbage collection when cache exceeds limit
   - Docker restarted, BuildKit v0.14.1 active
   - Current baseline: 11.13GB cache (healthy)

3. AUTOMATED CLEANUP SCRIPT (ready to use):
   - Script: /home/icke/traderv4/cleanup_trading_bot.sh (94 lines)
   - Features: Keeps last 2 images, prunes cache, protects volumes
   - Usage: Manual (after builds) or automated (cron daily)
   - Typical savings: 40-50 GB per run

WHY THIS MATTERS:
- User previously hit 40GB cache accumulation
- BuildKit auto-cleanup provides 20GB safety net
- Manual script gives on-demand control
- Documented process for team reference

IMPLEMENTATION STATUS:
 Multi-stage builds confirmed in Dockerfile
 BuildKit configured in daemon.json (20GB threshold)
 Cleanup script exists and executable
 Docker daemon restarted with new config
 Current disk usage healthy (11.13GB < 20GB)

Files documented:
- /etc/docker/daemon.json (BuildKit config)
- /home/icke/traderv4/cleanup_trading_bot.sh (manual cleanup)
- Dockerfile (multi-stage builds)

Added monitoring commands, usage recommendations, safety measures,
and typical space savings data for team reference.
2025-11-26 21:19:11 +01:00
mindesbunister
6734c93064 docs: Update copilot-instructions.md with v9 momentum + revenge timing
Updated Indicator Version Tracking section:
- Changed v8 from PRODUCTION to ARCHIVED (Nov 18-26)
- Added v9 as new PRODUCTION SYSTEM (Nov 26+)
- Documented v9 momentum-based SHORT filter (ADX + Price Position)
- Removed RSI filter rationale (RSI 50+ has best 68.2% WR)
- Added data evidence from 95 SHORT trade analysis
- Documented first day results: 2 losses, both blocked by momentum filter

Updated Stop Hunt Revenge System section:
- Added 'Revenge Timing Enhancement - 90s Confirmation' subsection
- Documented Nov 26 retest problem (would stop at $137.50 before $144.50 move)
- Explained Option 2 approach (90s = 1.5 minutes confirmation)
- Added implementation code snippets from stop-hunt-tracker.ts
- User insight: ATR not suitable (measures volatility, not S/R)
- Status: DEPLOYED Nov 26, 20:52:55 CET, VERIFIED

Related commits:
- 2017cba: v9 SHORT quality improvements - momentum-based filtering
- 40ddac5: Revenge timing Option 2 - 90s confirmation (DEPLOYED)
2025-11-26 20:56:20 +01:00
mindesbunister
2338bb6283 docs: Update copilot-instructions.md for Nov 26 quality scoring enhancement
- Multi-Timeframe section: Added Nov 26 implementation note
- Quality scoring now calculated for ALL timeframes (not just 5min)
- Data collection signals get real quality scores (not hardcoded 0)
- BlockedSignal records include full quality metadata
- Enables SQL: WHERE signalQualityScore >= minScoreRequired
- Execute Trade workflow: Added timeframe routing logic
- When Making Changes: Added item #19 for multi-timeframe updates
- Reflects implementation in commit dbada47
2025-11-26 15:21:08 +01:00
mindesbunister
bdd25e4d7b docs: Add HA infrastructure section to copilot instructions
- Complete architecture overview with ASCII diagram
- Database replication configuration and verification
- DNS failover monitor details (systemd service)
- Automatic failover sequence explanation
- Live test results from Nov 25, 2025 (90s detection, 0s downtime)
- Critical operational notes (firewall, ports, health checks)
- Manual failover and secondary update procedures
- Documentation references (DEPLOY_SECONDARY_MANUAL.md, HA_SETUP_ROADMAP.md)
- When making changes guidance for HA environment

Status: PRODUCTION READY 
All phases tested and validated with zero-downtime failover/failback
2025-11-25 23:20:44 +01:00
mindesbunister
fa3c76c878 docs: Add AI agent prompt for Trading Bot v4
Created comprehensive agent prompt emphasizing:
- Mandatory reading of full copilot-instructions.md (4,400+ lines)
- VERIFICATION MANDATE must be understood before any work
- This is a real money system - every bug costs money
- Never declare 'done/fixed/working' without 100% verification
- Proper workflow: read → code → deploy → verify → document

Key Requirements:
- Check container timestamp > commit timestamp before declaring deployed
- Add logging to confirm changes execute
- Test in production with real data
- Check Common Pitfalls (60+ documented bugs) before coding
- Show verification results as proof, not just code appearance

Financial Stakes:
- User building from $901 → $100,000+ with this system
- Manual restarts = system failure
- Unverified changes = financial risk
- Every change affects real money positions

Prompt ensures agents understand the verification ethos and financial responsibility before starting any work.
2025-11-25 10:25:45 +01:00
mindesbunister
a854d74a2a docs: CRITICAL - Make verification mandate absolute top priority
REAL MONEY SYSTEM - NO EXCEPTIONS ON VERIFICATION

Changes:
- Moved VERIFICATION MANDATE to very top of copilot-instructions.md
- Added clear visual separators with ⚠️ and 🚨 emojis
- Made it unmissable: Must be read before any other instructions
- Added explicit definition of what 'working' means vs does NOT mean
- Emphasized: Deployment ≠ Working without verification

Added concrete example (Nov 25, 2025 Health Monitor Bug):
- What went wrong: Declared 'working' without testing
- What should have been done: Add logging, test API, verify errors recorded
- Lesson: Never trust code appearance, always verify with real data

Why this matters:
- User building from $901 → $100,000+ with this system
- Every unverified change is financial risk
- This is not a hobby project - it's user's financial future
- Declaring something working without proof = causing financial loss

Development Ethos:
- NEVER say done/finished without testing
- NEVER skip verification for 'simple' changes
- ALWAYS double-check new development for 100% functionality
- Code appearance ≠ Code correctness
- Deployment ≠ Feature working

This is mandatory for all AI agents working on this codebase.
2025-11-25 10:21:40 +01:00
mindesbunister
595a0ac7a2 docs: Update DRIFT SDK MEMORY LEAK section with Nov 24 health monitoring
- Replaced blind 2-hour timer documentation with error-based health monitoring
- Documented DriftHealthMonitor class with 30-second sliding window
- Added 50 error threshold and flag file restart mechanism
- Documented /api/drift/health endpoint
- Explained benefits: no unnecessary restarts, faster response (30s vs 2h)
- Preserved accurate symptom/root cause/manifestation information
- References implementation commit dc197f5
2025-11-24 16:55:10 +01:00
mindesbunister
594f547a87 docs: Add biggest losers analysis validating quality thresholds
Nov 24, 2025 Analysis: Top 15 losing trades validation

Key Findings:
- Top 2 losses: Quality 90 SHORTS (-86.62, -38.35) = -24.97
- Quality 80 trades: 4 losses totaling -12.76
- Total prevented by current thresholds: -47.07
- Missed winners from blocked signals: ~10
- NET BENEFIT: +37 (3:1 loss avoidance ratio)

Validates direction-specific thresholds:
- LONG 90+: Allows profitable quality 90-94 longs
- SHORT 95+: Blocks catastrophic quality 80-90 shorts

Trade-off confirmed: Sacrifice 1-2 winners/week to eliminate
disaster trades that caused user's ,380 → 04 drawdown.

Updated: .github/copilot-instructions.md (Direction-Specific Quality Thresholds section)
2025-11-24 11:39:13 +01:00
mindesbunister
c09201ccde docs: Document TRAILING_SL exit reason distinction in copilot instructions
Added comprehensive documentation for the trailing SL feature:
- Exit reason tracking: Regular SL vs TRAILING_SL distinction
- Detection logic: tp2Hit + trailingStopActive + price pullback check
- Database storage: TRAILING_SL as separate exitReason value
- Analytics UI: Purple styling with runner emoji for trailing stops
- Code locations: Position Manager (3 locations) + Analytics frontend
- Implementation date: Nov 24, 2025 (commit 9d7932f)

Purpose: Enable separate analysis of runner trailing stop performance
vs early hard stop losses for optimization insights.
2025-11-24 08:50:13 +01:00
mindesbunister
9d7932ff2f feat: Add distinction between regular SL and trailing SL
User Request: Distinguish between SL and Trailing SL in analytics overview

Changes:
1. Position Manager:
   - Updated ExitResult interface to include 'TRAILING_SL' exit reason
   - Modified trailing stop exit (line 1457) to use 'TRAILING_SL' instead of 'SL'
   - Enhanced external closure detection (line 937) to identify trailing stops
   - Updated handleManualClosure to detect trailing SL at price target

2. Database:
   - Updated UpdateTradeExitParams interface to accept 'TRAILING_SL'

3. Frontend Analytics:
   - Updated last trade display to show 'Trailing SL' with special formatting
   - Purple background/border for TRAILING_SL vs blue for regular SL
   - Runner emoji (🏃) prefix for trailing stops

Impact:
- Users can now see when trades exit via trailing stop vs regular SL
- Better understanding of runner system performance
- Trailing stops visually distinct in analytics dashboard

Files Modified:
- lib/trading/position-manager.ts (4 locations)
- lib/database/trades.ts (UpdateTradeExitParams interface)
- app/analytics/page.tsx (exit reason display)
- .github/copilot-instructions.md (Common Pitfalls #61, #62)
2025-11-24 08:40:09 +01:00
mindesbunister
1176df4299 docs: Document adaptive leverage system in copilot instructions
- Added Adaptive Leverage System section in Architecture Overview
- Documented quality-based leverage tiers (95+ = 15x, 90-94 = 10x)
- Added configuration details and helper function usage
- Updated Configuration System with adaptive leverage integration
- Modified Execute Trade workflow to show early quality calculation
- Added critical execution order note (quality MUST be calculated before sizing)
- Added item #13 in When Making Changes section for adaptive leverage modifications
- Fixed numbering sequence (was duplicate 11s, now sequential 1-18)
- Cross-referenced ADAPTIVE_LEVERAGE_SYSTEM.md for complete details
2025-11-24 00:56:39 +01:00
mindesbunister
4f6a4b76cf docs: Document direction-specific quality thresholds in copilot instructions
Architecture Overview Updates:
- Updated Signal Quality System section with direction-specific thresholds
- Added detailed subsection explaining Nov 23, 2025 implementation
- Data-driven rationale: 227 trades analysis showed $778.52 P&L gap
- Configuration: LONG=90 (71.4% WR), SHORT=95 (28.6% WR toxic)
- Helper function, fallback logic, and expected impact documented
- Reference to complete analysis in docs/DIRECTION_SPECIFIC_QUALITY_THRESHOLDS.md

Context for Future AI Agents:
- Why different thresholds: historical data shows clear directional bias
- Quality 90-94 longs profitable (+$44.77 on 7 trades)
- Quality 90-94 shorts toxic (-$553.76 on 7 trades)
- System now captures profitable longs while blocking toxic shorts
2025-11-23 15:10:34 +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
187a123a25 docs: Add Common Pitfall #60 (stale array snapshot duplicate processing)
Documented Nov 23, 2025 bug where monitoring loop created array snapshot
before async processing, causing removed trades to be processed twice.

Real incident:
- Trade cmibdii4k0004pe07nzfmturo (manual closure)
- 97% size reduction detected
- First iteration removed trade from Map
- Second iteration processed stale reference
- Result: Duplicate Telegram notifications

Fix: Added activeTrades.has() guard at start of checkTradeConditions()
Prevents duplicate processing when trade removed during loop iteration

Also documented:
- Quality threshold .env discrepancy (81 vs 91)
- Settings UI restart requirement
- Why Next.js modules need container restart for env changes

Related to Common Pitfall #59 (Layer 2 ghost detection duplicates)
but different trigger - normal monitoring vs rate limit storm detection
2025-11-23 11:03:02 +01:00
mindesbunister
d71254a57e docs: Document quality-blocked signal tracking discovery
Updates to copilot-instructions.md:
- Multi-Timeframe Price Tracking System section enhanced
- BlockedSignalTracker purpose clarified: validates quality 91 threshold
- Current Status updated with Nov 22 enhancement details
- First false negative result documented (quality 80, +0.52% missed profit)

Signal Quality Scoring section:
- Added 'Threshold Validation In Progress' subsection
- User observation documented: 'green dots shot up'
- Data collection criteria defined (20-30 blocked signals)
- Decision framework added: Keep 91 vs lower to 85 vs adjust weights
- Possible outcomes listed for data-driven optimization

Next Steps:
- Continue collecting quality-blocked signal data (2-4 weeks)
- Target: 20-30 signals with complete price tracking
- SQL analysis: Compare blocked signal win rate vs executed trades
- Decision: Validate quality 91 threshold or adjust based on data

Purpose: Complete documentation of missed opportunity discovery and
validation plan for quality threshold optimization.
2025-11-22 16:15:18 +01:00
mindesbunister
bba91c1df8 feat: Archive old indicator versions, focus on v8 production system
Version Management:
- v8 Money Line: PRODUCTION (8 trades, 57.1% WR, +$262.70, quality ≥95 = 100% wins)
- v5/v6/v7: ARCHIVED (historical baseline for future v9 comparison)

API Changes (app/api/analytics/version-comparison/route.ts):
- Added 'archived' flag to version stats
- Added 'production' field pointing to v8
- Updated sort order: v8 first, then archived versions
- Enhanced descriptions with PRODUCTION/ARCHIVED labels

UI Changes (app/analytics/page.tsx):
- v8 highlighted with blue gradient + 🚀 PRODUCTION badge
- Archived versions greyed out (60% opacity) + ARCHIVED badge
- Updated header: 'Indicator Versions (v8 Production)'
- Data collection notice: v8 shows 8/50 trades progress
- Kept comparison infrastructure for future v9 development

Documentation (.github/copilot-instructions.md):
- Updated Indicator Version Tracking section
- Documented perfect quality separation (≥95 = 100% wins)
- Clarified v8 production status, archived versions purpose
- Analytics UI behavior documented

Purpose: Keep comparison infrastructure for statistical validation
and future v9 testing while focusing user attention on v8 results.
2025-11-22 14:45:48 +01:00
mindesbunister
81926c24b9 docs: Add Common Pitfall #59 - Layer 2 duplicate Telegram notifications
Bug: Trade #8 (SHORT SOL-PERP, Nov 22, 04:05) sent 13 duplicate notifications
- P&L compounded $11.50 → $155.05 (8.2× actual $18.79)
- Root cause: Layer 2 ghost detection ignored closingInProgress flag
- Rate limit storm: 6,581 failures → Layer 2 triggered 13 times
- Each call sent notification before async DB update completed

Real incident details:
- TP1: +$32.63 (60% closed)
- Runner: -$13.84 (40% closed at breakeven)
- Net: +$18.79 (Drift confirmed)
- Database showed $155.05 (manually corrected)

Fix: Added closingInProgress check before Layer 2 ghost detection
Related: Pitfalls #40 (death spiral), #48 (closingInProgress), #49 (compounding)
2025-11-22 14:13:26 +01:00
mindesbunister
c9972ffd99 docs: Add perfect quality score separation data (validates 91 threshold)
Critical finding from 7 v8 trades analysis:
- ALL 4 winners: quality ≥95 (95, 95, 100, 105)
- ALL 3 losers: quality ≤90 (80, 90, 90)
- Perfect separation validates 91 threshold decision
- Would have prevented 100% of losses (-$624.90 total)

Updated:
- SIGNAL_QUALITY_SETUP_GUIDE.md (overview + threshold history)
- SIGNAL_QUALITY_OPTIMIZATION_ROADMAP.md (current system)
- BLOCKED_SIGNALS_TRACKING.md (quality score analysis)
- .github/copilot-instructions.md (data validation sections)

This proves 91 is data-driven optimal, not too strict.
2025-11-21 19:16:07 +01:00