
    V.jS                     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 d dlmZ d dl	m
Z
 d dlmZmZmZmZmZ d dlZd dlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ dZ  G d de      Z! G d de"e      Z# G d d      Z$ G d de$      Z% G d d      Z& G d de      Z'y)    N)sleep)Enum)random)gaierror)OptionalListDictCallableAny)ConnectionClosedError   )AsyncClient)FuturesType)BinanceWebsocketUnableToConnect)ContractType)get_loop)ThreadedApiManageri,  c                       e Zd ZdZdZdZdZy)WSListenerStateInitialising	StreamingReconnectingExitingN)__name__
__module____qualname__INITIALISING	STREAMINGRECONNECTINGEXITING     QC:\xampp\htdocs\tradingbinance\backend\.venv\Lib\site-packages\binance/streams.pyr   r      s    !LI!LGr"   r   c                        e Zd ZdZdZdZdZdZy)BinanceSocketTypeSpotUSD_M_FuturesCoin_M_FuturesVanilla_OptionsAccountN)r   r   r   SPOTUSD_M_FUTURESCOIN_M_FUTURESOPTIONSACCOUNTr!   r"   r#   r%   r%       s    D#M%NGGr"   r%   c            	           e Zd ZdZdZdZdZdZdZ	 dde	de
e	   d	e	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edefdZd Zd Zd Zy)ReconnectingWebsocket   <   皙?
   d   Nurlpathprefix	is_binaryc                 F   t               | _        t        j                  t              | _        || _        || _        || _        || _	        d| _
        || _        d | _        d | _        d | _        t        j                   | _        t%        j&                         | _        d | _        y )Nr   )r   _looplogging	getLoggerr   _log_path_url
_exit_coro_prefix_reconnects
_is_binary_conn_socketwsr   r   ws_stateasyncioQueue_queue_handle_read_loop)selfr7   r8   r9   r:   	exit_coros         r#   __init__zReconnectingWebsocket.__init__0   s     Z
%%h/	
	##
8<'44mmo!%r"   c                 B   K   | j                          d {    | S 7 wN)connectrN   s    r#   
__aenter__z ReconnectingWebsocket.__aenter__B   s     lln 	s   c                   K   | j                   r#| j                  | j                         d {    t        j                  | _        | j
                  r| j
                  j                          | j                  r;t        | j                  d      r%| j                  j                  |||       d {    d | _        | j                  s4| j                  j                  d       | j                          d {    y y 7 7 N7 
w)NprotocolzCANCEL read_loop)rB   r@   r   r    rI   rH   fail_connectionrF   hasattr	__aexit__rM   r?   error_kill_read_loop)rN   exc_typeexc_valexc_tbs       r#   rZ   zReconnectingWebsocket.__aexit__F   s     ??//$**---'//77GG##%::'$**j9**&&x&AAA%%IIOO./&&((( & .
 B )s5   +DC<BD/C>0AD5D 6D>D Dc                 t  K   | j                          d {    | j                  sJ | j                  | j                  z   | j                  z   }t	        j
                  |d      | _        	 | j                  j                          d {   | _        t        j                  | _        d| _        | j                          d {    | j                  s>| j                  j!                  t"        j$                  | j'                               | _        y y 7 7 #  | j                          d {  7   Y y xY w7 sw)Nr4   )close_timeoutr   )_before_connectr@   rA   rC   rH   rS   rF   rU   
_reconnectr   r   rI   rD   _after_connectrM   r<   call_soon_threadsaferJ   create_task
_read_loop)rN   ws_urls     r#   rS   zReconnectingWebsocket.connectS   s     ""$$$zzzT\\)DJJ6ZZc:
	 JJ1133DG (11!!###%%%)ZZ%D%DWEXEXZ^ZiZiZk%lD" & 	%
 4	//### 	$sS   D8DAD8,D 	D
	D /D8D6AD8D D3+D.,D31D8c                    K   t         j                  | _        | j                  r!t	        d       d {    | j                  r y y 7 wNr4   )r   r    rI   rM   r   rT   s    r#   r\   z%ReconnectingWebsocket._kill_read_loopd   s7     '//$$* $$s   0AAAAc                    K   y wrR   r!   rT   s    r#   rb   z%ReconnectingWebsocket._before_connecti   	        c                    K   y wrR   r!   rT   s    r#   rd   z$ReconnectingWebsocket._after_connectl   rl   rm   c                     | j                   r	 t        j                  |      }	 t        j                  |      S # t        t        f$ r Y y w xY w# t        $ r! | j                  j                  d|        Y y w xY w)Nzerror parsing evt json:)	rE   gzip
decompress
ValueErrorOSErrorjsonloadsr?   debug)rN   evts     r#   _handle_messagez%ReconnectingWebsocket._handle_messageo   ss    ??ooc*	::c?" (   	IIOO5cU;<	s    9 A A
A'A87A8c                 R  K   	 	 	 | j                   t        j                  k(  r6| j                          d {    | j                   t        j                  k(  r6| j                   t        j                  k(  r7| j
                  j                  d| j                   d| j                           n| j                  j                  t        j                  j                  j                  k(  rt        j                  d       d {    | j                  j                  t        j                  j                  j                  k(  r| j!                          d {    n | j                   t        j"                  k(  r| j                  sJ t        j$                  | j                  j'                         | j(                         d {   }| j+                  |      }|r| j,                  j/                         | j0                  k  r$| j,                  j3                  |       d {    nU| j
                  j                  d| j0                   d       | j,                  j3                  ddd	       d {    t4        yd | _!        d| _"        y 7 W7 7 >7 7 v7 (# t        j6                  $ r, | j
                  j                  d
| j(                   d       Y ^t        j8                  $ r(}| j
                  j                  d|        Y d }~d }~wt        j:                  $ r)}| j
                  j                  d| d       Y d }~d }~wt<        $ r)}| j
                  j                  d| d       Y d }~d }~wt>        $ r*}| j
                  j                  d| d       Y d }~.d }~wt4        $ r*}| j
                  j                  d| d       Y d }~]d }~wt@        $ r*}| j
                  j                  d| d       Y d }~d }~ww xY w# d | _!        d| _"        w xY ww)Nz_read_loop z break for r4   timeoutzQueue overflow z. Message not filledr[   z"Queue overflow. Message not filledemno message in  secondszcancelled error zincomplete read error ()zconnection close error (zDNS Error (z!BinanceWebsocketUnableToConnect (zUnknown exception (r   )#rI   r   r   _run_reconnectr    r?   rv   r@   rH   staterW   StateCLOSINGrJ   r   CLOSEDrc   r   wait_forrecvTIMEOUTrx   rL   qsizeMAX_QUEUE_SIZEputr   TimeoutErrorCancelledErrorIncompleteReadErrorr   r   	ExceptionrM   rD   )rN   resr}   s      r#   rg   z ReconnectingWebsocket._read_loop{   s2    0	!+--?+G+GG"11333 --?+G+GG }}(?(??		+djj\T]]O(\]"++*;*;*C*CC%mmC000 "++*;*;*B*BB"oo////*C*CC#www$+$4$4TWW\\^T\\$ZZ"2237#{{002T5H5HH&*kkooc&: : : $		/$BUBUAVVj0k l&*kkoo)0)M7" '# !# !# 'F E5 \ &*D" DY 4 1 0 [ !;!#
 ++ MIIOOnT\\N($KL-- IIOO&6qc$:;22 DIIOO&=aS$BCC, EIIOO&>qc$CDD 8IIOOk!A$6776 IIOO&Gs!$LM  IIOO&9!A$>? &*D" Ds9  P'P 0J J!J AJ +P -AJ  JJ P AJ JA.J JAJ !J"AJ 1J2
J <P >P'J J J J J J <PP P,L
P P%M	P 	PM94P 9PN*$P *P6OP P'PP PP P$$P'c                 8  K   | j                          d {    | j                  | j                  k  r| j                  | j                        }| j                  j                  d| j                  | j                  z
   d|        t        j                  |       d {    | j                          d {    y | j                  j                  d| j                   d       | j                  j                  ddd       d {    t        7 7 t7 ^7 w)Nzwebsocket reconnecting. z reconnects left - waiting zMax reconnections z	 reached:r[   zMax reconnect retries reachedr|   )before_reconnectrD   MAX_RECONNECTS_get_reconnect_waitr?   rv   rJ   r   rS   r[   rL   r   r   )rN   reconnect_waits     r#   r   z$ReconnectingWebsocket._run_reconnect   s    ##%%%d111!55d6F6FGNIIOO*4+>+>AQAQ+Q*R S)*, --///,,.  IIOO01D1D0EYOP++//4#    21! 	& 0 sG   DDBDD D7D8ADDDDDDc                 (  K   d }|sE	 t        j                  | j                  j                         | j                         d {   }|sE|S 7 	# t         j
                  $ r, | j                  j                  d| j                   d       Y Ew xY ww)Nrz   r   r   )rJ   r   rL   getr   r   r?   rv   )rN   r   s     r#   r   zReconnectingWebsocket.recv   s}     I#,,T[[__->UU 
 
 V'' I		.h GHIs@   B<A AA 	BBA <BBBBc                 &  K   | j                   t        j                  k7  rn| j                   t        j                  k7  rPt	        d       d {    | j                   t        j                  k7  r| j                   t        j                  k7  rNy y y y 7 Cwrj   )rI   r   r   r    r   rT   s    r#   _wait_for_reconnectz)ReconnectingWebsocket._wait_for_reconnect   sg     mm888T]]oNeNe=e* mm888T]]oNeNe=e8=e8s   A	BB>BBattemptsreturnc                 l    d|z  }t        t               t        | j                  |dz
        z  dz         S )N   r   )roundr   minMAX_RECONNECT_SECONDS)rN   r   expos      r#   r   z)ReconnectingWebsocket._get_reconnect_wait   s3    H}VXD$>$>q IIAMNNr"   c                    K   | j                   r8| j                  r,| j                  j                  d d d        d {    d | _         | xj                  dz  c_        y 7 !w)Nr   )rH   rF   rZ   rD   rT   s    r#   r   z&ReconnectingWebsocket.before_reconnect   sL     77tzz**&&tT4888DGA 9s   9AA"Ac                 d    | j                   j                  d       t        j                  | _        y )Nz!No message received, reconnecting)r?   rv   r   r   rI   rT   s    r#   _no_message_received_reconnectz4ReconnectingWebsocket._no_message_received_reconnect   s     		;<'44r"   c                 6   K   t         j                  | _        y wrR   )r   r   rI   rT   s    r#   rc   z ReconnectingWebsocket._reconnect   s     '44s   )Nws/FN)r   r   r   r   r   MIN_RECONNECT_WAITr   NO_MESSAGE_RECONNECT_TIMEOUTr   strr   boolrP   rU   rZ   rS   r\   rb   rd   rx   rg   r   r   r   intr   r   r   rc   r!   r"   r#   r1   r1   (   s    NG#% N mq&&&sm&<?&TX&$)m"

