4 Commits

Author SHA1 Message Date
root
17ff829c6c docs: Update copilot-instructions.md für Leverage 5x (Jan 30, 2026)
Alle Leverage-Referenzen von 10x/15x auf 5x aktualisiert:
- Adaptive Leverage Status, Configuration, Rationale
- Position Sizing (notional: ~$2,700 statt ~$8,100)
- Per-Symbol defaults (SOL 5x, ETH 5x)
- Pyramid stacking leverage
- Quick Reference Table

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-30 17:47:19 +01:00
root
fdab446aa4 docs: Fix .env-Deployment-Pitfall - restart vs up -d
docker compose restart liest .env NICHT neu ein, weil die
environment:-Section in docker-compose.yml ${VAR:-default} Syntax
nutzt, die nur bei docker compose up ausgewertet wird.

Korrigiert in copilot-instructions.md und ZERO_DOWNTIME_CHANGES.md.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-30 17:25:49 +01:00
root
c80a62ed26 security: .env und .env.* aus Git-Tracking entfernen
.env enthielt Private Keys und API Secrets im Klartext.
.gitignore aktualisiert: alle .env-Dateien ignorieren, nur .env.example behalten.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-30 14:46:44 +01:00
root
da5bddddc8 docs: copilot-instructions.md von .github/ in Projekt-Root verschieben
Claude Code liest automatisch copilot-instructions.md aus dem Root.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-30 14:46:34 +01:00
5 changed files with 48 additions and 533 deletions

482
.env
View File

