
    &(id                         d dl Zd dlZd dlmZmZmZmZ d dlm	Z	 d Z
d Zd Zd ZddZd	 Zd
 Zd Zd Zd Zd ZddZddZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z d Z!y)    N)OptionalDictListTuple)dequec                 n    dddddddd}i }|j                         D ]  \  }}t        | ||      ||<    |S )	z/Calculate price changes for multiple timeframes<      ,  X        )1m3m5m10m15m20m30m)itemscalc_single_price_change)current_priceprice_history
timeframeschangesnamesecondss         +/var/www/html/crypto/indicators_extended.pycalc_all_price_changesr       s^     J G#))+ Xg0wWX N    c                     |syddl }|j                         }||z
  }d}t        d      }|D ]  \  }}	t        ||z
        }
|
|k  s|
}|	} ||dk(  ry| |z
  |z  dz  }t        |      S )z-Calculate price change for a single timeframe        r   Ninfg      Y@)timefloatabs)r   r   seconds_backr%   current_timetarget_timeclosest_pricemin_time_difftsprice	time_diffprice_change_pcts               r   r   r   #   s    99;L-KM%LM" "	E[()	}$%M!M	"  2&6-G5P!""r!   c                     t        t        |             }t        |d      }t        |      }t        |d      }t        |      }t        |d      }t        |      }||||dS )z0Calculate momentum slope for multiple timeframesr   r   r   )2mr   r   r   )compute_smoothlistget_prices_for_timeframe)	price_windowr   	smooth_2m	prices_5m	smooth_5m
prices_10m
smooth_10m
prices_15m
smooth_15ms	            r   calc_smooth_multi_tfr>   @   ss     tL12I )<Iy)I *-=J
+J *-=J
+J 	 r!   c                 x    ddl }|j                         }||z
  }| D cg c]  \  }}||k\  s| }}}|S c c}}w )z%Extract prices for specific timeframer   N)r%   )r   r   r%   r)   cutoff_timer-   r.   pricess           r   r5   r5   Z   sC    99;L(K%2H	EbK6GeHFHM Is   66c                 l   t        |       dk  ryt        j                  t        |             }t        j                  | t              }	 t        j
                  ||d      \  }}t        j                  ||j                         |z  dz   z        }t	        |      S # t        $ r d}Y t	        |      S w xY w)z*Calculate momentum using linear regression   r#   )dtype   g:0yE>)	lennparangearrayr&   polyfittanhmean	Exception)rA   scalexym_smooths          r   r3   r3   d   s    
6{Q
		#f+A
u%Azz!Q"1affh.567 =  =s   
AB B32B3c                 b   ddl }|j                         }| D cg c]  \  }}||z
  dk  s| }}}t        |      dkD  r.t        j                  |      t        j                  |      z  dz  nd}| D cg c]  \  }}||z
  dk  s| }}}t        |      dkD  r.t        j                  |      t        j                  |      z  dz  nd}t        |      dkD  r)t        |      }	t        |      }
|
dkD  r|	|
z
  |
z  dz  nd}nd}t        |      t        |      t        |      dS c c}}w c c}}w )	zACalculate volatility (standard deviation) for multiple timeframesr   Nr	   rE   d   r#   r   )r   r   high_low_range_5m)r%   rF   rG   stdrL   maxminr&   )r   r%   r)   r-   p	prices_1mvol_1mr8   vol_5mhigh_5mlow_5mhigh_low_ranges               r   calc_volatilityra   y   s)    99;L !.Iur11Bb1HIII=@^a=ORVVI!33c9UXF !.Jur11Bc1IJIJ=@^a=ORVVI!33c9UXF 9~i.Y>Dqj'F*f4s:c FmFm">2  J Ks   D%D%5D+D+c                    ddl }|j                         }t        |      }t        |       }|D cg c]  }||d   dz  z
  dk  s| }}t        |      }|D cg c]  }||d   dz  z
  dk  s| }	}t        |	      }
