# 🤖 SYSTÈME AUTONOME - GUIDE COMPLET

## ✅ SYSTÈME OPÉRATIONNEL

Votre bot de trading est maintenant **100% autonome** avec surveillance et redémarrage automatiques.

---

## 🚀 DÉMARRAGE RAPIDE

### Option 1: Démarrage Manuel (Session Actuelle)
```batch
START_AUTONOME.bat
```
✅ Déjà fait! Le système est actuellement actif.

### Option 2: Installation Permanente (Démarrage Automatique au Boot)
```powershell
# Exécuter en tant qu'administrateur:
powershell -ExecutionPolicy Bypass -File "install_autonomous_service.ps1"
```

**Résultat:** Le bot se lancera automatiquement à chaque démarrage de Windows.

---

## 📊 SURVEILLANCE

### Dashboard en Temps Réel
- **URL:** http://localhost:8889
- **Bannière de statut:** Affiche l'état de surveillance en temps réel
  - 🟢 **Vert:** Bot actif et surveillé (OPTIMAL)
  - 🟠 **Orange:** Bot actif sans surveillance (RISQUÉ)
  - 🔴 **Rouge:** Bot inactif (PROBLÈME)
- **Rafraîchissement:** Automatique toutes les 10 secondes

### API de Statut
```bash
GET http://localhost:8889/api/watchdog-status
```

**Réponse:**
```json
{
  "watchdog_active": true,
  "bot_active": true,
  "bot_uptime": "2m 15s",
  "watchdog_uptime": "3m 42s",
  "status": "ok",
  "message": "✅ Système autonome opérationnel"
}
```

---

## 🐕 WATCHDOG (SURVEILLANCE)

### Fonctionnement
- **Fréquence:** Vérifie toutes les 60 secondes
- **Détection:** 2 vérifications échouées consécutives = redémarrage
- **Délai de réaction:** 120 secondes maximum
- **Protection:** Maximum 5 redémarrages par heure

### Logs
```bash
watchdog.log
```

**Exemple de redémarrage automatique:**
```
[11:17:52] [SUCCESS] 🐕 Bot Watchdog démarré
[11:17:52] [ERROR] ❌ Bot inactif (tentative 1)
[11:18:52] [ERROR] ❌ Bot inactif (tentative 2)
[11:18:52] [WARNING] 🔄 Redémarrage du bot...
[11:18:52] [INFO] 🚀 Démarrage du bot de trading...
[11:18:52] [INFO] Bot lancé (processus: 4732)
[11:19:02] [SUCCESS] ✅ Bot démarré avec succès
```

---

## 🔧 COMPOSANTS DU SYSTÈME

### 1. Trading Bot (`trading_bot.py`)
- **Fonction:** Trading automatique
- **PID:** Enregistré dans `bot.pid`
- **Logs:** `trading_bot.log`

### 2. Watchdog (`bot_watchdog.py`)
- **Fonction:** Surveillance et redémarrage automatique
- **Cycle:** 60 secondes
- **Logs:** `watchdog.log`

### 3. Dashboard API (`dashboard_api_server.py`)
- **Fonction:** Interface web + API REST
- **Port:** 8889
- **Logs:** `dashboard_log.txt`

### 4. Auto-Updater (`auto_updater_service.py`)
- **Fonction:** Mises à jour automatiques
- **Cycle:** Selon configuration
- **Logs:** Intégrés au bot

---

## 🛠️ COMMANDES UTILES

### Vérifier le Statut
```powershell
Get-Process python | Where-Object { $_.CommandLine -match "trading_bot|watchdog|dashboard" }
```

### Voir les Logs en Temps Réel
```powershell
Get-Content watchdog.log -Wait -Tail 20
Get-Content trading_bot.log -Wait -Tail 20
```

### Arrêter le Système
```powershell
Get-Process python | Where-Object { 
    $cmd = (Get-CimInstance Win32_Process -Filter "ProcessId = $($_.Id)").CommandLine
    $cmd -match "crypto_trading_bot"
} | Stop-Process -Force
```

### Redémarrer le Système
```batch
START_AUTONOME.bat
```

---

## 🎯 SCÉNARIOS GÉRÉS AUTOMATIQUEMENT

### ✅ Bot Crashe
- **Détection:** Watchdog détecte en 120s maximum
- **Action:** Redémarrage automatique
- **Notification:** Log dans `watchdog.log`

### ✅ Python Error
- **Détection:** Watchdog détecte processus absent
- **Action:** Relance avec environnement virtuel
- **Limite:** 5 tentatives/heure

### ✅ Windows Redémarre (avec service installé)
- **Détection:** Tâche planifiée se déclenche
- **Action:** Lancement automatique au boot
- **Vérification:** Check horaire de sécurité