@@ -1,482 +0,0 @@
# Trading Bot v4 - Environment Variables Template
# Copy this file to .env.local and fill in your values
#
# IMPORTANT: Never commit .env.local to git!
# ================================
# REQUIRED - DRIFT PROTOCOL TRADING
# ================================
# Your Solana wallet private key (base58 format)
# ⚠️ SECURITY: Use a dedicated trading wallet with limited funds
# Get from: Phantom → Settings → Export Private Key
# Or: solana-keygen new --outfile ~/trading-wallet.json
DRIFT_WALLET_PRIVATE_KEY=[91,24,199,66,154,166,231,159,121,123,20,165,118,229,96,114,145,170,28,1,59,164,186,37,170,234,46,107,26,119,205,206,39,1,96,252,82,190,199,68,182,144,131,53,153,66,255,138,238,57,28,249,224,239,172,252,157,230,171,224,154,252,142,171]
# Drift environment
# Options: mainnet-beta (production), devnet (testing)
DRIFT_ENV=mainnet-beta
# Drift Program ID (default - don't change unless using custom program)
DRIFT_PROGRAM_ID=dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH
# API secret key for authenticating n8n webhook requests
# Generate with: openssl rand -hex 32
# Or: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
# API authentication secret for endpoints
# Generate with: openssl rand -hex 32
API_SECRET_KEY=2a344f0149442c857fb56c038c0c7d1b113883b830bec792c76f1e0efa15d6bb
# Public API key for frontend (must start with NEXT_PUBLIC_)
# This is safe to expose to the browser - it's for authenticated endpoints only
NEXT_PUBLIC_API_SECRET_KEY=2a344f0149442c857fb56c038c0c7d1b113883b830bec792c76f1e0efa15d6bb
# ================================
# REQUIRED - SOLANA RPC ENDPOINT
# ================================
# Solana RPC URL (Required for blockchain access)
#
# PRIMARY: Helius (ONLY PROVIDER THAT WORKS RELIABLY)
# Drift SDK REQUIRES WebSocket subscriptions - Alchemy doesn't support this
# Alchemy "working" state was temporary - always breaks after first trade or shortly after init
SOLANA_RPC_URL=https://mainnet.helius-rpc.com/?api-key=5e236449-f936-4af7-ae38-f15e2f1a3757
# Alternative RPC providers (reference):
#
# QuickNode: https://solana-mainnet.quiknode.pro/YOUR_ENDPOINT/
# Alchemy: https://solana-mainnet.g.alchemy.com/v2/YOUR_ALCHEMY_KEY
# Ankr: https://rpc.ankr.com/solana
# Public (not recommended): https://api.mainnet-beta.solana.com
# ================================
# REQUIRED - PYTH NETWORK (Price Feeds)
# ================================
# Pyth Hermes WebSocket endpoint (for real-time prices)
# Default: https://hermes.pyth.network (no API key needed)
PYTH_HERMES_URL=https://hermes.pyth.network
# Alternative Pyth endpoints:
# Stable: https://hermes-beta.pyth.network
# Devnet: https://hermes-dev.pyth.network
# ================================
# TRADING CONFIGURATION (Optional - Override defaults)
# ================================
# Position sizing
# Base position size in USD (default: 50 for safe testing)
# Example: 50 with 10x leverage = $500 notional position
MAX_POSITION_SIZE_USD=210
# Leverage multiplier (1-20, default: 10)
# Higher leverage = bigger gains AND bigger losses
# Updated Jan 2, 2026: 10x leverage justified by 82% WR, 2.18 PF, 6.19% DD
LEVERAGE=10
# Risk parameters (LEGACY FALLBACK - used when ATR unavailable)
# Stop Loss: Close 100% of position when price drops this much
# Example: -1.5% on 10x = -15% account loss
STOP_LOSS_PERCENT=-1.3
# ================================
# DUAL STOP SYSTEM (Advanced)
# ================================
# Enable dual stop system to avoid wicks while guaranteeing exit
# When enabled, places TWO stop orders:
# 1. Soft Stop (TRIGGER_LIMIT) - Avoids false breakouts/wicks
# 2. Hard Stop (TRIGGER_MARKET) - Guarantees exit if price keeps falling
USE_DUAL_STOPS=false
# Soft Stop (Primary, Stop-Limit)
# Triggers first, tries to avoid wicks
SOFT_STOP_PERCENT=-1.5
SOFT_STOP_BUFFER=0.4 # Buffer between trigger and limit (0.4% = limit at -1.9%)
# Hard Stop (Backup, Stop-Market)
# Only triggers if soft stop doesn't fill
# Guarantees exit during strong breakdowns
HARD_STOP_PERCENT=-2.5
# Take Profit 1: Close X% of position at this profit level (FALLBACK)
# Example: +0.8% on 10x = +8% account gain
TAKE_PROFIT_1_PERCENT=1.45
# Take Profit 1 Size: What % of position to close at TP1
# 60 = close 60%, leave 40% for runner
TAKE_PROFIT_1_SIZE_PERCENT=100
# Take Profit 2: Trigger trailing stop at this profit level (FALLBACK)
# Example: +1.8% on 10x = +18% account gain
TAKE_PROFIT_2_PERCENT=1.8
# Take Profit 2 Size: What % of remaining position to close at TP2
# 0 = don't close at TP2, activate trailing stop on full remaining position
TAKE_PROFIT_2_SIZE_PERCENT=0
# ================================
# ATR-BASED TP/SL (PRIMARY SYSTEM - Nov 17, 2025)
# ================================
# Enable dynamic TP/SL based on market volatility (RECOMMENDED)
# ATR (Average True Range) adapts to current market conditions
# Bull market: Different ATR → Different targets automatically
# Bear market: Different ATR → Different targets automatically
# No manual intervention needed when market regime changes!
USE_ATR_BASED_TARGETS=true
# ATR multipliers for TP1, TP2, and SL
# Example with SOL ATR = 0.45% of price:
# TP1 = 0.45% × 2.0 = 0.90% target
# TP2 = 0.45% × 4.0 = 1.80% target
# SL = 0.45% × 3.0 = 1.35% distance
ATR_MULTIPLIER_TP1=2.0
ATR_MULTIPLIER_TP2=4.0
ATR_MULTIPLIER_SL=3.0
# Safety bounds (prevent extreme values)
# TP1 bounds
MIN_TP1_PERCENT=1.45 # Clamp TP1 to requested 1.1%
MAX_TP1_PERCENT=1.45 # Clamp TP1 to requested 1.1%
# TP2 bounds
MIN_TP2_PERCENT=1
MAX_TP2_PERCENT=3
# SL bounds
MIN_SL_PERCENT=1.3 # Clamp SL to requested 2.8%
MAX_SL_PERCENT=1.3 # Clamp SL to requested 2.8%
# Emergency Stop: Hard stop if this level is breached
# Example: -2.0% on 10x = -20% account loss (rare but protects from flash crashes)
EMERGENCY_STOP_PERCENT=-1.5
# Dynamic stop-loss adjustments
# Move SL to breakeven when profit reaches this level
PROFIT_LOCK_AFTER_TP1_PERCENT=-0.55 # Allow -0.55% drawdown on runner after TP1 (gives room for retracements while TP1 profit already banked)
# Lock in profit when price reaches this level
PROFIT_LOCK_TRIGGER_PERCENT=1
# How much profit to lock (move SL to this profit level)
PROFIT_LOCK_PERCENT=0.6
# Risk limits
# Stop trading if daily loss exceeds this amount (USD)
# Example: -150 = stop trading after losing $150 in a day
MAX_DAILY_DRAWDOWN=-1000
# Maximum number of trades allowed per hour (prevents overtrading)
MAX_TRADES_PER_HOUR=20
# ================================
# PYRAMIDING / POSITION STACKING
# ================================
# Stack positions when confirmation signals arrive within time window
# Data-driven: Signals ≤72 bars (6h) apart have 100% win rate
# Enable pyramiding feature
ENABLE_PYRAMIDING=true
# Leverage for first/base entry (e.g., 7x)
BASE_LEVERAGE=10
# Leverage for additional stack entries (e.g., 7x)
STACK_LEVERAGE=10
# Maximum combined leverage across all pyramid levels (e.g., 14x)
MAX_LEVERAGE_TOTAL=20
# Maximum pyramid levels (e.g., 2 = base + 1 stack)
MAX_PYRAMID_LEVELS=2
# Time window for stacking in minutes (e.g., 240 = 4 hours)
# Conservative setting vs 6h (360min) optimal from backtest
STACKING_WINDOW_MINUTES=240
# Minimum time between trades in minutes (cooldown period)
# Example: 10 = 10 minutes between trades
MIN_TIME_BETWEEN_TRADES=1
# DEX execution settings
# Maximum acceptable slippage on market orders (percentage)
# Example: 1.0 = accept up to 1% slippage
SLIPPAGE_TOLERANCE=0.1
# How often to check prices (milliseconds)
# Example: 2000 = check every 2 seconds
PRICE_CHECK_INTERVAL_MS=2000
# Order confirmation timeout (milliseconds)
# Example: 30000 = wait up to 30 seconds for order confirmation
CONFIRMATION_TIMEOUT_MS=30000
# ================================
# N8N WORKFLOW INTEGRATION (Optional but recommended)
# ================================
# n8n instance URL (for workflow automation)
# Get from: https://n8n.io (cloud) or self-hosted
# Example: https://your-username.app.n8n.cloud
N8N_WEBHOOK_URL=https://flow.egonetix.de/webhook/3371ad7c-0866-4161-90a4-f251de4aceb8
# n8n API key (if using n8n API directly)
N8N_API_KEY=your_n8n_api_key
# TradingView webhook secret (for validating incoming alerts)
# Must match the secret in your TradingView alert URL
# Generate with: openssl rand -hex 16
TRADINGVIEW_WEBHOOK_SECRET=your_tradingview_webhook_secret
# ================================
# NOTIFICATIONS (Optional - for trade alerts)
# ================================
# Telegram Bot (recommended for mobile alerts)
# 1. Create bot: Message @BotFather on Telegram, send /newbot
# 2. Get token from BotFather
# 3. Get chat ID: Message @userinfobot or your bot, it will show your chat ID
TELEGRAM_BOT_TOKEN=8240234365:AAEm6hg_XOm54x8ctnwpNYreFKRAEvWU3uY
TELEGRAM_CHAT_ID=579304651
# Discord Webhook (good for team channels)
# 1. Go to Discord channel settings
# 2. Integrations → Webhooks → New Webhook
# 3. Copy webhook URL
DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/YOUR_WEBHOOK_ID/YOUR_WEBHOOK_TOKEN
# Email (SMTP) - for important alerts
# Gmail setup:
# 1. Enable 2FA on your Google account
# 2. Generate App Password: https://myaccount.google.com/apppasswords
# 3. Use the 16-character app password below
EMAIL_SMTP_HOST=smtp.gmail.com
EMAIL_SMTP_PORT=587
EMAIL_SMTP_SECURE=false
EMAIL_FROM=your-email@gmail.com
EMAIL_TO=notification-email@gmail.com
EMAIL_USER=your-email@gmail.com
EMAIL_PASSWORD=your_16_character_app_password
# Other SMTP providers:
# Outlook: smtp-mail.outlook.com:587
# Yahoo: smtp.mail.yahoo.com:587
# SendGrid: smtp.sendgrid.net:587
# ================================
# DATABASE (Optional - Phase 3 feature)
# ================================
# PostgreSQL connection string
# Format: postgresql://username:password@host:port/database
#
# IMPORTANT: Use different URLs for different environments:
# - Docker container (runtime): trading-bot-postgres (container name)
# - Local development (Prisma CLI): localhost:5432
#
# The URL below is for Docker runtime. For Prisma migrations from host:
# DATABASE_URL="postgresql://postgres:postgres@localhost:5432/trading_bot_v4" npx prisma migrate dev
#
# PostgreSQL Database (for trade history and analytics)
DATABASE_URL=postgresql://postgres:postgres@trading-bot-postgres:5432/trading_bot_v4
# Cloud PostgreSQL providers:
# - Supabase: https://supabase.com (free tier available)
# - Neon: https://neon.tech (serverless, free tier)
# - Railway: https://railway.app
# - Heroku Postgres
# Database connection pool settings (optional)
DATABASE_POOL_MIN=2
DATABASE_POOL_MAX=10
# ================================
# SECURITY & ACCESS CONTROL
# ================================
# JWT secret for API authentication (if implementing auth)
# Generate with: openssl rand -hex 64
JWT_SECRET=your_jwt_secret_here
# Allowed origins for CORS (comma-separated)
# Example: http://localhost:3000,https://yourdomain.com
ALLOWED_ORIGINS=http://localhost:3000
# Rate limiting (requests per minute)
RATE_LIMIT_PER_MINUTE=60
# IP whitelist (comma-separated, leave empty to allow all)
# Example: 192.168.1.100,10.0.0.5
IP_WHITELIST=
# ================================
# DEVELOPMENT & DEBUGGING
# ================================
# Node environment (development, production, test)
NODE_ENV=production
# Log level (debug, info, warn, error)
# Use 'debug' for detailed logs during development
LOG_LEVEL=info
# Enable detailed logging for specific modules
DEBUG=drift:*,pyth:*,trading:*
# Enable dry run mode (simulate trades without executing)
# Set to 'true' for testing without real money
DRY_RUN=false
# API server port (default: 3000)
PORT=3000
# Enable performance monitoring
ENABLE_METRICS=false
# Sentry DSN (for error tracking in production)
SENTRY_DSN=
# ================================
# MONITORING & ANALYTICS (Optional)
# ================================
# DataDog API key (for metrics and logs)
DATADOG_API_KEY=
# Grafana Cloud endpoint
GRAFANA_ENDPOINT=
# New Relic license key
NEW_RELIC_LICENSE_KEY=
# ================================
# NOTES & QUICK REFERENCE
# ================================
# Typical Production Setup:
# - MAX_POSITION_SIZE_USD=1000 (start with $1k)
# - LEVERAGE=10 (10x multiplier)
# - Helius RPC (best performance)
# - Telegram notifications enabled
# - DRY_RUN=false
# - LOG_LEVEL=info
#
# Safe Testing Setup:
# - MAX_POSITION_SIZE_USD=50 (only $50 per trade)
# - LEVERAGE=10 (still test with leverage)
# - DRY_RUN=false (test with real tiny amounts)
# - LOG_LEVEL=debug (see everything)
#
# Recommended Daily Limits:
# - MAX_DAILY_DRAWDOWN=-150 (stop at -15% loss)
# - MAX_TRADES_PER_HOUR=6 (prevent overtrading)
# - MIN_TIME_BETWEEN_TRADES=10 (10min cooldown)
#
# Expected Risk Per Trade (with defaults):
# - Max Loss: $7.50 (50 * 10 * 0.015)
# - TP1 Gain: $3.50 (50 * 10 * 0.007)
# - TP2 Gain: $7.50 (50 * 10 * 0.015)
# - Full Win: $11.00 (TP1 + TP2)
#
# Getting API Keys:
# - Helius: https://helius.dev (free tier: 100k requests/day)
# - Telegram: @BotFather on Telegram
# - Discord: Channel Settings → Integrations → Webhooks
# - Gmail: myaccount.google.com/apppasswords (need 2FA enabled)
#
# Testing Checklist:
# [ ] Copy this file to .env.local
# [ ] Fill in DRIFT_WALLET_PRIVATE_KEY
# [ ] Fill in SOLANA_RPC_URL (Helius recommended)
# [ ] Fill in API_SECRET_KEY (random 32-byte hex)
# [ ] Set MAX_POSITION_SIZE_USD=50 for testing
# [ ] Run: npx tsx v4/test-price-monitor.ts
# [ ] Run: npx tsx v4/test-position-manager.ts
# [ ] Run: npx tsx v4/test-full-flow.ts (careful: real trade!)
# [ ] Configure TradingView alerts
# [ ] Import n8n-workflow-v4.json
# [ ] Test with manual TradingView alert
#
# Security Reminders:
# ⚠️ Never commit .env.local to git
# ⚠️ Use a dedicated trading wallet
# ⚠️ Start with small position sizes
# ⚠️ Keep private keys secure
# ⚠️ Use hardware wallet for large amounts
# ⚠️ Rotate API keys regularly
# ⚠️ Monitor for suspicious activity
#
# Support & Documentation:
# - v4/README.md - Project overview
# - v4/SETUP.md - Detailed setup guide
# - v4/TESTING.md - Testing procedures
# - v4/QUICKREF_PHASE2.md - Quick reference
# - TRADING_BOT_V4_MANUAL.md - Complete manual
# - PHASE_2_COMPLETE_REPORT.md - Feature summary
USE_TRAILING_STOP=false
TRAILING_STOP_PERCENT=0.5
TRAILING_STOP_ACTIVATION=0.4
MIN_SIGNAL_QUALITY_SCORE=95
MIN_SIGNAL_QUALITY_SCORE_LONG=95
MIN_SIGNAL_QUALITY_SCORE_SHORT=80
# Adaptive Leverage System (Nov 24, 2025)
# Updated Jan 2, 2026: Fixed 10x leverage (adaptive disabled)
# Long-only strategy validated: 82% WR, 2.18 PF, 6.19% DD
USE_ADAPTIVE_LEVERAGE=false
HIGH_QUALITY_LEVERAGE=10
LOW_QUALITY_LEVERAGE=10
QUALITY_LEVERAGE_THRESHOLD_LONG=95
QUALITY_LEVERAGE_THRESHOLD_SHORT=90
QUALITY_LEVERAGE_THRESHOLD=95 # Kept for backward compatibility
SOLANA_ENABLED=true
SOLANA_POSITION_SIZE=100
SOLANA_LEVERAGE=10
SOLANA_USE_PERCENTAGE_SIZE=true
ETHEREUM_ENABLED=false
ETHEREUM_POSITION_SIZE=50
ETHEREUM_LEVERAGE=5
ETHEREUM_USE_PERCENTAGE_SIZE=false
ENABLE_POSITION_SCALING=true
MIN_SCALE_QUALITY_SCORE=75
MIN_PROFIT_FOR_SCALE=0.4
MAX_SCALE_MULTIPLIER=2
SCALE_SIZE_PERCENT=50
MIN_ADX_INCREASE=5
MAX_PRICE_POSITION_FOR_SCALE=70
TRAILING_STOP_ATR_MULTIPLIER=2.5
TRAILING_STOP_MIN_PERCENT=0.25
TRAILING_STOP_MAX_PERCENT=2.5
USE_PERCENTAGE_SIZE=false
BREAKEVEN_TRIGGER_PERCENT=0.4
ATR_MULTIPLIER_FOR_TP2=2
# ================================
# SMART ENTRY TIMING (Phase 2 - Nov 27, 2025)
# ================================
# Wait for optimal pullback within 2 minutes after 5-min signal
# Expected impact: 0.2-0.5% better entry per trade = $1,600-4,000 over 100 trades
SMART_ENTRY_ENABLED=true # Set to true to enable smart entry timing
SMART_ENTRY_MAX_WAIT_MS=120000 # 120,000ms = 2 minutes max wait
SMART_ENTRY_PULLBACK_MIN=0.15 # 0.15% minimum pullback to consider
SMART_ENTRY_PULLBACK_MAX=0.50 # 0.50% maximum pullback (beyond = possible reversal)
SMART_ENTRY_ADX_TOLERANCE=2 # Max ADX drop allowed (2 points)
# How it works:
# - 5-min signal arrives at candle close
# - Bot waits up to 2 minutes for price to pullback
# - LONG: Waits for dip 0.15-0.5% below signal price
# - SHORT: Waits for bounce 0.15-0.5% above signal price
# - Validates ADX hasn't dropped >2 points
# - Timeout: Executes at market if no pullback within 2 minutes
ENABLE_AUTO_WITHDRAWALS=false
WITHDRAWAL_INTERVAL_HOURS=168
WITHDRAWAL_PROFIT_PERCENT=10
MIN_WITHDRAWAL_AMOUNT=5
MIN_ACCOUNT_BALANCE=500
LAST_WITHDRAWAL_TIME=2025-11-19T19:34:47.185Z
TOTAL_WITHDRAWN=12.50
# Production Logging Configuration (Phase 1 Optimization - Dec 5, 2025)
DEBUG_LOGS=false