|D cg c]  }||d   dz  z
  dk  s| }}t        |      }|D cg c]  }||d   dz  z
  dk  s| }}t        |      }||z
  }|||
||t        |      d	S c c}w c c}w c c}w c c}w )
z1Calculate buy/sell ratios for multiple timeframesr   NT  r   r   r   r   )r   r   r   r   r   mf_acceleration)r%   r4   calc_single_ratior&   )trades_currenttrades_windowr%   r)   trades_listratio_1mt	trades_5mratio_5m
trades_15m	ratio_15m
trades_20m	ratio_20m
trades_30m	ratio_30mre   s                   r   calc_all_ratiosrt      s=    99;L }%K !0H (Mq<!C&++E+LMIM +H )NL1S6$;,F#,M!NJN!*-I )OL1S6$;,F$,N!OJO!*-I )OL1S6$;,F$,N!OJO!*-I )O  1 % N O P Ps/   C&C&C+,C+C0C0*C5>C5c                 z    | syd}d}| D ]  }|d   }|d   r||z  }||z  } ||z   }|dk(  ryt        ||z        S )z-Calculate buy/sell ratio for a list of trades      ?r#   qisBuyerMakerr   r&   )tradesbuysellrk   qtytotals         r   rf   rf      sh    
CD f^CKD3JC $JEzur!   c                 R   ddl }|j                         }|D cg c]  \  }}||z
  dk  s| }}}|rt        j                  |      n| }|D cg c]  \  }}||z
  dk  s| }}}|rt        j                  |      n| }	t        |      dkD  r|d   |d   z
  }
nd}
t        |      dk\  r5t	        |      d	d D cg c]  \  }}|	 }}}|d   d
|d   z  z
  |d	   z   }nd}t        |       t        |      t        |	      t        |
      t        |      dS c c}}w c c}}w c c}}w )zCalculate extended CVD metricsr   Nr   r   rE   r#         )currentr   r   change_rateacceleration)r%   rG   rL   rF   r4   r&   )cvd_currentcvd_historyr%   r)   r-   cvdcvd_5m_valuescvd_5mcvd_15m_valuescvd_15mcvd_change_raterR   recent_cvdscvd_accelerations                 r   calc_cvd_extendedr      sF    99;L )4PWR|b7HC7OSPMP'4RWW]#+F *5Qgb#r8IS8PcQNQ)7bggn%[G =A'+mA.>> ;1)-k):23)?@vq#s@@&r?Q{2->>RP %FmW~_-./ ) Q R As   DDD!D<D#c           	          | d   }| d   }| d   }| d   }| d   }| d   }|dkD  r||z  }n	|dkD  r|nd}t        |      t        |      t        |      t        |      t        |      t        |      t        |      d	S )
z Calculate extended whale metricswhale_total	whale_buy
whale_sellwhale_countwhale_largest	whale_avgr   r#   )r~   r{   r|   countlargestavgbuy_sell_ratio)r&   int)	
whale_datawhale_historyr   r   r   r   r   r   whale_buy_sell_ratios	            r   calc_whale_extendedr     s     ]+K;'IL)J]+K/M;'I A~(:5,5Mys {#Yj![!'Y 45 r!   c                 ^   | j                  dg       }| j                  dg       }|r|s;i ddddddddd	dd
dddddddddddddd|d|ddddddddddS t        d |D              }t        d |D              }|dkD  r||z  nd}t        |d   d         }t        |d   d         }|dkD  r||z  nd}	||z
  }
|dkD  r|
|z  dz  nd}t        d |dd D              }t        d |dd D              }||z   dkD  r||z
  ||z   z  nd}t        d |dd  D              }t        d! |dd  D              }||z   dkD  r||z
  ||z   z  nd}|D cg c]  }t        |d"          }}|D cg c]  }t        |d"          }}|rt        |      nd}|rt        |      nd}|dkD  r7|j	                  |      }t        ||   d         }t        ||z
        |z  dz  }nd}|dkD  r7|j	                  |      }t        ||   d         }t        ||z
        |z  dz  }nd}t        ||      }t        ||d#$      }t        ||d%$      }||z
  d&z  } t        |d'      }!t        |d'd#$      }"t        ||      }#t        |      }$t        |      }%t        ||      }&t        ||      }'t        ||||      }(i dt        |      dt        |	      dt        |
      dt        |      d	t        |      d