### ✅ Dashboard Inaccessible
- **Détection:** Banner orange sur dashboard
- **Action:** Vérifier logs, relancer si nécessaire
- **API:** Continue de fonctionner même si dashboard crash

---

## 📈 HISTORIQUE DES AMÉLIORATIONS

### Problème Initial
- Bot s'arrêtait sans surveillance (ex: 9h20, opportunité ETH +0.49% manquée)
- Aucun système de redémarrage automatique
- Nécessitait intervention manuelle constante

### Solution Implémentée (18/01/2026)
1. ✅ Watchdog intégré dans `Reset_trading.py`
2. ✅ Correction de `bot_watchdog.py` (lance `trading_bot.py` directement)
3. ✅ API `/api/watchdog-status` pour monitoring temps réel
4. ✅ Banner dashboard avec indicateur visuel
5. ✅ `START_AUTONOME.bat` pour démarrage simplifié
6. ✅ `install_autonomous_service.ps1` pour installation permanente

### Résultat
- 🟢 **Autonomie:** 100% - aucune intervention manuelle requise
- 🟢 **Fiabilité:** Redémarrage automatique en cas de crash
- 🟢 **Visibilité:** Monitoring temps réel via dashboard
- 🟢 **Pérennité:** Survit aux redémarrages Windows (avec service)

---

## ⚠️ POINTS D'ATTENTION

### Fichiers PID
Les fichiers `.pid` peuvent parfois ne pas se créer immédiatement au démarrage.
- **Normal:** Délai de 30-60 secondes
- **Problème:** Si absent après 2 minutes
- **Solution:** Le watchdog détecte et corrige automatiquement

### Processus Multiples
Si plusieurs instances du bot apparaissent:
```powershell
# Arrêter tous les processus Python du bot
Get-Process python | Where-Object { 
    $cmd = (Get-CimInstance Win32_Process -Filter "ProcessId = $($_.Id)").CommandLine
    $cmd -match "crypto_trading_bot"
} | Stop-Process -Force

# Nettoyer les PID
Remove-Item bot.pid, watchdog.pid, dashboard_api.pid -ErrorAction SilentlyContinue

# Relancer
.\START_AUTONOME.bat
```

### Limites du Watchdog
- **Maximum 5 redémarrages/heure:** Évite les boucles infinies
- **Si limite atteinte:** Vérifier `trading_bot.log` pour erreurs critiques
- **Reset manuel:** Arrêter watchdog, corriger problème, relancer

---

## 🎓 POUR ALLER PLUS LOIN

### Personnaliser le Watchdog
Éditer `bot_watchdog.py`:
```python
CHECK_INTERVAL = 60  # Secondes entre chaque vérification
MAX_RETRIES = 2      # Échecs avant redémarrage
MAX_RESTARTS_PER_HOUR = 5  # Limite de sécurité
```

### Notifications
Ajouter notifications par email/Telegram en cas de redémarrage:
```python
# Dans bot_watchdog.py, fonction restart_bot()
if restart_successful:
    send_notification("✅ Bot redémarré automatiquement")
```

### Logs Détaillés
Augmenter verbosité dans `config.py`:
```python
LOG_LEVEL = "DEBUG"  # Pour plus de détails
```

---

## 📞 SUPPORT

### Logs à Vérifier en Cas de Problème
1. `watchdog.log` - État de la surveillance
2. `trading_bot.log` - Erreurs du bot
3. `dashboard_log.txt` - API et dashboard
4. Windows Event Viewer - Tâche planifiée (si installée)

### Commande de Diagnostic
```powershell
# Tout-en-un
Write-Output "=== DIAGNOSTIC COMPLET ===" 
Get-Content watchdog.log -Tail 10
Get-Content trading_bot.log -Tail 10
Get-Process python | Where { $_.CommandLine -match "trading_bot|watchdog" }
```

---

## 🏆 STATUT ACTUEL (18/01/2026 11:20)

✅ **Système 100% opérationnel**
- Bot: ACTIF (PID: 4732, 19536)
- Watchdog: ACTIF (PID: 24924, 20220)
- Dashboard: ACTIF (http://localhost:8889)
- API Surveillance: ACTIF
- Auto-Updater: ACTIF

🎯 **Prochaine Étape Recommandée:**
```powershell
# Installation permanente (exécuter en admin)
powershell -ExecutionPolicy Bypass -File "install_autonomous_service.ps1"
```

**Résultat attendu:** Bot se lance automatiquement à chaque démarrage Windows, surveillance 24/7 sans intervention.

---

*Documentation créée le 18/01/2026 - Système Autonome v1.0*
