
    i-                        d Z ddlZddlZddlZddlZddlZddlZddlZddlmZ ddl	m
Z
 ej                  dk(  r]	  ej                  ej                  j                  dd      e_         ej                  ej                  j                  dd      e_         e
e      j$                  j'                         Zed	z  Zed
z  Zedz  Zedz  ZdZdZ G d d      ZddZd Zd Zd Zd Z d Z!d Z"d Z#e$dk(  r e#        yy# e$ r Y pw xY w)uL  
Bot Watchdog - Surveillance et redémarrage automatique du bot
============================================================

Fonctionnalités :
- Vérifie toutes les 60 secondes si le bot est actif
- Redémarre automatiquement le bot s'il crash
- Envoie des alertes en cas de problèmes répétés
- Logs détaillés des incidents
    N)datetime)Pathwin32utf-8replace)encodingerrorszbot.pidzwatchdog.pidzwatchdog.logzwatchdog_status.json<      c                        e Zd ZdZdZdZdZdZy)Colorsz[92mz[93mz[91mz[94mz[0mN)__name__
__module____qualname__GREENYELLOWREDBLUERESET     ./bot_watchdog.pyr   r   (   s    EF
CDEr   r   c                    t        j                         j                  d      }t        j                  t        j
                  t        j                  t        j                  dj                  |t        j                        }d| d| d|  }	 t        | | t        j                   d       	 t!        t"        d
d      5 }|j%                  |dz          ddd       y# t        t        f$ rV |j                  dd	      j                  d      }	 t        | | t        j                   d       n# t        $ r Y nw xY wY w xY w# 1 sw Y   yxY w# t        $ r~ 	 | j                  dd      j                  d      }d| d| d| }t!        t"        d
d      5 }|j%                  |dz          ddd       n# 1 sw Y   nxY wY yY y# t        $ r Y Y yw xY ww xY w)zLog avec timestamp%Y-%m-%d %H:%M:%S)INFOSUCCESSWARNINGERROR[z] [z] T)flushasciir   ar   r   
Nignore)r   nowstrftimer   r   r   r   r   getr   printUnicodeEncodeErrorUnicodeDecodeErrorencodedecode	ExceptionopenWATCHDOG_LOGwrite)	msglevel	timestampcolorlog_linesafef	msg_cleanlog_line_cleans	            r   log_messager;   /   s   ''(;<I<<==	
 
c% 
 9+Sr#/Hz&,,0=
,g6 	%!GGHtO$	% 	%  23 w	299'B	UGD6&,,0= 				% 	% 	

7H5<<WEI 3ugR	{CNlC': /a-./ / / / 		s   !C /E EE 0E!D21E2	D>;E=D>>EEEE E 	G>G	F90	G	9G	>G			GGGGc                      t         j                         r0	 t        t         d      5 } t        j                  |       cddd       S g ddddS # 1 sw Y   nxY w#  Y xY w)zCharger le statut du watchdogrNr   )restartstotal_restarts
last_checklast_restart)WATCHDOG_STATUSexistsr/   jsonload)r8   s    r   load_watchdog_statusrF   P   sk    	os+ $qyy|$ $
 	 	$ $ $	s!   A A	A AA Ac                 ~    t        t        d      5 }t        j                  | |d       ddd       y# 1 sw Y   yxY w)z!Sauvegarder le statut du watchdogw   )indentN)r/   rB   rD   dump)statusr8   s     r   save_watchdog_statusrM   _   s3    	os	# 'q		&!A&' ' 's   3<c                     t         j                         sy	 t        t         d      5 } t        | j	                         j                               }ddd       t        j                        r6t        j                  |      }d|j                         j                         v ryy# 1 sw Y   UxY w# t        t        j                  t        j                  f$ r Y yw xY w)u   Vérifier si le bot est actifFr=   NpythonT)BOT_PID_FILErC   r/   intreadstrippsutil