t        |      dt        |      dt        |      dt        |      dt        |      dt        |      dt        |       dt        |!      dt        |"      dt        |#      dt        |$      dt        |%      t        |&      t        |'      t        |(      dS c c}w c c}w )(z<Calculate extended orderbook metrics with liquidity analysisbidsasksdepth_ratio      ?best_level_ratiospreadr#   
spread_pctimbalance_5imbalance_20bid_wall_sizeask_wall_sizewall_distance_pctliquidity_bid_pressureliquidity_ask_pressureliquidity_shiftimpact_buy_priceimpact_sell_priceorderbook_entropyliquidity_gap_bidsliquidity_gap_asks)spoof_buy_scorespoof_sell_scoreiceberg_scorec              3   8   K   | ]  }t        |d            ywrE   Nry   .0rO   s     r   	<genexpr>z*calc_orderbook_extended.<locals>.<genexpr>E       /QU1Q4[/   c              3   8   K   | ]  }t        |d            ywr   ry   r   s     r   r   z*calc_orderbook_extended.<locals>.<genexpr>F  r   r   r   rU   c              3   8   K   | ]  }t        |d            ywr   ry   r   s     r   r   z*calc_orderbook_extended.<locals>.<genexpr>Q       2AE!A$K2r   NrC   c              3   8   K   | ]  }t        |d            ywr   ry   r   s     r   r   z*calc_orderbook_extended.<locals>.<genexpr>R  r   r   c              3   8   K   | ]  }t        |d            ywr   ry   r   s     r   r   z*calc_orderbook_extended.<locals>.<genexpr>U       4QU1Q4[4r      c              3   8   K   | ]  }t        |d            ywr   ry   r   s     r   r   z*calc_orderbook_extended.<locals>.<genexpr>V  r   r   rE   T)is_bidFg       @      $@)getsumr&   rX   indexr'   rY   calc_liquidity_pressurecalc_market_impact_pricecalc_orderbook_entropycalc_liquidity_gapscalc_spoof_scorecalc_iceberg_score))	orderbookr   r   r   
bid_volume
ask_volumer   best_bidbest_askr   r   r   	bid_vol_5	ask_vol_5r   
bid_vol_20
ask_vol_20r   rO   	bid_sizes	ask_sizesr   r   bid_wall_idxbid_wall_pricebid_wall_distanceask_wall_idxask_wall_priceask_wall_distancer   r   r   r   r   r   r   r   r   r   r   r   s)                                            r   calc_orderbook_extendedr   %  s0    ==$D==$Dt
3

 c
 #	

 3
 C
 S
 S
  
 %c
 %c
 s
 
  
   !
" !##
$ !#%
&  # # +
 	
2 /$//J/$//J-7!^*z)KT!WQZ HT!WQZ H.6lx(* F.6l&8#s*J 2bq22I2bq22IHQT]H]abGb9y(Y-BChkK4$s)44J4$s)44JMWZdMdhiLiJ+
Z0GHorL '++qt+I+&*+qt+I+&/C	NSM&/C	NSMq }5tL1!45 >?-ORUUq }5tL1!45 >?-ORUU-/@A 5T=QUV4T=QVW .0FF#MO 0d;0tDI /tT: -T2,T2 't];O'm< 'tT:zJMu[)E"23 	%- 	eJ'	
 	u[) 	l+ 	}- 	}- 	U#45 	!%(>"? 	!%(>"? 	51 	E"23 	U#45  	U#45!" 	e$67#$ 	e$67%& !1!"23}-+ g ,+s   N%3N*c                     | syd}| dd D ]?  \  }}t        |      }t        |      }t        ||z
        |z  }dd|dz  z   z  }	|||	z  z  }A |S )z%Calculate weighted liquidity pressurer#   Nr   r   rU   )r&   r'   )
