Files
mindesbunister dc674ec6d5 docs: Add 1-minute simplified price feed to reduce TradingView alert queue pressure
- Create moneyline_1min_price_feed.pinescript (70% smaller payload)
- Remove ATR/ADX/RSI/VOL/POS from 1-minute alerts (not used for decisions)
- Keep only price + symbol + timeframe for market data cache
- Document rationale in docs/1MIN_SIMPLIFIED_FEED.md
- Fix: 5-minute trading signals being dropped due to 1-minute flood (60/hour)
- Impact: Preserve priority for actual trading signals
2025-12-04 11:19:04 +01:00

220 lines
7.6 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# System Architecture & Design
**Core technical design documentation for Trading Bot v4 autonomous trading system.**
This directory contains architectural decisions, system design patterns, and technical specifications for major system components.
---
## 🏗️ Key Architecture Documents
### **Adaptive Leverage System**
- `ADAPTIVE_LEVERAGE_SYSTEM.md` - **Complete implementation guide**
- Quality-based leverage tiers (10x for ≥95, 5x for 90-94)
- Direction-specific thresholds (LONG ≥95, SHORT ≥90)
- Settings UI with real-time collateral display
- Risk-adjusted position sizing based on signal confidence
- **Status:** ✅ ACTIVE in production (Dec 1, 2025)
### **ATR Trailing Stop System**
- `ATR_TRAILING_STOP_FIX.md` - **Phase 7.3 adaptive trailing enhancement**
- Real-time 1-minute ADX monitoring (not static entry ADX)
- Dynamic trail multipliers: base 1.5× + ADX strength tier + acceleration bonus
- ADX acceleration (+7 points) → 1.3× multiplier
- Profit acceleration (>2%) → additional 1.3× multiplier
- Combined max: 3.16× multiplier for strong trending moves
- **Status:** ✅ DEPLOYED (Nov 27, 2025)
### **Indicator Version Tracking**
- `INDICATOR_VERSION_TRACKING.md` - **TradingView strategy versioning**
- v9: Money Line with MA Gap + Momentum SHORT Filter (PRODUCTION)
- v8: Money Line Sticky Trend (ARCHIVED - 57.1% WR baseline)
- Historical versions (v5-v7) for comparison
- Database field tracking for performance analysis
- **Purpose:** A/B testing and strategy evolution
### **Position Synchronization**
- `POSITION_SYNC_QUICK_REF.md` - **Position Manager sync procedures**
- Startup validation (orphan detection)
- External closure handling
- Ghost position cleanup
- Database-first state management
- **Critical for:** System restarts, container crashes
---
## 🎯 Design Principles
### **1. Database as Source of Truth**
- All state-changing operations write to database FIRST
- In-memory state (Position Manager) is derived from database
- Container restarts restore state from database
- External closures update database before removing from memory
### **2. Dual-Layer Redundancy**
- **Layer 1:** On-chain orders (Drift Protocol TP/SL limit orders)
- **Layer 2:** Software monitoring (Position Manager every 2 seconds)
- If on-chain orders fail, Position Manager executes via market orders
- Both layers track to same database for complete history
### **3. Singleton Pattern Everywhere**
```typescript
// CORRECT: Use getter functions
const driftService = await initializeDriftService()
const positionManager = await getInitializedPositionManager()
const prisma = getPrismaClient()
// WRONG: Never create multiple instances
const driftService = new DriftService() // ❌
```
### **4. Adaptive Systems Over Static Parameters**
- **ATR-based TP/SL:** Adapts to market volatility automatically
- **Adaptive Leverage:** Scales risk with signal quality
- **ADX-based Trailing:** Widens trail during trend acceleration
- **Smart Entry:** Validates price action before execution
### **5. Direction-Specific Configuration**
- LONG signals: Different quality thresholds than SHORT
- SHORT signals: Higher baseline difficulty, lower thresholds
- Momentum filters: Different for LONG (breakout) vs SHORT (reversal)
- Risk management: ADX-based runner SL positioning
---
## 📊 System Components
### **Core Services (Singletons)**
- **DriftService:** Drift Protocol SDK wrapper, WebSocket subscriptions
- **Position Manager:** Software monitoring loop (2-second price checks)
- **Pyth Price Monitor:** Real-time oracle price feeds (WebSocket)
- **Stop Hunt Tracker:** 4-hour revenge window monitoring
- **Blocked Signal Tracker:** 30-minute price tracking for blocked signals
- **Smart Validation Queue:** Pullback confirmation system (30-second checks)
### **Key Workflows**
1. **Trade Execution:** TradingView → n8n → check-risk → execute → database → Position Manager
2. **Exit Management:** Price check → TP/SL trigger → closePosition → database → Telegram notification
3. **Startup Recovery:** Database query → Drift validation → restore Position Manager → resume monitoring
4. **Ghost Detection:** Drift API check → database cleanup → Position Manager removal
### **Data Flow**
```
TradingView Alert (5-min candle)
↓ [Webhook]
n8n Parse Signal Enhanced
↓ [HTTP POST]
/api/trading/check-risk
↓ [Quality score, cooldown, duplicates]
/api/trading/execute
↓ [Market order, TP/SL placement]
Database (Trade table)
↓ [State persistence]
Position Manager (monitoring)
↓ [2-second price checks]
Exit Detection (TP1/TP2/SL/Trailing)
↓ [Market close order]
Database Update (exit details)
↓ [P&L, exit reason, timestamps]
Telegram Notification
```
---
## 🔧 Configuration Architecture
### **Three-Layer Merge Priority**
1. **Per-symbol ENV vars** (highest): `SOLANA_*`, `ETHEREUM_*`
2. **Market config** (code): `SUPPORTED_MARKETS` in config/trading.ts
3. **Global ENV vars** (fallback): `MAX_POSITION_SIZE_USD`, `LEVERAGE`
4. **Default config** (lowest): `DEFAULT_TRADING_CONFIG`
### **Key Configuration Files**
- `config/trading.ts` - Central config with merge logic
- `.env` - Environment variables (482 lines)
- `prisma/schema.prisma` - Database schema
- `.github/copilot-instructions.md` - System documentation (6,400+ lines)
---
## 🚀 Adding New Architecture
**When to Create Architecture Docs:**
- Major system component (Position Manager, Drift client, etc.)
- Risk management system (leverage, stops, entry validation)
- Data flow pattern (TradingView → execution → monitoring)
- Critical decision (database-first vs in-memory, singleton vs multiple instances)
**Template Structure:**
```markdown
# [Component Name]
**Purpose:** [One-line description]
## Architecture Decision
[Why this design was chosen, alternatives considered]
## Implementation
[Code structure, key classes, integration points]
## Data Flow
[How data moves through the component]
## Configuration
[ENV variables, defaults, merge priority]
## Error Handling
[Failure scenarios, recovery procedures]
## Verification
[How to test, expected behaviors, logs to watch]
## Deployment
[Restart requirements, migration steps]
## Lessons Learned
[What worked, what didn't, future improvements]
```
---
## 🔍 Finding Architecture Info
**By Component:**
- Leverage system → `ADAPTIVE_LEVERAGE_SYSTEM.md`
- Trailing stops → `ATR_TRAILING_STOP_FIX.md`
- Indicator versions → `INDICATOR_VERSION_TRACKING.md`
- Position sync → `POSITION_SYNC_QUICK_REF.md`
**By Pattern:**
- Singleton → All architecture docs mention singleton pattern
- Adaptive systems → ATR, Leverage, Trailing Stop docs
- Database-first → Position Sync, all architecture patterns
- Direction-specific → Leverage, Indicator docs
---
## ⚠️ Critical Architecture Constraints
**Real Money System:**
- Every architectural decision affects financial outcomes
- Database integrity is non-negotiable (write FIRST, read to restore)
- Position Manager MUST have TP/SL backup (on-chain orders can fail)
- Container restarts MUST restore full state (database = source of truth)
**Performance Requirements:**
- Position Manager: 2-second monitoring loop (not slower)
- Price feeds: WebSocket real-time (not HTTP polling)
- Order placement: <1 second execution (market orders)
- Database writes: Non-blocking (async, don't wait for confirmation)
**Scalability Limits:**
- Maximum 20 simultaneous positions tracked
- Maximum 10 trades per hour per symbol
- Drift SDK: 50 RPC calls/second burst, 10/second sustained
- PostgreSQL: 10 concurrent connections max
---
See `../README.md` for overall documentation structure.