
    6i;                         d dl Z d dlmZ d dlZd dlZd dlmZmZmZ ddl	m
Z
 ddlmZ ddlmZ  G d	 d
e      ZdZ G d d      Z G d de      Z G d de      Z G d de      Z G d de      Zy)    N)
itemgetter)OptionalDictCallable   )get_loop   )BinanceSocketManager)ThreadedApiManagerc                   P    e Zd ZefdefdZd Zd Zd Zd Z	e
defdefd       Zy	)

DepthCache	conv_typec                     || _         i | _        i | _        d| _        || _        t        j                  t              | _        y)zInitialise the DepthCache

        :param symbol: Symbol to create depth cache for
        :type symbol: string
        :param conv_type: Optional type to represent price, and amount, default is float.
        :type conv_type: function.

        N)	symbol_bids_asksupdate_timer   logging	getLogger__name___log)selfr   r   s      S/var/www/app/trading-bot/venv/lib/python3.12/site-packages/binance/ws/depthcache.py__init__zDepthCache.__init__   s:     

#,%%h/	    c                 ~    | j                  |d         | j                  |d   <   |d   dk(  r| j                  |d   = yy)zFAdd a bid to the cache

        :param bid:
        :return:

        r	   r   
0.00000000N)r   r   )r   bids     r   add_bidzDepthCache.add_bid   D     "^^CF3

3q6q6\!

3q6" "r   c                 ~    | j                  |d         | j                  |d   <   |d   dk(  r| j                  |d   = yy)zGAdd an ask to the cache

        :param ask:
        :return:

        r	   r   r   N)r   r   )r   asks     r   add_askzDepthCache.add_ask(   r    r   c                 Z    t         j                  | j                  d| j                        S )a  Get the current bids

        :return: list of bids with price and quantity as conv_type

        .. code-block:: python

            [
                [
                    0.0001946,  # Price
                    45.0        # Quantity
                ],
                [
                    0.00019459,
                    2384.0
                ],
                [
                    0.00019158,
                    5219.0
                ],
                [
                    0.00019157,
                    1180.0
                ],
                [
                    0.00019082,
                    287.0
                ]
            ]

        Treverser   )r   
sort_depthr   r   r   s    r   get_bidszDepthCache.get_bids3   s$    > $$TZZ$XXr   c                 Z    t         j                  | j                  d| j                        S )a  Get the current asks

        :return: list of asks with price and quantity as conv_type.

        .. code-block:: python

            [
                [
                    0.0001955,  # Price
                    57.0'       # Quantity
                ],
                [
                    0.00019699,
                    778.0
                ],
                [
                    0.000197,
                    64.0
                ],
                [
                    0.00019709,
                    1130.0
                ],
                [
                    0.0001971,
                    385.0
                ]
            ]

        Fr%   )r   r'   r   r   r(   s    r   get_askszDepthCache.get_asksT   s+    > $$JJ % 
 	
r   Fc                 b   t        | t              r1| j                         D cg c]  \  }} ||       ||      g }}}nJt        | t              r#| D cg c]  \  }} ||       ||      g }}}nt	        dt        |              t        |t        d      |      }|S c c}}w c c}}w )zSort bids or asks by pricez$Unknown order book depth data type: r   )keyr&   )
isinstancedictitemslist
ValueErrortypesortedr   )valsr&   r   pricequantitylsts         r   r'   zDepthCache.sort_depthw   s     dD! (,zz|#E8 5!9X#67C  d#RVWuhIe$i&9:WCWCDJ<PQQSjmW=

 Xs   B%B+N)r   
