Commit Graph

170 Commits

Author SHA1 Message Date
mindesbunister
6b7082eef3 docs: add Common Pitfall #21 for CreateTradeParams interface sync 2025-11-12 10:02:05 +01:00
mindesbunister
4eef5a8165 docs: add financial goals section to copilot instructions
Added 'Mission & Financial Goals' section at the top to provide critical
context for AI agents making decisions:

**Current Phase Context:**
- Starting capital: $106 (+ $1K deposit in 2 weeks)
- Target: $2,500 by Month 2.5
- Strategy: Aggressive compounding, 0 withdrawals
- Position sizing: 100% of account at 20x leverage
- Win target: 20-30% monthly returns

**Why This Matters:**
- Every dollar counts - optimize for profitability
- User needs $300-500/month withdrawals starting Month 3
- No changes that reduce win rate unless they improve profit factor
- System must prove itself before scaling

**Key Constraints:**
- Can't afford extended drawdowns (limited capital)
- Must maintain 60%+ win rate to compound effectively
- Quality > quantity (70+ signal scores only)
- Stop after 3 consecutive losses

Also added 'Financial Roadmap Integration' subsection linking technical
improvements to phase objectives (Phase 1: prove system, Phase 2-3:
sustainable growth + withdrawals, Phase 4+: scale + reduce risk).

This ensures future AI agents understand the YOLO/recovery context and
prioritize profitability over conservative safety during Phase 1.
2025-11-11 20:44:16 +01:00
mindesbunister
6a192bfb76 docs: update copilot-instructions for ATR trailing + dynamic runner% + rate limits
Updated .github/copilot-instructions.md to reflect recent system improvements:

**ATR-Based Trailing Stop:**
- Dynamic trailing calculation formula documented
- Configurable runner % (default 25%, adjustable via TAKE_PROFIT_1_SIZE_PERCENT)
- All UI displays now dynamically calculate runner% as 100 - TP1_SIZE
- Removed hardcoded '25%' references, replaced with dynamic language

**Rate Limit Monitoring:**
- NEW Section #4: Rate Limit Monitoring
- Exponential backoff mechanism (2s→4s→8s)
- Database logging (3 event types: hit/recovered/exhausted)
- Analytics endpoint for monitoring
- Links to RATE_LIMIT_MONITORING.md for SQL queries

**Section Renumbering:**
- Old Section #4 (Order Placement) → Section #5
- Old Section #5 (Database) → Section #6
- Maintains logical flow and consistency

**Updated References:**
- Exit Strategy: Dynamic runner% description
- Position Manager: ATR trailing formula + on-chain sync notes
- Common Pitfalls: Dynamic runner % configuration notes
- Roadmap: Phase 5 shows configurable runner with formula

All documentation now accurately reflects user's 70/30 TP1/Runner split
and recent infrastructure improvements (ATR trailing, rate limits).

Related: settings UI updated in previous commit (app/settings/page.tsx)
2025-11-11 20:40:05 +01:00
mindesbunister
03e91fc18d feat: ATR-based trailing stop + rate limit monitoring
MAJOR FIXES:
- ATR-based trailing stop for runners (was fixed 0.3%, now adapts to volatility)
- Fixes runners with +7-9% MFE exiting for losses
- Typical improvement: 2.24x more room (0.3% → 0.67% at 0.45% ATR)
- Enhanced rate limit logging with database tracking
- New /api/analytics/rate-limits endpoint for monitoring

DETAILS:
- Position Manager: Calculate trailing as (atrAtEntry / price × 100) × multiplier
- Config: TRAILING_STOP_ATR_MULTIPLIER=1.5, MIN=0.25%, MAX=0.9%
- Settings UI: Added ATR multiplier controls
- Rate limits: Log hits/recoveries/exhaustions to SystemEvent table
- Documentation: ATR_TRAILING_STOP_FIX.md + RATE_LIMIT_MONITORING.md

