docs: fix CRITICAL copilot instructions + add Nov 12 bugs

CRITICAL FIXES:
- Lines 217-225: Reversed position.size documentation (was WRONG: "USD", now CORRECT: "tokens")
  This incorrect doc caused the Position Manager bug we fixed today!
- Updated capital: $97.55 USDC (was $106)
- Updated leverage: 15x (was 20x)
- Updated per-symbol defaults: 100%, 15x (was $210, 10x)

NEW PITFALLS ADDED:
#22: Position.size tokens vs USD bug (false TP1 detection fix)
     - Root cause, symptoms, fix with code examples
     - Affects Position Manager lines 322, 519, 558, 591
#23: Leverage display bug (showing 10x instead of 15x)
     - Symbol-specific vs global config
     - Affects execute/route.ts lines 345, 448, 522, 557
#24: Indicator version tracking (v5 vs v6 comparison)
     - Buy/Sell Signal vs HalfTrend+BarColor strategies

CURRENT STATUS SECTION:
- 161 trades executed
- Three optimization initiatives in data collection
- Expected 35-40% P&L improvement when complete
- Links to OPTIMIZATION_MASTER_ROADMAP.md

This ensures future AI agents have accurate info and won't repeat
the position.size bug that caused false TP1 hits today.
This commit is contained in:
mindesbunister
2025-11-12 12:50:09 +01:00
parent eeebfbc5df
commit 4404103f6a

View File