__module____qualname__floatr   r   r   r#   r)   r+   staticmethodr'    r   r   r   r      sH    5: 0( 0 	#	#YB!
F !&e 8  r   r   i  c                   v    e Zd ZdZdeddefdee   fdZ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)BaseDepthCacheManager<   N
   refresh_intervalc                    || _         d| _        |xs
 t               | _        || _        || _        d| _        |xs t        | j                         | _        || _	        d| _
        || _        t        j                  t              | _        y)a  Create a DepthCacheManager instance

        :param client: Binance API client
        :type client: binance.Client
        :param loop:
        :type loop:
        :param symbol: Symbol to create depth cache for
        :type symbol: string
        :param refresh_interval: Optional number of seconds between cache refresh, use 0 or None to disable
        :type refresh_interval: int
        :param bm: Optional BinanceSocketManager
        :type bm: BinanceSocketManager
        :param limit: Optional number of orders to get from orderbook
        :type limit: int
        :param conv_type: Optional type to represent price, and amount, default is float.
        :type conv_type: function.

        N)_client_depth_cacher   _loop_symbol_limit_last_update_idr
   _bm_refresh_interval	_conn_key
_conv_typer   r   r   r   )r   clientr   looprB   bmlimitr   s           r   r   zBaseDepthCacheManager.__init__   su    :  'XZ
#;-dll;!1#%%h/	r   c                    K   t        j                  | j                         | j                                d {    | j                  j                          d {    | S 7 (7 wN)asynciogather_init_cache_start_socket_socket
__aenter__r(   s    r   rY   z BaseDepthCacheManager.__aenter__   sQ     nnT--/1C1C1EFFFll%%''' 	G's!   6A%A!!A%A#A%#A%c                    K   | j                   j                  d| j                           | j                  j                  |i | d {    y 7 w)Nz Exiting depth cache manager for )r   debugrG   rX   	__aexit__)r   argskwargss      r   r\   zBaseDepthCacheManager.__aexit__   sA     		:4<<.IJ$dll$$d5f555s   AA
AAc                   K   d }|s|	 t        j                  | j                  j                         | j                         d {   }| j
                  j                  d|        | j                  |       d {   }|s||S 7 @7 # t        $ r=}| j
                  j                  d|j                  j                   d       Y d }~Jd }~ww xY ww)N)timeoutzReceived message: zException recieving message: z (e) )rT   wait_forrX   recvTIMEOUTr   r[   _depth_event	Exceptionwarning	__class__r   )r   dcreses       r   rb   zBaseDepthCacheManager.recv   s     2#,,T\\->->-@$,,WW		"4SE :;  ,,S11  	 X
 2  _		!!$A!++BVBVAWW\"]^^_sX   C<B	 B"B	 'C;B<CCB	 C		C3C
C
CCc                    K   | j                   j                  d| j                          t        | j                  | j                        | _        | j                  r0t        t        j                               | j                  z   | _	        yyw)KInitialise the depth cache calling REST endpoint

        :return:
        zInitialising depth cache for )r   N)
r   r[   rG   r   rM   rE   rK   inttime_refresh_timer(   s    r   rV   z!BaseDepthCacheManager._init_cache   si     
 			7~FG&t||tO !!!$TYY[!1D4J4J!JD "s   BBc                 6   K   | j                         | _        yw)7Start the depth cache socket

        :return:
        N)_get_socketrX   r(   s    r   rW   z#BaseDepthCacheManager._start_socket   s     
 '')s   c                     t         rS   )NotImplementedErrorr(   s    r   rr   z!BaseDepthCacheManager._get_socket   s    !!r   c                    K   | j                   j                  d|        |syd|v r(|d   dk(  r | j                   j                  d|        |S | j                  |       d{   S 7 w)zDHandle a depth event

        :param msg:
        :return:

        zReceived depth event: Nrj   errorz'Error in depth event restarting cache: )r   r[   rv   _process_depth_messager   msgs     r   rd   z"BaseDepthCacheManager._depth_event   sl      			067#:#c(g-IIOOEcUKLJ005555s   A"A+$A)%A+c                    K   | j                  |       | j                  }| j                  rBt        t	        j                               | j
                  kD  r| j                          d{    |S 7 w)cProcess a depth event message.

        :param msg: Depth event message.
        :return:

        N)_apply_ordersrE   rK   rm   rn   ro   rV   r   ry   ri   s      r   rw   z,BaseDepthCacheManager._process_depth_message   sb      	3  !!c$))+&69K9K&K""$$$
 %s   A'A2)A0*A2c                    | j                   sJ |j                  dg       |j                  dg       z   D ]  }| j                   j                  |        |j                  dg       |j                  dg       z   D ]  }| j                   j                  |        |j                  d      xs |j                  d      | j                   _        y )NbbidsaasksElastUpdateId)rE   getr   r#   r   )r   ry   r   r"   s       r   r|   z#BaseDepthCacheManager._apply_orders	  s        773#cggfb&99 	+C%%c*	+773#cggfb&99 	+C%%c*	+ ),(O8O%r   c                     | j                   S )zIGet the current depth cache

        :return: DepthCache object

        rE   r(   s    r   get_depth_cachez%BaseDepthCacheManager.get_depth_cache  s        r   c                    K   d| _         yw)zAClose the open socket for this manager

        :return:
        Nr   r(   s    r   closezBaseDepthCacheManager.close  s     
 !s   	c                     | j                   S )z0Get the symbol

        :return: symbol
        )rG   r(   s    r   
get_symbolz BaseDepthCacheManager.get_symbol"  s    
 ||r   )r   r9   r:   rc   DEFAULT_REFRESHr;   r   rm   r   rY   r\   rb   rV   rW   rr   rd   rw   r|   r   r   r   r=   r   r   r?   r?      sj    G *9'0
 #3-'0R
6
K*"6&(P!!r   r?   c                   X     e Zd Zddddedfdee   f fdZ fdZ fdZd Z	d Z
 xZS )	DepthCacheManagerNi  rB   c	           	      >    t         	|   |||||||       || _        y)a   Initialise the DepthCacheManager

        :param client: Binance API client
        :type client: binance.Client
        :param loop: asyncio loop
        :param symbol: Symbol to create depth cache for
        :type symbol: string
        :param refresh_interval: Optional number of seconds between cache refresh, use 0 or None to disable
        :type refresh_interval: int
        :param limit: Optional number of orders to get from orderbook
        :type limit: int
        :param conv_type: Optional type to represent price, and amount, default is float.
        :type conv_type: function.
        :param ws_interval: Optional interval for updates on websocket, default None. If not set, updates happen every second. Must be 0, None (1s) or 100 (100ms).
        :type ws_interval: int

        N)superr   _ws_interval)
r   rN   r   rO   rB   rP   rQ   r   ws_intervalrg   s
            r   r   zDepthCacheManager.__init__+  s'    8 	/?UIV'r   c                   K   d| _         g | _        | j                  j                  | j                  | j
                         d{   }t        |           d{    | j                  |       | j                  sJ |d   D ]  }| j                  j                  |        |d   D ]  }| j                  j                  |        |d   | _         | j                  D ]  }| j                  |       d{     g | _        y7 7 7 w)rl   N)r   rQ   r   r   r   )rI   _depth_message_bufferrD   get_order_bookrG   rH   r   rV   r|   rE   r   r#   rw   )r   ri   r   r"   ry   rg   s        r   rV   zDepthCacheManager._init_cacheJ  s    
  $%'"LL//t||4;;/WW g!### 	3    v; 	+C%%c*	+v; 	+C%%c*	+  #>2 -- 	3C--c222	3 &("+ X 	$ 3s7   ADDDDBD7D
8DD
Dc                 f   K   t        | dd      sg | _        t        |           d{    y7 w)rq   r   N)getattrr   r   rW   )r   rg   s    r   rW   zDepthCacheManager._start_socketi  s/     
 t4d;)+D&g#%%%s   &1/1c                 d    | j                   j                  | j                  | j                        S )N)interval)rJ   depth_socketrG   r   r(   s    r   rr   zDepthCacheManager._get_sockets  s&    xx$$T\\D<M<M$NNr   c                   K   | j                   | j                  j                  |       y|d   | j                   k  ry|d   | j                   dz   k7  r| j                          d{    | j	                  |       | j
                  }|d   | _         | j                  rBt        t        j                               | j                  kD  r| j                          d{    |S 7 {7 w)r{   NuUr	   )
rI   r   appendrV   r|   rE   rK   rm   rn   ro   r}   s      r   rw   z(DepthCacheManager._process_depth_messagev  s      '&&--c2s8t+++X--11 ""$$$ 	3 "3x !!c$))+&69K9K&K""$$$
 % %s%   A$C&&C"'A4C&C$C&$C&)r   r9   r:   r;   r   rm   r   rV   rW   rr   rw   __classcell__rg   s   @r   r   r   *  s?    
 *.(
 #3-(>(>&O!r   r   c                   *     e Zd Z fdZd Zd Z xZS )FuturesDepthCacheManagerc                 `   K   |j                  d      }t        | 	  |       d{   S 7 w)r{   dataN)r   r   rw   )r   ry   rg   s     r   rw   z/FuturesDepthCacheManager._process_depth_message  s,      ggfoW3C8888s   $.,.c                 
   | j                   sJ |j                  dg       | j                   _        |j                  dg       | j                   _        |j                  d      xs |j                  d      | j                   _        y )Nr   r   r   r   )rE   r   r   r   r   rx   s     r   r|   z&FuturesDepthCacheManager._apply_orders  si        "%''#r"2"%''#r"2 ),(O8O%r   c                 P    | j                   j                  | j                        }|S rS   )rJ   futures_depth_socketrG   )r   socks     r   rr   z$FuturesDepthCacheManager._get_socket  s    xx,,T\\:r   )r   r9   r:   rw   r|   rr   r   r   s   @r   r   r     s    9Pr   r   c                       e Zd Zd Zy)OptionsDepthCacheManagerc                 L    | j                   j                  | j                        S rS   )rJ   options_depth_socketrG   r(   s    r   rr   z$OptionsDepthCacheManager._get_socket  s    xx,,T\\::r   N)r   r9   r:   rr   r=   r   r   r   r     s    ;r   r   c                        e Zd Z	 	 	 	 	 ddee   dee   deeeef      dedef
 fdZdddefd	e	d
edefdZ
dddedfd	e	d
edefdZdddefd	e	d
edefdZdddefd	e	d
edefdZ xZS )ThreadedDepthCacheManagerNapi_key
api_secretrequests_paramstldtestnetc                 ,    t         |   |||||       y rS   )r   r   )r   r   r   r   r   r   rg   s         r   r   z"ThreadedDepthCacheManager.__init__  s     	*osGLr   rA   callbackr   returnc                 |   | j                   s"t        j                  d       | j                   s" |d| j                   || j                  ||||d|}	|j	                         dz   t        |      z   }
d| j                  |
<   | j                  j                  t        j                  | j                  |	|
|             |
S )Ng{Gz?)rN   r   rO   rB   rP   rQ   r   z@depthTr=   )rD   rn   sleeprF   lowerstr_socket_running	call_soonrT   create_taskstart_listener)r   	dcm_classr   r   rB   rP   rQ   r   r^   dcmpaths              r   _start_depth_cachez,ThreadedDepthCacheManager._start_depth_cache  s     ,,JJt ,,  	
<<-	
 	
 ||~(3u:5%)T"

!4!4S$!I	
 r   r   c           
      <    | j                  t        |||||||      S )N)r   r   r   rB   rP   rQ   r   r   )r   r   )r   r   r   rB   rP   rQ   r   r   s           r   start_depth_cachez+ThreadedDepthCacheManager.start_depth_cache  s4     &&'-# ' 	
 		
r   c           	      :    | j                  t        ||||||      S N)r   r   r   rB   rP   rQ   r   )r   r   r   r   r   rB   rP   rQ   r   s          r   start_futures_depth_socketz4ThreadedDepthCacheManager.start_futures_depth_socket  1     &&.- ' 
 	
r   c           	      :    | j                  t        ||||||      S r   )r   r   r   s          r   start_options_depth_socketz4ThreadedDepthCacheManager.start_options_depth_socket	  r   r   )NNNcomF)r   r9   r:   r   r   r   boolr   r;   r   r   r   r   r   r   r   s   @r   r   r     s&    "&$(48M#M SMM "$sCx.1	M
 M M   	 
F 

 
 

2 

 
 

. 

 
 

r   r   )r   operatorr   rT   rn   typingr   r   r   helpersr   streamsr
   threaded_streamr   objectr   r   r?   r   r   r   r   r=   r   r   <module>r      s|        + +  ) /x xv ] ]@m- m`4 0;4 ;
c
 2 c
r   