Commit Graph

149 Commits

Author SHA1 Message Date
mindesbunister
d49e0feb5f docs: Add mandatory npm test requirement before Position Manager deployment
- Added STEP 1: Run tests BEFORE deployment (113 tests in ~30s)
- Added STEP 2: Validate with test trade AFTER deployment
- Why mandatory: Catch bugs (tokens vs USD, false TP1, wrong SL) before real money loss
- Tests prevent Common Pitfalls #24, #43, #45, #52, #54, #67 recurrence
- DO NOT deploy if tests fail - fix issue or update tests first
2025-12-05 14:20:32 +01:00
mindesbunister
389bcd6f4c Merge remote-tracking branch 'github/master' 2025-12-05 13:49:00 +01:00
copilot-swe-agent[bot]
98a68ae357 docs: Add "DO I ALREADY HAVE THIS?" Feature Discovery section
Added comprehensive feature discovery section to copilot-instructions.md:
- Quick Reference Table: 9 common scenarios with existing features
- Quick Search Commands: bash commands for feature discovery
- Feature Discovery by Category: 6 categories with 30+ features
- Decision Flowchart: 5-step verification process
- Historical Examples: why each feature was built

This helps users/AI agents discover existing features before rebuilding.

Co-authored-by: mindesbunister <32161838+mindesbunister@users.noreply.github.com>
2025-12-05 12:39:19 +00:00
mindesbunister
d7d8369cc7 fix: Correct BlockedSignal data contamination numbers
- Only 31 records from multi-timeframe alerts (not 11,429)
- 11,398 records are 1-minute data (kept as DATA_COLLECTION_ONLY)
- Total marked as OLD_V9_VERSION: 31 (15min/1H/4H/Daily only)
2025-12-05 10:40:02 +01:00
mindesbunister
eefee98818 docs: Document BlockedSignal data contamination from old v9 alerts
- Discovery: All TradingView alerts (5min/15min/1H/4H/Daily) attached to OLD v9 version
- Impact: 11,429 records from wrong indicator settings (confirmBars=0 vs current)
- Solution: Marked as DATA_COLLECTION_OLD_V9_VERSION to prevent analysis contamination
- Exception: 1-minute data (11,398) kept as DATA_COLLECTION_ONLY (unaffected)
- Fresh data from corrected alerts will use DATA_COLLECTION_ONLY going forward
- Old data preserved for historical reference, clearly marked
2025-12-05 10:37:01 +01:00
mindesbunister
8ec4eb0782 docs: Add Common Pitfall #72 - MFE data unit mismatch
CRITICAL LESSON LEARNED (Dec 5, 2025):
Document the data analysis disaster caused by MFE/MAE stored in mixed units.

What Happened:
- Analyzed blocked vs executed signals to improve win rate
- SQL showed executed signals: 20.15% avg MFE (appeared excellent)
- Implemented "optimizations" based on this data:
  * Tighter ATR multipliers (2.0→1.5, 4.0→3.0)
  * Higher TP1 close (60%→75%)
  * Increased leverage (1×→5×)
- User questioned: Why doesn't TP1 hit if it's 20% MFE?
- Investigation: Only 2/11 trades reached TP1 price target
- Root cause: Old records stored MFE in DOLLARS, new in PERCENTAGES
- TRUE MFE: 0.76% (long), 1.20% (short) - NOT 20%!
- 26× inflation due to unit mismatch

Why This Matters:
- This is a REAL MONEY system - wrong analysis = wrong trades = losses
- MFE/MAE used for critical decisions (exit timing, quality validation)
- Agent made "data-driven" optimizations on 26× inflated data
- All changes had to be reverted (commits a67a338, f65aae5)

MANDATORY SQL Pattern:
- ALWAYS filter by createdAt >= '2025-11-23' for MFE/MAE queries
- OR recalculate from prices (maxFavorablePrice - entryPrice)
- NEVER trust raw AVG(maxFavorableExcursion) without date filter

Prevention:
- Verify stored vs calculated values before ANY MFE/MAE analysis
- Check sample of recent vs old records to detect unit changes
- Document data format changes in Common Pitfalls immediately