@@ -5,12 +5,14 @@
**Primary Objective:** Build wealth systematically from $106 → $100,000+ through algorithmic trading
**Current Phase:** Phase 1 - Survival & Proof (Nov 2025 - Jan 2026)
- **Starting Capital:** $106 (+ $1,000 deposit in 2 weeks)
- **Current Capital:** $97.55 USDC (zero debt, 100% health)
- **Starting Capital:** $106 (Nov 2025)
- **Target:** $2,500 by end of Phase 1 (Month 2.5)
- **Strategy:** Aggressive compounding, 0 withdrawals
- **Position Sizing:** 100% of account ($106 at 20x leverage = $2,120 notional)
- **Position Sizing:** 100% of free collateral (~$97 at 15x leverage = ~$1,463 notional)
- **Risk Tolerance:** EXTREME - This is recovery/proof-of-concept mode
- **Win Target:** 20-30% monthly returns to reach $2,500
- **Trades Executed:** 161 (as of Nov 12, 2025)
**Why This Matters for AI Agents:**
- Every dollar counts at this stage - optimize for profitability, not just safety
@@ -39,8 +41,8 @@
- **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)
- `ETHEREUM_ENABLED`, `ETHEREUM_POSITION_SIZE`, `ETHEREUM_LEVERAGE` (defaults: true, $4, 1x)
- `SOLANA_ENABLED`, `SOLANA_POSITION_SIZE`, `SOLANA_LEVERAGE` (defaults: true, 100%, 15x)
- `ETHEREUM_ENABLED`, `ETHEREUM_POSITION_SIZE`, `ETHEREUM_LEVERAGE` (defaults: true, 100%, 1x)
- BTC and other symbols fall back to global settings (`MAX_POSITION_SIZE_USD`, `LEVERAGE`)
- **Priority:** Per-symbol ENV → Market config → Global ENV → Defaults
@@ -208,16 +210,16 @@ console.log('✅ Transaction confirmed on-chain')
```
Without this, the SDK returns signatures for transactions that never execute, causing phantom trades/closes.
**CRITICAL: Drift SDK position.size is USD, not tokens**
The Drift SDK returns `position.size` as USD notional value, NOT token quantity:
**CRITICAL: Drift SDK position.size is BASE ASSET TOKENS, not USD**
The Drift SDK returns `position.size` as token quantity (SOL/ETH/BTC), NOT USD notional:
```typescript
// WRONG: Multiply by price (inflates by 156x for SOL at $157)
const positionSizeUSD = position.size * currentPrice
// CORRECT: Convert tokens to USD by multiplying by current price
const positionSizeUSD = Math.abs(position.size) * currentPrice
// CORRECT: Use directly as USD value
// WRONG: Using position.size directly as USD (off by 150x+ for SOL!)
const positionSizeUSD = Math.abs(position.size)
```
This affects Position Manager's TP1 detection - if calculated incorrectly, TP1 will never trigger because expected size won't match actual size.
**This affects Position Manager's TP1/TP2 detection** - if position.size is not converted to USD before comparing to tracked USD values, the system will never detect partial closes correctly. See Common Pitfall #22 for the full bug details and fix applied Nov 12, 2025.
**Solana RPC Rate Limiting with Exponential Backoff**
Solana RPC endpoints return 429 errors under load. Always use retry logic for order operations:
@@ -681,6 +683,46 @@ trade.realizedPnL += actualRealizedPnL // NOT: result.realizedPnL from SDK
- TypeScript build will fail if endpoint passes field not in interface
- Example: indicatorVersion tracking required 3-file update (execute route.ts, CreateTradeParams interface, createTrade function)
22. **Position.size tokens vs USD bug (CRITICAL - Fixed Nov 12, 2025):**
- **Symptom:** Position Manager detects false TP1 hits, moves SL to breakeven prematurely
- **Root Cause:** `lib/drift/client.ts` returns `position.size` as BASE ASSET TOKENS (12.28 SOL), not USD ($1,950)
- **Bug:** Comparing tokens (12.28) directly to USD ($1,950) → 12.28 < 1,950 × 0.95 = "99.4% reduction" → FALSE TP1!
- **Fix:** Always convert to USD before comparisons:
```typescript
// In Position Manager (lines 322, 519, 558, 591)
const positionSizeUSD = Math.abs(position.size) * currentPrice
// Now compare USD to USD
if (positionSizeUSD < trade.currentSize * 0.95) {
// Actual 5%+ reduction detected
}
```
- **Impact:** Without this fix, TP1 never triggers correctly, SL moves at wrong times, runner system fails
- **Where it matters:** Position Manager, any code querying Drift positions
- **Database evidence:** Trade showed `tp1Hit: true` when 100% still open, `slMovedToBreakeven: true` prematurely
23. **Leverage display showing global config instead of symbol-specific (Fixed Nov 12, 2025):**
- **Symptom:** Telegram notifications showing "⚡ Leverage: 10x" when actual position uses 15x or 20x
- **Root Cause:** API response returning `config.leverage` (global default) instead of symbol-specific value
- **Fix:** Use actual leverage from `getPositionSizeForSymbol()`:
```typescript
// app/api/trading/execute/route.ts (lines 345, 448, 522, 557)
const { size, leverage, enabled } = getPositionSizeForSymbol(driftSymbol, config)
// Return symbol-specific leverage
leverage: leverage, // NOT: config.leverage
```
- **Impact:** Misleading notifications, user confusion about actual position risk
- **Hierarchy:** Per-symbol ENV (SOLANA_LEVERAGE) → Market config → Global ENV (LEVERAGE) → Defaults
24. **Indicator version tracking (Nov 12, 2025+):**
- Database field `indicatorVersion` tracks which TradingView strategy generated the signal
- **v5:** Buy/Sell Signal strategy (pre-Nov 12)
- **v6:** HalfTrend + BarColor strategy (Nov 12+)
- Used for performance comparison between strategies
- Must update `CreateTradeParams` interface when adding new database fields (see pitfall #21)
- Analytics endpoint `/api/analytics/version-comparison` compares v5 vs v6 performance
## File Conventions
- **API routes:** `app/api/[feature]/[action]/route.ts` (Next.js 15 App Router)
@@ -800,6 +842,17 @@ if (!enabled) {
## Development Roadmap
**Current Status (Nov 12, 2025):**
- **161 trades executed** with quality scores and MAE/MFE tracking
- **Capital:** $97.55 USDC at 100% health (zero debt, all USDC collateral)
- **Leverage:** 15x SOL (reduced from 20x for safer liquidation cushion)
- **Three active optimization initiatives** in data collection phase:
1. **Signal Quality:** 0/20 blocked signals collected → need 10-20 for analysis
2. **Position Scaling:** 161 v5 trades, collecting v6 data → need 50+ v6 trades
3. **ATR-based TP:** 1/50 trades with ATR data → need 50 for validation
- **Expected combined impact:** 35-40% P&L improvement when all three optimizations complete
- **Master roadmap:** See `OPTIMIZATION_MASTER_ROADMAP.md` for consolidated view
See `SIGNAL_QUALITY_OPTIMIZATION_ROADMAP.md` for systematic signal quality improvements:
- **Phase 1 (🔄 IN PROGRESS):** Collect 10-20 blocked signals with quality scores (1-2 weeks)
- **Phase 2 (🔜 NEXT):** Analyze patterns and make data-driven threshold decisions