
    V.j8                         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 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      TC:\xampp\htdocs\tradingbinance\backend\.venv\Lib\site-packages\binance/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_bids4   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_asksU   s$    > $$TZZ$..$YYr   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 price
        z$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_depthv   s     dD!RVR\R\R^_R^uhIe$i&9:R^C_d#RVWRVuhIe$i&9:RVCWCDJ<PQQSjmW=
 `Ws   B%B+N)r   
__module____qualname__floatr   r   r   r"   r(   r*   staticmethodr&    r   r   r   r      sI    5: 0( 0 	#	#YBZB !&e 
8 
 
r   r   c                   n    e Zd ZdZdZdddd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)BaseDepthCacheManageri  <   N
   c                 .   || _         d| _        |xs
 t               | _        || _        || _        d| _        |xs t        | j                         | _        |xs | 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DEFAULT_REFRESH_refresh_interval	_conn_key
_conv_typer   r   r   r   )r   clientr   looprefresh_intervalbmlimitr   s           r   r   zBaseDepthCacheManager.__init__   s    (  'XZ
#;-dll;!1!IT5I5I#%%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__   s\     nn 
 	
 	
 ll%%'''	
 	(s!   6A%A!!A%A#A%#A%c                 X   K    | j                   j                  |i | d {    y 7 wrS   )rX   	__aexit__)r   argskwargss      r   r[   zBaseDepthCacheManager.__aexit__   s%     $dll$$d5f555s    *(*c                 <  K   d }|s^	 t        j                  | j                  j                         | j                         d {   }| j                  |       d {   }|s^|S 7 "7 # t        $ r%}| j                  j                  |       Y d }~2d }~ww xY ww)N)timeout)	rT   wait_forrX   recvTIMEOUT_depth_event	Exceptionr   warning)r   dcreses       r   ra   zBaseDepthCacheManager.recv   s     2#,,T\\->->-@$,,WW  ,,S11  	 X 2  %		!!!$$%sX   B<A+ A'A+ 	BA)B%B'A+ )B+	B4BBBBc                    K   t        | j                  | j                        | _        | j                  r0t        t        j                               | j                  z   | _        yyw)KInitialise the depth cache calling REST endpoint

        :return:
        )r   N)r   rE   rL   rC   rJ   inttime_refresh_timer'   s    r   rV   z!BaseDepthCacheManager._init_cache   sM      't||tO !!!$TYY[!1D4J4J!JD "s   A$A&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   rp   z!BaseDepthCacheManager._get_socket   s    !!r   c                    K   |syd|v r!|d   dk(  r| j                          d{    y| j                  |       d{   S 7 7 w)zDHandle a depth event

        :param msg:
        :return:

        Nrh   error)close_process_depth_messager   msgs     r   rc   z"BaseDepthCacheManager._depth_event   sS      #:#c(g-**, 00555 
 6s    #AA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_ordersrC   rJ   rk   rl   rm   rV   r   rx   rg   s      r   rv   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)rC   getr   r"   r   )r   rx   r   r!   s       r   r{   z#BaseDepthCacheManager._apply_orders   s        773#cggfb&99C%%c* :773#cggfb&99C%%c* : ),(O8O%r   c                     | j                   S )zIGet the current depth cache

        :return: DepthCache object

        rC   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   ru   zBaseDepthCacheManager.close  s     
 !s   	c                     | j                   S )z0Get the symbol

        :return: symbol
        )rE   r'   s    r   
get_symbolz BaseDepthCacheManager.get_symbol  s    
 ||r   )r   r8   r9   rI   rb   r:   r   rY   r[   ra   rV   rW   rp   rc   rv   r{   r   ru   r   r<   r   r   r>   r>      s]    OG,04DXZfk 0@6	K*"6((P!!r   r>   c                   L     e Zd Zddddedf fd	Z fdZ fdZd Zd Z xZ	S )DepthCacheManagerNi  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   rM   r   rN   rO   rP   rQ   r   ws_interval	__class__s
            r   r   zDepthCacheManager.__init__   s'    ( 	/?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)rj   N)r   rQ   r   r   r   )rG   _depth_message_bufferrB   get_order_bookrE   rF   r   rV   r{   rC   r   r"   rv   )r   rg   r   r!   rx   r   s        r   rV   zDepthCacheManager._init_cache7  s    
  $%'"LL//t||4;;/WW g!### 	3    v;C%%c* v;C%%c*   #>2 --C--c222 . &("+ 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)ro   r   N)getattrr   r   rW   )r   r   s    r   rW   zDepthCacheManager._start_socketV  s/     
 t4d;)+D&g#%%%s   &1/1c                 d    | j                   j                  | j                  | j                        S )N)interval)rH   depth_socketrE   r   r'   s    r   rp   zDepthCacheManager._get_socket`  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)rz   NuUr   )
rG   r   appendrV   r{   rC   rJ   rk   rl   rm   r|   s      r   rv   z(DepthCacheManager._process_depth_messagec  s      '&&--c2s8t+++X--11 ""$$$ 	3 "3x !!c$))+&69K9K&K""$$$
 % %s%   A$C&&C"'A4C&C$C&$C&)
r   r8   r9   r:   r   rV   rW   rp   rv   __classcell__r   s   @r   r   r     s.     $($4s^cqu(.(>&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)rz   dataN)r   r   rv   )r   rx   r   s     r   rv   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   )rC   r   r   r   r   rw   s     r   r{   z&FuturesDepthCacheManager._apply_orders  si        "%''#r"2"%''#r"2 ),(O8O%r   c                 P    | j                   j                  | j                        }|S rS   )rH   futures_depth_socketrE   )r   socks     r   rp   z$FuturesDepthCacheManager._get_socket  s    xx,,T\\:r   )r   r8   r9   rv   r{   rp   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   )rH   options_depth_socketrE   r'   s    r   rp   z$OptionsDepthCacheManager._get_socket  s    xx,,T\\::r   N)r   r8   r9   rp   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   r   s         r   r   z"ThreadedDepthCacheManager.__init__  s    
 	*osGLr   r@   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?)rM   r   rN   rO   rP   rQ   r   z@depthTr<   )rB   rl   sleeprD   lowerstr_socket_running	call_soonrT   create_taskstart_listener)r   	dcm_classr   r   rO   rP   rQ   r   r]   dcmpaths              r   _start_depth_cachez,ThreadedDepthCacheManager._start_depth_cache  s    
 ,,JJt ,,  	
<<-	
 	
 ||~(3u:5%)T"

W00$2E2Ec4QY2Z[r   r   c           
      <    | j                  t        |||||||      S )N)r   r   r   rO   rP   rQ   r   r   )r   r   )r   r   r   rO   rP   rQ   r   r   s           r   start_depth_cachez+ThreadedDepthCacheManager.start_depth_cache  s4     &&'-# ' 	
 		
r   c           	      :    | j                  t        ||||||      S N)r   r   r   rO   rP   rQ   r   )r   r   r   r   r   rO   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   r8   r9   r   r   r   boolr   r:   r   r   r   r   r   r   r   s   @r   r   r     s    JNEJM}M9A#M!$sCx.1M?BM M $bE#+58 
0 AEUWchvw
 
*-
	
 EITY[gl
$
.1
	
 AEUWch
 
*-
	
r   r   )r   operatorr   rT   rl   typingr   r   r   helpersr   streamsr	   threaded_streamr
   objectr   r>   r   r   r   r   r<   r   r   <module>r      su        + +  ) /u upW Wtf- fR4 0;4 ;F
 2 F
r   