
    i
7                        d Z ddlZddlmZmZmZmZ ddlmZmZ ddl	Z	ddl
Z
ddlmZmZ ddlmZ ddlmZmZ  ej&                  ej(                          ej*                  d	      Z G d
 d	      ZdadefdZedk(  r	  ed        ed        ed        e       Z ed       g dZg dZej?                  deedd      \  Z Z! ede         e!r* ede!jD                           ede!jF                           ed       g dZ$ej?                  dee$dd      \  Z Z! ede         e!r* ede!jJ                           ede!jF                           ed       ejM                           ed       yy) uU  
FreqAI Integration Module
Module d'intégration des améliorations inspirées de FreqAI

Fonctionnalités:
1. Auto-retraining adaptatif (toutes les 48h ou si performances faibles)
2. Outlier detection (pumps artificiels, flash crashes)
3. Backtesting adaptatif (simulation réaliste avec retraining)

Intégration dans trading_bot.py:
    from freqai_integration import FreqAIManager
    
    freqai = FreqAIManager()
    
    # Dans trading_loop():
    if freqai.should_check_outliers(symbol, prices, volumes):
        skip_trade = True
    
    # Toutes les heures:
    freqai.periodic_check()
    N)DictListTupleOptional)datetime	timedelta)get_outlier_detectorOutlierAnalysis)get_adaptive_retrainer)AdaptiveBacktestercompare_adaptive_vs_classic)levelFreqAIManagerc                       e Zd ZdZ	 	 	 ddededefdZ	 	 	 ddedee	   d	ee	   d
e
e	   de
e	   dedeee
e   f   fdZdedee	   d	ee	   defdZde
e   fdZ	 	 ddededee   de	dedefdZdefdZd Zy)r   u   
    Gestionnaire central des fonctionnalités FreqAI
    
    Orchestrate:
    - Outlier detection
    - Auto-retraining
    - Backtesting adaptatif
    enable_outlier_detectionenable_auto_retrainingretraining_check_interval_hoursc                    || _         || _        || _        |r
