Files
Place-Order-Trading-Bot/DRAWDOWN_PROTECTION_SETUP.md
T

378 lines
8.7 KiB
Markdown

# 🛡️ Drawdown Protection - Installation & Usage
## Was macht Drawdown Protection?
Das System **pausiert automatisch den Trading Bot**, wenn:
- ✅ Tagesverlust $100 überschreitet
- ✅ Wochenverlust $300 überschreitet
- ✅ Monatsverlust $800 überschreitet
- ✅ 5 Verluste hintereinander auftreten
**Vorteil:** Schützt dein Konto vor Overtrading in schlechten Marktphasen!
---
## 🚀 Installation (im Notebook)
### Schritt 1: Nach Infrastructure Setup (Cell ~8)
Füge eine neue Cell hinzu:
```python
# ==========================================
# DRAWDOWN PROTECTION SETUP
# ==========================================
from drawdown_protection import DrawdownProtection, create_protected_trading_check, print_protection_status
print("🛡️ Initializing Drawdown Protection...")
# Erstelle Drawdown Protection
drawdown_protection = DrawdownProtection(
database=infra.db,
telegram=infra.telegram,
max_daily_loss=100, # $100 pro Tag
max_weekly_loss=300, # $300 pro Woche
max_monthly_loss=800, # $800 pro Monat
max_consecutive_losses=5,
cooldown_hours=24 # 24h Pause nach Limit-Trigger
)
print("✅ Drawdown Protection aktiviert!")
print(f" Max Daily Loss: ${drawdown_protection.max_daily_loss}")
print(f" Max Weekly Loss: ${drawdown_protection.max_weekly_loss}")
print(f" Max Monthly Loss: ${drawdown_protection.max_monthly_loss}")
print(f" Max Consecutive Losses: {drawdown_protection.max_consecutive_losses}")
print(f" Cooldown: {drawdown_protection.cooldown_hours} hours")
```
### Schritt 2: Trading Check Wrapping (NACH Session Filter Setup)
**WICHTIG:** Diese Cell muss NACH dem Session Filter Setup kommen!
Ersetze oder füge hinzu:
```python
# ==========================================
# PROTECTED TRADING CHECK
# ==========================================
# Wrapper um trading_check (fügt Drawdown Protection hinzu)
original_trading_check = trading_check
trading_check = create_protected_trading_check(infra, original_trading_check)
print("✅ Trading Check ist jetzt geschützt durch Drawdown Protection!")
print(" Bot wird automatisch pausiert bei:")
print(" • Tagesverlust > $100")
print(" • Wochenverlust > $300")
print(" • Monatsverlust > $800")
print(" • 5 Verluste in Folge")
```
### Schritt 3: Status Check (Optional - neue Cell)
```python
# ==========================================
# DRAWDOWN PROTECTION STATUS
# ==========================================
print_protection_status(drawdown_protection)
```
---
## ✅ Verifikation
Nach Notebook Restart (`Kernel → Restart & Run All`):
### Test 1: Protection ist aktiv
```python
# Sollte ausgeben:
can_trade, reason = drawdown_protection.can_trade()
print(f"Can trade: {can_trade}, Reason: {reason}")
# Erwartung: Can trade: True, Reason: OK
```
### Test 2: Status anzeigen
```python
print_protection_status(drawdown_protection)
# Sollte aktuellen Status zeigen
```
### Test 3: Trading Check läuft
```python
# Führe manuell aus:
trading_check()
# Sollte normal funktionieren (wenn Limits nicht erreicht)
```
---
## 🎯 Wie funktioniert es?
### Automatischer Schutz:
**Szenario 1: Tagesverlust > $100**
```
1. Bot macht $100 Verlust an einem Tag
2. Drawdown Protection erkennt Limit
3. Trading wird pausiert für 24h
4. Telegram Notification: "🛑 Trading paused - Daily loss limit"
5. Nach 24h: Automatische Fortsetzung
```
**Szenario 2: 5 Verluste in Folge**
```
1. Bot hat 5 losing trades hintereinander
2. Protection pausiert Trading für 24h
3. Telegram: "🛑 Too many consecutive losses"
4. Zeit zum Review der Strategie
```
**Szenario 3: Wochenverlust > $300**
```
1. Kumulierter Verlust diese Woche > $300
2. Pause für 48h (2x cooldown)
3. Zeit für ausführliche Analyse
```
---
## 🔧 Konfiguration anpassen
### Limits ändern:
```python
# Konservativer (weniger Risk):
drawdown_protection = DrawdownProtection(
database=infra.db,
telegram=infra.telegram,
max_daily_loss=50, # $50/Tag
max_weekly_loss=150, # $150/Woche
max_monthly_loss=400, # $400/Monat
max_consecutive_losses=3,
cooldown_hours=24
)
```
```python
# Aggressiver (mehr Risk):
drawdown_protection = DrawdownProtection(
database=infra.db,
telegram=infra.telegram,
max_daily_loss=200, # $200/Tag
max_weekly_loss=500, # $500/Woche
max_monthly_loss=1500, # $1500/Monat
max_consecutive_losses=7,
cooldown_hours=12
)
```
### Empfohlene Settings nach Account Size:
| Account | Daily | Weekly | Monthly | Consec |
|---------|-------|--------|---------|--------|
| $1,000 | $20 | $60 | $150 | 3 |
| $5,000 | $100 | $300 | $800 | 5 |
| $10,000 | $200 | $600 | $1,600 | 5 |
| $50,000 | $500 | $1,500 | $4,000 | 7 |
**Faustregel:** Max Daily Loss = 2% vom Account
---
## 🎮 Manuelle Kontrolle
### Trading manuell pausieren:
```python
# In Jupyter Notebook Cell:
drawdown_protection.force_pause("Manual review needed", hours=12)
```
**Telegram Notification:**
```
🛑 TRADING PAUSED
Reason: Manual review needed
Duration: 12 hours
Resume at: 2025-12-06 20:00
```
### Trading manuell fortsetzen:
```python
drawdown_protection.force_resume()
```
**Telegram Notification:**
```
✅ TRADING RESUMED
Previous pause reason: Manual review needed
Time: 2025-12-06 08:00
```
---
## 📊 Status überwachen
### Im Notebook:
```python
# Schneller Check:
print_protection_status(drawdown_protection)
```
**Ausgabe:**
```
======================================================================
🛡️ DRAWDOWN PROTECTION STATUS
======================================================================
✅ Trading ALLOWED
📊 Current Losses:
Daily: $45.20 / $100.00
Weekly: $123.50 / $300.00
Monthly: $456.80 / $800.00
📉 Consecutive Losses: 2 / 5
======================================================================
```
### Programmatisch:
```python
status = drawdown_protection.get_status()
print(f"Trading allowed: {status['trading_allowed']}")
print(f"Daily loss: ${status['daily_loss']:.2f}")
print(f"Consecutive losses: {status['consecutive_losses']}")
```
---
## ⚠️ Was passiert bei Pause?
### Während einer Pause:
1. **Kein neuer Entry:**
- `can_trade()` gibt `False` zurück
- Trading Check wird übersprungen
- Keine neuen Positionen
2. **Offene Positionen:**
- ✅ Bleiben offen
- ✅ Position Monitor läuft weiter
- ✅ Exits werden normal tracked
- ✅ SL/TP funktionieren
3. **Notifications:**
- ✅ Telegram Alert bei Pause
- ✅ Telegram Alert bei Resume
- ✅ Logs in Jupyter
### Nach Pause-Ende:
- ✅ Trading automatisch fortgesetzt
- ✅ Neue Entries möglich
- ✅ Normal Operation
---
## 🔍 Troubleshooting
### Problem 1: Protection blockiert immer
**Check:**
```python
status = drawdown_protection.get_status()
print(status)
```
**Lösung:** Limits zu niedrig? → Erhöhe max_daily_loss
### Problem 2: Protection greift nicht
**Check:**
```python
# Ist Protection integriert?
print(hasattr(trading_check, 'protection'))
# Sollte True sein
```
**Lösung:** Stelle sicher dass `create_protected_trading_check()` aufgerufen wurde
### Problem 3: Falsche Verlust-Berechnung
**Check:**
```python
daily_loss = drawdown_protection._get_loss_today()
print(f"Daily loss: ${daily_loss:.2f}")
```
**Lösung:** Prüfe ob Exit-Daten in DB korrekt sind
---
## 💡 Best Practices
### DO:
- ✅ Setze Limits auf ~2% vom Account (Daily)
- ✅ Überwache Status täglich
- ✅ Nutze manuell Pause bei Unsicherheit
- ✅ Review nach automatischer Pause
### DON'T:
- ❌ Limits zu hoch (kein Schutz)
- ❌ Limits zu niedrig (zu viele Pausen)
- ❌ Manuell Resume ohne Analyse
- ❌ Ignoriere Pause-Notifications
---
## 📈 Integration mit Dashboard
Das Drawdown Protection Status kann ins Dashboard integriert werden:
```python
# In trading_dashboard.py (optional):
if hasattr(trading_check, 'protection'):
status = trading_check.protection.get_status()
if not status['trading_allowed']:
st.error(f"🛑 Trading Paused: {status['pause_reason']}")
else:
st.success("✅ Trading Active")
# Progress bars
st.progress(status['daily_loss'] / status['daily_limit'])
st.caption(f"Daily: ${status['daily_loss']:.2f} / ${status['daily_limit']:.2f}")
```
---
## ✅ Zusammenfassung
**Was hast du jetzt:**
- ✅ Automatischer Schutz vor übermäßigen Verlusten
- ✅ Multi-Level Limits (Daily/Weekly/Monthly)
- ✅ Consecutive Loss Protection
- ✅ Telegram Notifications
- ✅ Manuelle Kontrolle
- ✅ Automatisches Resume
**Deployment:**
1. Upload `drawdown_protection.py` auf VPS
2. Füge 2-3 Cells ins Notebook ein
3. Restart Notebook
4. Fertig! 🎉
**Nächste Schritte:**
- Teste mit ersten Trades
- Überwache Status
- Passe Limits nach Bedarf an
---
**Status:** ✅ Ready for Production!