ordersr   r   pressure	price_strqty_strr.   r}   distanceweights
             r   r   r     sx    H$Sbk !	7i Gn u},-=hn,-C&L ! Or!   c                     | s| rt        | d   d         S dS d}d}| D ]A  \  }}t        |      }t        |      }||z   |k\  r||z
  }	||	|z  z  }|} n|||z  z  }||z  }C |dk(  rt        | d   d         S ||z  }
|
S )z0Calculate average price for executing target_qtyr   r#   ry   )r   
target_qtyr   cumulative_qty
total_costr   r   r.   r}   	remaining	avg_prices              r   r   r     s    &,uVAYq\"5#5NJ$ "	7i GnC:-"^3I)e++J'N#+%Jc!N" VAYq\""^+Ir!   c                 0   | dd D cg c]  }t        |d          c}|dd D cg c]  }t        |d          c}z   }|rt        |      dk(  ryt        |      }|D cg c]  }|dkD  s	||z   }}t        d |D               }|S c c}w c c}w c c}w )zCCalculate entropy of order book (measure of liquidity distribution)Nr   rE   r   r#   c              3   X   K   | ]"  }|d kD  s	|t        j                  |      z   $ yw)r   N)rG   log2)r   rZ   s     r   r   z)calc_orderbook_entropy.<locals>.<genexpr>  s"     :aAE1rwwqz>:s   
**)r&   r   )r   r   rO   	all_sizesr~   sizeprobsentropys           r   r   r     s    &*3Bi0qt0cr3SAE!A$K3SSII!+ 	NE$-:DT%Z:E: :5:::GN 13S ;s   B	B 
B+Bc                 "   t        |       dk  ry| dd D cg c]  }t        |d          }}t        j                  |      }d}t	        t        |      dz
        D ]"  }||   |dz  kD  s||dz      |dz  k  s|dz  }$ t        |      S c c}w )z-Detect gaps in liquidity (potential spoofing)r   r#   Nr   rE   r   rv   )rF   r&   rG   rL   range)r   rO   sizesavg_sizegapsis         r   r   r     s    
6{Q"("+.QU1Q4[.E.wwu~H D3u:a<  8hl"uQqSzHsN'BAID ; /s   Bc                     | r|dk(  ry| dd D cg c]  }t        |d          }}t        j                  |      |dz  kD  r(t        fd|dd D              }t	        d|d	z        }|S d}|S c c}w )
zCalculate spoofing score (0-1)r   r#   Nr   rE   r   c              3   4   K   | ]  }|d z  k  sd  yw)rv   rE   N )r   sr   s     r   r   z#calc_spoof_score.<locals>.<genexpr>  s     DqX^1CDs   r   r   )r&   rG   rL   r   rY   )r   	wall_sizerO   r   
thin_countspoof_scorer   s         @r   r   r     s    Y!^"("+.QU1Q4[.E.wwu~H 8a<DE!"IDD
#zD01   /s   A1c                     | r|syy)zDetect potential iceberg ordersr#   r  )r   r   r   r   s       r   r   r   	  s    t r!   c                    ddl }|j                         }t        d | D              }t        |      }|D cg c]  \  }}||z
  dk  s| }}}|rt        |      n|}	|D cg c]  \  }}||z
  dk  s| }
}}|
rt        |
      n|}|r(t        j                  |D cg c]  \  }}|	 c}}      n|}|dkD  r||z
  |z  dz  }nd}t        |      dkD  r|d	   |d   z
  }nd}| r|t        |       z  nd}t        |       d