View File

@@ -1,17 +0,0 @@
# Telegram Trade Bot Configuration
# Get your bot token from @BotFather on Telegram
TELEGRAM_BOT_TOKEN=8240234365:AAEm6hg_XOm54x8ctnwpNYreFKRAEvWU3uY
# Your n8n webhook URL (after importing telegram-manual-trade-FINAL.json, activate it and replace this URL)
# Your n8n webhook URL (public HTTPS)
N8N_WEBHOOK_URL=https://flow.egonetix.de/webhook/3371ad7c-0866-4161-90a4-f251de4aceb8
# Your Telegram chat ID (already set to 579304651)
TELEGRAM_CHAT_ID=579304651
# Trading Bot API URL (internal Docker network)
TRADING_BOT_URL=http://trading-bot-v4:3000
# API Secret Key (same as in main .env file)
API_SECRET_KEY=2a344f0149442c857fb56c038c0c7d1b113883b830bec792c76f1e0efa15d6bb

5
.gitignore vendored
View File

@@ -10,8 +10,9 @@ out/
build/
# Environment variables
.env.local
.env*.local
.env
.env.*
!.env.example
# IDE
.vscode/

View File

@@ -126,17 +126,20 @@
- **Last Updated:** Jan 3, 2026 (TP1 fixed to 1.45%)
### Adaptive Leverage System
- **Status:** ❌ DISABLED (Jan 2, 2026) - Using fixed leverage (SOL 10x, ETH 5x)
- **Status:** ❌ DISABLED (Jan 2, 2026) - Using fixed leverage (SOL 5x, ETH 5x)
- **Configuration:**
* `USE_ADAPTIVE_LEVERAGE=false`
* `LEVERAGE=10` (global default)
* `SOLANA_LEVERAGE=10`
* `LEVERAGE=5` (global default)
* `BASE_LEVERAGE=5`
* `STACK_LEVERAGE=5`
* `MAX_LEVERAGE_TOTAL=10`
* `SOLANA_LEVERAGE=5`
* `ETHEREUM_LEVERAGE=5`
* `HIGH_QUALITY_LEVERAGE=10`
* `LOW_QUALITY_LEVERAGE=10`
- **Rationale:** 10x leverage justified by 82% WR, 2.18 PF, 6.19% max DD (Jan 2, 2026 analysis)
- **Previous Config:** Was 5x fixed (Dec 26, 2025)
- **Last Updated:** Jan 2, 2026
* `HIGH_QUALITY_LEVERAGE=5`
* `LOW_QUALITY_LEVERAGE=5`
- **Rationale:** Reduced from 10x to 5x (Jan 30, 2026) for risk reduction
- **Previous Config:** Was 10x fixed (Jan 2 - Jan 30, 2026), 5x fixed before that (Dec 26, 2025)
- **Last Updated:** Jan 30, 2026
### Projection Page & Analytics Stats (Jan 13, 2026 - UPDATED)
- **Purpose:** 12-month financial projection dashboard showing actual vs planned progress
@@ -200,7 +203,7 @@ docker logs trading-bot-v4 | grep "Server starting" | head -1
| "I want to..." | Existing Feature | Search Term |
|----------------|------------------|-------------|
| Re-enter after stop-out | **Stop Hunt Revenge System** - Auto re-enters quality 85+ signals after price reverses through original entry | `grep -i "stop hunt revenge"` |
| Scale position by quality | **Adaptive Leverage System** - 10x for quality 95+, 5x for borderline signals | `grep -i "adaptive leverage"` |
| Scale position by quality | **Adaptive Leverage System** - Currently disabled, fixed 5x leverage (Jan 30, 2026) | `grep -i "adaptive leverage"` |
| Test different timeframes | **Multi-Timeframe Data Collection** - Parallel data collection for 5min/15min/1H/4H/Daily | `grep -i "multi-timeframe"` |
| Monitor blocked signals | **BlockedSignal Tracker** - Tracks quality-blocked signals with price analysis | `grep -i "blockedsignal"` |
| Survive server failures | **HA Failover** - Secondary server with auto DNS failover (90s detection) | `grep -i "high availability"` |
@@ -1049,7 +1052,7 @@ When you have high-resolution data (1 minute), use it immediately. Arbitrary del
- **Trading P&L:** -$6 (early v6/v7 testing before v8 optimization)
- **Target:** $2,500 by end of Phase 1 (Month 2.5) - 4.6x growth from current
- **Strategy:** Aggressive compounding, 0 withdrawals, data-driven optimization
- **Position Sizing:** 100% of free collateral (~$540 at 15x leverage = ~$8,100 notional)
- **Position Sizing:** 100% of free collateral (~$540 at 5x leverage = ~$2,700 notional)
- **Risk Tolerance:** HIGH - Proof-of-concept mode with increased capital cushion
- **Win Target:** 15-20% monthly returns to reach $2,500 (more achievable with larger base)
- **Trades Executed:** 170+ (as of Nov 19, 2025)
@@ -1139,8 +1142,8 @@ When you have high-resolution data (1 minute), use it immediately. Arbitrary del
- **Implementation:** Nov 24, 2025 (commit 9d7932f)
**Per-Symbol Configuration:** SOL and ETH have independent enable/disable toggles and position sizing:
- `SOLANA_ENABLED`, `SOLANA_POSITION_SIZE`, `SOLANA_LEVERAGE` (defaults: true, 100%, 15x)
- `ETHEREUM_ENABLED`, `ETHEREUM_POSITION_SIZE`, `ETHEREUM_LEVERAGE` (defaults: true, 100%, 1x)
- `SOLANA_ENABLED`, `SOLANA_POSITION_SIZE`, `SOLANA_LEVERAGE` (defaults: true, 100%, 5x)
- `ETHEREUM_ENABLED`, `ETHEREUM_POSITION_SIZE`, `ETHEREUM_LEVERAGE` (defaults: true, 100%, 5x)
- BTC and other symbols fall back to global settings (`MAX_POSITION_SIZE_USD`, `LEVERAGE`)
- **Priority:** Per-symbol ENV → Market config → Global ENV → Defaults
@@ -1160,12 +1163,10 @@ Frequency penalties (overtrading / flip-flop / alternating) now ignore 1-minute
**Adaptive Leverage System (Nov 24, 2025 - RISK-ADJUSTED POSITION SIZING):**
- **Purpose:** Automatically adjust leverage based on signal quality score - high confidence gets full leverage, borderline signals get reduced risk exposure
- **Quality-Based Leverage Tiers:**
- **Quality 95-100:** 15x leverage ($540 × 15x = $8,100 notional position)
- **Quality 90-94:** 10x leverage ($540 × 10x = $5,400 notional position)
- **Currently disabled** - fixed 5x leverage for all signals (Jan 30, 2026)
- **Previous tiers (historical):** Quality 95-100: 15x, Quality 90-94: 10x
- **Quality <90:** Blocked by direction-specific thresholds
- **Risk Impact:** Quality 90-94 signals save $2,700 exposure (33% risk reduction) vs fixed 15x
- **Data-Driven Justification:** v8 indicator quality 95+ = 100% WR (4/4 wins), quality 90-94 more volatile
- **Configuration:** `USE_ADAPTIVE_LEVERAGE=true`, `HIGH_QUALITY_LEVERAGE=15`, `LOW_QUALITY_LEVERAGE=10`, `QUALITY_LEVERAGE_THRESHOLD=95` in .env
- **Configuration:** `USE_ADAPTIVE_LEVERAGE=false`, `LEVERAGE=5`, `HIGH_QUALITY_LEVERAGE=5`, `LOW_QUALITY_LEVERAGE=5` in .env
- **Implementation:** Quality score calculated EARLY in execute endpoint (before position sizing), passed to `getActualPositionSizeForSymbol(qualityScore)`, leverage determined via `getLeverageForQualityScore()` helper
- **Log Message:** `📊 Adaptive leverage: Quality X → Yx leverage (threshold: 95)`
- **Trade-off:** ~$21 less profit on borderline wins, but ~$21 less loss on borderline stops = better risk-adjusted returns
@@ -2001,11 +2002,19 @@ docker logs trading-bot-v4 | grep "Server starting" | head -1
|------------|--------|----------|------|
| Documentation (`.md`) | **NONE** | 0s | Just commit and push |
| Workflows (`.json`, `.pinescript`) | **NONE** | 0s | Import manually to TradingView/n8n |
| ENV variables (`.env`) | **RESTART** | 5-10s | `docker compose restart trading-bot` |
| ENV variables (`.env`) | **RECREATE** | 5-10s | `docker compose up -d trading-bot` (NOT `restart` — see below) |
| Database schema | **MIGRATE + RESTART** | 10-15s | `prisma migrate + restart` |
| Code (`.ts`, `.tsx`, `.js`) | **REBUILD** | 40-70s | TypeScript must recompile |
| Dependencies (`package.json`) | **REBUILD** | 40-70s | npm install required |
**⚠️ PITFALL: `docker compose restart` liest .env NICHT neu ein (Bug #90, Jan 30 2026)**
- `docker-compose.yml` nutzt `environment:` mit `${VAR:-default}` Syntax
- Diese Variablen werden nur bei `docker compose up` ausgewertet, NICHT bei `restart`
- `restart` startet den Container mit den **alten** Environment-Variablen neu
- **Richtig:** `docker compose up -d trading-bot` → recreated den Container mit neuen Werten
- **Falsch:** `docker compose restart trading-bot` → alte .env-Werte bleiben aktiv
- **Verifizierung:** `docker exec trading-bot-v4 env | grep VARIABLE` zeigt die tatsächlich aktiven Werte
**Smart Batching Strategy:**
- **DON'T:** Rebuild after every single code change (6× rebuilds = 6 minutes downtime)
- **DO:** Batch related changes together (6 fixes → 1 rebuild = 50 seconds total)
@@ -2938,8 +2947,8 @@ MIN_TP1_PERCENT=0.5 # Don't go below 0.5% for TP1
MAX_TP1_PERCENT=1.5 # Don't go above 1.5% for TP1
MIN_TP2_PERCENT=1.0 # Don't go below 1.0% for TP2
MAX_TP2_PERCENT=3.0 # Don't go above 3.0% for TP2
MIN_SL_PERCENT=1.3 # Fixed SL (Jan 16, 2026 - optimized for 10x leverage)
MAX_SL_PERCENT=1.3 # Fixed SL (Jan 16, 2026 - optimized for 10x leverage)
MIN_SL_PERCENT=1.3 # Fixed SL (Jan 16, 2026 - may need adjustment for 5x leverage)
MAX_SL_PERCENT=1.3 # Fixed SL (Jan 16, 2026 - may need adjustment for 5x leverage)
# Legacy fallback (used when ATR unavailable)
STOP_LOSS_PERCENT=-1.3
@@ -3028,7 +3037,7 @@ const driftSymbol = normalizeTradingViewSymbol(body.symbol)
**Adaptive Leverage Configuration:**
- **Helper function:** `getLeverageForQualityScore(qualityScore, config)` returns leverage tier based on quality
- **Quality threshold:** Configured via `QUALITY_LEVERAGE_THRESHOLD` (default: 95)
- **Leverage tiers:** HIGH_QUALITY_LEVERAGE (default: 15x), LOW_QUALITY_LEVERAGE (default: 10x)
- **Leverage tiers:** HIGH_QUALITY_LEVERAGE (current: 5x), LOW_QUALITY_LEVERAGE (current: 5x)
- **Integration:** Pass `qualityScore` parameter to `getActualPositionSizeForSymbol(symbol, config, qualityScore?)`
- **Flow:** Quality score → getLeverageForQualityScore() → returns 15x or 10x → applied to position sizing
- **Logging:** System logs adaptive leverage decisions for monitoring and validation
@@ -3036,7 +3045,7 @@ const driftSymbol = normalizeTradingViewSymbol(body.symbol)
// Example usage in execute endpoint
const qualityResult = scoreSignalQuality({ atr, adx, rsi, volumeRatio, pricePosition, timeframe })
const { size, leverage } = getActualPositionSizeForSymbol(driftSymbol, config, qualityResult.score)
// leverage is now 15x for quality ≥95, or 10x for quality 90-94
// leverage is currently fixed 5x (adaptive disabled since Jan 2, 2026)
```
## API Endpoints Architecture
@@ -6107,9 +6116,9 @@ model Trade {
```
**Core Logic Flow:**
1. **First signal** → Open position with 10x leverage (`pyramidLevel: 1`)
1. **First signal** → Open position with 5x leverage (`pyramidLevel: 1`)
2. **Second signal within 4 hours** → Check same direction + within window + under max levels
3. **If valid** → Add 7x position (`pyramidLevel: 2`, `parentTradeId` = base trade ID)
3. **If valid** → Add 5x position (`pyramidLevel: 2`, `parentTradeId` = base trade ID)
4. **Position Manager** tracks pyramid group via `pyramidGroups` Map
5. **Exit** → Close ALL pyramid levels together via `closeAllPyramidLevels()` (unified exit)
@@ -6424,7 +6433,7 @@ const tracker = new StopHuntTracker() // ❌ Don't do this
- **CURRENT Configuration (Dec 1, 2025):**
```bash
USE_ADAPTIVE_LEVERAGE=true
HIGH_QUALITY_LEVERAGE=10 # 10x for high-quality signals
HIGH_QUALITY_LEVERAGE=5 # 5x for high-quality signals (reduced Jan 30, 2026)
LOW_QUALITY_LEVERAGE=5 # 5x for borderline signals
QUALITY_LEVERAGE_THRESHOLD_LONG=95 # LONG quality threshold (configurable via UI)
QUALITY_LEVERAGE_THRESHOLD_SHORT=90 # SHORT quality threshold (configurable via UI)

View File

@@ -25,10 +25,11 @@
- **Example:** parse_signal_enhanced.json, indicator scripts
### 4. **Environment Variables** (`.env` file)
- **Method:** Edit `.env` → restart container only
- **Command:** `docker compose restart trading-bot`
- **Method:** Edit `.env` → recreate container (NOT restart!)
- **Command:** `docker compose up -d trading-bot`
- **Time:** 5-10 seconds (vs 40-70 seconds for rebuild)
- **Example:** Changing `MIN_SIGNAL_QUALITY_SCORE=91`
- **⚠️ PITFALL:** `docker compose restart` liest .env NICHT neu ein! Die `environment:` Section in docker-compose.yml nutzt `${VAR:-default}` Syntax, die nur bei `up` ausgewertet wird.
### 5. **Database Schema** (`prisma/schema.prisma`)
- **Method:** `npx prisma migrate dev``npx prisma generate` → restart
@@ -43,17 +44,20 @@
---
## ⚠️ Changes That Need Container RESTART Only (10 seconds)
## ⚠️ Changes That Need Container RECREATE Only (10 seconds)
### 1. **Environment Variables**
```bash
# Edit .env file
vim /home/icke/traderv4/.env
# Restart container (NOT rebuild)
docker compose restart trading-bot
# Recreate container (NOT restart! restart does NOT re-read .env)
docker compose up -d trading-bot
# Verify
# Verify env vars are active
docker exec trading-bot-v4 env | grep VARIABLE_NAME
# Check logs
docker logs --tail=30 trading-bot-v4
```
@@ -112,7 +116,7 @@ cd /home/icke/traderv4 && docker compose build trading-bot > /tmp/docker-build-l
|------------|-----------------|----------|---------|
| **Documentation (`.md`)** | None | 0s | `git commit && git push` |
| **Workflows (`.json`, `.pinescript`)** | Manual import | 0s | Update in TradingView/n8n |
| **ENV variables (`.env`)** | Restart | 5-10s | `docker compose restart trading-bot` |
| **ENV variables (`.env`)** | Recreate | 5-10s | `docker compose up -d trading-bot` (NOT restart!) |
| **Database schema** | Migrate + Restart | 10-15s | `prisma migrate + restart` |
| **Code changes (`.ts`, `.tsx`)** | **REBUILD** | 40-70s | `docker compose build + restart` |
| **Dependencies (`package.json`)** | **REBUILD** | 40-70s | `docker compose build + restart` |