1!f2&OC OC O55r"   r1   c                   R     e Zd Z	 	 d	def fdZ fdZd Zd Zd Zd Z	d Z
 xZS )
KeepAliveWebsocketclientc                 v    t         |   d ||||       || _        || _        |xs t        | _        d | _        y )N)r8   r7   r9   r:   rO   )superrP   _keepalive_type_clientKEEPALIVE_TIMEOUT_user_timeout_timer)	rN   r   r7   keepalive_typer9   r:   rO   user_timeout	__class__s	           r#   rP   zKeepAliveWebsocket.__init__   sB     	dFi[de-)>->r"   c                    K   | j                   sy | j                  r!| j                  j                          d | _        t        |   |i | d {    y 7 wrR   )r@   r   cancelr   rZ   )rN   argskwargsr   s      r#   rZ   zKeepAliveWebsocket.__aexit__   sG     zz;;KK DKg0000s   AAAAc                 d   K   | j                   s| j                          d {   | _         y y 7 wrR   )r@   _get_listen_keyrT   s    r#   rb   z"KeepAliveWebsocket._before_connect   s(     zz#3355DJ 5s    0.0c                 ,   K   | j                          y wrR   )_start_socket_timerrT   s    r#   rd   z!KeepAliveWebsocket._after_connect   s       "s   c                 b      j                   j                   j                   fd       _        y )Nc                  J    t        j                   j                               S rR   )rJ   rf   _keepalive_socketrT   s   r#   <lambda>z8KeepAliveWebsocket._start_socket_timer.<locals>.<lambda>   s    G''(>(>(@Ar"   )r<   
call_laterr   r   rT   s   `r#   r   z&KeepAliveWebsocket._start_socket_timer   s%    jj++A
r"   c                   K   | j                   dk(  r$| j                  j                          d {   }|S | j                   dk(  r$| j                  j                          d {   }|S | j                   dk(  r$| j                  j	                          d {   }|S | j                   dk(  r$| j                  j                          d {   }|S | j                  j                  | j                          d {   }|S 7 7 7 l7 ;7 w)Nusermarginfuturescoin_futures)r   r   stream_get_listen_keymargin_stream_get_listen_keyfutures_stream_get_listen_key"futures_coin_stream_get_listen_key%isolated_margin_stream_get_listen_keyrN   
listen_keys     r#   r   z"KeepAliveWebsocket._get_listen_key  s     6)#||AACCJ  !!X-#||HHJJJ  !!Y.#||IIKKJ  !!^3#||NNPPJ   $||QQRVRfRfggJ DJKP hsW   -DC>2D"D #2DD2DD	.D7D8D DDDDc                   K   	 | j                          d {   }|| j                  k7  r<| j                  j                  d       || _        | j	                          d {    nG| j                  j                  d       | j
                  dk(  r.| j                  j                  | j                         d {    n| j
                  dk(  r.| j                  j                  | j                         d {    n| j
                  dk(  r.| j                  j                  | j                         d {    nu| j
                  dk(  r.| j                  j                  | j                         d {    n8| j                  j                  | j
                  | j                         d {    | j                          y 7 7 b7 7 7 7 [7 $# t        $ r Y -w xY w# | j                          w xY ww)Nzlisten key changed: reconnectzlisten key same: keepaliver   r   r   r   )r   r@   r?   rv   rc   r   r   stream_keepalivemargin_stream_keepalivefutures_stream_keepalivefutures_coin_stream_keepalive isolated_margin_stream_keepaliver   r   r   s     r#   r   z$KeepAliveWebsocket._keepalive_socket  s    	'#3355JTZZ'		 ?@'
oo'''		 <=''61,,77

CCC))X5,,>>tzzJJJ))Y6,,??

KKK))^;,,DDTZZPPP ,,GGH\H\^b^h^hiii $$&+ 6 ( DJKP j 		 $$&s   G4G F?AG  G!AG 9G:<G 6G7<G 3G
4<G 0G18G )G*G .G4?G G G G 
G G G 	GG GG G11G4)r   FNN)r   r   r   r   rP   rZ   rb   rd   r   r   r   __classcell__r   s   @r#   r   r      s8     bf!16#
'r"   r   c                      e 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efdefdZdIdee   fdZdddej*                  fdedee   dedededefdZ	 dJdedee   dedefdZdKdededefdZdLdedefdZdefdZdMdedee   d ee   fd!Zej@                  fdefd"Z!ej@                  ejD                  e#jH                  fdeded#e#fd$Z%dNd%efd&Z&defd'Z'defd(Z(ejD                  fdedefd)Z)defd*Z*defd+Z+d, Z,dOded.efd/Z-d
ejD                  fdedefd0Z.d-ejD                  fded.edefd1Z/d-ejD                  fd.edefd2Z0ejD                  fdedefd3Z1ejD                  fdedefd4Z2ejD                  fdefd5Z3defd6Z4d7 Z5d8e6e   fd9Z7d8e6e   fd:Z8ejD                  fd8e6e   defd;Z9d< Z:d= Z;d> Z<d? Z=d@ Z>defdAZ?defdBZ@dedCefdDZAdefdEZBej@                  fdefdFZCdPdedefdGZDdH ZEy)QBinanceSocketManagerzwss://stream.binance.{}:9443/zwss://testnet.binance.vision/zwss://fstream.binance.{}/zwss://stream.binancefuture.com/zwss://dstream.binance.{}/z wss://dstream.binancefuture.com/zwss://vstream.binance.{}/zwss://testnetws.binanceops.{}/51020r   c                 &   | j                   j                  |j                        | _         | j                  j                  |j                        | _        | j                  j                  |j                        | _        | j
                  j                  |j                        | _        | j                  j                  |j                        | _        i | _        t               | _	        || _
        || _        | j                  j                  | _        y)zInitialise the BinanceSocketManager

        :param client: Binance API client
        :type client: binance.AsyncClient

        N)
STREAM_URLformattldFSTREAM_URLDSTREAM_URLVSTREAM_URLVSTREAM_TESTNET_URL_connsr   r<   r   r   testnet)rN   r   r   s      r#   rP   zBinanceSocketManager.__init__7  s     //00<++226::>++226::>++226::>#'#;#;#B#B6::#N Z
)||++r"   N
stream_urlc                 V    |r|S | j                   }| j                  r| j                  }|S rR   )r   r   STREAM_TESTNET_URLrN   r   s     r#   _get_stream_urlz$BinanceSocketManager._get_stream_urlK  s,    __
<<00Jr"   r   Fr8   r9   r:   socket_typer   c                       d| }| j                   vr0t        | j                  |      | fd|       j                   |<    j                   |   S )N_c                 0    j                   d|        S )Nr   )_exit_socket)prN   r   s    r#   r   z2BinanceSocketManager._get_socket.<locals>.<lambda>]  s    D$5$5Qqc6J$Kr"   )r8   r7   r9   rO   r:   )r   r1   r   )rN   r8   r   r9   r:   r   conn_ids   `    ` r#   _get_socketz BinanceSocketManager._get_socketS  s_     !M4&)$++%#8((4K#$DKK  {{7##r"   c           	          t         j                   d| }|| j                  vrLt        | j                  | j                  |      ||| j                  || j                        | j                  |<   | j                  |   S )Nr   )r   r7   r   r9   rO   r:   r   )r%   r/   r   r   r   r   r   r   )rN   r8   r   r9   r:   r   s         r#   _get_account_socketz(BinanceSocketManager._get_account_socketc  s{     '../q7$++%#5||((4#++#!//$DKK  {{7##r"   futures_typec                    t         j                  }|t        j                  k(  r%| j                  }| j
                  r1| j                  }n$| j                  }| j
                  r| j                  }| j                  ||||      S )N)r   )
r%   r,   r   USD_Mr   r   FSTREAM_TESTNET_URLr   DSTREAM_TESTNET_URLr   )rN   r8   r   r9   r   r   s         r#   _get_futures_socketz(BinanceSocketManager._get_futures_sockett  so    ):)H)H;,,,))J||!55
))J||!55
j&kRRr"   c                     | j                   }| j                  r| j                  }| j                  |||dt        j
                        S )NT)r:   r   )r   r   r   r   r%   r.   )rN   r8   r9   r   s       r#   _get_options_socketz(BinanceSocketManager._get_options_socket  sB    %%
<<11Jj&DVgVoVoppr"   c                 B   K   | j                  |       d {    y 7 wrR   )_stop_socket)rN   r8   s     r#   r   z!BinanceSocketManager._exit_socket  s     %%%s   symboldepthintervalc                     |j                         dz   }|r|dk7  r| | }|r|dv r	| d| d}nt        d      | j                  |      S )a		  Start a websocket for symbol market depth returning either a diff or a partial book

        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#partial-book-depth-streams

        :param symbol: required
        :type symbol: str
        :param depth: optional Number of depth entries to return, default None. If passed returns a partial book instead of a diff
        :type depth: str
        :param interval: optional interval for updates, default None. If not set, updates happen every second. Must be 0, None (1s) or 100 (100ms)
        :type interval: int

        :returns: connection key string if successful, False otherwise

        Partial Message Format

        .. code-block:: python

            {
                "lastUpdateId": 160,  # Last update ID
                "bids": [             # Bids to be updated
                    [
                        "0.0024",     # price level to be updated
                        "10",         # quantity
                        []            # ignore
                    ]
                ],
                "asks": [             # Asks to be updated
                    [
                        "0.0026",     # price level to be updated
                        "100",        # quantity
                        []            # ignore
                    ]
                ]
            }


        Diff Message Format

        .. code-block:: python

            {
                "e": "depthUpdate", # Event type
                "E": 123456789,     # Event time
                "s": "BNBBTC",      # Symbol
                "U": 157,           # First update ID in event
                "u": 160,           # Final update ID in event
                "b": [              # Bids to be updated
                    [
                        "0.0024",   # price level to be updated
                        "10",       # quantity
                        []          # ignore
                    ]
                ],
                "a": [              # Asks to be updated
                    [
                        "0.0026",   # price level to be updated
                        "100",      # quantity
                        []          # ignore
                    ]
                ]
            }

        @depth1)r   r6   @mszAWebsocket interval value not allowed. Allowed values are [0, 100])lowerrr   r   )rN   r  r  r  socket_names        r#   depth_socketz!BinanceSocketManager.depth_socket  sf    @ llnx/Uc\(M%1K8#!,Qxj; !dee,,r"   c                 N    |j                          d| }| j                  |      S )aW  Start a websocket for symbol kline data

        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#klinecandlestick-streams

        :param symbol: required
        :type symbol: str
        :param interval: Kline interval, default KLINE_INTERVAL_1MINUTE
        :type interval: str

        :returns: connection key string if successful, False otherwise

        Message Format

        .. code-block:: python

            {
                "e": "kline",					# event type
                "E": 1499404907056,				# event time
                "s": "ETHBTC",					# symbol
                "k": {
                    "t": 1499404860000, 		# start time of this bar
                    "T": 1499404919999, 		# end time of this bar
                    "s": "ETHBTC",				# symbol
                    "i": "1m",					# interval
                    "f": 77462,					# first trade id
                    "L": 77465,					# last trade id
                    "o": "0.10278577",			# open
                    "c": "0.10278645",			# close
                    "h": "0.10278712",			# high
                    "l": "0.10278518",			# low
                    "v": "17.47929838",			# volume
                    "n": 4,						# number of trades
                    "x": false,					# whether this bar is final
                    "q": "1.79662878",			# quote volume
                    "V": "2.34879839",			# volume of active buy
                    "Q": "0.24142166",			# quote volume of active buy
                    "B": "13279784.01349473"	# can be ignored
                    }
            }
        @kline_)r  r   )rN   r  r  r8   s       r#   kline_socketz!BinanceSocketManager.kline_socket  s-    R ,,.!
3%%r"   contract_typec                 n    |j                          d|j                   d| }| j                  |d|      S )a  Start a websocket for symbol kline data for the perpeual futures stream

        https://binance-docs.github.io/apidocs/futures/en/#continuous-contract-kline-candlestick-streams

        :param symbol: required
        :type symbol: str
        :param interval: Kline interval, default KLINE_INTERVAL_1MINUTE
        :type interval: str
        :param futures_type: use USD-M or COIN-M futures default USD-M
        :param contract_type: use PERPETUAL or CURRENT_QUARTER or NEXT_QUARTER default PERPETUAL

        :returns: connection key string if successful, False otherwise

        Message Format

        .. code-block:: python

                {
                "e":"continuous_kline",   // Event type
                "E":1607443058651,        // Event time
                "ps":"BTCUSDT",           // Pair
                "ct":"PERPETUAL"          // Contract type
                "k":{
                    "t":1607443020000,      // Kline start time
                    "T":1607443079999,      // Kline close time
                    "i":"1m",               // Interval
                    "f":116467658886,       // First trade ID
                    "L":116468012423,       // Last trade ID
                    "o":"18787.00",         // Open price
                    "c":"18804.04",         // Close price
                    "h":"18804.04",         // High price
                    "l":"18786.54",         // Low price
                    "v":"197.664",          // volume
                    "n": 543,               // Number of trades
                    "x":false,              // Is this kline closed?
                    "q":"3715253.19494",    // Quote asset volume
                    "V":"184.769",          // Taker buy volume
                    "Q":"3472925.84746",    //Taker buy quote asset volume
                    "B":"0"                 // Ignore
                }
            }
            <pair>_<contractType>@continuousKline_<interval>
        r   z@continuousKline_r   r9   r   )r  valuer   )rN   r  r  r   r  r8   s         r#   kline_futures_socketz)BinanceSocketManager.kline_futures_socket  sB    ^ ,,.!=#6#6"77H
S''U'VVr"   update_timec                 ,    | j                  d| d      S )a  Start a miniticker websocket for all trades

        This is not in the official Binance api docs, but this is what
        feeds the right column on a ticker page on Binance.

        :param update_time: time between callbacks in milliseconds, must be 1000 or greater
        :type update_time: int

        :returns: connection key string if successful, False otherwise

        Message Format

        .. code-block:: python

            [
                {
                    'e': '24hrMiniTicker',  # Event type
                    'E': 1515906156273,     # Event time
                    's': 'QTUMETH',         # Symbol
                    'c': '0.03836900',      # close
                    'o': '0.03953500',      # open
                    'h': '0.04400000',      # high
                    'l': '0.03756000',      # low
                    'v': '147435.80000000', # volume
                    'q': '5903.84338533'    # quote volume
                }
            ]
        z!miniTicker@arr@r
  r   )rN   r  s     r#   miniticker_socketz&BinanceSocketManager.miniticker_socket1  s    < "2;-r BCCr"   c                 F    | j                  |j                         dz         S )a  Start a websocket for symbol trade data

        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#trade-streams

        :param symbol: required
        :type symbol: str

        :returns: connection key string if successful, False otherwise

        Message Format

        .. code-block:: python

            {
                "e": "trade",     # Event type
                "E": 123456789,   # Event time
                "s": "BNBBTC",    # Symbol
                "t": 12345,       # Trade ID
                "p": "0.001",     # Price
                "q": "100",       # Quantity
                "b": 88,          # Buyer order Id
                "a": 50,          # Seller order Id
                "T": 123456785,   # Trade time
                "m": true,        # Is the buyer the market maker?
                "M": true         # Ignore.
            }

        @trader   r  rN   r  s     r#   trade_socketz!BinanceSocketManager.trade_socketQ  s     <  9::r"   c                 F    | j                  |j                         dz         S )a  Start a websocket for symbol trade data

        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#aggregate-trade-streams

        :param symbol: required
        :type symbol: str

        :returns: connection key string if successful, False otherwise

        Message Format

        .. code-block:: python

            {
                "e": "aggTrade",		# event type
                "E": 1499405254326,		# event time
                "s": "ETHBTC",			# symbol
                "a": 70232,				# aggregated tradeid
                "p": "0.10281118",		# price
                "q": "8.15632997",		# quantity
                "f": 77489,				# first breakdown trade id
                "l": 77489,				# last breakdown trade id
                "T": 1499405254324,		# trade time
                "m": false,				# whether buyer is a maker
                "M": true				# can be ignored
            }

        	@aggTrader  r  s     r#   aggtrade_socketz$BinanceSocketManager.aggtrade_socketq  s     :  <==r"   c                 J    | j                  |j                         dz   |      S )aP  Start a websocket for aggregate symbol trade data for the futures stream

        :param symbol: required
        :param futures_type: use USD-M or COIN-M futures default USD-M

        :returns: connection key string if successful, False otherwise

        Message Format

        .. code-block:: python

            {
                "e": "aggTrade",  // Event type
                "E": 123456789,   // Event time
                "s": "BTCUSDT",    // Symbol
                "a": 5933014,     // Aggregate trade ID
                "p": "0.001",     // Price
                "q": "100",       // Quantity
                "f": 100,         // First trade ID
                "l": 105,         // Last trade ID
                "T": 123456785,   // Trade time
                "m": true,        // Is the buyer the market maker?
            }

        r   r   r   r  rN   r  r   s      r#   aggtrade_futures_socketz,BinanceSocketManager.aggtrade_futures_socket  s&    4 ''(DS_'``r"   c                 F    | j                  |j                         dz         S )a  Start a websocket for a symbol's miniTicker data

                https://binance-docs.github.io/apidocs/spot/en/#individual-symbol-mini-ticker-stream

                :param symbol: required
                :type symbol: str

                :returns: connection key string if successful, False otherwise

                Message Format

                .. code-block:: python

                    {
                        "e": "24hrMiniTicker",  // Event type
                        "E": 123456789,         // Event time
                        "s": "BNBBTC",          // Symbol
                        "c": "0.0025",          // Close price
                        "o": "0.0010",          // Open price
                        "h": "0.0025",          // High price
                        "l": "0.0010",          // Low price
                        "v": "10000",           // Total traded base asset volume
                        "q": "18"               // Total traded quote asset volume
                    }

                z@miniTickerr  r  s     r#   symbol_miniticker_socketz-BinanceSocketManager.symbol_miniticker_socket  s     6  >??r"   c                 F    | j                  |j                         dz         S )a  Start a websocket for a symbol's ticker data

        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#individual-symbol-ticker-streams

        :param symbol: required
        :type symbol: str

        :returns: connection key string if successful, False otherwise

        Message Format

        .. code-block:: python

            {
                "e": "24hrTicker",  # Event type
                "E": 123456789,     # Event time
                "s": "BNBBTC",      # Symbol
                "p": "0.0015",      # Price change
                "P": "250.00",      # Price change percent
                "w": "0.0018",      # Weighted average price
                "x": "0.0009",      # Previous day's close price
                "c": "0.0025",      # Current day's close price
                "Q": "10",          # Close trade's quantity
                "b": "0.0024",      # Best bid price
                "B": "10",          # Bid bid quantity
                "a": "0.0026",      # Best ask price
                "A": "100",         # Best ask quantity
                "o": "0.0010",      # Open price
                "h": "0.0025",      # High price
                "l": "0.0010",      # Low price
                "v": "10000",       # Total traded base asset volume
                "q": "18",          # Total traded quote asset volume
                "O": 0,             # Statistics open time
                "C": 86400000,      # Statistics close time
                "F": 0,             # First trade ID
                "L": 18150,         # Last trade Id
                "n": 18151          # Total number of trades
            }

        @tickerr  r  s     r#   symbol_ticker_socketz)BinanceSocketManager.symbol_ticker_socket  s!    R  :;;r"   c                 $    | j                  d      S )a"  Start a websocket for all ticker data

        By default all markets are included in an array.

        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#all-market-tickers-stream

        :param coro: callback function to handle messages
        :type coro: function

        :returns: connection key string if successful, False otherwise

        Message Format

        .. code-block:: python

            [
                {
                    'F': 278610,
                    'o': '0.07393000',
                    's': 'BCCBTC',
                    'C': 1509622420916,
                    'b': '0.07800800',
                    'l': '0.07160300',
                    'h': '0.08199900',
                    'L': 287722,
                    'P': '6.694',
                    'Q': '0.10000000',
                    'q': '1202.67106335',
                    'p': '0.00494900',
                    'O': 1509536020916,
                    'a': '0.07887800',
                    'n': 9113,
                    'B': '1.00000000',
                    'c': '0.07887900',
                    'x': '0.07399600',
                    'w': '0.07639068',
                    'A': '2.41900000',
                    'v': '15743.68900000'
                }
            ]
        z!ticker@arrr  rT   s    r#   ticker_socketz"BinanceSocketManager.ticker_socket  s    T ..r"   Tfastc                 r    |rdnd}| j                  |j                         |z   t        j                        S )aP  Start a websocket for a symbol's futures mark price
        https://binance-docs.github.io/apidocs/delivery/en/#index-price-stream
        :param symbol: required
        :param fast: use faster or 1s default
        :returns: connection key string if successful, False otherwise

        Message Format
        .. code-block:: python
            {
                "e": "indexPriceUpdate",  // Event type
                "E": 1591261236000,       // Event time
                "i": "BTCUSD",            // Pair
                "p": "9636.57860000",     // Index Price
              }
        z@indexPrice@1sz@indexPricer#  )r   r  r   COIN_M)rN   r  r.  stream_names       r#   index_price_socketz'BinanceSocketManager.index_price_socket   s6      +/&M''(DS^SeSe'ffr"   c                 b    | j                  |j                         dz   t        |      z   |      S )aq  Subscribe to a futures depth data stream

        https://binance-docs.github.io/apidocs/futures/en/#partial-book-depth-streams

        :param symbol: required
        :type symbol: str
        :param depth: optional Number of depth entries to return, default 10.
        :type depth: str
        :param futures_type: use USD-M or COIN-M futures default USD-M
        r  r#  )r   r  r   )rN   r  r  r   s       r#   futures_depth_socketz)BinanceSocketManager.futures_depth_socket3  s/     ''(ACJ(N]i'jjr"   c                 V    |rdnd}| j                  |j                         |z   |      S )a  Start a websocket for a symbol's futures mark price
        https://binance-docs.github.io/apidocs/futures/en/#mark-price-stream
        :param symbol: required
        :param fast: use faster or 1s default
        :param futures_type: use USD-M or COIN-M futures default USD-M
        :returns: connection key string if successful, False otherwise
        Message Format
        .. code-block:: python
            {
                "e": "markPriceUpdate",  // Event type
                "E": 1562305380000,      // Event time
                "s": "BTCUSDT",          // Symbol
                "p": "11185.87786614",   // Mark price
                "r": "0.00030000",       // Funding rate
                "T": 1562306400000       // Next funding time
            }
        z@markPrice@1sz
@markPricer#  r$  )rN   r  r.  r   r1  s        r#   symbol_mark_price_socketz-BinanceSocketManager.symbol_mark_price_socket@  s/    $ *.o<''(DS_'``r"   c                 4    |rdnd}| j                  ||      S )ai  Start a websocket for all futures mark price data
        By default all symbols are included in an array.
        https://binance-docs.github.io/apidocs/futures/en/#mark-price-stream-for-all-market
        :param fast: use faster or 1s default
        :param futures_type: use USD-M or COIN-M futures default USD-M
        :returns: connection key string if successful, False otherwise
        Message Format
        .. code-block:: python

            [
                {
                    "e": "markPriceUpdate",  // Event type
                    "E": 1562305380000,      // Event time
                    "s": "BTCUSDT",          // Symbol
                    "p": "11185.87786614",   // Mark price
                    "r": "0.00030000",       // Funding rate
                    "T": 1562306400000       // Next funding time
                }
            ]
        z!markPrice@arr@1sz!markPrice@arrr#  r   )rN   r.  r   r1  s       r#   all_mark_price_socketz*BinanceSocketManager.all_mark_price_socketU  s%    * .2)7G'','OOr"   c                 J    | j                  |j                         dz   |      S )a  Start a websocket for a symbol's ticker data
        By default all markets are included in an array.
        https://binance-docs.github.io/apidocs/futures/en/#individual-symbol-book-ticker-streams
        :param symbol: required
        :param futures_type: use USD-M or COIN-M futures default USD-M
        :returns: connection key string if successful, False otherwise
        .. code-block:: python
            [
                {
                  "u":400900217,     // order book updateId
                  "s":"BNBUSDT",     // symbol
                  "b":"25.35190000", // best bid price
                  "B":"31.21000000", // best bid qty
                  "a":"25.36520000", // best ask price
                  "A":"40.66000000"  // best ask qty
                }
            ]
        @bookTickerr#  r$  r%  s      r#   symbol_ticker_futures_socketz1BinanceSocketManager.symbol_ticker_futures_socketm  s&    & ''(FUa'bbr"   c                 J    | j                  |j                         dz   |      S )ai  Start a futures websocket for a single symbol's ticker data
        https://binance-docs.github.io/apidocs/futures/en/#individual-symbol-ticker-streams
        :param symbol: required
        :type symbol: str
        :param futures_type: use USD-M or COIN-M futures default USD-M
        :returns: connection key string if successful, False otherwise
        .. code-block:: python
            {
                "e": "24hrTicker",  // Event type
                "E": 123456789,     // Event time
                "s": "BTCUSDT",     // Symbol
                "p": "0.0015",      // Price change
            }
        r*  r#  r$  r%  s      r#   'individual_symbol_ticker_futures_socketz<BinanceSocketManager.individual_symbol_ticker_futures_socket  s&     ''(BQ]'^^r"   c                 (    | j                  d|      S )a  Start a websocket for all ticker data
        By default all markets are included in an array.
        https://binance-docs.github.io/apidocs/futures/en/#all-book-tickers-stream
        :param futures_type: use USD-M or COIN-M futures default USD-M
        :returns: connection key string if successful, False otherwise
        Message Format
        .. code-block:: python
            [
                {
                  "u":400900217,     // order book updateId
                  "s":"BNBUSDT",     // symbol
                  "b":"25.35190000", // best bid price
                  "B":"31.21000000", // best bid qty
                  "a":"25.36520000", // best ask price
                  "A":"40.66000000"  // best ask qty
                }
            ]
        !bookTickerr#  r8  )rN   r   s     r#   all_ticker_futures_socketz.BinanceSocketManager.all_ticker_futures_socket  s    ( ''L'QQr"   c                 F    | j                  |j                         dz         S )a  Start a websocket for the best bid or ask's price or quantity for a specified symbol.

        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#individual-symbol-book-ticker-streams

        :param symbol: required
        :type symbol: str

        :returns: connection key string if successful, False otherwise

        Message Format

        .. code-block:: python

            {
                "u":400900217,     // order book updateId
                "s":"BNBUSDT",     // symbol
                "b":"25.35190000", // best bid price
                "B":"31.21000000", // best bid qty
                "a":"25.36520000", // best ask price
                "A":"40.66000000"  // best ask qty
            }

        r;  r  r  s     r#   symbol_book_ticker_socketz.BinanceSocketManager.symbol_book_ticker_socket  s     0  >??r"   c                 $    | j                  d      S )a  Start a websocket for the best bid or ask's price or quantity for all symbols.

        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#all-book-tickers-stream

        :returns: connection key string if successful, False otherwise

        Message Format

        .. code-block:: python

            {
                // Same as <symbol>@bookTicker payload
            }

        r@  r  rT   s    r#   book_ticker_socketz'BinanceSocketManager.book_ticker_socket  s      ..r"   streamsc                 P    ddj                  |       }| j                  |d      S )at  Start a multiplexed socket using a list of socket names.
        User stream sockets can not be included.

        Symbols in socket name must be lowercase i.e bnbbtc@aggTrade, neobtc@ticker

        Combined stream events are wrapped as follows: {"stream":"<streamName>","data":<rawPayload>}

        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md

        :param streams: list of stream names in lower case
        :type streams: list

        :returns: connection key string if successful, False otherwise

        Message Format - see Binance API docs for all types

        streams=/stream?r9   )joinr   )rN   rF  r8   s      r#   multiplex_socketz%BinanceSocketManager.multiplex_socket  s0    $ #((7+,-Y77r"   c                     dj                  |D cg c]  }|j                          c}      }d| }| j                  |d      S c c}w )af  Start a multiplexed socket using a list of socket names.
        User stream sockets can not be included.

        Symbols in socket name must be lowercase i.e bnbbtc@aggTrade, neobtc@ticker

        Combined stream events are wrapped as follows: {"stream":"<streamName>","data":<rawPayload>}

        https://binance-docs.github.io/apidocs/voptions/en/#account-and-trading-interface

        :param streams: list of stream names in lower case
        :type streams: list

        :returns: connection key string if successful, False otherwise

        Message Format - see Binance API docs for all types

        rI  rH  rJ  rK  )rL  r  r   )rN   rF  sr1  stream_paths        r#   options_multiplex_socketz-BinanceSocketManager.options_multiplex_socket  sN    $ hh7;7a	7;< .''I'FF  <s   Ac                 R    ddj                  |       }| j                  |d|      S )a  Start a multiplexed socket using a list of socket names.
        User stream sockets can not be included.

        Symbols in socket name must be lowercase i.e bnbbtc@aggTrade, neobtc@ticker

        Combined stream events are wrapped as follows: {"stream":"<streamName>","data":<rawPayload>}

        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md

        :param streams: list of stream names in lower case
        :param futures_type: use USD-M or COIN-M futures default USD-M

        :returns: connection key string if successful, False otherwise

        Message Format - see Binance API docs for all types

        rH  rI  rJ  r  )rL  r   )rN   rF  r   r8   s       r#   futures_multiplex_socketz-BinanceSocketManager.futures_multiplex_socket   s2    $ #((7+,-''Y\'ZZr"   c                 p    | j                   }| j                  r| j                  }| j                  d|      S )a\  Start a websocket for user data

        https://github.com/binance-exchange/binance-official-api-docs/blob/master/user-data-stream.md
        https://binance-docs.github.io/apidocs/spot/en/#listen-key-spot

        :returns: connection key string if successful, False otherwise

        Message Format - see Binance API docs for all types
        r   r   r   r   r   r   r   s     r#   user_socketz BinanceSocketManager.user_socket  s5     __
<<00J'':'FFr"   c                 p    | j                   }| j                  r| j                  }| j                  d|      S )a	  Start a websocket for coin futures user data

        https://binance-docs.github.io/apidocs/futures/en/#user-data-streams

        :returns: connection key string if successful, False otherwise

        Message Format - see Binanace API docs for all types
        r   rU  r   r   r   r   r   s     r#   futures_user_socketz(BinanceSocketManager.futures_user_socket$  s7     %%
<<11J''	j'IIr"   c                 p    | j                   }| j                  r| j                  }| j                  d|      S )a   Start a websocket for cross-margin data

        https://binance-docs.github.io/apidocs/spot/en/#listen-key-margin

        :returns: connection key string if successful, False otherwise

        Message Format - see Binance API docs for all types
        r   rU  rV  r   s     r#   margin_socketz"BinanceSocketManager.margin_socket3  s5     __
<<00J''Z'HHr"   c                 p    | j                   }| j                  r| j                  }| j                  d|      S )a	  Start a websocket for futures data

            https://binance-docs.github.io/apidocs/futures/en/#websocket-market-streams

        :returns: connection key string if successful, False otherwise

        Message Format - see Binance API docs for all types
        r   rU  rY  r   s     r#   futures_socketz#BinanceSocketManager.futures_socketA  s7     %%
<<11J''	j'IIr"   c                 p    | j                   }| j                  r| j                  }| j                  d|      S )a  Start a websocket for coin futures data

            https://binance-docs.github.io/apidocs/delivery/en/#websocket-market-streams

        :returns: connection key string if successful, False otherwise

        Message Format - see Binance API docs for all types
        r   rU  )r   r   r   r   r   s     r#   coin_futures_socketz(BinanceSocketManager.coin_futures_socketO  s7     %%
<<11J'':'NNr"   c                 p    | j                   }| j                  r| j                  }| j                  ||      S )ap  Start a websocket for isolated margin data

        https://binance-docs.github.io/apidocs/spot/en/#listen-key-isolated-margin

        :param symbol: required - symbol for the isolated margin account
        :type symbol: str

        :returns: connection key string if successful, False otherwise

        Message Format - see Binance API docs for all types
        rU  rV  )rN   r  r   s      r#   isolated_margin_socketz+BinanceSocketManager.isolated_margin_socket]  s5     __
<<00J'':'FFr"   c                 F    | j                  |j                         dz         S )zSubscribe to a 24 hour ticker info stream

        https://binance-docs.github.io/apidocs/voptions/en/#market-streams-payload-24-hour-ticker

        :param symbol: required
        :type symbol: str
        r*  r   r  r  s     r#   options_ticker_socketz*BinanceSocketManager.options_ticker_socketn  s      ''(BCCr"   expiration_datec                 L    | j                  |j                         dz   |z         S )a,  Subscribe to a 24 hour ticker info stream
        https://binance-docs.github.io/apidocs/voptions/en/#24-hour-ticker-by-underlying-asset-and-expiration-data
        :param symbol: required
        :type symbol: str
        :param expiration_date : required
        :type expiration_date: str
        z@ticker@rd  )rN   r  rf  s      r#   #options_ticker_by_expiration_socketz8BinanceSocketManager.options_ticker_by_expiration_socketx  s%     ''(Co(UVVr"   c                 F    | j                  |j                         dz         S )zSubscribe to a latest completed trades stream

        https://binance-docs.github.io/apidocs/voptions/en/#market-streams-payload-latest-completed-trades

        :param symbol: required
        :type symbol: str
        r  rd  r  s     r#   options_recent_trades_socketz1BinanceSocketManager.options_recent_trades_socket  s      ''(ABBr"   c                 L    | j                  |j                         dz   |z         S )a)  Subscribe to a candlestick data stream

        https://binance-docs.github.io/apidocs/voptions/en/#market-streams-payload-candle

        :param symbol: required
        :type symbol: str
        :param interval: Kline interval, default KLINE_INTERVAL_1MINUTE
        :type interval: str
        r  rd  )rN   r  r  s      r#   options_kline_socketz)BinanceSocketManager.options_kline_socket  s%     ''(BX(MNNr"   c                 ^    | j                  |j                         dz   t        |      z         S )a%  Subscribe to a depth data stream

        https://binance-docs.github.io/apidocs/voptions/en/#market-streams-payload-depth

        :param symbol: required
        :type symbol: str
        :param depth: optional Number of depth entries to return, default 10.
        :type depth: str
        r  )r   r  r   )rN   r  r  s      r#   options_depth_socketz)BinanceSocketManager.options_depth_socket  s)     ''(ACJ(NOOr"   c                 D   K   || j                   vry| j                   |= yw)zStop a websocket given the connection key

        :param conn_key: Socket connection key
        :type conn_key: string

        :returns: None
        N)r   )rN   conn_keys     r#   r  z!BinanceSocketManager._stop_socket  s#      4;;&[["s    rR   )Nr   F)zstream?streams=)r   NNi  Tr   )Fr   r   r   r   r   r   r   r   r   r   r   WEBSOCKET_DEPTH_5WEBSOCKET_DEPTH_10WEBSOCKET_DEPTH_20r   r   rP   r   r   r   r%   r+   r   r1   r   r   r   r   r   r   r   r  KLINE_INTERVAL_1MINUTEr  r   r   	PERPETUALr  r  r  r!  r&  r(  r+  r-  r2  r4  r6  r9  r<  r>  rA  rC  rE  r   rM  rQ  rS  rW  rZ  r\  r^  r`  rb  re  rh  rj  rl  rn  r  r!   r"   r#   r   r   )  s   0J8-K;-K<-K:9J ,{ ,((3-  6:bg):)?)?$$%-c]$CF$[_$&$ 