IMPACT:
- Runners can now capture big moves (like morning's $172→$162 SOL drop)
- Rate limit visibility prevents silent failures
- Data-driven optimization for RPC endpoint health
2025-11-11 14:51:41 +01:00
mindesbunister
6ef5fea41a docs: add essential SQL queries to AI agent instructions
Added SQL Analysis Queries section with:
- Phase 1 monitoring queries (count, score distribution, recent signals)
- Phase 2 comparison queries (blocked vs executed trades)
- Pattern analysis queries (range extremes, ADX distribution)

Benefits:
- AI agents have immediate access to standard queries
- Consistent analysis approach each time
- No need to context-switch to separate docs
- Quick reference for common investigations

Includes usage pattern guidance and reference to full docs.
2025-11-11 12:02:22 +01:00
mindesbunister
356b4ed578 docs: update AI agent instructions with blocked signals tracking
- Added BlockedSignal to database models list
- Updated signalQualityVersion to v4 (current)
- Added blocked signals tracking functions to database section
- Updated check-risk endpoint description
- Added Signal Quality Optimization Roadmap reference
- Documented blocked signals analysis workflow
- Added reference to BLOCKED_SIGNALS_TRACKING.md

This ensures AI agents understand the new data collection system.
2025-11-11 11:52:24 +01:00
mindesbunister
c3a053df63 CRITICAL FIX: Use ?? instead of || for tp2SizePercent to allow 0 value
BUG FOUND:
Line 558: tp2SizePercent: config.takeProfit2SizePercent || 100

When config.takeProfit2SizePercent = 0 (TP2-as-runner system), JavaScript's ||
operator treats 0 as falsy and falls back to 100, causing TP2 to close 100%
of remaining position instead of activating trailing stop.

IMPACT:
- On-chain orders placed correctly (line 481 uses ?? correctly)
- Position Manager reads from DB and expects TP2 to close position
- Result: User sees TWO take-profit orders instead of runner system

FIX:
Changed both tp1SizePercent and tp2SizePercent to use ?? operator:
- tp1SizePercent: config.takeProfit1SizePercent ?? 75
- tp2SizePercent: config.takeProfit2SizePercent ?? 0

This allows 0 value to be saved correctly for TP2-as-runner system.

VERIFICATION NEEDED:
Current open SHORT position in database has tp2SizePercent=100 from before
this fix. Next trade will use correct runner system.
2025-11-10 19:46:03 +01:00
mindesbunister
089308a07e Add Position Sync feature for recovering tracking after partial fills
- New /api/trading/sync-positions endpoint (no auth)
- Fetches actual Drift positions and compares with Position Manager
- Removes stale tracking, adds missing positions with calculated TP/SL
- Settings UI: Orange 'Sync Positions' button added
- CLI script: scripts/sync-positions.sh for terminal access
- Full documentation in docs/guides/POSITION_SYNC_GUIDE.md
- Quick reference: POSITION_SYNC_QUICK_REF.md
- Updated AI instructions with pitfall #23

Problem solved: Manual Telegram trades with partial fills can cause
Position Manager to lose tracking, leaving positions without software-
based stop loss protection. This feature restores dual-layer protection.

Note: Docker build not picking up route yet (cache issue), needs investigation
2025-11-10 17:05:32 +01:00
mindesbunister
2e47731e8e Update AI instructions with latest fixes
Added sections:
- Recent Critical Fixes (2024-11-10): Runner system + anti-chop filter V2
- JavaScript || vs ?? operator gotcha (#21)
- Range-bound chop detection details (#22)
- Updated anti-chop filter description with backtest results
2025-11-10 15:43:48 +01:00
mindesbunister
d20190c5b0 docs: Update copilot-instructions.md with configurable quality score threshold
- Updated Signal Quality System to reflect MIN_SIGNAL_QUALITY_SCORE is configurable (default: 65)
- Added critical pitfall #7: Never use hardcoded config values in endpoints
- Emphasized settings page can modify minSignalQualityScore dynamically
- Renumbered remaining pitfalls for clarity
2025-11-10 13:00:40 +01:00
mindesbunister
14cd1a85ba Update copilot-instructions with critical Drift SDK insights
- Document Drift SDK position.size returns USD, not token quantity
- Add Solana RPC rate limiting retry pattern with exponential backoff
- Document /api/trading/cancel-orders endpoint for ghost order cleanup
- Clarify symbol normalization requirement for manual close endpoint
- Captures lessons learned from TP1 detection and P&L calculation debugging
2025-11-09 18:04:43 +01:00
mindesbunister
9b767342dc feat: Implement re-entry analytics system with fresh TradingView data
- Add market data cache service (5min expiry) for storing TradingView metrics
- Create /api/trading/market-data webhook endpoint for continuous data updates
- Add /api/analytics/reentry-check endpoint for validating manual trades
- Update execute endpoint to auto-cache metrics from incoming signals
- Enhance Telegram bot with pre-execution analytics validation
- Support --force flag to override analytics blocks
- Use fresh ADX/ATR/RSI data when available, fallback to historical
- Apply performance modifiers: -20 for losing streaks, +10 for winning
- Minimum re-entry score 55 (vs 60 for new signals)
- Fail-open design: proceeds if analytics unavailable
- Show data freshness and source in Telegram responses
- Add comprehensive setup guide in docs/guides/REENTRY_ANALYTICS_QUICKSTART.md

Phase 1 implementation for smart manual trade validation.
2025-11-07 20:40:07 +01:00
mindesbunister
5acc61cf66 Fix P&L calculation and update Copilot instructions
- Fix P&L calculation in Position Manager to use actual entry vs exit price instead of SDK's potentially incorrect realizedPnL
- Calculate actual profit percentage and apply to closed position size for accurate dollar amounts
- Update database record for last trade from incorrect 6.58 to actual .66 P&L
- Update .github/copilot-instructions.md to reflect TP2-as-runner system changes
- Document 25% runner system (5x larger than old 5%) with ATR-based trailing
- Add critical P&L calculation pattern to common pitfalls section
- Mark Phase 5 complete in development roadmap
2025-11-07 16:24:43 +01:00
mindesbunister
a8de1c9d37 Update copilot instructions with signal quality versioning
- Added signalQualityVersion field documentation (v1/v2/v3 tracking)
- Documented /api/analytics/version-comparison endpoint
- Added Prisma Decimal type handling pitfall (#18)
- Added signal quality version tracking section to Development Roadmap
- References SQL analysis file for version comparison queries

Enables AI agents to understand the version tracking system for
data-driven algorithm optimization.
2025-11-07 13:38:56 +01:00
mindesbunister
625dc44c59 Add signal quality version tracking to database
- Added signalQualityVersion field to Trade model
- Tracks which scoring logic version was used for each trade
- v1: Original logic (price position < 5% threshold)
- v2: Added volume compensation for low ADX
- v3: CURRENT - Stricter logic requiring ADX > 18 for extreme positions (< 15%)

This enables future analysis to:
- Compare performance between logic versions
- Filter trades by scoring algorithm
- Data-driven improvements based on clean datasets

All new trades will be marked as v3. Old trades remain null/v1 for comparison.
2025-11-07 12:56:35 +01:00
mindesbunister
1313031acd docs: Update copilot instructions with per-symbol settings
- Updated TP/SL percentages to current values (0.4%/0.7%)
- Added Per-Symbol Configuration section with SOL/ETH controls
- Documented getPositionSizeForSymbol() usage pattern
- Added per-symbol settings to API endpoints documentation
- Updated execute workflow to include symbol enabled checks
- Corrected ETH minimum size (0.01 ETH, not 0.002)
- Added comprehensive Per-Symbol Trading Controls section
2025-11-03 13:33:07 +01:00
mindesbunister
aa8e9f130a docs: update AI agent instructions with recent fixes
Added documentation for recent improvements:
- MAE/MFE tracking for trade optimization
- On-chain order synchronization after TP1 hits
- Exit reason detection using trade state flags (not current price)
- Per-symbol cooldown to avoid missing opportunities
- Quality score integration in analytics dashboard

Updated workflows and pitfalls sections with lessons learned from debugging session
2025-11-03 08:33:46 +01:00
mindesbunister
056440bf8f feat: add quality score display and timezone fixes
- Add qualityScore to ExecuteTradeResponse interface and response object
- Update analytics page to always show Signal Quality card (N/A if unavailable)
- Fix n8n workflow to pass context metrics and qualityScore to execute endpoint
- Fix timezone in Telegram notifications (Europe/Berlin)
- Fix symbol normalization in /api/trading/close endpoint
- Update Drift ETH-PERP minimum order size (0.002 ETH not 0.01)
- Add transaction confirmation to closePosition() to prevent phantom closes
- Add 30-second grace period for new trades in Position Manager
- Fix execution order: database save before Position Manager.addTrade()
- Update copilot instructions with transaction confirmation pattern
2025-11-01 17:00:37 +01:00
mindesbunister
27c6a06d31 Update copilot-instructions.md with latest system features
Major additions:
- Exit strategy details: 3-tier scaling (TP1 75%, TP2 80% of remaining, 5% runner with trailing stop)
- Signal quality system: 5 metrics scored 0-100, filters trades at 60+ threshold
- Runner implementation: Trailing stop activation after TP2, peakPrice tracking
- Database fields: signalQualityScore, MAE/MFE, configSnapshot for state persistence
- New API endpoints: /check-risk, /analytics/last-trade, /restart
- Updated workflows with quality score validation and runner management
- Common pitfalls: Quality score duplication, runner configuration confusion
- Development roadmap: Link to POSITION_SCALING_ROADMAP.md with 6 phases

Critical corrections:
- Position Manager singleton: getPositionManager() → getInitializedPositionManager()
- Updated monitoring loop details with external closure detection and state saving
2025-10-31 12:04:20 +01:00
mindesbunister
3e2cf2eec2 feat: add Telegram bot for manual trade commands
- Added telegram_command_bot.py with slash commands (/buySOL, /sellBTC, etc)
- Docker compose setup with DNS configuration
- Sends trades as plain text to n8n webhook (same format as TradingView)
- Improved Telegram success message formatting
- Only responds to authorized chat ID (579304651)
- Commands: /buySOL, /sellSOL, /buyBTC, /sellBTC, /buyETH, /sellETH
2025-10-27 00:23:09 +01:00