t               nd| _        |r
t               nd| _        d| _        d| _        d| _	        t        j                  d       t        j                  d       t        j                  d       t        j                  d|rdnd        t        j                  d|rdnd        t        j                  d	| d
       y)u   
        Args:
            enable_outlier_detection: Activer la détection d'outliers
            enable_auto_retraining: Activer le retraining automatique
            retraining_check_interval_hours: Intervalle entre vérifications retraining
        Nr   <============================================================u   🚀 FreqAI Manager initialiséu      • Outlier Detection: u   ✅ ONu   ❌ OFFu      • Auto-Retraining: u      • Check Interval: h)enable_outliersenable_retrainingcheck_intervalr	   outlier_detectorr   	retrainerlast_retraining_checkoutliers_detectedoutliers_blockedloggerinfo)selfr   r   r   s       5/home/ubuntu/crypto_trading_bot/freqai_integration.py__init__zFreqAIManager.__init__1   s      8!7= ;S 4 6X\5K/1QU &*"!" !F56F0=U[d0efg.;QxW`.abc-.M-NaPQ    Nsymbolpricesvolumesrsibb_positionblock_on_outlierreturnc                    | j                   r| j                  y	 | j                  j                  |||||      }| xj                  dz  c_        |j                  r| xj
                  dz  c_        t        j                  d| d       t        j                  d|j                          t        j                  d|j                          t        j                  d	|j                  d
       t        j                  d|j                  d       |rd|fS d|fS # t        $ r%}t        j                  d| d|        Y d}~yd}~ww xY w)u  
        Vérifier si les données sont des outliers
        
        Args:
            symbol: Symbole crypto
            prices: Historique des prix
            volumes: Historique des volumes
            rsi: RSI actuel
            bb_position: Position Bollinger
            block_on_outlier: Si True, retourne True pour bloquer le trade
        
        Returns:
            (should_block_trade, outlier_analysis)
        N)FNr%   r&   r'   r(   r)      u   🚫 OUTLIER détecté sur :      • Méthode:       • Raison: u      • Confidence: .2%u      • Score: .2fTFu!   ❌ Erreur outlier detection sur : )r   r   detect_outlierr   
is_outlierr   r   warningmethodreason
confidencescore	Exceptionerror)	r!   r%   r&   r'   r(   r)   r*   analysises	            r"   should_check_outliersz#FreqAIManager.should_check_outliersO   s9   * ##t'<'<'D	,,;;' < H ""a'"""%%*%!<VHAFG!28??2CDE0ABC!4X5H5H4MNOs/CDE#>)(?" 	LL<VHBqcJK	s   C>D D 	E'EEc                    | j                   r| j                  y	 | j                  j                  |||      \  }}|rt        j	                  d| d|        |S # t
        $ r"}t        j                  d|        Y d}~yd}~ww xY w)uj   
        Détecter un pump&dump
        
        Returns:
            True si pump&dump détecté
        NF)r%   r&   r'   u   🚨 PUMP&DUMP détecté sur r4   u    ❌ Erreur pump&dump detection: )r   r   detect_pump_dumpr   r7   r<   r=   )r!   r%   r&   r'   is_pumpr9   r?   s          r"   check_pump_dumpzFreqAIManager.check_pump_dump   s     ##t'<'<'D	"33DD E OGV !>vhbQRN 	LL;A3?@	s   ?A 	B$BBc                    | j                   r| j                  yt        j                         }| j                  )|| j                  z
  }|t        | j                        k  ry|| _        	 t        j                  d       | j                  j                         }|6t        j                  d       |j                  dd      }|dk(  r)t        j                  d|j                  d	d
              nt        j                  d       t        j                  d       t        j                  d|        t        j                  d|j                  dd      dd       |j                  di       }|j                         D cg c]
  \  }}|s	| }}}|r't        j                  ddj                  |              t        j                  d       |S c c}}w # t        $ r"}	t        j                  d|	        Y d}	~	yd}	~	ww xY w)u   
        Vérification périodique (retraining)
        
        À appeler toutes les heures dans trading_loop()
        
        Returns:
            Résultats du retraining si exécuté, None sinon
        N)hoursu,   🔍 Vérification retraining périodique...r   statusUNKNOWNFAILEDu   ⚠️ RETRAINING ÉCHOUÉ: r9   NO_DATAu   ✅ RETRAINING EFFECTUÉ      • Statut: u      • Durée: durationr   z.1fsresultsu      • Modèles: z, u%   ❌ Erreur vérification retraining: )r   r   r   nowr   r   r   r   r    check_and_retraingetitemsjoinr<   r=   )
r!   rO   elapsedrN   rG   sub_resultskvmodelsr?   s
             r"   periodic_checkzFreqAIManager.periodic_check   s    %%)? lln%%1D666G)<)<==%("	KKFGnn668G"F# Xy9X%KK">w{{8U^?_>` abKK :;F#ofX67ogkk*a.H-MQOP%kk)R8(3(9(9(;A1q!AAKK"3DIIf4E3F GHF#N B  	LL@DE	s2   +DG 
GGAG G 	H$HH
start_dateend_datesymbolsinitial_capitalretrain_interval_daysc                 R   	 t         j                  d       t         j                  d       t         j                  d       t         j                  d|j                          d|j                                 t         j                  dt        |              t         j                  d| d       t         j                  d| d	       t         j                  d       t	        ||
      }|j                  |||      }t         j                  d       t         j                  d       t         j                  d       t         j                  d|j                          t         j                  d|j                  d       t         j                  d|j                  dd|j                  |z  dd       t         j                  d|j                  d       t         j                  d|j                  d       t         j                  d|j                  d       t         j                  d|j                  d       t         j                  d       ||j                         |j                         ||dS # t        $ r}t         j                  d|         d}~ww xY w)un  
        Lancer un backtest adaptatif
        
        Args:
            start_date: Date de début
            end_date: Date de fin
            symbols: Liste des symboles à tester
            initial_capital: Capital initial
            retrain_interval_days: Intervalle de retraining (jours)
        
        Returns:
            Résultats du backtest
        r   u!   🧪 LANCEMENT BACKTEST ADAPTATIFu      • Période: u    → u      • Symboles: u      • Capital: z USDTu      • Retraining: tous les z jours)r]   r^   )rZ   r[   r\   =
============================================================u   📊 RÉSULTATS BACKTESTu      • Total Trades: u      • Win Rate: r2   u      • Net Profit: z+.2fz USDT (z+.2%)u      • Profit Factor: r3   u      • Max Drawdown: u      • Sharpe Ratio: u      • Sortino Ratio: )metricsrZ   r[   r\   r]   u   ❌ Erreur backtest: N)r   r    datelenr   runtotal_tradeswin_rate
net_profitprofit_factormax_drawdownsharpe_ratiosortino_ratio	isoformatr<   r=   )	r!   rZ   r[   r\   r]   r^   
backtesterrb   r?   s	            r"   run_backtestzFreqAIManager.run_backtest   sA   &+	KKKK;<KKKK+JOO,=+>eHMMOCTUVKK+CL>:;KK*?*;5ABKK67L6MVTUKK+ /&;J
 !nn%! % G KK&KK23KKKK/0D0D/EFGKK+G,<,<S+ABCKK-g.@.@-FggN`N`apNpquMvvwxyKK01F1Fs0KLMKK/0D0DS/IJKKK/0D0DS/IJKKK01F1Fs0KLMKK #(224$..0"#2   	LL045	s   I<I? ?	J&J!!J&c                 .   | j                   | j                  | j                  | j                  dkD  r| j                  | j                  z  ndd| j                  | j                  r| j                  j                         nd| j                  dd}| j                  rz| j                  n|d   j                  | j                  j                  r$| j                  j                  j                         ndt        | j                  j                        d       |S )zv
        Obtenir les statistiques du manager
        
        Returns:
            Statistiques d'utilisation
        r   )enabledtotal_checksr   