$" ch$$%-c]$CF$[_$"
S 
S; 
SPS 
Sq qS q&s &H-3 H-x} H-xX[} H-T 2=1S1S *&3 *&X :E9[9[9D9J9J;G;Q;Q0W3 0W+60W,80WdDS D@;3 ;@>c >> P[O`O` ac a a8@s @:)<3 )<V*/Xg gD g& >BP[PaPa k3 ks k BFcnctct as a$ aU` a* 26S^SdSd P$ P[ P0 U`TeTe c3 ck c* `k_p_p _c _Q\ _" EPDUDU Rk R,@ @4/$8S	 8*GS	 G, XcWhWh [S	 [ [*GJIJOGS G"DC DW# WPS WC3 C :E9[9[ 
O3 
O
P3 
Ps 
P$r"   r   c                       e Zd Z	 	 	 d;dee   dee   deeeef      dededeeeef      f fdZd Z		 d<d	e
d
edeeef   dee   def
dZ	 d=d	e
dedee   dee   def
dZej                  fd	e
dedefdZej                  ej$                  ej(                  fd	e
dedededef
dZd>d	e
dedefdZd	e
dedefdZd	e
dedefdZej$                  fd	e
dededefdZd	e
dedefdZd	e
dedefdZd	e
defdZd?d	e
ded edefd!Zdej$                  fd	e
ded ededef
d"Zdej$                  fd	e
d ededefd#Zej$                  fd	e
dededefd$Z ej$                  fd	e
dededefd%Z!ej$                  fd	e
dedefd&Z"d	e
dedefd'Z#d	e
defd(Z$d	e
d)e%e   defd*Z&d	e
d)e%e   defd+Z'ej$                  fd	e
d)e%e   dedefd,Z(d	e
defd-Z)d	e
defd.Z*d	e
defd/Z+d	e
defd0Z,d	e
defd1Z-d	e
dedefd2Z.d	e
dedefd3Z/d	e
ded4edefd5Z0d	e
dedefd6Z1ej                  fd	e
dedefd7Z2d@d	e
dededefd9Z3d8ej$                  fd	e
dededefd:Z4 xZ5S )AThreadedWebsocketManagerapi_key
api_secretrequests_paramsr   r   session_paramsc                 <    t         |   ||||||       d | _        y rR   )r   rP   _bsm)rN   r|  r}  r~  r   r   r  r   s          r#   rP   z!ThreadedWebsocketManager.__init__  s#    
 	*osG^\48	r"   c                 ^   K   | j                   sJ t        | j                         | _        y w)N)r   )r   r   r  rT   s    r#   _before_socket_listener_startz6ThreadedWebsocketManager._before_socket_listener_start  s"     |||(=	s   +-callbackr  paramsr8   r   c                 N   | j                   s"t        j                  d       | j                   s" t        | j                   |      di |}|xs |j                  }d| j
                  |<   | j                  j                  t        j                  | j                  |||             |S )Nr4   Tr!   )r  timer   getattrr@   _socket_runningr<   re   rJ   rf   start_listener)rN   r  r  r  r8   socketsocket_paths          r#   _start_async_socketz,ThreadedWebsocketManager._start_async_socket  s     ))JJsO ))0K0:6:/6<<,0[)

''(;(;T=P=PQWYdfn=opr"   r  r  r  c                 2    | j                  |d|||d      S )Nr  )r  r  r  r  r  r  r  )rN   r  r  r  r  s        r#   start_depth_socketz+ThreadedWebsocketManager.start_depth_socket  s0     ''& $ ( 
 	
r"   c                 0    | j                  |d||d      S )Nr  r  r  r  r  rN   r  r  r  s       r#   start_kline_socketz+ThreadedWebsocketManager.start_kline_socket  s+    ''& $ ( 
 	
r"   r   r  c           	      4    | j                  |d||||d      S )Nr  )r  r  r   r  r  r  )rN   r  r  r  r   r  s         r#   start_kline_futures_socketz3ThreadedWebsocketManager.start_kline_futures_socket  s3     ''. $ ,!.	 ( 	
 		
r"   r  c                 .    | j                  |dd|i      S )Nr  r  r  r  )rN   r  r  s      r#   start_miniticker_socketz0ThreadedWebsocketManager.start_miniticker_socket  s*    ''+{ ( 
 	
r"   c                 .    | j                  |dd|i      S )Nr  r  r  r  rN   r  r  s      r#   start_trade_socketz+ThreadedWebsocketManager.start_trade_socket  s*    ''&& ( 
 	
r"   c                 .    | j                  |dd|i      S )Nr!  r  r  r  r  s      r#   start_aggtrade_socketz.ThreadedWebsocketManager.start_aggtrade_socket  s*    '')& ( 
 	
r"   c                 0    | j                  |d||d      S )Nr&  r  r   r  r  rN   r  r  r   s       r#   start_aggtrade_futures_socketz6ThreadedWebsocketManager.start_aggtrade_futures_socket  s-     ''1  , ( 
 	
r"   c                 .    | j                  |dd|i      S )Nr(  r  r  r  r  s      r#   start_symbol_miniticker_socketz7ThreadedWebsocketManager.start_symbol_miniticker_socket  s*    ''2& ( 
 	
r"   c                 .    | j                  |dd|i      S )Nr+  r  r  r  r  s      r#   start_symbol_ticker_socketz3ThreadedWebsocketManager.start_symbol_ticker_socket!  s*    ''.& ( 
 	
r"   c                 *    | j                  |di       S )Nr-  r  r  rN   r  s     r#   start_ticker_socketz,ThreadedWebsocketManager.start_ticker_socket*  #    ''' ( 
 	
r"   Tr.  c                 0    | j                  |d||d      S )Nr2  )r  r.  r  r  )rN   r  r  r.  s       r#   start_index_price_socketz1ThreadedWebsocketManager.start_index_price_socket1  s+    '',  ( 
 	
r"   c                 2    | j                  |d|||d      S )Nr6  )r  r.  r   r  r  )rN   r  r  r.  r   s        r#   start_symbol_mark_price_socketz7ThreadedWebsocketManager.start_symbol_mark_price_socket;  s0     ''2  , ( 
 	
r"   c                 0    | j                  |d||d      S )Nr9  )r.  r   r  r  )rN   r  r.  r   s       r#   start_all_mark_price_socketz4ThreadedWebsocketManager.start_all_mark_price_socketH  s-     ''/ , ( 
 	
r"   c                 0    | j                  |d||d      S )Nr<  r  r  r  r  s       r#   "start_symbol_ticker_futures_socketz;ThreadedWebsocketManager.start_symbol_ticker_futures_socketT  s-     ''6  , ( 
 	
r"   c                 0    | j                  |d||d      S )Nr>  r  r  r  r  s       r#   -start_individual_symbol_ticker_futures_socketzFThreadedWebsocketManager.start_individual_symbol_ticker_futures_socket`  s-     ''A  , ( 
 	
r"   c                 .    | j                  |dd|i      S )NrA  r   r  r  )rN   r  r   s      r#   start_all_ticker_futures_socketz8ThreadedWebsocketManager.start_all_ticker_futures_socketl  s*    ''3 ( 
 	
r"   c                 .    | j                  |dd|i      S )NrC  r  r  r  r  s      r#   start_symbol_book_ticker_socketz8ThreadedWebsocketManager.start_symbol_book_ticker_socketu  s*    ''3& ( 
 	
r"   c                 *    | j                  |di       S )NrE  r  r  r  s     r#   start_book_ticker_socketz1ThreadedWebsocketManager.start_book_ticker_socket~  s#    '', ( 
 	
r"   rF  c                 .    | j                  |dd|i      S )NrM  rF  r  r  rN   r  rF  s      r#   start_multiplex_socketz/ThreadedWebsocketManager.start_multiplex_socket  s*    ''*7 ( 
 	
r"   c                 .    | j                  |dd|i      S )NrQ  rF  r  r  r  s      r#   start_options_multiplex_socketz7ThreadedWebsocketManager.start_options_multiplex_socket  s*    ''27 ( 
 	
r"   c                 0    | j                  |d||d      S )NrS  )rF  r   r  r  )rN   r  rF  r   s       r#   start_futures_multiplex_socketz7ThreadedWebsocketManager.start_futures_multiplex_socket  s-     ''2" , ( 
 	
r"   c                 *    | j                  |di       S )NrW  r  r  r  s     r#   start_user_socketz*ThreadedWebsocketManager.start_user_socket  s#    ''% ( 
 	
r"   c                 *    | j                  |di       S )NrZ  r  r  r  s     r#   start_futures_user_socketz2ThreadedWebsocketManager.start_futures_user_socket  #    ''- ( 
 	
r"   c                 *    | j                  |di       S )Nr\  r  r  r  s     r#   start_margin_socketz,ThreadedWebsocketManager.start_margin_socket  r  r"   c                 *    | j                  |di       S )Nr^  r  r  r  s     r#   start_futures_socketz-ThreadedWebsocketManager.start_futures_socket  s#    ''( ( 
 	
r"   c                 *    | j                  |di       S )Nr`  r  r  r  s     r#   start_coin_futures_socketz2ThreadedWebsocketManager.start_coin_futures_socket  r  r"   c                 .    | j                  |dd|i      S )Nrb  r  r  r  r  s      r#   start_isolated_margin_socketz5ThreadedWebsocketManager.start_isolated_margin_socket  s*    ''0& ( 
 	
r"   c                 .    | j                  |dd|i      S )Nre  r  r  r  r  s      r#   start_options_ticker_socketz4ThreadedWebsocketManager.start_options_ticker_socket  s*    ''/& ( 
 	
r"   rf  c                 0    | j                  |d||d      S )Nrh  )r  rf  r  r  )rN   r  r  rf  s       r#   )start_options_ticker_by_expiration_socketzBThreadedWebsocketManager.start_options_ticker_by_expiration_socket  s+    ''= #2 ( 
 	
r"   c                 .    | j                  |dd|i      S )Nrj  r  r  r  r  s      r#   "start_options_recent_trades_socketz;ThreadedWebsocketManager.start_options_recent_trades_socket  s*    ''6& ( 
 	
r"   c                 0    | j                  |d||d      S )Nrl  r  r  r  r  s       r#   start_options_kline_socketz3ThreadedWebsocketManager.start_options_kline_socket  s-     ''. $ ( 
 	
r"   r   c                 0    | j                  |d||d      S )Nrn  )r  r  r  r  )rN   r  r  r  s       r#   start_options_depth_socketz3ThreadedWebsocketManager.start_options_depth_socket  s+    ''.  ( 
 	
r"   c                 2    | j                  |d|||d      S )Nr4  )r  r  r   r  r  )rN   r  r  r  r   s        r#   start_futures_depth_socketz3ThreadedWebsocketManager.start_futures_depth_socket  s.    ''.  , ( 
 	
r"   )NNNcomFNrR   rq  rr  rs  rt  )6r   r   r   r   r   r	   r   r   rP   r  r
   r  r   r  r   rx  r  r   r   r   ry  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   s   @r#   r{  r{    sD    JNEJJN9}99A#9!$sCx.19?B9 9 08S#X/G9>
 cg	 	/2	<@cN	RZ[^R_			 gk
 
*-
6>sm
V^_bVc
	
 LWKmKm 
8 
S 
ru 
 -8,N,N?J?P?PAMAWAW
8 
S 
1<
 3?
 ]`

 
s 
VY 

8 
S 
S 

h 
 
 
 LWK\K\

 

*-

=H

	


x 
 
QT 

8 
S 
S 

H 
 

 
3 
d 
^a 
 =A^i^o^o
 
*-
59
P[
	
 04Q\QbQb

 

(,

CN

	

 LWK\K\

 

*-

=H

	

 LWK\K\

 

*-

=H

	

 _j^o^o 
 
P[ 
tw 

 
# 
RU 

 
c 

x 
$s) 
PS 

x 
$s) 
X[ 
 S^RcRc

 

+/9

DO

	


( 
s 

( 
s 

H 
 

X 
# 

( 
s 

X 
s 
s 

H 
c 
c 

( 
TW 
jm 
ru 

8 
S 
UX 
 9D8Z8Z

 

*-

	


8 
S 
QT 
`c 
 X\juj{j{ 	
8 	
S 	
QT 	
  AD 	
r"   r{  )(rJ   rp   rt   r=   r  r   enumr   r   r  r   typingr   r   r	   r
   r   
websocketsrH   websockets.exceptionsr   r   r   enumsr   
exceptionsr   r   helpersr   threaded_streamr   r   r   r   r%   r1   r   r   r{  r!   r"   r#   <module>r     s             6 6  7   7   / d T u5 u5pF'. F'RF$ F$RX
1 X
r"   