pid_existsProcessnamelower
ValueErrorNoSuchProcessAccessDenied)r8   pidprocs      r   is_bot_runningr^   d   s     ,$ 	(affhnn&'C	( S!>>#&D499;,,..	( 	( ,,f.A.AB s)   B/ (B#AB/ #B,(B/ /(CCc                     t         dz  dz  } | j                         sy	 t        | dd      5 }|j                         }|s
	 ddd       y|d   j	                         }|rt        j                  |      }|j                  d	d
      }	 t        j                  |d      }t        j                         |z
  j                         }|dkD  r&t        dt        |dz         dd       	 ddd       y	 ddd       y	 ddd       y#  t        j                  |d      }Y ~xY w# 1 sw Y   yxY w# t        $ r}t        d| d       Y d}~yd}~ww xY w)u3   Vérifier si le bot génère des signaux récemment
trade_logszsignals_log.jsonlFr=   r   r#   Nr4    z%Y-%m-%d %H:%M:%S.%fr   iX  u   ⚠️ Aucun signal depuis r
   z minutesr   Tu-   Erreur lors de la vérification d'activité: r   )
SCRIPT_DIRrC   r/   	readlinesrS   rD   loadsr(   r   strptimer&   total_secondsr;   rQ   r.   )	signals_logr8   lines	last_linedatatimestamp_strlast_signal_time	time_diffes	            r   check_bot_activityrp   x   s\   |+.AAK+sW5 	KKME	 	 b	)Izz), $b 9]'/'8'8H^'_$
 &\\^.>>MMO	s?"=c)B,>O=PPX Y[de +	 	. /	 	 	 	]'/'8'8H['\$	 	0  CA3GQsk   D* DD* 
<DDAD$D* -D.D* 8D* DDD'#D* 'D* *	E3EEc            
         t        dd       	 t        j                  dk(  rt        dz  dz  dz  } nt        dz  dz  dz  } | j	                         rt        |       }nt        j                  }t        d	z  }|j	                         st        d
d       yd}d}t        j                  dk(  rbt        j                  |t        |      g||z  t        j                  t        j                  t        j                  t        t              d      }n]t        j                  |t        |      gt        j                  t        j                  t        j                  t        t              d      }t        d|j                   dd       t        j                  d       t               rt        dd       yt        dd       y# t         $ r}t        d| d       Y d}~yd}~ww xY w)u   Démarrer le botu$   🚀 Démarrage du bot de trading...r   r   z.venvScriptsz
python.exebinpython3ztrading_bot.pyu   ❌ trading_bot.py non trouvé!r   Fi      ntT)creationflagsstdoutstderrstdincwdstart_new_session)rx   ry   rz   r{   r|   u   Bot lancé (processus: )   u   ✅ Bot démarré avec succèsr   uC   ❌ Échec du démarrage du bot (PID non créé ou crash immédiat)u   ❌ Erreur lors du démarrage: N)r;   sysplatformrc   rC   str
executableosrW   
subprocessPopenDEVNULLr\   timesleepr^   r.   )venv_python
python_exe
bot_scriptCREATE_NO_WINDOWDETACHED_PROCESSprocessro   s          r   	start_botr      s   6?7<<7"$w.:\IK$w.6BK[)JJ"22
  "97C &%77d? &&S_-.1AA!))!)) ((
O"&G !&&S_-!))!)) ((
O"&G 	-gkk]!<fE 	

28)D]_fg 5aS97Cs%   BF; DF; .F; ;	GGGc                     t        j                         }| d   D cg c]-  }|t        j                  |      z
  j                         dk  r|/ }}t	        |      t
        k\  r&t        dt	        |       dd       t        dd       yt        dd	       t        j                         r	 t        t        d
      5 }t        |j                         j                               }ddd       t        j                        rZt        j                  |      }|j!                          t#        j$                  d       |j'                         r|j)                          t+        j,                  t               t1               rN| d   j3                  |j5                                | dxx   dz  cc<   |j5                         | d<   t7        |        yyc c}w # 1 sw Y   xY w# t.        $ r}t        d| d	       Y d}~d}~ww xY w)u&   Redémarrer le bot avec vérificationsr>   i  u$   🛑 ALERTE: Trop de redémarrages (u   ) dans la dernière heurer   uK   Le bot semble avoir un problème récurrent. Intervention manuelle requise.Fu   🔄 Redémarrage du bot...r   r=   NrI   u&   Erreur lors de l'arrêt du processus: r?      rA   T)r   r&   fromisoformatrg   lenMAX_RESTARTS_PER_HOURr;   rP   rC   r/   rQ   rR   rS   rT   rU   rV   	terminater   r   