block_rateN)rq   
last_checkcheck_interval_hours)outlier_detectionauto_retrainingrw   )last_retraintotal_retrains)r   r   r   r   r   rm   r   r   updaterx   rd   retrain_history)r!   statss     r"   	get_statszFreqAIManager.get_stats  s      // $ 6 6$($9$9PTPfPfijPjd33d6L6LLpq	"  11HLHbHbd88BBDhl(,(;(; 
 !!dnn&@#$++KO>>KfKf ; ; E E Glp"%dnn&D&D"E- 
 r$   c                 d   | j                         }t        d       t        d       t        d       |d   }t        d       t        d|d   rdnd	        |d   r4t        d
|d           t        d|d           t        d|d   d       |d   }t        d       t        d|d   rdnd	        |d   rlt        d|d    d       t        d|j                  dd              t        d|j                  dd              t        d|j                  dd              t        d       y)zAfficher les statistiquesr`   u"   📊 FreqAI Manager - Statistiquesr   rv   u   
🔍 Outlier Detection:rK   rq   u   ✅ Activéu   ❌ Désactivéu      • Total checks: rr   u      • Outliers bloqués: r   u      • Taux de blocage: rs   r2   rw   u   
🔄 Auto-Retraining:u      • Intervalle: ru   r   u      • Dernière vérif: rt   Jamaisu      • Dernier retrain: rx   u      • Total retrains: ry   r   N)r}   printrQ   )r!   r|   odars       r"   print_statszFreqAIManager.print_stats-  sL    m23f &')+IDUVWXi=)"^*<)=>?.r2D/E.FGH,R-=c,BCD $%')IDUVWXi='+A(B'C1EF-bff\8.L-MNO,RVVNH-M,NOP+BFF3CQ,G+HIJfr$   )TTr.   )NNT)'     )__name__
__module____qualname____doc__boolintr#   strr   floatr   r   r
   r@   rD   r   rY   r   ro   r}   r    r$   r"   r   r   '   sH    370489R+/R)-R 36RD 59<@6:2%(2%)%[2 '+5k2 #+5/	2
 +35/2 042 @ET8TcKdEd?e2h # $U "&e 26:- -f .312> (>&> "#Y> &+	>
 ,/>
 8<>@4 <r$   r+   c                  .    t         
t               a t         S )z'Obtenir l'instance singleton du manager)_freqai_manager_instancer   r   r$   r"   get_freqai_managerr   N  s      '#0? ##r$   __main__r   u   🧪 TEST FREQAI MANAGERu    
1️⃣ Test outlier detection:)d   e   g      Y@f   g     `Y@g   g     Y@h   )  L      r     r   r   BTCUSDT2   g      ?r-   u      • Bloquer trade: u      • Outlier: r1   u   
2️⃣ Test volume spike:)r   r   r   r   r   r   r   r   ETHUSDTr0   u   
3️⃣ Statistiques:u   
✅ Tests terminés)'r   loggingtypingr   r   r   r   r   r   jsonosrv   r	   r
   ai_adaptive_retrainerr   backtesting_adaptiver   r   basicConfigINFO	getLoggerr   r   r   r   r   r   managernormal_pricesnormal_volumesr@   should_blockr>   r6   r9   spike_volumesr8   r   r   r$   r"   <module>r      s  ,  . . (  	 D 8 P   ',, '			?	+a aJ	   $M $ z 	&M	
$%	&M "G 

-.BMDN$:: ; L( 
"<.
12 !4!4 567012 

()DM$:: ; L( 
"<.
12!(//!234012 

#$	
!"_ r$   