z  }t        d | D              }|d
z  }t        |      t        |	      t        |      t        |      t        |      t        |      t        |      t        |      t        |      d	S c c}}w c c}}w c c}}w )z!Calculate extended volume metricsr   Nc              3   &   K   | ]	  }|d      ywrw   Nr  r   rk   s     r   r   z'calc_volume_extended.<locals>.<genexpr>  s     +qAcF+   r   r   rU   r#   rE   r   r	   c              3   >   K   | ]  }|d    |d   z  dk\  sd  yw)rZ   rw   i'  rE   Nr  r  s     r   r   z'calc_volume_extended.<locals>.<genexpr>?  s#     J!3!C&E1IAJs   )	r   r   r   avg_1mr   r   avg_trade_sizetrade_frequencylarge_trade_frequency)r%   r   r4   rG   rL   rF   r&   )rz   volume_windowr%   r)   	volume_1mvolume_window_listr-   vol
volumes_5m	volume_5mvolumes_15m
volume_15mrR   avg_volume_1mvolume_change_ratevolume_accelerationr  r  large_trade_countr  s                       r   calc_volume_extendedr    s    99;L +F++I m,%7T'"c<";LPS;S#TJT#-J9I '9U72sL2<MQT<T3UKU%0[!iJ HZBGG/ABVQSBC_hM q(=8MISP  :(nz!}<! 17YV,CN &kB&O JvJJ-2 IIZ &/012/ 1!&'<!=
 
A U V Cs   E9E9#E?4E? F
c                    | sddddddddddddddS t        |       dz  }t        d | D              }t        d | D              }t        |       }|dkD  r||z  dz  nd}|dkD  r||z  dz  nd}t        |       dkD  r\| D cg c]  }|d	   	 }	}t        t        |	      dz
        D 
cg c]  }
|	|
dz      |	|
   z
   }}
|rt        j                  |      nd}nd}t        d
 | D              }t        d | D              }||z   }|dkD  r||z
  |z  nd}t        |       }| r| d   d   nd}|dkD  r||z
  |z  nd}t        |      }t        |d      }t        |d      }t        |d      }t        |       }t        |       }t        |      t        |      t        |      t        |      t        |      t        |      t        |      t        |      t        |      t        |      t        |      t        |      t        |      dS c c}w c c}
w )z'Calculate market microstructure metricsr#   r   )trades_per_minutebuy_trades_countsell_trades_countavg_time_between_tradesaggressive_buy_pctaggressive_sell_pctdelta_strength
vwap_driftmicro_trend_3smicro_trend_7smicro_trend_12svariance_ratiobreakout_energyr	   c              3   ,   K   | ]  }|d    r	d  ywrx   rE   Nr  r  s     r   r   z-calc_market_microstructure.<locals>.<genexpr>i  s     @1a.?Q@   
c              3   ,   K   | ]  }|d    s	d  ywr/  r  r  s     r   r   z-calc_market_microstructure.<locals>.<genexpr>j  s     =A1^+<a=r0  rU   rE   rc   c              3   2   K   | ]  }|d    r	|d     ywrx   rw   Nr  r  s     r   r   z-calc_market_microstructure.<locals>.<genexpr>}  s     E1^3DQsVE   

c              3   2   K   | ]  }|d    s	|d     ywr3  r  r  s     r   r   z-calc_market_microstructure.<locals>.<genexpr>~  s     B.0AafBr4  r   rZ   r         )rF   r   r   rG   rL   	calc_vwapr4   calc_micro_trendcalc_variance_ratiocalc_breakout_energyr&   r   )rz   rh   r!  
buy_tradessell_tradestotal_tradesr%  r&  rk   
timestampsr   
time_diffsr$  
buy_volumesell_volumetotal_volumer'  vwapr   r(  ri   r)  r*  r+  r,  r-  s                             r   calc_market_microstructurerE  S  sX    !$ !!"'*"%#&!!!"!"
 	
