diff --git a/.env b/.env index fdfc5a0..f4942a9 100644 --- a/.env +++ b/.env @@ -97,7 +97,7 @@ TAKE_PROFIT_1_PERCENT=0.4 # Take Profit 1 Size: What % of position to close at TP1 # Example: 50 = close 50% of position -TAKE_PROFIT_1_SIZE_PERCENT=75 +TAKE_PROFIT_1_SIZE_PERCENT=70 # Take Profit 2: Close remaining 50% at this profit level # Example: +1.5% on 10x = +15% account gain diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index cdfe561..c8c8627 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -9,9 +9,10 @@ **Key Design Principle:** Dual-layer redundancy - every trade has both on-chain orders (Drift) AND software monitoring (Position Manager) as backup. **Exit Strategy:** TP2-as-Runner system (CURRENT): -- TP1 at +0.4%: Close 75% (configurable via `TAKE_PROFIT_1_SIZE_PERCENT`) -- TP2 at +0.7%: **Activates trailing stop** on full 25% remaining (no position close) -- Runner: 25% remaining with ATR-based trailing stop (5x larger than old 5% system) +- TP1 at +0.4%: Close configurable % (default 75%, adjustable via `TAKE_PROFIT_1_SIZE_PERCENT`) +- TP2 at +0.7%: **Activates trailing stop** on full remaining % (no position close) +- Runner: Remaining % after TP1 with ATR-based trailing stop (default 25%, configurable) +- **Note:** All UI displays dynamically calculate runner% as `100 - TAKE_PROFIT_1_SIZE_PERCENT` **Per-Symbol Configuration:** SOL and ETH have independent enable/disable toggles and position sizing: - `SOLANA_ENABLED`, `SOLANA_POSITION_SIZE`, `SOLANA_LEVERAGE` (defaults: true, $210, 10x) @@ -77,10 +78,11 @@ await positionManager.addTrade(activeTrade) **Key behaviors:** - Tracks `ActiveTrade` objects in a Map -- **TP2-as-Runner system**: TP1 (75%) → TP2 trigger (no close, activate trailing) → 25% runner with ATR-based trailing stop +- **TP2-as-Runner system**: TP1 (configurable %, default 75%) → TP2 trigger (no close, activate trailing) → Runner (remaining %) with ATR-based trailing stop - Dynamic SL adjustments: Moves to breakeven after TP1, locks profit at +1.2% -- **On-chain order synchronization:** After TP1 hits, calls `cancelAllOrders()` then `placeExitOrders()` with updated SL price at breakeven -- Trailing stop: Activates when TP2 price hit, tracks `peakPrice` and trails by ATR-based % +- **On-chain order synchronization:** After TP1 hits, calls `cancelAllOrders()` then `placeExitOrders()` with updated SL price at breakeven (uses `retryWithBackoff()` for rate limit handling) +- **ATR-based trailing stop:** Calculates trail distance as `(atrAtEntry / currentPrice × 100) × trailingStopAtrMultiplier`, clamped between min/max % +- Trailing stop: Activates when TP2 price hit, tracks `peakPrice` and trails dynamically - Closes positions via `closePosition()` market orders when targets hit - Acts as backup if on-chain orders don't fill - State persistence: Saves to database, restores on restart via `configSnapshot.positionManagerState` @@ -131,7 +133,36 @@ const health = await driftService.getAccountHealth() ``` - Wallet handling: Supports both JSON array `[91,24,...]` and base58 string formats from Phantom wallet -### 4. Order Placement (`lib/drift/orders.ts`) +### 4. Rate Limit Monitoring (`lib/drift/orders.ts` + `app/api/analytics/rate-limits`) +**Purpose:** Track and analyze Solana RPC rate limiting (429 errors) to prevent silent failures + +**Retry mechanism with exponential backoff:** +```typescript +await retryWithBackoff(async () => { + return await driftClient.cancelOrders(...) +}, maxRetries = 3, baseDelay = 2000) +``` + +**Database logging:** Three event types in SystemEvent table: +- `rate_limit_hit`: Each 429 error (logged with attempt #, delay, error snippet) +- `rate_limit_recovered`: Successful retry (logged with total time, retry count) +- `rate_limit_exhausted`: Failed after max retries (CRITICAL - order operation failed) + +**Analytics endpoint:** +```bash +curl http://localhost:3001/api/analytics/rate-limits +``` +Returns: Total hits/recoveries/failures, hourly patterns, recovery times, success rate + +**Key behaviors:** +- Only RPC calls wrapped: `cancelAllOrders()`, `placeExitOrders()`, `closePosition()` +- Position Manager 2s loop does NOT make RPC calls (only price checks via Pyth WebSocket) +- Exponential backoff: 2s → 4s → 8s delays on retry +- Logs to both console and database for post-trade analysis + +**Monitoring queries:** See `docs/RATE_LIMIT_MONITORING.md` for SQL queries + +### 5. Order Placement (`lib/drift/orders.ts`) **Critical functions:** - `openPosition()` - Opens market position with transaction confirmation - `closePosition()` - Closes position with transaction confirmation @@ -205,7 +236,7 @@ Without this, order cancellations fail silently during TP1→breakeven order upd - Soft SL: TRIGGER_LIMIT reduce-only - Hard SL: TRIGGER_MARKET reduce-only -### 5. Database (`lib/database/trades.ts` + `prisma/schema.prisma`) +### 6. Database (`lib/database/trades.ts` + `prisma/schema.prisma`) **Purpose:** PostgreSQL via Prisma ORM for trade history and analytics **Models:** Trade, PriceUpdate, SystemEvent, DailyStats, BlockedSignal @@ -551,9 +582,9 @@ ORDER BY MIN(adx) DESC; 8. **TP2-as-Runner configuration:** - `takeProfit2SizePercent: 0` means "TP2 activates trailing stop, no position close" - - This creates 25% runner (vs old 5% system) for better profit capture + - This creates runner of remaining % after TP1 (default 25%, configurable via TAKE_PROFIT_1_SIZE_PERCENT) - `TAKE_PROFIT_2_PERCENT=0.7` sets TP2 trigger price, `TAKE_PROFIT_2_SIZE_PERCENT` should be 0 - - Settings UI correctly shows "TP2 activates trailing stop" instead of size percentage + - Settings UI correctly shows "TP2 activates trailing stop" with dynamic runner % calculation 9. **P&L calculation CRITICAL:** Use actual entry vs exit price calculation, not SDK values: ```typescript @@ -750,10 +781,10 @@ See `POSITION_SCALING_ROADMAP.md` for planned position management optimizations: - **Phase 2:** ATR-based dynamic targets (adapt to volatility) - **Phase 3:** Signal quality-based scaling (high quality = larger runners) - **Phase 4:** Direction-based optimization (shorts vs longs have different performance) -- **Phase 5 (✅ COMPLETE):** TP2-as-runner system implemented - 25% runner with ATR-based trailing stop +- **Phase 5 (✅ COMPLETE):** TP2-as-runner system implemented - configurable runner (default 25%, adjustable via TAKE_PROFIT_1_SIZE_PERCENT) with ATR-based trailing stop - **Phase 6:** ML-based exit prediction (future) -**Recent Implementation:** TP2-as-runner system provides 5x larger runner (25% vs 5%) for better profit capture on extended moves. When TP2 price is hit, trailing stop activates on full remaining position instead of closing partial amount. +**Recent Implementation:** TP2-as-runner system provides 5x larger runner (default 25% vs old 5%) for better profit capture on extended moves. When TP2 price is hit, trailing stop activates on full remaining position instead of closing partial amount. Runner size is configurable (100% - TP1 close %). **Blocked Signals Tracking (Nov 11, 2025):** System now automatically saves all blocked signals to database for data-driven optimization. See `BLOCKED_SIGNALS_TRACKING.md` for SQL queries and analysis workflows. diff --git a/TRADING_GOALS.md b/TRADING_GOALS.md new file mode 100644 index 0000000..3b209b4 --- /dev/null +++ b/TRADING_GOALS.md @@ -0,0 +1,296 @@ +# Trading Goals & Financial Roadmap + +**Bot:** Trading Bot v4 (Drift Protocol + TradingView v6 Signals) +**Start Date:** November 11, 2025 +**Starting Capital:** $106 (+ $1,000 deposit in 2 weeks) +**Primary Objective:** Systematic wealth building through algorithmic trading + +--- + +## 🎯 Vision: Multi-Phase Wealth Building + +**Initial Target:** $100,000 (proof of concept) +**Mid-term Target:** $500,000 (financial freedom) +**Long-term Target:** $1,000,000+ (generational wealth) + +**Philosophy:** Compound growth with risk reduction as capital scales. Start aggressive, end conservative. + +--- + +## 📊 Phase Breakdown + +### **Phase 1: Survival & Proof (Months 0-2.5)** +**Capital:** $106 → $2,500 +**Strategy:** YOLO recovery, then aggressive compounding +**Withdrawals:** $0 (reinvest everything) +**Position Sizing:** 100% → 20-25% of account +**Leverage:** 20x → 15x + +**Milestones:** +- ✅ Week 0: $106 starting capital +- ⏳ Week 2: +$1,000 deposit → $1,100-1,300 base +- 🎯 Month 2.5: $2,500 account (20x growth on initial, 2x on deposited) + +**Success Criteria:** +- v6 signals prove profitable (60%+ win rate) +- ATR trailing stop captures runners properly +- No catastrophic drawdowns (>50% account loss) + +**Risk Level:** 🔴 EXTREME (20x leverage, full position) + +--- + +### **Phase 2: Cash Flow Foundation (Months 3-6)** +**Capital:** $2,500 → $3,000-4,000 +**Strategy:** Sustainable growth while funding life +**Withdrawals:** $300/month (start Month 3) +**Position Sizing:** 20-25% of account +**Leverage:** 10-15x + +**Milestones:** +- Month 3: First $300 withdrawal (bills covered!) +- Month 4: Account stays above $2,500 despite withdrawals +- Month 6: Account grows to $3,500+ while taking $1,200 total + +**Success Criteria:** +- Consistent 15-20% monthly returns +- Withdrawals don't inhibit growth +- Psychological comfort with system + +**Risk Level:** 🟠 HIGH (15x leverage, significant position) + +--- + +### **Phase 3: Momentum Building (Months 7-12)** +**Capital:** $3,500 → $6,000-8,000 +**Strategy:** Increase income, maintain growth +**Withdrawals:** $400-500/month +**Position Sizing:** 20-30% of account +**Leverage:** 10x + +**Milestones:** +- Month 7: Increase withdrawal to $400-500 +- Month 9: Account hits $5,000 (first major psychological barrier) +- Month 12: $6,000-8,000 account + $3,000-4,000 withdrawn total + +**Success Criteria:** +- 10-15% monthly returns (easier with larger capital) +- Living expenses fully covered +- System runs mostly autonomous + +**Risk Level:** 🟡 MODERATE (10x leverage, 25% position) + +--- + +### **Phase 4: Acceleration (Year 2: Months 13-24)** +**Capital:** $8,000 → $50,000 +**Strategy:** Scale position size, reduce leverage +**Withdrawals:** $500-1,000/month +**Position Sizing:** 30-40% of account +**Leverage:** 5-10x + +**Milestones:** +- Month 15: $10,000 account (100x initial capital!) +- Month 18: $20,000 account +- Month 21: $30,000 account +- Month 24: $50,000 account + +**Success Criteria:** +- 8-12% monthly returns (sustainable at scale) +- $10,000+ withdrawn over the year +- Risk management becomes priority + +**Risk Level:** 🟢 MODERATE-LOW (5-10x leverage, diversified positions) + +--- + +### **Phase 5: The $100K Milestone (Months 25-30)** +**Capital:** $50,000 → $100,000 +**Strategy:** Capital preservation with growth +**Withdrawals:** $1,000-2,000/month +**Position Sizing:** 30-50% of account +**Leverage:** 3-5x + +**Milestones:** +- Month 27: $75,000 account +- Month 30: **$100,000 ACHIEVED** 🎉 + +**Success Criteria:** +- 5-8% monthly returns (compounding does the work) +- Withdrawals become substantial ($12,000-24,000/year) +- System proven over 2.5 years + +**Risk Level:** 🟢 LOW (3-5x leverage, conservative) + +--- + +## 🚀 Beyond $100K: The Real Game Begins + +### **Phase 6: Financial Freedom Territory ($100K → $500K)** +**Timeline:** 12-18 months +**Withdrawals:** $2,000-5,000/month (covers all living + savings) +**Strategy:** Split capital - 50% aggressive growth, 50% income generation +**Target Returns:** 5-7% monthly (compounding to $500K) + +### **Phase 7: Wealth Building ($500K → $1M+)** +**Timeline:** 18-24 months +**Withdrawals:** $5,000-10,000/month (upgrade lifestyle) +**Strategy:** 70% conservative (3-5% monthly), 30% aggressive (10-15% monthly) +**Endgame:** Multiple income streams, true financial independence + +### **Phase 8: Legacy Mode ($1M+)** +**Timeline:** Indefinite +**Withdrawals:** Whatever you want +**Strategy:** Capital preservation + modest growth (3-5% monthly = $30K-50K/month) +**Focus:** Teaching system to others, retiring early, living free + +--- + +## 📈 Key Performance Indicators (KPIs) + +### **Trading Metrics:** +- **Win Rate Target:** 60%+ (aggressive phases), 55%+ (conservative phases) +- **Profit Factor:** >1.5 consistently +- **Average Win:** 8-12% (TP1 + partial runner) +- **Average Loss:** -1.5% (stop loss) +- **Monthly Return Target:** + - Phases 1-2: 20-30% (aggressive) + - Phases 3-4: 10-15% (sustainable) + - Phases 5-6: 5-10% (conservative) + +### **Risk Metrics:** +- **Max Drawdown:** <30% at any phase +- **Consecutive Losses:** Stop trading after 3 in a row (review system) +- **Daily Loss Limit:** -10% of account (circuit breaker) + +### **System Health:** +- **Signal Quality Score:** Average >70 (Phase 1-2), >75 (Phase 3+) +- **Rate Limit Hits:** <5 per day (RPC health) +- **Runner Capture Rate:** >50% of MFE realized (ATR trailing working) + +--- + +## 🛡️ Risk Management by Phase + +| Phase | Leverage | Position Size | Max Risk/Trade | Max Daily Risk | +|-------|----------|---------------|----------------|----------------| +| 1-2 | 15-20x | 20-100% | 30% | 50% | +| 3 | 10-15x | 20-25% | 15% | 30% | +| 4 | 10x | 25-30% | 10% | 20% | +| 5 | 5-10x | 30-40% | 8% | 15% | +| 6 | 3-5x | 30-50% | 5% | 10% | +| 7-8 | 3-5x | 50%+ | 3% | 5% | + +--- + +## 💰 Cumulative Financial Goals + +**End of Year 1 (Month 12):** +- Account: $6,000-8,000 +- Total Withdrawn: $2,000-3,000 +- Net Worth Impact: +$8,000-11,000 (from $106 start) + +**End of Year 2 (Month 24):** +- Account: $50,000 +- Total Withdrawn: $12,000-15,000 +- Net Worth Impact: +$62,000-65,000 + +**End of Year 3 (Month 36):** +- Account: $100,000+ +- Total Withdrawn: $30,000-50,000 +- Net Worth Impact: +$130,000-150,000 + +**End of Year 5:** +- Account: $500,000-1,000,000 +- Total Withdrawn: $100,000-200,000 +- Net Worth Impact: $600,000-1,200,000 +- **Status: Financially Independent** + +--- + +## 🎯 Current Status + +**Date:** November 11, 2025 +**Phase:** 1 (Survival & Proof) +**Account:** $106 +**Next Milestone:** $1,000 deposit (2 weeks) +**Days Until First Withdrawal:** ~75 days (Month 3) + +**Recent Improvements:** +- ✅ v6 Pine Script deployed (100-bar price position filtering) +- ✅ ATR-based trailing stop implemented (captures runners properly) +- ✅ 70/30 TP1/Runner split (increased runner size from 25% to 30%) +- ✅ Rate limit monitoring (prevents silent failures) +- ✅ Signal quality scoring (blocks weak setups) + +**System Readiness:** 🟢 READY +**Confidence Level:** 🔥 HIGH (infrastructure is solid, just needs signals) + +--- + +## 📝 Rules of Engagement + +### **The Non-Negotiables:** +1. **Never skip the 2-month compound period** (Phases 1-2) +2. **Always lower risk when account grows** (follow phase guidelines) +3. **Stop trading after 3 consecutive losses** (review system, don't revenge trade) +4. **Only trade signals with 70+ quality score** (especially in Phase 1-2) +5. **Never increase leverage above phase max** (greed kills accounts) + +### **The Promises:** +1. **Patience in Phase 1-2** (no withdrawals, let it compound) +2. **Discipline in Phase 3-5** (consistent withdrawals, no FOMO) +3. **Humility in Phase 6+** (protect capital, it's real money now) + +### **The Vision:** +This isn't just about $100K. This is about building a systematic income machine that: +- Pays for life expenses (Phase 3+) +- Builds wealth (Phase 5+) +- Creates legacy (Phase 8+) +- **Proves algorithmic trading works when done right** + +--- + +## 🚨 Failure Modes & Contingencies + +### **If Account Drops 50%+ in Phase 1-2:** +- STOP trading immediately +- Review all losing trades (what went wrong?) +- Analyze signal quality scores (were they actually 70+?) +- Check v6 configuration (filters working?) +- Consider waiting for $1K deposit before resuming + +### **If Win Rate <50% After 20 Trades:** +- System may not be working as expected +- Review blocked signals vs executed signals +- Increase MIN_SIGNAL_QUALITY_SCORE to 75 +- Reduce position size by 50% + +### **If Can't Make Withdrawals in Phase 3:** +- Lower withdrawal amount to $200/month +- Extend Phase 2 by 1-2 months +- Consider side income to reduce pressure +- Don't break the system by over-withdrawing + +--- + +## 🎉 Success Celebrations + +**$500:** First 5x - Pizza night +**$1,000:** 10x initial capital - Nice dinner out +**$2,500:** Phase 1 complete - Weekend trip +**$5,000:** Psychological barrier broken - New laptop/gear +**$10,000:** 100x initial capital - Week vacation +**$25,000:** Quarter of goal - Upgrade living situation +**$50,000:** Halfway to first target - Tell family about success +**$100,000:** FIRST MAJOR GOAL - Celebrate properly, then keep building +**$500,000:** Financial freedom achieved - Quit day job if desired +**$1,000,000:** Life changed forever - You made it + +--- + +**Remember:** $100K is just the beginning. The real wealth comes from phases 6-8. Stay disciplined, trust the system, and let compound growth do the heavy lifting. + +**This isn't gambling. This is systematic wealth building with defined risk, clear milestones, and a proven edge.** + +Let's build something legendary. 🚀 diff --git a/app/settings/page.tsx b/app/settings/page.tsx index 6688496..b8c6910 100644 --- a/app/settings/page.tsx +++ b/app/settings/page.tsx @@ -205,7 +205,8 @@ export default function SettingsPage() { const maxLoss = size * lev * (Math.abs(settings.STOP_LOSS_PERCENT) / 100) // Calculate gains/losses for risk calculator const tp1Gain = size * lev * (settings.TAKE_PROFIT_1_PERCENT / 100) * (settings.TAKE_PROFIT_1_SIZE_PERCENT / 100) - const tp2RunnerSize = size * (1 - settings.TAKE_PROFIT_1_SIZE_PERCENT / 100) // 25% remaining after TP1 + const tp2RunnerSize = size * (1 - settings.TAKE_PROFIT_1_SIZE_PERCENT / 100) // Remaining % after TP1 + const runnerPercent = 100 - settings.TAKE_PROFIT_1_SIZE_PERCENT // Calculate runner % for display // Use ATR-based TP2 if enabled, otherwise use static const tp2Percent = settings.USE_ATR_BASED_TARGETS @@ -217,10 +218,10 @@ export default function SettingsPage() { ? settings.MAX_TP2_PERCENT : settings.TAKE_PROFIT_2_PERCENT - const runnerValue = tp2RunnerSize * lev * (tp2CalcPercent / 100) // Full 25% runner value at TP2 + const runnerValue = tp2RunnerSize * lev * (tp2CalcPercent / 100) // Runner value at TP2 const fullWin = tp1Gain + runnerValue - return { maxLoss, tp1Gain, runnerValue, fullWin, tp2Percent } + return { maxLoss, tp1Gain, runnerValue, fullWin, tp2Percent, runnerPercent } } if (loading) { @@ -276,7 +277,7 @@ export default function SettingsPage() {
+${risk.tp1Gain.toFixed(2)}
-
Runner Value (25%)
+
Runner Value ({risk.runnerPercent}%)
+${risk.runnerValue.toFixed(2)}
{risk.tp2Percent}
@@ -594,11 +595,14 @@ export default function SettingsPage() { {/* Trailing Stop */} -
+

- NEW SYSTEM: When TP2 price is hit, no position is closed. Instead, trailing stop activates on the full 25% remaining position for maximum runner potential. - This gives you a 5x larger runner (25% vs 5%) to capture extended moves. + NEW SYSTEM: When TP2 price is hit, no position is closed. Instead, trailing stop activates on the full {100 - settings.TAKE_PROFIT_1_SIZE_PERCENT}% remaining position for maximum runner potential. + Current split: {settings.TAKE_PROFIT_1_SIZE_PERCENT}% at TP1, {100 - settings.TAKE_PROFIT_1_SIZE_PERCENT}% becomes runner.