is_runningkillr   remover.   r   append	isoformatrM   )rL   r&   r=   recent_restartsr8   r\   r]   ro   s           r   restart_botr      s   
,,.C *%(((++::<tC 	
O 
 ?44233G2HHab	
 	acjk-y9 	QlC( ,A!&&(..*+,   %~~c* 

1??$IIKIIl#
 {z!!#--/2 A% !$~V$Q$, ,  	Q@DiPP	Qs6   2G
)G 9(G!BG GG 	G=$G88G=c                  b   	 t        t        d      5 } | j                  t        t	        j
                                      ddd       t        dt	        j
                          d       t        dd       t        dd	       t        dd       t               }d
}d
}	 	 	 t        j                         j                         |d<   t               rt        dd	       d
}d
}n4|dz  }t        d| dd       |dk\  rt        |      rd
}nt        dd       t        |       t        j                   t"               # 1 sw Y   xY w# t        $ r}t        d| d       Y d}~d}~ww xY w# t        $ r]}|dz  }t        d| d| d       |dk\  rt        d| dd       t        dd       d
}t        j                   t"               Y d}~d}~ww xY w# t$        $ r t        dd       Y nBt        $ r7}t        d| d       d
dl}t        |j)                         d       Y d}~nd}~ww xY w	 t        j+                         rt	        j,                  t               t        dd       y#  Y yxY w# 	 t        j+                         rt	        j,                  t               t        dd       w #  Y w xY wxY w)zBoucle principale du watchdogrH   NzWatchdog PID: r   u*   ⚠️ Impossible d'écrire watchdog.pid: r   z<============================================================zBot Watchdog demarrer   r   r@   z	Bot actifr   zBot inactif (tentative r}   r   rI   u$   ⛔ Impossible de redémarrer le botzErreur dans check (#z): r   z
CRITIQUE: z* erreurs consecutives - Watchdog instable!zTentative de recuperation...z!Watchdog arrete par l'utilisateurzERREUR FATALE WATCHDOG: u   Watchdog arrêté proprement)r/   WATCHDOG_PID_FILEr1   r   r   getpidr;   r.   rF   r   r&   r   r^   r   rM   r   r   CHECK_INTERVALKeyboardInterrupt	traceback
format_excrC   r   )r8   ro   rL   consecutive_failureserror_countr   s         r   mainr   	  s   Q#S) 	&QGGC		$%	&nRYY[M2F; &!&	2&!!#FK4#+'/||~'?'?'A|$ "#Y7+,("#K(A-("9:N9Oq QSZ[ ,q0&v.340'(NPWX %V, 

>*1 	& 	&  Q@DiPPQL  
+q 2;-s1#FP !#*[M9c dfmn >	J"#K

>**
+  D7C 5.qc2G<I((*G445	 '')		+,6?		 '')		+,6?	s   E -D6)E G BE' 5G 6D?;E 	E$EE$'	G0AGG GG H&%I+ 'H&/-H!I+ !H&&I+ *9I$ $I(+J.-9J'&J.'J+)J.__main__)r   )%__doc__r   r   ior   rD   r   rT   r   pathlibr   r   TextIOWrapperrx   bufferry   AttributeError__file__parentabsoluterc   rP   r   r0   rB   r   r   r   r;   rF   rM   r^   rp   r   r   r   r   r   r   r   <module>r      s0  	 
 
 	       <<7%R%%cjj&7&7'R[\
%R%%cjj&7&7'R[\

 (^""++-
I%/ N*55  B'
(#J;z-^FP zF k	  s   AD   DD