" Fb(@@@J===Kv;L>JQ>N*|3s:TW@Lq@P;5<VY 6{Q&,-af-
-?DS_UVEV?WX!j1o
15X
X9C"''*"5"% EVEEJBfBBK+LBNQRBRj;.,>X[N VD'-F2JsO1M26(-$&$.J }%K%k15N%k15N&{B7O )0N +62O ##45
O -#()@#A#$67$%89/J'// 1/ 1 C .Xs    H'Hc                 h    | syt        d | D              }t        d | D              }|dkD  r||z  S dS )z'Calculate Volume-Weighted Average Pricer#   c              3   2   K   | ]  }|d    |d   z    yw)rZ   rw   Nr  r  s     r   r   zcalc_vwap.<locals>.<genexpr>  s     6!afqvo6s   c              3   &   K   | ]	  }|d      ywr  r  r  s     r   r   zcalc_vwap.<locals>.<genexpr>  s     .!qv.r  r   )r   )rz   total_valuerC  s      r   r8  r8    s?    6v66K.v..L)5)9;%BsBr!   c                    ddl }| sy|j                         }||z
  }| D cg c]  }|d   dz  |k\  s| }}t        |      dk  ry|D cg c]  }|d   	 }}|d   }|d   }	|dkD  r|	|z
  |z  nd}
t        |
      S c c}w c c}w )	z$Calculate micro trend over N secondsr   Nr#   rc   rd   r   rZ   r   )r%   rF   r&   )ri   r   r%   r)   cutoffrk   recent_tradesrA   first_price
last_pricetrends              r   r9  r9    s    99;LG#F +E1qvd{f/DQEME
=A+,af,F,)KJ8CaZ+%4SE< F
 -s   A=A=Bc                 6   t        |       dk  ry| D cg c]  }|d   	 }}t        j                  |      |dd z  }t        |      dk  ryt        j                  |      }t        j                  |ddd         }|dkD  r|d|z  z  nd}t	        |      S c c}w )	z-Calculate variance ratio (for mean reversion)
   r#   rZ   Nr   r   r   r   )rF   rG   diffvarr&   )rz   rk   rA   returnsvar_1var_2r,  s          r   r:  r:    s    
6{R$%af%F%ggfos+G
7|aFF7OEFF73Q3< E,1AIUa%i(3N   &s   Bc                     t        |       dk  ry| D cg c]  }|d   	 }}| D cg c]  }|d   	 }}|d   dkD  r|d   |d   z
  |d   z  nd}t        |      }t        |      |z  }t        |      S c c}w c c}w )z1Calculate breakout energy (volume * price_change)r   r#   rZ   rw   r   r   )rF   r   r'   r&   )rz   rk   rA   volumesprice_change
volume_sumenergys          r   r;  r;    s    
6{Q$%af%F%%&!qv&G&;A!9q=F2J*fQi7cLWJ+F= &&s
   A3A8c           	         t        dt        d| dz  |dz
  dz  z   |dz  z   |dz  z               }|| dkD  rdndz  }t        dt        d|dz
  dz  |dz  z   |dz  z   |dz
  d	z  z               }d|z
  }	t        j                  | d
z  |dz
  dz  z   |dz  z   |dz  z         }
t	        |      t	        |      t	        |      t	        |	      t	        |
      dS )z%Calculate composite market indicatorsr   rU   (   rv   rC   rQ  rE   r   r   r      g?g?)momentum_strengthvolume_price_trendbuying_pressureselling_pressuremarket_sentiment)rX   rY   rG   rK   r&   )rS   	buy_ratior   whalevolume_changer   r_  vptra  rb  rc  s              r   calc_composite_indicatorsrh    s4    As3	SC	 a	 	
	   
1
3C !S	SCb			 
qB	 O _, ww
	SA	c		 		 ##45#Cj 1!"23!"23 r!   )g-C6?)T)F)"numpyrG   mathtypingr   r   r   r   collectionsr   r    r   r>   r5   r3   ra   rt   rf   r   r   r   r   r   r   r   r   r   r  rE  r8  r9  r:  r;  rh  r  r!   r   <module>rm     s      . . *#:4*B&R4!P@~B&: "$5xOdC,!$&'r!   