Related:
- Common Pitfall #54: Original MFE/MAE units bug (Nov 23, 2025)
- Revert commit: a15f17f
- Incorrect optimization: a67a338, f65aae5
2025-12-05 10:07:06 +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
f65aae5eb7 docs: Document exit strategy optimization (Dec 5, 2025)
Updated copilot-instructions.md with:
- New ATR multipliers (1.5×/3.0×/2.5× vs 2.0×/4.0×/3.0×)
- Rationale: 0% TP hit rate despite 17-24% avg MFE
- Problem: Targets hit then reversed before monitoring loop detected
- Solution: Tighter targets catch moves before reversal
- 75% close at TP1 (vs 60%) to bank profit immediately
- 25% runner (vs 40%) for extended trends with tighter trail
- Leverage 5× during testing phase

This is MANDATORY documentation update per #1 priority rule.
2025-12-05 09:54:20 +01:00
mindesbunister
b187f1dc8b Merge pull request #1 from mindesbunister/copilot/extract-common-pitfalls-documentation
docs: Extract Common Pitfalls to dedicated documentation
2025-12-05 09:12:02 +01:00
mindesbunister
aee12432f5 Merge pull request #6 from mindesbunister/copilot/document-recent-prs
docs: Document 4 undocumented PRs in copilot-instructions.md
2025-12-05 09:10:12 +01:00
copilot-swe-agent[bot]
863f10dc77 docs: Improve .gitignore fix instructions in Pitfall #72
Co-authored-by: mindesbunister <32161838+mindesbunister@users.noreply.github.com>
2025-12-05 07:49:22 +00:00
copilot-swe-agent[bot]
6ee29279b7 docs: Document test infrastructure, security fix, common pitfalls reorganization, and CI/CD pipeline
MANDATORY DOCUMENTATION UPDATE (4 PRs):

1. Test Infrastructure (PR #2): 113 tests, coverage requirements, how to run
2. Security Fix (PR #3): Expanded Pitfall #72 with process details
3. Common Pitfalls (PR #1): Reorganization structure and benefits
4. CI/CD Pipeline (PR #5): 4 workflows, troubleshooting, branch protection

Restores compliance with mandatory git commit + documentation workflow
(lines 217-256 of copilot-instructions.md).

Related PRs: #1, #2, #3, #5

Co-authored-by: mindesbunister <32161838+mindesbunister@users.noreply.github.com>
2025-12-05 07:47:51 +00:00
mindesbunister
12212502bd docs: Document dual remote setup and post-commit hook automation
- Added DUAL REMOTE SETUP section with origin (Gitea) and github (GitHub) configuration
- Documented post-commit hook location and purpose (.git/hooks/post-commit)
- Explained auto-sync to github vs manual push to origin workflow
- Added verification commands for sync status checking
- Included automation setup details and testing confirmation
- Updated commit workflow to reflect hook behavior
- Added recent example (de77cfe test commit) to demonstrate automation
2025-12-05 08:41:58 +01:00
copilot-swe-agent[bot]
0c76bca1cc docs: Extract Common Pitfalls to dedicated documentation
- Created docs/COMMON_PITFALLS.md with all 72 pitfalls
- Organized by severity and category for better navigation
- Added quick reference table and cross-reference index
- Reduced copilot-instructions.md from 6,575 to 3,608 lines (45%)
- Kept Top 10 critical pitfalls in main instructions
- Preserved all git commits, dates, code examples
- Updated docs/README.md with references to new doc

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

Co-authored-by: mindesbunister <32161838+mindesbunister@users.noreply.github.com>
2025-12-05 00:19:16 +00:00
mindesbunister
cc3a0a85a0 docs: Document manual trade quality bypass requirement
User mandate: Manual Telegram trades bypass quality scoring entirely.

Documentation updates:
- Added 'Manual Trade Quality Bypass' section
- Explains user requirement for instant execution
- Documents implementation details (timeframe='manual' detection)
- Clarifies that analytics check is now advisory only
- Notes --force flag no longer needed for manual trades

Context: This is part of the mandatory documentation workflow -
every code change requires corresponding documentation update.

Related commit: 0982578 (quality bypass implementation)
Date: Dec 4, 2025
2025-12-04 19:56:54 +01:00
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