
    eif                        d dl Zd dlmZmZmZmZ d dlZd dlm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZ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 d
l!m"Z"  G d dej#        j$                  Z$dS )    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheBySymbolBySideArrayCacheByTimestamp)AnyBalancesIntLiquidationNumOrder	OrderBook	OrderSide	OrderTypePositionStrStringsTickerTickersTrade)Client)List)ArgumentsRequired)
BadRequest)NotSupported)ChecksumError)Precisec                       e Zd Zdef fdZd Zd ZdefdZdde	d	e	fd
Z
d Zd Zd Zddi fdedededee         fdZddi fdee         dededee         fdZdefdZddZddi fdedededee         fdZddi fdee         dededee         fdZdefdZdi fdededefdZdi fdee         dedefdZi fdee         defdZi fdedefdZdi fdededefdZdefdZd  Z d! Z!d" Z"defd#Z#defd$Z$defd%Z%defd&Z&ded'e'fd(Z(ddi fdee         dededee)         fd)Z*i fdee         defd*Z+i fdedefd+Z,ddi fdedededee)         fd,Z-dde)fd-Z.defd.Z/d/ddi fded0edededee0         f
d1Z1ddi fd2eee                  dedefd3Z2i fd2eee                  defd4Z3d/i fded0edefd5Z4defd6Z5i fdede6fd7Z7d/ddi fded0edededee0         f
d8Z8defd9Z9i fdede6fd:Z:i fdede6fd;Z;di fde<de=fd<Z>di fde<de=fd=Z?di fde<defd>Z@di fde<defd?ZAi fdedefd@ZBi fdedefdAZCdi fde<de=fdBZDdi dCfdDede<dEeEfdFZFdG ZGdefdHZHdefdIZIdefdJZJdefdKZKdefdLZLi fdMZMddOefdPZNdefdQZOdRi fdOefdSZPi fdTZQi fdUZRi fdVZSddefdWZTdX ZUi fdeVfdYZWdefdZZXdefd[ZYi fdedeeZ         fd\Z[di fde<deeZ         fd]Z\defd^Z]i fdeVfd_Z^defd`Z_daee         defdbZ`i fdcZadi fdedebddecdeeddfeedeffdgZgdefdhZhdefdiZiddi fdjededebddecdeeedfeedeffdkZjdefdlZkdi fdjede	deffdmZldi fde	fdnZmdi fdjede	deffdoZndddi fde	dededeef         fdpZodddi fde	dededeef         fdqZpdddi fde	dededeef         fdrZqdddi fde	dededeef         fdsZrddtZsdefduZtdddi fde<dededeeZ         fdvZuddede<fdwZvdx Zwdy ZxddzZydddi fde	dededee)         fd{Zzddi fdedededee)         fd|Z{defd}Z|dddi fde	dededee)         fd~Z}defdZ~defdZd ZdefdZdefdZdefdZ xZS )binancereturnc                     t          t          |                                           }|                     ||                                           S N)superr   describedeep_extenddescribe_data)selfsuperDescribe	__class__s     N/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/pro/binance.pyr#   zbinance.describe   s@    gt,,5577t/A/A/C/CDDD    c                    i ddddddddddddddd	dd
dddddddddddddddddi ddddddddddddddddddddddddd dd!dd"dd#dd$di d%dd&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0dd1dd2dd3dd4dd5dddddd6dd7d7d8d9d:d;d<d=d>idd?d?d8d9d@d;d<d=d>iddAdAdBdCdDdEdFd=dGdHidIdJdKdLii dMddNdOdOdOdOdPdQdRdRdRdRdPdS|                                  dTdUdVdWdXdYdZdYd[dYd\dYd]dYd^|                                  d_dYdd`daidd`dbidd`dcid
d`ddideddfdddgdhdiidddjdkdldmdnidbdcdodpdqdrdsdtdudvS )wNwsTwatchBalancewatchLiquidationswatchLiquidationsForSymbolswatchMyLiquidationswatchMyLiquidationsForSymbolswatchBidsAskswatchMyTrades
watchOHLCVwatchOHLCVForSymbolswatchOrderBookwatchOrderBookForSymbolswatchOrderswatchOrdersForSymbolswatchPositionswatchTickerwatchTickerswatchMarkPriceswatchMarkPricewatchTradeswatchTradesForSymbolscreateOrderWseditOrderWscancelOrderWscancelOrdersWsFcancelAllOrdersWsfetchBalanceWsfetchDepositsWsfetchMarketsWsfetchMyTradesWsfetchOHLCVWsfetchOrderBookWsfetchOpenOrdersWsfetchOrderWsfetchOrdersWsfetchPositionWsfetchPositionForSymbolWsfetchPositionsWsfetchTickerWsfetchTradesWsfetchTradingFeesWsfetchWithdrawalsWsunWatchTickerunWatchTickersunWatchOHLCVunWatchOHLCVForSymbolsunWatchOrderBookunWatchOrderBookForSymbolsunWatchTradesunWatchTradesForSymbolsunWatchMyTrades)unWatchOrdersunWatchPositionsunWatchMarkPricesunWatchMarkPricez&wss://stream.testnet.binance.vision/wsz"wss://fstream.binancefuture.com/wsz"wss://dstream.binancefuture.com/wsz-wss://ws-api.testnet.binance.vision/ws-api/v3z*wss://testnet.binancefuture.com/ws-fapi/v1z*wss://testnet.binancefuture.com/ws-dapi/v1)spotfuturedelivery)rc   marginrd   re   ws-apiz wss://demo-stream.binance.com/wsz'wss://demo-ws-api.binance.com/ws-api/v3z wss://stream.binance.com:9443/wszwss://fstream.binance.com/wszwss://dstream.binance.com/wsz&wss://ws-api.binance.com:443/ws-api/v3z$wss://ws-fapi.binance.com/ws-fapi/v1z$wss://ws-dapi.binance.com/ws-dapi/v1zwss://fstream.binance.com/pm/ws)rc   rf   rd   re   rg   papiz!https://developers.binance.com/en)testdemoapidoc	keepAlivei  returnRateLimitsstreamLimits2   )rc   rf   rd   re   subscriptionLimitByStream   streamBySubscriptionsHashstreamIndexwatchOrderBookRated   liquidationsLimit  myLiquidationsLimittradesLimitordersLimit
OHLCVLimit	requestIdwatchOrderBookLimitnametradeticker
miniTickerkline   )
maxRetrieschecksum)fetchBalanceSnapshotawaitBalanceSnapshotdefaultTypeswap)fetchPositionsSnapshotawaitPositionsSnapshotwbO cost   	markPrice	ticker_1h	ticker_4h	ticker_1d
bookTicker)
24hrTicker24hrMiniTickermarkPriceUpdate1hTicker4hTicker1dTickerr   )r6   r-   r/   r:   walletlistenKeyRefreshRater,   tickerChannelsMap)hasurls	streamingoptions)create_safe_dictionary)r&   s    r)   r%   zbinance.describe_data   s^   8d88 $T8 .t	8
 &t8 08  8  8 d8 '8 !$8 +D8 t8 (8 !$8  t!8" #8 8$ "4%8& !$'8( t)8* (+8,  -8. t/80  182 !%384 $T586 !$788 "598: !%;8< "4=8> ?8@ #DA8B $TC8D E8 8 8F  G8H "4I8J +DK8L #DM8N  O8P  Q8R %eS8T %eU8V  W8X !$Y8Z [8\ )$]8^ #D_8` -da8b  c8d *4e8f "5g8 8h "'$)%)$(o8 8 8v  H"J"F$H$S&R(T# #
 
  B"D"F$H$M&R(T# #
 
  B"D"@$B$L&L(N# #
 !B  ;S* *X VD"ED   "	! !D ,!! #	. .D ,T-H-H-J-JD rD$ %c%D& $T'D( &t)D* t+D, t-D. d/D0 T88::1D2 &t3D4 G 5D: H ;D@ L!ADF GGDN #$ $# #
 -2,0! !
 "60 /3.2# # (/A #+&2'2 + + +".	& 	&uD D DQm
 m
 m	
r*   c                     |                      | j        d|                                           }|                     ||d          }|                     |d          }|| j        d         |<   |S )Nr~   r      )	safe_dictr   r   safe_integersum)r&   urlr   previousValuenewValues        r)   
request_idzbinance.request_id   se    ..{D<W<W<Y<YZZ))'3::88M1--)1[!#&r*   clientc                 z    |j                             d          dk    p|j                             d          dk    S )Nz/streamru   zdemo-stream)r   find)r&   r   s     r)   is_spot_urlzbinance.is_spot_url   s4    zy))B.XFJOOM4R4RUW4WXr*   r   typesubscriptionHashc                    |                      | j        d|                                           }|                     ||          }|8|                     | j        dd          }|                     | j        d          }|                     ||          }|dz   }||z  }	|| j        d<   |                     |	          }|| j        d         |<   |                     | j        d          }
|
|                                 | j        d<   |                     | j        d         |d          }||z   }|                     | j        d         |d	          }||k    rt          | j        d
z             ||z   | j        d         |<   |S )Nrs   rt   ru   ro   r   numSubscriptionsByStreamr   rq   rr   z reached the limit of subscriptions by stream. Increase the number of streams, or increase the stream limit or subscription limit by stream if the exchange allows.)	r   r   r   safe_stringr   
safe_valuenumber_to_stringr   id)r&   r   r   numSubscriptionsrs   streamrt   ro   streamLimitnormalizedIndexsubscriptionsByStreamssubscriptionsByStreamnewNumSubscriptionsrq   s                 r)   r   zbinance.stream   s   $(NN4<A\^b^y^y^{^{$|$|!!!";=MNN>++DL-LLK??4<HHL++L$??K%/K)K7O*5DL'**?;;FJPDL456FG%)__T\C]%^%^"%-;?;V;V;X;X78$($5$5dlC]6^`fhi$j$j!"7:J"J(,(9(9$,Gb:ceikn(o(o%"%>>>   ,Q  "Q  R  R  R?TWg?gDL34V<r*   c                 |    | j         d         d         |         }|dk    r|                    dd|z   dz             S |S )Nrk   r,   rd   z/ws/)r   replace)r&   r   categorybaseUrls       r)   
get_ws_urlzbinance.get_ws_url   sE    )E"4(.8??5#.5*@AAAr*   c                 F    |dk    s|dk    s|dk    s|dk    s|dk    rdS dS )NdepthrpiDepthr   r   aggTradepublicmarket )r&   channels     r)   get_future_ws_categoryzbinance.get_future_ws_category   sO    gJ!6!6'\:Q:QU\`gUgUgkr  wA  lA  lA8xr*   c                     |dk    r|                      |d          dz   |z   S | j        d         d         |         dz   |z   S )Nrd   privatez?listenKey=rk   r,   r   )r   r   )r&   r   	listenKeys      r)   get_private_ws_urlzbinance.get_private_ws_url   sL    8??433mCiOOy%d+c1I==r*   Nsymbolsincelimitc                 D   K   |                      |g|||           d{V S )a  
        watch the public liquidations of a trading pair

        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Liquidation-Order-Streams
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Liquidation-Order-Streams

        :param str symbol: unified CCXT market symbol
        :param int [since]: the earliest time in ms to fetch liquidations for
        :param int [limit]: the maximum number of liquidation structures to retrieve
        :param dict [params]: exchange specific parameters for the bitmex api endpoint
        :returns dict: an array of `liquidation structures <https://github.com/ccxt/ccxt/wiki/Manual#liquidation-structure>`
        N)watch_liquidations_for_symbolsr&   r   r   r   paramss        r)   watch_liquidationszbinance.watch_liquidations   s7       88&5%QWXXXXXXXXXr*   symbolsc                   K   |                                   d{V  g }g }d}|                     |ddd          }|                     |          r+|                    d           |                    d           nt	          dt          |                    D ]Y}|                     ||                   }	|                    |	d         dz              |                    d||         z              Z|d	d
                    |          z   z  }|                     |          }
d}| 	                    d|
|          \  }}|dk    rt          | j        dz             d}|                     d|
|          \  }}|                     ||          rd}n|                     ||          rd}t          |          }|                     ||                     d                    dz   |                     |||          z   }|                     |          }d||d}d|i}|                     |||                     ||          ||           d{V }| j        r|S |                     | j        |||d          S )a  
        watch the public liquidations of a trading pair

        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Liquidation-Order-Streams
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/All-Market-Liquidation-Order-Streams

        :param str[] symbols: list of unified market symbols
        :param int [since]: the earliest time in ms to fetch liquidations for
        :param int [limit]: the maximum number of liquidation structures to retrieve
        :param dict [params]: exchange specific parameters for the bitmex api endpoint
        :returns dict: an array of `liquidation structures <https://github.com/ccxt/ccxt/wiki/Manual#liquidation-structure>`
        NliquidationsTz!forceOrder@arrr   lowercaseIdz@forceOrderliquidations::::,r/   rc   z> watchLiquidationsForSymbols is not supported for spot symbolsrd   re   
forceOrderr   	SUBSCRIBEmethodr   r   r   )load_marketsmarket_symbolsis_emptyappendrangelenr   joinget_market_from_symbolshandle_market_type_and_paramsr   r   handle_sub_type_and_paramsisLinear	isInverser   r   r   r   watch_multipleextend
newUpdatesfilter_by_symbols_since_limitr   )r&   r   r   r   r   subscriptionHashesmessageHashes
streamHashir   firstMarketr   subTyper   r   r~   request	subscribenewLiquidationss                      r)   r   z&binance.watch_liquidations_for_symbols	  s      !!!!!!!!!#
%%gtT4@@==!! 	3%%&<===  00001c'll++ D DWQZ00"))&*?-*OPPP$$%5
%BCCCC$'!2!222J227;;99:WYdflmmf6>>TW'gghhh99:WYdflmm==w'' 	DD^^D'** 	D122oodD$?$?$M$MNNQTTW[WbWbcgis  vF  XG  XG  GOOC((	!(
 
 )
	 !% 3 3CT[]cHdHdfx  {D  !E  !E  E  E  E  E  E  E? 	#""11$2CWeUZ\`aaar*   c                    |                      |di           }|                     |d          }|                     |d dd          }|d         }|                     ||          }| j        0|                     | j        dd          }t          |          | _        | j        }	|	                    |           |	                    |gd           |	                    |gd	|z              d S )
Nos contractr   rx   ry   r   r   )
r   r   safe_marketparse_ws_liquidationr   r   r   r   r   resolve)
r&   r   messagerawLiquidationmarketIdr   r   liquidationr   caches
             r)   handle_liquidationzbinance.handle_liquidation?  s    P #r::##NC88!!(D"jAA!//GG$%%dl4GNNE *5 1 1D![!!!}n555}&6&?@@@@@r*   c                    |                      |d          }|                     ||d d          }|                     |d          }|                     ||                     ||          |                     |d          |                     |d          |                     |d          |                     |d          d d ||                     |          d
          S )	Nr  r   TlcontractSizeapS)
infor   	contractsr  priceside	baseValue
quoteValue	timestampdatetime)r   r  r   safe_liquidationsafe_symbolsafe_numbersafe_string_loweriso8601)r&   r  r   r
  r  s        r)   r  zbinance.parse_ws_liquidationt  s    V ##K55!!(FD&AA%%k377	$$&&x88))+s;; ,,V^DD%%k488**;<<"Y//&
 &
   	r*   c                 8   K   |                      |g|||          S )a  
        watch the private liquidations of a trading pair

        https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Order-Update
        https://developers.binance.com/docs/derivatives/coin-margined-futures/user-data-streams/Event-Order-Update

        :param str symbol: unified CCXT market symbol
        :param int [since]: the earliest time in ms to fetch liquidations for
        :param int [limit]: the maximum number of liquidation structures to retrieve
        :param dict [params]: exchange specific parameters for the bitmex api endpoint
        :returns dict: an array of `liquidation structures <https://github.com/ccxt/ccxt/wiki/Manual#liquidation-structure>`
        )!watch_my_liquidations_for_symbolsr   s        r)   watch_my_liquidationszbinance.watch_my_liquidations  s$       55vhufUUUr*   c                 .  K   |                                   d{V  |                     |dddd          }|                     |          }dg}|                     |          s@t	          dt          |                    D ]"}||         }|                    d|z              #d}	|                     d||          \  }	}d}
|                     d||          \  }
}| 	                    |	|
          rd}	n| 
                    |	|
          rd}	|                     |           d{V  | j        |	         d	         }|                     |	|          }d}|                     ||||	g           d{V }| j        r|S |                     | j        |||          S )
a  
        watch the private liquidations of a trading pair

        https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Order-Update
        https://developers.binance.com/docs/derivatives/coin-margined-futures/user-data-streams/Event-Order-Update

        :param str[] symbols: list of unified market symbols
        :param int [since]: the earliest time in ms to fetch liquidations for
        :param int [limit]: the maximum number of liquidation structures to retrieve
        :param dict [params]: exchange specific parameters for the bitmex api endpoint
        :returns dict: an array of `liquidation structures <https://github.com/ccxt/ccxt/wiki/Manual#liquidation-structure>`
        NTmyLiquidationsr   myLiquidations::r1   rd   re   r   )r   r   r   r   r   r   r   r   r   r   r   authenticater   r   r   r   r   r   )r&   r   r   r   r   r   r   r   r   r   r   r   r   r  r   s                  r)   r"  z)binance.watch_my_liquidations_for_symbols  s      !!!!!!!!!%%gtT4FF--g66)*}}W%% 	B1c'll++ B B $$%7&%@AAAA99:Y[acijjf99:Y[acijj==w'' 	DD^^D'** 	D'''''''''L&{3	%%dI66 $ 3 3CRVQW X XXXXXXX? 	#""11$2CWeUZ[[[r*   c                    |                      |d          }|dk    rd S |                      |d          }|                     |d d d          }|                     ||          }|                     ||          }| j        }|+|                     | j        dd          }	t          |	          }|                    |           || _        |	                    |gd           |	                    |gd|z              d S )	Nr  LIQUIDATIONr  r   rz   ry   r%  r&  )
r   r  r  r  r%  r   r   r   r   r  )
r&   r   r  	orderTyper
  r   r   r  r  r   s
             r)   handle_my_liquidationzbinance.handle_my_liquidation  s	   Z $$Wc22	%%F##GS11!!(D$??!!(F33//@@#=%%dl4I4PPEu%%E[!!!#}&6777}&86&ABBBBBr*   c                 B   K   |                      |g||           d{V S )aO  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#partial-book-depth-streams
        https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#diff-depth-stream
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams-RPI
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        N)watch_order_book_for_symbols)r&   r   r   r   s       r)   watch_order_bookzbinance.watch_order_bookA  s5      l 66xOOOOOOOOOr*   c                   K   |                                   d{V  |                     |dddd          }|                     |d                   }|d         }|d         r|d         rdnd	}d
}d}|Gt          |          }|dk    rt	          | j        dz             |dd                    |          z   z  }d}	|                     |ddd          \  }	}d}
|                     |ddd          \  }
}|
r
|dk    rd}d}	g }g }t          dt          |                    D ]r}||         }|                     |          }|	                    d|z              |d         dz   |z   }|dz   t          |	          z   dz   }|	                    |           st          |          }|                     ||                     |                    dz   |                     |||          z   }|                     |          }d||d}t          |          ||| j        |||d}|                     |||                     ||          ||           d{V }|                                S )a  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#partial-book-depth-streams
        https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#diff-depth-stream
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams-RPI
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams

        :param str[] symbols: unified array of symbols
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.rpi]: *future only* set to True to use the RPI endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        NFTr   r   r  linearrd   re   r   multipleOrderbookrr   z} watchOrderBookForSymbols() accepts 200 symbols at most. To watch more symbols call watchOrderBookForSymbols() multiple timesr   r   r7   rv   100rpir   500orderbook::r   @msr   r   r   )r   r   r   r   r   r   r   )r   r   r   r   r   r   r   handle_option_and_paramsr   r   strr   r   r   r   handle_order_book_subscriptionr   r   r   )r&   r   r   r   r   r   r   r   symbolsLengthrv   r3  	subParamsr   r   r   r   r   
symbolHashmessageHashesLengthr   r~   r   subscription	orderbooks                           r)   r-  z$binance.watch_order_book_for_symbolsy  s     $ !!!!!!!!!%%gtUD$GGkk'!*--6"z" 	E*84D88*D(
LLMs""   ,k  "k  l  l  l$'!2!222J!%)%B%B6Keg{  ~C  &D  &D"F33F<VX]_deeV 	'48##D!&	q#g,,'' 	) 	)AQZF[[((F  !7888%m4s:TA)C/#6H2I2IIDPJZ((((!-00oodD$?$?$E$EFFLt{{[_ak  nA  PB  PB  BOOC((	!
 
 i..9
 
 --c=$++gW]B^B^`mo{||||||||	   r*   c                   K   |                                   d{V  |                     |dddd          }|                     |d                   }|d         }|d         r|d         rdnd	}d
}d}||dd                    |          z   z  }|                     | j        dd          }g }g }	g }
t          dt          |                    D ]}}||         }|                     |          }|	                    d|z              |
                    d|z              |d         dz   |z   }|dz   |z   dz   }|                    |           ~t          |	          }| 	                    || 
                    d
                    dz   |                     |||          z   }|                     |          }d||d}dt          |          ||	|
dd}|                     ||
|                     ||          |
|           d{V S )ab  
        unWatches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#partial-book-depth-streams
        https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#diff-depth-stream
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams

        :param str[] symbols: unified array of symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        NFTr   r   r  r0  rd   re   r   r1  r   r   rv   r2  r5  zunsubscribe:orderbook:r   r6  r7  r   UNSUBSCRIBEr   r@  )unsubscriber   r   subMessageHashesr   topic)r   r   r   r   r   r   r   r   r   r   r   r   r   r9  r   r   )r&   r   r   r   r   r   r   rv   r<  rD  r   r   r   r   r   r=  r>  r   r~   r   r?  s                        r)   un_watch_order_book_for_symbolsz'binance.un_watch_order_book_for_symbols  sw      !!!!!!!!!%%gtUD$GGkk'!*--6"z" 	E*84D88*D(
$'!2!222J!--dl<PRWXX	q#g,,'' 	) 	)AQZF[[((F##MF$:;;;  !9F!BCCC%m4s:TA)C/2DDtKJZ((((!"233oodD$?$?$H$HIICORVR]R]^bdn  qD  SE  SE  EOOC((	#
 
  i.. 0* 
 
 ((mT[[RX=Y=Y[hjvwwwwwwwwwr*   c                 @   K   |                      |g|           d{V S )a_  
        unWatches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#partial-book-depth-streams
        https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#diff-depth-stream
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams

        :param str symbol: unified array of symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        N)rF  r&   r   r   s      r)   un_watch_order_bookzbinance.un_watch_order_book  s2       996(FKKKKKKKKKr*   c                   K   |                                   d{V  |                     |          }d|d         i}|||d<   |                     d||          }|dk    rt          | j        dz             | j        d         d	         d
         |         }|                     |          }t          |          }	d}
|                     |ddd          \  }
}|
|d<   | 	                    |d          }|	d| 
                    |                     ||                    d}d| j        i}|                     ||	||	|           d{V }|d         |d<   |S )a  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/market-data-requests#order-book
        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api/Order-Book

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        Nr   r   r   rK   rd   z, fetchOrderBookWs only supports swap marketsrk   r,   rg   FrA   rn   ri   r   r   r   r   r   )r   r   get_market_typer   r   r   r   r9  r8  omitsign_paramsr   handle_fetch_order_bookwatch)r&   r   r   r   r   payload
marketTyper   r~   messageHashrn   r  r?  r@  s                 r)   fetch_order_book_wszbinance.fetch_order_book_ws  s      !!!!!!!!!V$$fTl
 $GG))*<ffMM
!!TW'UUVVVit$X.z:OOC((	)nn #'#@#@Zlns#t#t &&6"#66**&&t{{7F'C'CDD
 
 d2
 **S+w\ZZZZZZZZ	$X.	(r*   c                    |                      |d          }|                     |d          }|                     |d          }|                     |d |          }|                     |dd          |d<   |                    ||           d S )Nr   resultr  lastUpdateIdunonce)r   r   r   parse_order_booksafe_integer_2r  )r&   r   r  rS  rV  r  r@  s          r)   rO  zbinance.handle_fetch_order_book-  s    0 &&w5522%%fc22	))&$	BB	!00MM	'y+.....r*   c                 v  K   |                      |d          }d|z   }	 |                     | j        dd          }|                     |d          }|                     |d|          }|                     |d          }	|                     |||	           d {V }
|                     | j        |          d S | j        |         }|                    |
           |j        }g |_        t          dt          |                    D ]}||         }|                     |d	          }|                     |d
          }|                     |d          }|dk    rI||d         k     r_||d         k    r||d         k    s||d         k    r| 
                    |||           ||d         k    r|dz
  |d         k    r&|dz
  |d         k    r| 
                    |||           || j        |<   |                    ||           d S # t          $ r)}|j        |= |                    ||           Y d }~d S d }~ww xY w)Nr   r5  r   ry   r   r   r   r   UrX  purd   rY  r   )r   r   r   r   fetch_rest_order_book_safe
orderbooksresetr  r   r   handle_order_book_messager  	Exceptionsubscriptionsreject)r&   r   r  r?  r   rS  defaultLimitr   r   r   snapshotr@  messagesr   messageItemr]  rX  r^  es                      r)   fetch_order_book_snapshotz!binance.fetch_order_book_snapshotL  s     !!,99#f,(	*,,T\;PRVWWL??<88D%%lG\JJE__\8<<F "<<VUFSSSSSSSSHt77?/IOOH%%% H IO1c(mm,, W W&qk%%k377%%k377&&{D998##9W--- Yw///a9W;M6M6MSUYbcjYkSkSk66v{IVVV Ig... Q9W#555QUyQXGY<Y<Y66v{IVVV&/DOF#NN9k22222 	* 	* 	*$[1MM![)))))))))	*s   BH 8EH 
H8H33H8c                     |                      |d          }|                      |d          }|                    ||           d S )Nr   r   )
safe_floatstore)r&   booksidedeltar  amounts        r)   handle_deltazbinance.handle_deltay  sB    q))**uf%%%%%r*   c                 ~    t          dt          |                    D ]}|                     |||                    d S )Nr   )r   r   rr  )r&   ro  deltasr   s       r)   handle_deltaszbinance.handle_deltas~  sH    q#f++&& 	3 	3Ahq	2222	3 	3r*   c                 f   |                      |d          }|                     |d         |                     |dg                      |                     |d         |                     |dg                      ||d<   |                      |d          }||d<   |                     |          |d	<   |S )
NrX  asksabidsbrY  Er  r  )r   ru  r   r   )r&   r   r  r@  rX  r  s         r)   rb  z!binance.handle_order_book_message  s    gs++9V,doogsB.O.OPPP9V,doogsB.O.OPPP	'%%gs33	!*	+ $Y 7 7	*r*   c                 \   |                      |          }|rdnd}|                     |d          }|                     |d d |          }|d         }d|z   }|| j        vrd S | j        |         }	|                     |	d          }
|
|	j                            |           d S 	 |                     |d          }|                     |d          }|                     |d	          }|||	d         k    r|                     |	d
          }d }||dz
  |	d         k    o|dz
  |	d         k    }n|dz
  |	d         k    }|r=|                     |||	           |
|	d         k     r|                    |	|           d S d S | 	                    ddd          }|r/t          | j        dz   |                     |          z             d S d S ||	d         k    r||	d         k    s||	d         k    r=|                     |||	           |
|	d         k    r|                    |	|           d S d S | 	                    ddd          }|r/t          | j        dz   |                     |          z             d S d S # t          $ r1}| j        |= |j        |= |                    ||           Y d }~d S d }~ww xY w)Nrc   r   r  r   r5  rY  r]  rX  r^  r  r   r6   r   T )r   r   r  r`  r   r  r   rb  r  handle_optionr   r   orderbook_checksum_messagerc  rd  re  )r&   r   r  isSpotrR  r
  r   r   rS  r@  rY  r]  rX  r^  r  conditionalr   rj  s                     r)   handle_order_bookzbinance.handle_order_book  sf   & !!&)) &3VVV
##GS11!!(D$
CC!#f,$/)) FOF+	!!)W55=O""7++++++.%%gs33%%gs33&&w55: 9W---$($5$5i$M$M	&*$,,-Ei6H+H*mPQTUPUZcdkZlOlKK -.Ei6H+HK& m ::67IVVV$y'999 &y+ F F F F F  :9 (,'9'9:JJX\']']H' m&3DGcMDDcDcdjDkDk4k&l&l l# .-m m Ig... 7!333y?Q9Q9Q ::67IVVV$	'(::: &y+ F F F F F  ;: (,'9'9:JJX\']']H' m&3DGcMDDcDcdjDkDk4k&l&l l /.m m  . . .OF+(5a---------.s.   $CI0 ;AI0 AI0 &AI0 0
J+:&J&&J+c                    |                      | j        dd          }|                     |d          }|                     |d|g          }|                      |d|          }t	          dt          |                    D ]n}||         }	|	| j        v r| j        |	= |                     i |          | j        |	<   |                     |d|	i          }| 	                    | j
        |||           od S )Nr   ry   r   r   r   r   )r   r   r   r   r   r   r`  
order_bookr   spawnrk  )
r&   r   r  r?  rf  symbolOfSubscriptionr   r   r   r   s
             r)   r:  z&binance.handle_order_book_subscription  s    ((7LdSS#//hGG//,	<P;QRR!!,FFq#g,,'' 	V 	VAQZF((OF+&*oob%&@&@DOF#;;|h5GHHLJJt5vwUUUU	V 	Vr*   c                 >   |                      |d          }|                     |j        d          }|                     ||i           }|                     |d          }| ||||           |                     |dd          }|r|                     ||           |S )Nr   r   rC  F)r   index_byrd  r   	safe_boolhandle_un_subscription)r&   r   r  r   subscriptionsByIdr?  r   isUnSubMessages           r)   handle_subscription_statusz"binance.handle_subscription_status  s     gt,, MM&*>EE'8"bAAx88F67L111mUKK 	>''===r*   r?  c                    |                      |dg           }|                      |dg           }t          dt          |                    D ])}||         }||         }|                     |||           *|                     |           d S )Nr   rD  r   )	safe_listr   r   clean_unsubscriptionclean_cache)r&   r   r?  r   rD  j	unsubHashsubHashs           r)   r  zbinance.handle_un_subscription  s    |_bII>>,8JBOOq#m,,-- 	B 	BA%a(I&q)G%%fgyAAAA&&&&&r*   c                   K   |                                   d{V  |                     |dddd          }d}|Gt          |          }|dk    rt          | j        dz             |dd                    |          z   z  }d}|                     |d	d
d          \  }}|                     |d          }|                     |d                   }|d         }	|d         r|d         rdnd}	g }
g }t          dt          |                    D ]Z}||         }|                     |          }|

                    d|z              |d         dz   |z   }|
                    |           [|                     |d          }t          |          }|                     |	|                     |                    dz   |                     |	||          z   }|                     |          }d||d}d|i}|                     ||
|                     ||          |
|           d{V }| j        rB|                     |d          }|                     |d          }|                    ||          }|                     |||dd          S )a0  
        get the list of most recent trades for a list of symbols

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/market-data-requests#aggregate-trades
        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/market-data-requests#recent-trades
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Aggregate-Trade-Streams
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Aggregate-Trade-Streams

        :param str[] symbols: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.name]: the name of the method to call, 'trade' or 'aggTrade', default is 'trade'
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=public-trades>`
        NFTmultipleTradesrr   w watchTradesForSymbols() accepts 200 symbols at most. To watch more symbols call watchTradesForSymbols() multiple timesr   r   r@   r   r   callerMethodNamer   r   r  r0  rd   re   trade::r   r6  r   r   r   r   r   r  )r   r   r   r   r   r   r8  rM  r   r   r   r   r   r   r   r   r   r   r   r   getLimitfilter_by_since_limit)r&   r   r   r   r   r   r;  r   r   r   r   r<  r   r   r   rawHashquerysubParamsLengthr   r~   r   r   tradesfirsttradeSymbols                            r)   watch_trades_for_symbolsz binance.watch_trades_for_symbols  s       !!!!!!!!!%%gtUD$GG%
LLMs""   ,e  "e  f  f  f$'!2!222J44V=TV\^efff6#566kk'!*--6"z" 	E*84D88*D	q#g,,'' 	& 	&AQZF[[((F  V!3444]+c1D8GW%%%%		&&))i..oodD$?$?$E$EFFLt{{[_akm|O}O}}OOC((	!
 
 )
	 **3t{{7TY?Z?Z\iktuuuuuuuu? 	8OOFA..E**5(;;KOOK77E))&%TRRRr*   c                   K   |                                   d{V  |                     |dddd          }d}|Gt          |          }|dk    rt          | j        dz             |dd                    |          z   z  }d}|                     |d	d
d          \  }}|                     |d          }|                     |d                   }|d         }|d         r|d         rdnd}g }g }	g }
t          dt          |                    D ]r}||         }|                     |          }|
                    d|z              |

                    d|z              |d         dz   |z   }|	
                    |           s|                     |d          }t          |	          }|                     ||                     |                    dz   |                     |||          z   }|                     |          }d|	|d}dt          |          ||
|dd}|                     ||
|                     ||          |
|           d{V S )a  
        unsubscribes from the trades channel

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/market-data-requests#aggregate-trades
        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/market-data-requests#recent-trades
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Aggregate-Trade-Streams
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Aggregate-Trade-Streams

        :param str[] symbols: unified symbol of the market to fetch trades for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.name]: the name of the method to call, 'trade' or 'aggTrade', default is 'trade'
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=public-trades>`
        NFTr  rr   r  r   r   r@   r   r   r  r   r   r  r0  rd   re   r  zunsubscribe:trade:r   r6  r   rB  r   r  rC  r   rD  r   r   rE  )r   r   r   r   r   r   r8  rM  r   r   r   r   r   r   r   r9  r   r   )r&   r   r   r   r;  r   r   r   rD  r<  r   r   r   r   r  r  r  r   r~   r   r?  s                        r)   un_watch_trades_for_symbolsz#binance.un_watch_trades_for_symbolsG  s      !!!!!!!!!%%gtUD$GG%
LLMs""   ,e  "e  f  f  f$'!2!222J44V=TV\^efff6#566kk'!*--6"z" 	E*84D88*D	q#g,,'' 	& 	&AQZF[[((F##I$6777  !5!>???]+c1D8GW%%%%		&&))i..oodD$?$?$E$EFFLt{{[_akm|O}O}}OOC((	#
 
  i.. 0*
 
 ((mT[[RW=X=XZgiuvvvvvvvvvr*   c                 t   K   |                                   d{V  |                     |g|           d{V S )a  
        unsubscribes from the trades channel

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/market-data-requests#aggregate-trades
        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/market-data-requests#recent-trades
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Aggregate-Trade-Streams
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Aggregate-Trade-Streams

        :param str symbol: unified symbol of the market to fetch trades for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.name]: the name of the method to call, 'trade' or 'aggTrade', default is 'trade'
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=public-trades>`
        N)r   r  rH  s      r)   un_watch_tradeszbinance.un_watch_trades  sV       !!!!!!!!!55vhGGGGGGGGGr*   c                 N   K   d|d<   |                      |g|||           d{V S )a/  
        get the list of most recent trades for a particular symbol

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/market-data-requests#aggregate-trades
        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/market-data-requests#recent-trades
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Aggregate-Trade-Streams
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Aggregate-Trade-Streams

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.name]: the name of the method to call, 'trade' or 'aggTrade', default is 'trade'
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=public-trades>`
        r?   r  N)r  r   s        r)   watch_tradeszbinance.watch_trades  sA        &3!"22F8UE6RRRRRRRRRr*   c                    |                      |d          }|dk    }|s|                     ||          S |                     |dd          }|                     |d          }|                     |dd          }|                      |d          }|r|                      |d	|          }|                      |d
          }	|	||t	          j        ||          }	|                      |d          }
d|v rdnd}|                     |
d d |          }|                     |d          }d }|                      |d          }d|v r||d         rdnd}|d         rdnd}d }|                      |d          }|0|                      |d          }|                     |          }||d}|                     |d          }| 	                    ||| 
                    |          |||||||||	|d          S )NxTRADEtrx  r  Lpqr  Yr  psr  rc   r  r   msellbuymakertakernNr   currencyr  )r  r  r  r   r   orderr   takerOrMakerr  r  rq  r   fee)r   parse_tradesafe_string_2r   r   
string_mulr  r  safe_currency_code
safe_trader   )r&   r   r   executionTypeisTradeExecutionr   r  r  rq  r   r
  rR  r   r  r  orderIdr  feeCostfeeCurrencyIdfeeCurrencyCoder   s                        r)   parse_ws_tradezbinance.parse_ws_trade  sU   R ((44)W4 	3##E6222sC00%%eS11	""5#s33!!%-- 	:%%eS&99Fs++<!(:)%88##E3//$(EMMZZ
!!(D$
CC%%eS11""5#..%<<|!&s6vv&+Cj=77gL""5#.. ,,UC88M"55mDDO+ C %%eS11"Y//( 
  
   	r*   c                    |                      |          }|rdnd}|                     |d          }|                     |d d |          }|d         }d|z   }|                     ||          }	|                     | j        |          }
|
+|                     | j        dd          }t          |          }
|
	                    |	           |
| j        |<   |
                    |
|           d S )Nrc   r  r  r   r  r{   ry   )r   r   r  r  r   r  r   r   r   r   r  )r&   r   r  r  rR  r
  r   r   rS  r   tradesArrayr   s               r)   handle_tradezbinance.handle_trade@  s     !!&)) &7VVZ
##GS11!!(D$
CC!&(##GV44oodk6::%%dlM4HHE$U++K5!!!)F{K00000r*   1m	timeframec                    K   |                                   d{V  |                     |          }|d         }d|d<   |                     ||gg|||           d{V }||         |         S )aG  
        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/market-data-requests#klines
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Kline-Candlestick-Streams
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Kline-Candlestick-Streams

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param dict [params.timezone]: if provided, kline intervals are interpreted in that timezone instead of UTC, example '+08:00'
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Nr   r4   r  )r   r   watch_ohlcv_for_symbols)r&   r   r  r   r   r   r   rV  s           r)   watch_ohlcvzbinance.watch_ohlcvR  s        !!!!!!!!!V$$!%1!"33fi5H4I5RWY_````````f~i((r*   symbolsAndTimeframesc                   K   |                                   d{V  d}|                     |ddd          \  }}|                     |d          }|                     |dddd          }|                     |d                   }|d         }	|d	         r|d
         rdnd}	|	dk    }
d}|                     |dd          \  }}|duo|dk    pt          j        |d          }g }g }t          dt          |                    D ]}||         }|d         }|d         }| 
                    | j        ||          }|                     |          }|d         }|dk    r|                    dd          }|o|
}d}|r|nd}|                    |dz   |z   dz   |z   |z              |                    d|d         z   dz   |z              |                     |	|                     |                    dz   |                     |	d          z   }|                     |          }d||d}d |i}|                     |d!          }|                     |||                     ||          ||           d{V }|\  }}} | j        r|                     ||          }|                     | ||dd          }!|                     |||!          S )"a`  
        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/market-data-requests#klines
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Kline-Candlestick-Streams
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Kline-Candlestick-Streams

        :param str[][] symbolsAndTimeframes: array of arrays containing unified symbols and timeframes to fetch OHLCV data for, example [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param dict [params.timezone]: if provided, kline intervals are interpreted in that timezone instead of UTC, example '+08:00'
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Nr   r   r   r   FTr   r  r0  rd   re   rc   timezone+08:008r   r   indexPriceKline_perpr  @+08:00r6  _ohlcv::r   r   r   multipleOHLCVr   r   r   r  )r   handle_param_string_2get_list_from_object_valuesr   r   handle_param_stringr   	string_eqr   r   r   
timeframesr   r   r   r   r   r   rM  r   r   r   r  r  create_ohlcv_object)"r&   r  r   r   r   	klineTyper   marketSymbolsr   r   r  r  isUtc8	rawHashesr   r   symAndTfsymbolStringtimeframeStringintervalr   r
  shouldUseUTC8suffix	utcSuffixr   r~   r   r   resr   r  candlesfiltereds"                                     r)   r  zbinance.watch_ohlcv_for_symbolsi  sK      !!!!!!!!!	 66vy&RYZZ	6223GKK++GT5%NNkk-"2336"z" 	E*84D88*D&.33FJMM&$&hh(.B-gwGXYacfGgGg	q#23344 	X 	XA+A.H#A;L&qkO''/ZZH[[..Fm,H---#++GR88#.MF"/7RIX^i7#=H9TUUU  VH-=!=!D!VWWWWoodD$?$?	$J$JKKcQTXT_T_`dfuTvTvvOOC((	!
 
 )
	 6#566'']DKKQW<X<XZgirssssssss%("	7? 	4$$VU33E--gueQMM''	8DDDr*   c                 T  K   |                                   d{V  d}|                     |ddd          \  }}|                     |d          }|                     |dddd          }|                     |d                   }|d         }|d	         r|d
         rdnd}|dk    }d}	|                     |dd          \  }	}|	duo|	dk    pt          j        |	d          }
g }g }g }t          dt          |                    D ]}||         }|d         }|d         }| 
                    | j        ||          }|                     |          }|d         }|dk    r|                    dd          }|
o|}d}|r|nd}|                    |dz   |z   dz   |z   |z              |                    d|d         z   dz   |z              |                    d|d         z   dz   |z              |                     ||                     |                    dz   |                     |d          z   }|                     |          }d||d }dt%          |          ||||d!d"}|                     |d#          }|                     |||                     ||          ||           d{V S )$a  
        unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/market-data-requests#klines
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Kline-Candlestick-Streams
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Kline-Candlestick-Streams

        :param str[][] symbolsAndTimeframes: array of arrays containing unified symbols and timeframes to fetch OHLCV data for, example [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param dict [params.timezone]: if provided, kline intervals are interpreted in that timezone instead of UTC, example '+08:00'
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Nr   r   r   r   FTr   r  r0  rd   re   rc   r  r  r  r   r   r  r  r  r  r6  r  r  r   r   zunsubscribe::ohlcv::r   r  rB  r   ohlcv)rC  r   r   r  rD  r   rE  r  )r   r  r  r   r   r  r   r  r   r   r   r  r   r   r   r   r   r   r9  rM  r   r   )r&   r  r   r  r   r  r   r   r  r  r  r  rD  r   r   r  r  r  r  r   r
  r  r  r  r   r~   r   r   s                               r)   un_watch_ohlcv_for_symbolsz"binance.un_watch_ohlcv_for_symbols  s9      !!!!!!!!!	 66vy&RYZZ	6223GKK++GT5%NNkk-"2336"z" 	E*84D88*D&.33FJMM&$&hh(.B-gwGXYacfGgGg	q#23344 	e 	eA+A.H#A;L&qkO''/ZZH[[..Fm,H---#++GR88#.MF"/7RIX^i7#=H9TUUU##Ix0@$@4$G/$YZZZ  !7&:J!JT!QTc!cddddoodD$?$?	$J$JKKcQTXT_T_`dfuTvTvvOOC((	#
 
  i..$8 0*
 
	 6#566((mT[[RX=Y=Y[hjstttttttttr*   c                    K   |                                   d{V  |                     |          }|d         }d|d<   |                     ||gg|           d{V S )a  
        unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/market-data-requests#klines
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Kline-Candlestick-Streams
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Kline-Candlestick-Streams

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param dict [params.timezone]: if provided, kline intervals are interpreted in that timezone instead of UTC, example '+08:00'
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Nr   r4   r  )r   r   r  )r&   r   r  r   r   s        r)   un_watch_ohlcvzbinance.un_watch_ohlcv  s       !!!!!!!!!V$$!%1!"44vy6I5JFSSSSSSSSSr*   c           	      2   |                      |d          }ddd}|                      |||          }|                     |d          }|                     |dd          }|dk    r|                      |d          }|                      |d          }|                     |          }|                     |d	          |                     |d
          |                     |d          |                     |d          |                     |d          |                     |d          g}	|                     |          }
|
rdnd}|                     |d d |          }d|z   dz   |z   }|                     | j        |i           | j        |<   |                     | j        |         |          }|;|                     | j	        dd          }t          |          }|| j        |         |<   |                    |	           |||g}|                    ||           d S )Nrj  r  markPriceKline)indexPrice_klinemarkPrice_klinekr  r  r   r  r  hr  cvrc   r  r  r   r}   ry   )r   r   r  find_timeframer   rm  r   r  ohlcvsr   r   r   r  )r&   r   r  eventeventMapr   r
  r  unifiedTimeframeparsedr  rR  r   rS  storedr   resolveDatas                    r)   handle_ohlcvzbinance.handle_ohlcv  s'   6   #.. 1/
 
   5%88--%%eS$77%%%''66H##E3//..x88eS))OOE3''OOE3''OOE3''OOE3''OOE3''
 !!&)) &7VVZ
!!(D$
CC&(4/2BB"oodk62FFFV!46FGG>%%dlL$GGE*511F4:DK 01f/8{K00000r*   c                   K   |                                   d{V  |                     |          }d|d         i}|                     d||          }|dk    rt          | j        dz             | j        d         d         d	         |         }|                     |          }t          |          }d
| j        i}	d}
| 	                    |ddd          \  }
}|
|d<   | 
                    |d          }d}| 	                    |dd
d          \  }}|||                     |                     ||                    d}|                     |||||	           d{V }|S )a=  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.method]: method to use can be ticker.price or ticker.book
        :param boolean [params.returnRateLimits]: return the rate limits for the exchange
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        Nr   r   rR   rd   z) fetchTickerWs only supports swap marketsrk   r,   rg   r   Frn   ri   zticker.bookrK  )r   r   rL  r   r   r   r   r9  handle_ticker_wsr8  rM  rN  r   rP  )r&   r   r   r   rQ  r   r   r~   rS  r?  rn   r   r  r   s                 r)   fetch_ticker_wszbinance.fetch_ticker_ws;  s      !!!!!!!!!V$$fTl
 ##OVVDD8TW'RRSSSit$X.t4OOC((	)nnd+
 !#'#@#@Zlns#t#t &&6"#66**66vPXZghh&&t{{7F'C'CDD
 

 zz#{G[,WWWWWWWWr*   c                   K   |                                   d{V  |                     |          }|                     d||          }|dk    r|dk    rt          | j        dz             | j        d         d         d         |         }|                     |          }	t          |	          }
d	}|                     |dd
d	          \  }}| 	                    |          || j
        |         d}|                     |d          }|                     |d          }|||d<   |||d<   |||d<   |
d|                     ||          d}d| j        i}|                     ||
||
|           d{V S )a`  
        query historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/market-data-requests#klines

        :param str symbol: unified symbol of the market to query OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int since: timestamp in ms of the earliest candle to fetch
        :param int limit: the maximum amount of candles to fetch
        :param dict params: extra parameters specific to the exchange API endpoint
        :param int params['until']: timestamp in ms of the earliest candle to fetch

 EXCHANGE SPECIFIC PARAMETERS
        :param str params['timeZone']: default=0(UTC)
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        NrJ   rc   rd   z0 fetchOHLCVWs only supports spot or swap marketsrk   r,   rg   Frn   )r   rn   r  until	startTimer   endTimeklinesrK  r   )r   r   rL  r   r   r   r   r9  r8  	market_idr  r   rM  r   handle_fetch_ohlcvrP  )r&   r   r  r   r   r   r   rR  r   r~   rS  rn   rQ  r  r  r?  s                   r)   fetch_ohlcv_wszbinance.fetch_ohlcv_ws`  s     " !!!!!!!!!V$$)).&&II
J($:$:TW'YYZZZit$X.z:OOC((	)nn #'#@#@Ykmr#s#s &nnV,, 0	2
 

 !!&'2267++#(GK $GG!&GIkk'622
 
 d-
 ZZ[';UUUUUUUUUr*   c                     |                      |d          }|                     |          }|                     |d          }|                    ||           d S )NrV  r   )r  parse_ohlcvsr   r  )r&   r   r  rV  r  rS  s         r)   r  zbinance.handle_fetch_ohlcv  sZ    @ 22""6**&&w55v{+++++r*   c                    K   |                                   d{V  |                     |          }|                     |g|                     |ddi                     d{V }||         S )a  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-mini-ticker-stream
        https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-mini-tickers-stream
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.name]: stream to use can be ticker or miniTicker
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        Nr  r;   )r   r   watch_tickersr   r&   r   r   tickerss       r)   watch_tickerzbinance.watch_ticker  s        !!!!!!!!!V$$**F8T[[J\^kIl5m5mnnnnnnnnvr*   c                    K   |                                   d{V  |                     |          }|                     |g|                     |ddi                     d{V }||         S )aI  
        watches a mark price for a specific market

        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.use1sFreq]: *default is True* if set to True, the mark price will be updated every second, otherwise every 3 seconds
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        Nr  r>   )r   r   watch_mark_pricesr   r  s       r)   watch_mark_pricezbinance.watch_mark_price  s       !!!!!!!!!V$$..xVN`brMs9t9tuuuuuuuuvr*   c                    K   d}|                      |ddd          \  }}|                     d|||           d{V }| j        r|S |                     | j        d|          S )aW  
        watches the mark price for all markets

        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream-for-All-market

        :param str[] symbols: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.use1sFreq]: *default is True* if set to True, the mark price will be updated every second, otherwise every 3 seconds
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        Nr=   r   r   r   )r8  watch_multi_ticker_helperr   filter_by_arrayr  r&   r   r   channelName
newTickerss        r)   r  zbinance.watch_mark_prices  s        #;;FDUW]_jkkV99:K[Zacijjjjjjjj
? 	##DL(GDDDr*   c                    K   d}|                      |ddd          \  }}|dk    rt          | j        dz             |                     d|||           d{V }| j        r|S |                     | j        d|          S )a  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list

        https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-mini-ticker-stream
        https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-mini-tickers-stream
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams

        :param str[] symbols: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        Nr<   r   r   r   V deprecation notice - to subscribe for bids-asks, use watch_bids_asks() method insteadr   )r8  r   r   r  r   r  r  r   s        r)   r  zbinance.watch_tickers  s       ";;FNTZ\hiiV,&&TW'  A  A  A99.+W^`fgggggggg
? 	##DL(GDDDr*   c                    K   d}|                      |ddd          \  }}|dk    rt          | j        dz             |                     d|||d           d{V S )	a  
        unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list

        https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-mini-ticker-stream
        https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-mini-tickers-stream
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams

        :param str[] symbols: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        Nr<   r   r   r   r$  rW   T)r8  r   r   r  r&   r   r   r!  s       r)   un_watch_tickerszbinance.un_watch_tickers
  s       ";;FNTZ\deeV,&&TW'  A  A  A334DkSZ\bdhiiiiiiiiir*   c                    K   d}|                      |ddd          \  }}|                                  d{V  |                     d|||d           d{V S )a  
        unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list

        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream

        :param str[] symbols: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        Nr=   r   r   ra   T)r8  r   r  r&  s       r)   un_watch_mark_priceszbinance.un_watch_mark_prices  s       ";;FDUW]_jkkV!!!!!!!!!334GV]_egklllllllllr*   c                 @   K   |                      |g|           d{V S )a  
        unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list

        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        N)r)  rH  s      r)   un_watch_mark_pricezbinance.un_watch_mark_price.  s2       ..x@@@@@@@@@r*   c                 @   K   |                      |g|           d{V S )a  
        unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list

        https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-mini-ticker-stream
        https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-mini-tickers-stream
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        N)r'  rH  s      r)   un_watch_tickerzbinance.un_watch_ticker:  s2       **F8V<<<<<<<<<r*   c                    K   |                                   d{V  |                     |dddd          }|                     dd||           d{V }| j        r|S |                     | j        d|          S )a  
        watches best bid & ask for symbols

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/market-data-requests#symbol-order-book-ticker
        https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/All-Book-Tickers-Stream
        https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Book-Tickers-Stream

        :param str[] symbols: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        NTFr2   r   r   )r   r   r  r   r  bidsasks)r&   r   r   rV  s       r)   watch_bids_askszbinance.watch_bids_asksK  s       !!!!!!!!!%%gtT5$GG55o|U\^deeeeeeee? 	M##DM8WEEEr*   Fr!  isUnsubscribec                 f  K   |                                   d {V  |                     |d ddd          }|dk    }|dk    }|                     |dd          }d }	d }
|d u}|r|                     |d                   }	|rdnd }|                     ||	||          \  }
}d }|                     ||	|          \  }}d }|                     |
|          rd}n?|                     |
|          rd	}n&|
d
k    r|
}nt          | j	        dz   |z   dz             |r;| 
                    |
ddg          s#t          | j	        dz   |z   dz   |
z   dz             g }g }g }d}|r|rdnd}d }|rd}n|rd}nd}|rt          dt          |                    D ]}||         }|                     |          }|                    |d         dz   |z   |z              |                    |dz   |z   dz   |z              |r$|                    d|z   dz   |z   dz   |z              n|r<|
d
k    rt          | j	        dz   |z   dz             |                    d|z              n<|r|                    d|z   dz   |z              n|                    d|z   dz              |                    |dz   |z              |                    d|z              |}|r|dz   d                    |          z   }|                     ||                     |                    dz   |                     ||          z   }|                     |          }|rdnd||d }|}d!|i}|rdt)          |          |||dd"}|}|                     |||                     ||          ||           d {V }|r|S |s|S i }|||d#         <   |S )$NTFr   r   	use1sFreqr   r   rd   re   rc   r}  z#() does not support options marketsz() does not support z markets yetr  z@1sbidaskr   r   r6  :zunsubscribe::z5() requires symbols for self channel for spot markets!@arrs:r   r   r   rB  r   r   r   r  r   )r   r   r  r   r   r   r   r   r   r   in_arrayr   r   r   r   r   r   r   r   r   r9  r   r$   )r&   
methodNamer!  r   r   r1  isBidAskisMarkPricer3  r   rR  symbolsDefineddefaultMarketr   rawMarketTypesubscriptionArgsr   unsubscribeMessageHashesr  unifiedPrefixr   r   r   r   r   r~   r   hashesr?  rV  newDicts                                  r)   r  z!binance.watch_multi_ticker_helper^  s!     !!!!!!!!!%%gtT5$GG</"k1NN6;==	
!- 	2++gaj11K#.9T!??
KY_anoo
F99*kSYZZ==W-- 	c$MM^^J00 	c&MM6!!&MMtw}z9<aabbb 	rt}}Z&(9KLL 	rtw}z9<RRU__bppqqq#%  	2(1UUrF! 	%$MM 	%'MM$M 	K1c'll++ x x V,, ''}(=(Ck(QTZ(Z[[[$$]S%8;%F%Lv%UVVV  x,33Om4SVY4Y\g4gjm4mpv4vwwwx  D''+DGcMJ,F  JA  -A  B  B  B ''k(9:::: D ''k(9F(BV(KLLLL ''k(9F(BCCC  !5!CDDD$++Ok,IJJJ 
 	@$t+chhw.?.??JoomT-H-H-U-UVVY\\_c_j_jkx  {E  `F  `F  FOOC((	'4Emm+&
 

 )
  		.#)nn$1!9"! L .F**38H8HRX8Y8Y[acopppppppp 	M  	MG(.GF8$%Nr*   c                 J   |                      |dd          }|                     |d d |          }|                     |dd          }|dk    rd}|dk    r|                     ||                     |d          |                     |                     |d                    ||                     |d	          |                     |d
          d          S d }|dk    r|                     |dd          }n|                     |g d          }|                     |d d |          }|                      |dd          }|                     i d|d|d|                     |          d|                     |d          d|                     |d          d|                      |dd          d|                      |dd          d|                      |dd          d|                      |d d!          d"|                     |d#          d$|                     |d%          d&|d'|d(|                     |d)          d*|                     |d	          d+|                     |d,          d-d |                     |d.          |                     |d/          |d0|          S )1Nr  r   rj  r   r   r   r   r{  r  r   )r   r  r  r  r   
indexPricetime)Cr{  rG  r  r  r  r  highr  lowr  bidrz  bidPrice	bidVolumeBbidQtyaskrx  askPrice	askVolumeAaskQtyvwapwopenr  closelastpreviousCloser  change
percentagePaverager  r  )
baseVolumequoteVolumer  )	r  r  r   safe_tickerr   r   r[  safe_integer_nr  )	r&   r  rR  r
  r   r  r  r   rY  s	            r)   parse_ws_tickerzbinance.parse_ws_ticker  sI   J %%gsH==!!(D$
CC  #|<<L  E%%%## !..w<< LL):):7C)H)HII!--gs;;"..w<<% %    	L  ++GS&AAII ++G5G5G5GHHI!!(D$
CC!!'388 !
f!
!
 Y//!
 D$$Wc22	!

 4##GS11!
 4%%gsJ??!
 ++GS(CC!
 4%%gsJ??!
 ++GS(CC!
 D$$Wc22!
 D$$Wc22!
 T!
 D!
 T--gs;;!
 d&&w44!
  $**7C88!!
" t#!
$ **7C88++GS99)!
 !
 !
* +  	r*   c                     |                      |d          }|                     |di           }|                     |d          }|                    ||           d S )Nr   rV  rd   )r   r   rc  r  )r&   r   r  rS  rV  r   s         r)   r	  zbinance.handle_ticker_ws0  s]    6 &&w55(B77%%fh77v{+++++r*   c                 4    |                      ||d           d S )Nbidaskshandle_tickers_and_bids_asksr&   r   r  s      r)   handle_bids_askszbinance.handle_bids_asksP  s"     	))&'9EEEEEr*   c                 4    |                      ||d           d S )Nr  rg  ri  s      r)   handle_tickerszbinance.handle_tickers_  s"    < 	))&'9EEEEEr*   c                 4    |                      ||d           d S )N
markPricesrg  ri  s      r)   handle_mark_priceszbinance.handle_mark_prices  s     ))&'<HHHHHr*   c                    |                      |          }|rdnd}|dk    }|dk    }d }|rd}n|rd}nd}d }	g }
g }i }t          |t                    r|}n|                    |           t	          dt          |                    D ]}||         }|                     |d	          }|rd
}|                     | j        d         ||          }	|	I|                     ||          }|d         }|||<   |r|| j	        |<   n
|| j
        |<   |dz   |	z   dz   |z   }|
                    |           |                    ||           t          |
          }|dk    r |dz   |	z   }|                    ||           d S d S )Nrc   r  rf  rn  r4  r   r   r   rj  r   r   r   r5  r6  r8  )r   
isinstancelistr   r   r   r   r   rc  r/  r  r  )r&   r   r  
methodTyper  rR  r;  r<  rB  r!  resolvedMessageHashes
rawTickersr"  r   r   r  parsedTickerr   rS  lengthbatchMessageHashs                        r)   rh  z$binance.handle_tickers_and_bids_asks  s   !!&)) &7VVZ
)+!\1! 	%$MM 	%'MM$M "

gt$$ 	' JJg&&&q#j//** 	6 	6A]F$$VS11E %$**4<8K+LeUZ[[K"//
CCL!(+F!-Jv 4(4f%%'3V$'#-;cAFJK!((555NN<5555*++A::,t3kANN:'788888 :r*   c                    |                                   |                     | j        d          }|||d<   |                     |d          }|||d<   |                     |                                 | j        d|          }|                     |          }|                     |          }d }| j        	                    d          dk    ret          | j                  dk    r|                     || j        d          }n||                     |                     |          | j        d          }nL|                     |                     |          |                     | j                  t          j                  }||d<   |S )	N
recvWindow)r  apiKeyzPRIVATE KEYru   x   sha256ed25519	signature)check_required_credentialsr   r   r   rY  r{  keysort	rawencodesecretr   r   rsaeddsaencodehmachashlibr}  )r&   r   defaultRecvWindowrz  extendedParamsr  r  s          r)   rN  zbinance.sign_params  sm   ''))) --dlLII(#4F< &&v|<<
!#-F< k&
 &
   n55~..	;M**R//4;#%% HHUDKBB		 JJt{{5'9'94;	RR				$++e"4"4dkk$+6N6NPWP^__I&/{#r*   rc   rR  c                   K   | j         d         d         d         |         }|                     |          }|j        }t          |                                          }|                     |          }||k    rdS d|j        |<   |                     |          }t          |          }|d|                     i           d}	|| j	        |d}
| 
                    |||	||
           d{V  dS )	a  
        watches best bid & ask for symbols
 @param marketType {string} only support on 'spot'

        {@link https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/user-data-stream-requests#subscribe-to-user-data-stream-through-signature-subscription-user_data Binance User Data Stream Documentation}

        :returns: Promise<number> The subscription ID for the user data stream
        rk   r,   rg   NTz"userDataStream.subscribe.signaturerK  r   r   r?  )r   r   rd  rr  keys#get_account_type_from_subscriptionsr   r9  rN  !handle_user_data_stream_subscriberP  )r&   rR  r   r   rd  subscriptionsKeysaccountTyper~   rS  r  r?  s              r)   .ensure_user_data_stream_ws_subscribe_signaturez6binance.ensure_user_data_stream_ws_subscribe_signature  s      it$X.z:S!!, !3!3!5!566>>?PQQ*$$F+/Z(OOC((	)nn:&&r**
 
 <&
 

 jjk7KNNNNNNNNNNNr*   c                 r   |                      |d          }|j        }t          |                                          }|                     |          }|                     |di           }|                     |d          }||j        |= |                    ||           |                    ||           d S )Nr   rV  subscriptionId)	r   rd  rr  r  r  r   r   re  r  )	r&   r   r  rS  rd  r  r  rV  r  s	            r)   r  z)binance.handle_user_data_stream_subscribe  s     &&w55, !3!3!5!566>>?PQQ266**63CDD!$[1MM';///w,,,,,r*   rf   c           
      f  K   | j         d         d         d         d         }|                     | j        |i           }|                     |dd          }|                     | j        dd          }|                                 }|                     |d	          }||z
  |k    r|                     |d
          }	|                     |dd          }
|                     |d          }i }|
r8|	t          | j	        dz             | 
                    |	          }||d
<   d|d<   |||d<   |                     |           d{V }|                     |d          }|                     |d          }|                     |          }t          |          }|dd|id}|| j        |d}|                     |||||	|
|d          | j        |<   ||z
  dz
  }|dk    r4|                     |d|i          }|                     || j        |           |                     |||||           d{V  dS dS )a  
        subscribes to user data stream using listenToken(for margin)
        :param str marketType: - the market type(e.g., 'margin')
        :param dict params: - extra parameters specific to the request
        :param str [params.symbol]: - required for isolated margin
        :param boolean [params.isIsolated]: - whether it is isolated margin
        :param number [params.validity]: - validity in milliseconds, default 24 hours, max 24 hours

        {@link https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-api/user-data-stream Binance User Data Stream Documentation}

        :returns: Promise<void>
        rk   r,   rg   rc   lastAuthenticatedTimer   listenTokenRefreshRateim'  r   
isIsolatedFvalidityNza ensureUserDataStreamWsSubscribeListenToken() requires a symbol argument for isolated margin modeTtokenexpirationTimez$userDataStream.subscribe.listenTokenlistenTokenrK  r  )r  r  r  r   r  r  i`  r   )r   r   r   r   millisecondsr   r   r  r   r   r  sapiPostUserListenTokenr   r9  r  r   delayrenew_listen_tokenrP  )r&   rR  r   r   r   r  r  rG  r  r   r  r  r   r
  responser  r  r~   rS  r  r?  renewalTimer  s                          r)   1ensure_user_data_stream_ws_subscribe_listen_tokenz9binance.ensure_user_data_stream_ws_subscribe_listen_token  s      it$X.v6..z2>> $ 1 1';RTU V V!%!2!24<AY[c!d!d  ""/77''%//%%fh77FeDDJ((<<HG ->+DG  7Z  -Z  [  [  [>>&11$,!(,%#&.
#!99'BBBBBBBBH**8W==K!..x9IJJN,,Ii..K!@!; G "@ *" "L
 (,{{7*"0)- ($= = ( (DL$ )4/%7KQ!%Vfj5I!J!J

;(?PPP**S+w\RRRRRRRRRRR[ 0/r*   c                 \  K   |                      |dd          }|                     | j        |i           }|                      |d          }|                     |dd          }|                     |d          }i }|||d<   |r||d<   |||d<   |                     ||           d {V  d S )Nr   rf   r   r  Fr  )r   r   r   r  r   r  )r&   r   r   r   r   r  r  renewParamss           r)   r  zbinance.renew_listen_token=	  s      99..tR88!!'844^^G\5AA
$$Wj99$*K! 	3(2K%&.K
#DDT;WWWWWWWWWWWr*   c                 <  K   |                                  }d }|                     dd |          \  }}d }|                     dd |          \  }}d }|                     |dddd          \  }}|                     ||          rd}n|                     ||          rd}|dk    r|                     d           d {V  d S d }|                     d|          \  }}|dk    }|                     |d	          }|d
k    s|r.i }	|||	d	<   |rd|	d<   | 	                    d
|	           d {V  d S | 
                    |d	          }|                     | j        |i           }
|                     |
dd          }|                     | j        dd          }|                     |d          }||z
  |k    rd }|r4|                     |           d {V }|                     |ddi          }n_|dk    r|                     |           d {V }n=|dk    r|                     |           d {V }n|                     |           d {V }|                     |
|                     |d          |d          | j        |<   |                     || j        |           d S d S )Nr'  rh   portfolioMarginFrd   re   rc   isolatedr   rf   Tr  r  r   r   r   r  r   r   r  )r  r   r   handle_option_and_params_2r   r   r  handle_margin_mode_and_paramsr   r  rM  r   r   r   r   papiPostListenKeyr   fapiPrivatePostListenKeydapiPrivatePostListenKeypublicPostUserDataStreamr  keep_alive_listen_key)r&   r   rG  r   r   isPortfolioMargin
marginModeisIsolatedMarginr   marginParamsr   r  r   r  r  s                  r)   r'  zbinance.authenticateL	  sW       ""99.$PVWWf99.$PVWW $($C$CFN\bduw|$}$}!6==w'' 	DD^^D'** 	D6>>EEfMMMMMMMMMF
!??PVWW
F&*4!!&(338/!#L!)/X& 2-1\*HHS_`````````F68,,//$,b99 $ 1 1';RTU V V#00?UW^__-u55''%//H  G!%!7!7!?!???????V.?-FGG!!!%!>!>v!F!FFFFFFF##!%!>!>v!F!FFFFFFF!%!>!>v!F!FFFFFFF!%W!--hDD)-7 7 " "DL JJ+T-GPPPPP 0/r*   c                   K   |                      | j        ddd          }|                     |d|          }d }|                     |dddd          \  }}|                     dd |          }|d	         }|                     ||          rd
}n|                     ||          rd}|dk    rd S |                     | j        |i           }|                     |d          }|d S i }|                     |ddg          }| 	                                }		 |rH| 
                    |                     ||                     d {V  |                     |ddi          }n|d
k    r0|                     |                     ||                     d {V  nj|dk    r0|                     |                     ||                     d {V  n4||d<   |                     |                     ||                     d {V  n# t          $ r}
|}|rd}| j        |         d         }|                     ||          }|                     |          }t%          |j                                                  }t+          d	t-          |                    D ] }||         }|                    |
|           !|                     |d d	d          | j        |<   Y d }
~
d S d }
~
ww xY w|                     |||	d          | j        |<   t%          | j                                                  }|                     | j        dd          }t+          d	t-          |                    D ]~}||         }t%          |j                                                  }t+          d	t-          |                    D ]0}||         }||k    r |                     || j        |             d S 1d S )Nr   r'  rc   r   keepAliveListenKeyrh   r  Fr   rd   re   rf   r   r   Tr  r   r   )r  r   r   r  r   r   r   r   rM  r  papiPutListenKeyr   fapiPrivatePutListenKeydapiPrivatePutListenKeypublicPutUserDataStreamrc  r   r   rr  futuresr  r   r   re  clientsvaluesr   rd  r  r  )r&   r   r   r  subTypeInfor   r   r   r   rG  errorurlTypecachedListenKeyr   r   r   r   rS  r  r   subscriptionKeysr  subscribeTypes                          r)   r  zbinance.keep_alive_listen_key	  sw     !!$,~vVV55 $($C$CFL`bhj{  ~C  %D  %D!6556JDRXYYa.==w'' 	DD^^D'** 	D8F//$,b99$$Wk::	F6FH#566  ""	  	Q++DKK,H,HIIIIIIIIIV.?-FGG!!224;;w3O3OPPPPPPPPPP##224;;w3O3OPPPPPPPPPP'0$224;;w3O3OPPPPPPPPP 	 	 	G  ! "l40=O))'?CCC[[%%F !4!4!6!677M1c-0011 2 2+A.e[1111!%W!)*7 7 " "DL FFFFF	  "[["%)3
 3
  T
 t|**,,--#00?UW^__q#g,,'' 	 	AQZF#F$8$=$=$?$?@@1c"23344   0 3 D((JJ3T5OQWXXXFFF )	 	s   C*G= =
KC	KKc                 4   ||j         v r|| j        v rd S |                     | j        d          }|                     |dd          }|rE|dz   }||j        vr5|                    |           |                     | j        ||||           d S d S i | j        |<   d S )Nr-   r   F:fetchBalanceSnapshot)	rd  balancer   r   r  r  rd   r  load_balance_snapshot)r&   r   r   r  r   r   rS  s          r)   set_balance_cachezbinance.set_balance_cache	  s    F(((tt|/C/CF//$,??#~~g7MuUU 	$!88K6>11k***

45v{DRcddddd 21 "$DLr*   c                 f  K   d|i}|rd|d<   |                      |           d {V }|                     ||                     | j        |i                     | j        |<   ||j        v rG|j        |         }|                                 |                    | j        |         |dz              d S d S )Nr   Tr  :balance)fetch_balancer   r   r  r  r  )r&   r   rS  r   r  r   r  rd   s           r)   r  zbinance.load_balance_snapshot	  s      D
  	-(,F$%++F33333333![[4??4<QUWY3Z3Z[[T&.((^K0FNNNN4<-tj/@AAAAA )(r*   c                   K   |                                   d{V  |                     dd|          }|dk    r#|dk    r|dk    rt          | j        dz             | j        d         d         d	         |         }|                     |          }t          |          }d
}|                     |ddd
          \  }}d|i}d}|                     |ddd          \  }}|||                     | 	                    ||                    d}	d|dk    r| j
        n| j        i}
|                     |||	||
           d{V S )am  
        fetch balance and get the amount of funds available for trading or funds locked in orders

        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api/Futures-Account-Balance
        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/account-requests#account-information-user_data
        https://developers.binance.com/docs/derivatives/coin-margined-futures/account/websocket-api

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str|None [params.type]: 'future', 'delivery', 'savings', 'funding', or 'spot'
        :param str|None [params.marginMode]: 'cross' or 'isolated', for margin trading, uses self.options.defaultMarginMode if not passed, defaults to None/None/None
        :param str[]|None [params.symbols]: unified market symbols, only used in isolated margin mode
        :param str|None [params.method]: method to use. Can be account.balance, account.status, v2/account.balance or v2/account.status
        :returns dict: a `balance structure <https://docs.ccxt.com/?id=balance-structure>`
        NrF   rc   rd   re   z2 fetchBalanceWs only supports spot or swap marketsrk   r,   rg   Frn   r   zaccount.statusrK  )r   rL  r   r   r   r   r9  r8  rN  r   handle_account_status_wshandle_balance_wsrP  )r&   r   r   r   r~   rS  rn   rQ  r   r  r?  s              r)   fetch_balance_wszbinance.fetch_balance_ws	  s      !!!!!!!!!##$4dFCC6>>dh..4:3E3ETW'[[\\\it$X.t4OOC((	)nn #'#@#@IY[mot#u#u & 0
 66v?OQY[kll&&t{{7F'C'CDD
 
 BR8R8Rd33Y]Yo
 ZZ[';UUUUUUUUUr*   c                 N   |                      |d          }d }t          |d         t                    r|                     |dg           }n.|                     |di           }|                     |dg           }|                     |          }|                    ||           d S )Nr   rV  assets)r   rq  rr  r  r   parseBalanceCustomr  )r&   r   r  rS  
rawBalancerV  parsedBalancess          r)   r  zbinance.handle_balance_ws
  s     &&w55
gh'.. 	>2>>JJ ^^GXr::F"==J00<<~{33333r*   c                     |                      |d          }|                     |di           }|                     |          }|                    ||           d S Nr   rV  )r   r   r  r  )r&   r   r  rS  rV  r  s         r)   r  z binance.handle_account_status_ws
  s\    ^ &&w552660088~{33333r*   c                 @   K   |                      |g|           d{V S )a  
        fetch data on an open position

        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Position-Information

        :param str symbol: unified market symbol of the market the position is held in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `position structure <https://docs.ccxt.com/?id=position-structure>`
        N)fetch_positions_wsrH  s      r)   fetch_position_wszbinance.fetch_position_wsF
  s2       ,,fXv>>>>>>>>>r*   c                 T  K   |                                   d{V  i }d}|                     |dddd          }|;t          |          }|dk    r&|                     |d                   }|d         |d<   |                     d||          }||d	k    rd
}|d
k    r|dk    rt          | j        dz             | j        d         d         d         |         }|                     |          }t          |          }	d}
| 
                    |ddd          \  }
}|
|d<   d}| 
                    |ddd          \  }}|	||                     |                     ||                    d}d| j        i}|                     ||	||	|           d{V }|                     |d|d          S )a  
        fetch all open positions

        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Position-Information
        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/websocket-api/Position-Information

        :param str[] [symbols]: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.returnRateLimits]: set to True to return rate limit informations, defaults to False.
        :param str|None [params.method]: method to use. Can be account.position or v2/account.position
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/?id=position-structure>`
        Nr   Tr   r   r   r   rQ   rc   rd   re   z, fetchPositionsWs only supports swap marketsrk   r,   rg   Frn   r   zaccount.positionrK  )r   r   r   r   rL  r   r   r   r   r9  r8  rN  r   handle_positions_wsrP  filter_by_array_positions)r&   r   r   rQ  r   r;  r   r   r~   rS  rn   r   r  r?  rV  s                  r)   r  zbinance.fetch_positions_wsR
  s      !!!!!!!!!%%gvtT4HHLLM!!WQZ00$*4L!##$6GG? D8
 2 2TW'UUVVVit$X.t4OOC((	)nn #'#@#@I[]oqv#w#w &&6"#66v?QS[]opp&&t{{7F'C'CDD
 
 d.
 zz#{G[,WWWWWWWW--fhOOOr*   c                    |                      |d          }|                     |dg           }g }t          dt          |                    D ]Z}|                     ||                   }|                      |d          }|dk    r!|dk    r|dk    r|                    |           [|                    ||           d S )Nr   rV  r   
entryPrice0z0.0z
0.00000000)r   r  r   r   parse_position_riskr   r  )	r&   r   r  rS  rV  	positionsr   r  r  s	            r)   r  zbinance.handle_positions_ws
  s    > &&w55266	q#f++&& 	) 	)A--fQi88F))&,??Jc!!
e(;(;*P\B\B\  (((y+.....r*   c                 
  K   |                                   d{V  |                     |           d{V  |                     | j        dd          }|                     |d|          }d}|                     dd|          \  }}d}|                     |dddd          \  }}|                     ||          rd	}n|                     ||          rd
}d}|}|dk    s|dk    r | j        d         d         d         d         }n+|rd}| 	                    || j        |         d                   }| 
                    |          }|                     |||           |                     ||d|           |                     | j        d          }	|                     |	dd          }
|                     |	dd          }|
r |r|                    |dz              d{V  |dz   }d}|                     ||||           d{V S )a  
        watch balance and get the amount of funds available for trading or funds locked in orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.portfolioMargin]: set to True if you would like to watch the balance of a portfolio margin account
        :returns dict: a `balance structure <https://docs.ccxt.com/?id=balance-structure>`
        Nr   rc   r   r-   rh   r  Frd   re   r  rf   rk   r,   rg   r   r   r   Tr  r  )r   r'  r   r   r   r  r   r   r   r   r   r  set_positions_cacher   r  rd   rP  )r&   r   r   r   r   r  r   r  r   r   r   r   rS  r  s                 r)   watch_balancezbinance.watch_balance
  sj      !!!!!!!!!'''''''''&&t|]FKK<<99.$PVWW $($C$CFN\bduw|$}$}!6==w'' 	DD^^D'** 	D6>>TX--)E"4(26:CC  ! ))'4<3Ek3RSSCS!!vt->???  t5FGGG..~>>#~~g7MuUU#~~g7MtTT 	@$8 	@--'> >?????????Z'ZZ['4@@@@@@@@@r*   c                    |                      | j        dd          }|j        }t          |                                          }|                     |          }|dz   }| j        |         
i | j        |<   || j        |         d<   |                      |d          }|dk    r|                      |d          }	|                     |	          }
|                                 }|                      |d          }|
| j        |         v r\| j        |         |
         d	         }t          |t                    s|                     |          }t          j        ||          |d	<   n||d	<   || j        |         |
<   n|                     |d|          }|                     |d
          }t!          dt#          |                    D ]}||         }|                      |d          }	|                     |	          }
|                                 }|                      |d          |d	<   |                      |d          |d<   |                      ||          |d<   || j        |         |
<   |                     |d          }|| j        |         d<   |                     |          | j        |         d<   |                     | j        |                   | j        |<   |                    | j        |         |           d S )Nr   r   r  r  rj  balanceUpdaterx  dfreerN  r   fr  usedtotalr{  r  r  )r   r   rd  rr  r  r  r  r  accountrq  r9  r   r   
string_addr   r  r   r   r   r   safe_balancer  )r&   r   r  r   rd  r  r  rS  r  
currencyIdcoder  rp  r   rN  r   entryr  s                     r)   handle_balancezbinance.handle_balance
  s   D !!$,$??, !3!3!5!566>>?PQQ!J.<$,(*DL%,3[!&)  #..O##))'377J**:66DllnnG$$Wc22Et|K000 $[ 9$ ? G!-55 I$($9$9-$H$HM")"4]E"J"J"'.5DL%d++nnWc7;;Gw,,A1c!ff%% : :!!--eS99
..z::,,.."&"2"25#">">"&"2"25#">">#'#3#3E6#B#B 29[)$//%%gs33	1:[!+.04Y0G0G[!*-$($5$5dl;6O$P$P[!t|K0+>>>>>r*   rd  c                     d}t          dt          |                    D ]&}||         }|dk    s|dk    s|dk    s|dk    r|} n'|S )Nr  r   rc   rf   rd   re   )r   r   )r&   rd  r  r   r?  s        r)   r  z+binance.get_account_type_from_subscriptions>  s    q#m,,-- 	 	A(+L&&LH,D,D,ZbJbJbht  yC  iC  iC* iC r*   c                     d }|                      |||          \  }}d }|                     |||          \  }}|                     ||          rd}n|                     ||          rd}|S )Nrd   re   )r   r   r   r   )r&   r   r   r   r   r   s         r)   rL  zbinance.get_market_typeG  s    99&&&QQf99&&&QQ==w'' 	DD^^D'** 	Dr*   r  rq  r  c                   K   |                                   d{V  |                     |          }|                     d||          }|dk    r#|dk    r|dk    rt          | j        dz             | j        d         d         d	         |         }	|                     |	          }
t          |
          }|                     |d
dd          }| 	                    |d
d          }| 
                    |dd          }|                     |d|          }|                     |d          }|                     |d          }|                     |g d          }|du}|dup|du}|du}|du}|p|p|p|}|                     ||||||          }d}|                     |ddd          \  }}||d<   |                     |dd          }| 	                    |d          }|d         r|d         r|rd|d<   |d|                     |                     ||                    d}|r|rd|d<   nd|d<   |d         r|d         r|rd|d<   d| j        i}|                     |	||||           d{V S )a  
        create a trade order

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/trading-requests#place-new-order-trade
        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/New-Order
        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/websocket-api
        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/New-Algo-Order

        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float|None [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean params['test']: test order, default False
        :param boolean params['returnRateLimits']: set to True to return rate limit information, default False
        :returns dict: an `order structure <https://docs.ccxt.com/?id=order-structure>`
        NrA   rc   rd   re   z1 createOrderWs only supports spot or swap marketsrk   r,   rg   sorSORFtriggerPrice	stopPricestopLossPricetakeProfitPricetrailingDelta)trailingPercentcallbackRater  rn   ri   r0  r   CONDITIONALalgoTypezorder.placerK  zsor.order.testr   z
order.testzalgoOrder.place)r   r   rL  r   r   r   r   r9  safe_bool_2rM  r  r   safe_string_ncreate_order_requestr8  r  rN  r   handle_order_wsrP  )r&   r   r   r  rq  r  r   r   rR  r   r~   rS  r  r  r  r  r  r  isTrailingPercentOrder
isStopLossisTakeProfitisTriggerOrderisConditionalrQ  rn   ri   r  r?  s                               r)   create_order_wszbinance.create_order_wsR  s     & !!!!!!!!!V$$))/66JJ
J($:$:zZ?W?WTW'ZZ[[[it$X.z:OOC((	)nnvueU;;65%00))&.+NN((,OO**63DEE((AA,,V5i5i5ijj!0!<"$.K-t2K
&d2%T1&^*@^J^R^++FD$vVV #'#@#@Zlns#t#t &&6"#~~ffe4466**( 	0v 	0= 	0"/GJ#&&t{{7F'C'CDD
 

  	1 1$4!!$0!( 	2v 	2= 	2 1GHd*
 ZZ[';UUUUUUUUUr*   c                     |                      |d          }|                     |di           }|                     |          }|                    ||           d S r  r   r   parse_orderr  )r&   r   r  rS  rV  r  s         r)   r  zbinance.handle_order_ws  s\    ` &&w55266  ((uk*****r*   c                     |                      |d          }|                     |dg           }|                     |          }|                    ||           d S r  )r   r  parse_ordersr  )r&   r   r  rS  rV  orderss         r)   handle_orders_wszbinance.handle_orders_ws  s\    L &&w55266""6**v{+++++r*   r   c           	        K   |                                   d{V  |                     |          }|                     d||          }	|	dk    r#|	dk    r|	dk    rt          | j        dz             | j        d         d         d	         |	         }
|                     |
          }t          |          }|	dk    p|	dk    }d}|	dk    r|                     |||||||          }n|r| 	                    |||||||          }d
}| 
                    |ddd
          \  }}||d<   ||rdnd|                     |                     ||                    d}d| j        i}|                     |
||||           d{V S )a  
        edit a trade order

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/trading-requests#cancel-and-replace-order-trade
        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Modify-Order
        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/websocket-api/Modify-Order

        :param str id: order id
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of the currency you want to trade in units of the base currency
        :param float|None [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/?id=order-structure>`
        NrB   rc   rd   re   z/ editOrderWs only supports spot or swap marketsrk   r,   rg   Frn   zorder.modifyzorder.cancelReplacerK  r   )r   r   rL  r   r   r   r   r9  editSpotOrderRequesteditContractOrderRequestr8  rN  r   handle_edit_order_wsrP  )r&   r   r   r   r  rq  r  r   r   rR  r   r~   rS  isSwaprQ  rn   r  r?  s                     r)   edit_order_wszbinance.edit_order_ws  s     " !!!!!!!!!V$$))-HH
J($:$:zZ?W?WTW'XXYYYit$X.z:OOC((	)nn(DJ*,D//FD$PUW]^^GG 	c33BdFTY[abbG #'#@#@Xjlq#r#r &&6"#)/Knn6K&&t{{7F'C'CDD
 
 d/
 ZZ[';UUUUUUUUUr*   c                    |                      |d          }|                     |di           }|                     |d          }d }||                     |          }n|                     |          }|                    ||           d S )Nr   rV  newOrderResponser  )r&   r   r  rS  rV  newSpotOrderr  s          r)   r  zbinance.handle_edit_order_ws  s    F &&w55266~~f.@AA#$$\22EE$$V,,Euk*****r*   c                   K   |                                   d{V  |t          | j        dz             |                     |          }|                     d||          }| j        d         d         d         |         }|                     |          }t          |          }d}	|                     |ddd          \  }	}| 	                    |          |	d	}
| 
                    |g d
          }|                     |g d          }|d         o	|d         o|}||r||
d<   n9||
d<   n3|r|                     |          |
d<   n|                     |          |
d<   |                     |g d          }|d|                     |                     |
|                    d}|rd|d<   d| j        i}|                     |||||           d{V S )aB  
        cancel multiple orders

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/trading-requests#cancel-order-trade
        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Cancel-Order
        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/websocket-api/Cancel-Order
        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Cancel-Algo-Order

        :param str id: order id
        :param str [symbol]: unified market symbol, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str|None [params.cancelRestrictions]: Supported values: ONLY_NEW - Cancel will succeed if the order status is NEW. ONLY_PARTIALLY_FILLED - Cancel will succeed if order status is PARTIALLY_FILLED.
        :param boolean [params.trigger]: set to True if you would like to cancel a conditional order
        :returns dict: an list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        N  cancelOrderWs requires a symbolrC   rk   r,   rg   Frn   r   rn   )stoptriggerr  )clientAlgoIdorigClientOrderIdclientOrderIdr0  r   r!  r"  algoIdr  )r"  r#  r  r   r  zorder.cancelrK  zalgoOrder.cancelr   )r   r   r   r   rL  r   r   r9  r8  r  safe_bool_nr  r   rM  rN  r   r  rP  )r&   r   r   r   r   r   r   r~   rS  rn   rQ  r
  r#  shouldUseAlgoOrderr  r?  s                   r)   cancel_order_wszbinance.cancel_order_ws  s>       !!!!!!!!!>TW'IIJJJV$$##OVVDDit$X.t4OOC((	)nn #'#@#@Zlns#t#t &nnV,, 0
 
 ((1S1S1STT**63i3i3ijj#H-R&.R]$! =*7''/<+,,! ?$($9$9"$=$=!!%)%:%:2%>%>	"6#k#k#kll$&&t{{7F'C'CDD
 

  	3 2GHd*
 ZZ[';UUUUUUUUUr*   c                 f  K   |                                   d{V  |                     |          }|                     d||          }|dk    rt          | j        dz             | j        d         d         d         |         }|                     |          }t          |          }d}|                     |dd	d          \  }}| 	                    |          |d
}	|d| 
                    |                     |	|                    d}
d| j        i}|                     |||
||           d{V S )a  
        cancel all open orders in a market

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/trading-requests#cancel-open-orders-trade

        :param str [symbol]: unified market symbol of the market to cancel orders in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        NrE   rc   z- cancelAllOrdersWs only supports spot marketsrk   r,   rg   Frn   r  zopenOrders.cancelAllrK  r   )r   r   rL  r   r   r   r   r9  r8  r  rN  r   r  rP  )r&   r   r   r   r   r   r~   rS  rn   rQ  r  r?  s               r)   cancel_all_orders_wszbinance.cancel_all_orders_ws  sc      !!!!!!!!!V$$##$7HH6>>TW'VVWWWit$X.t4OOC((	)nn #'#@#@I\^prw#x#x &nnV,, 0
 

 ,&&t{{7F'C'CDD
 
 d+
 ZZ[';UUUUUUUUUr*   c                   K   |                                   d{V  |t          | j        dz             |                     |          }|                     d||          }|dk    r#|dk    r|dk    rt          | j        dz             | j        d         d	         d
         |         }|                     |          }t          |          }d}	|                     |ddd          \  }	}| 	                    |          |	d}
| 
                    |dd          }|||
d<   n|                     |          |
d<   |d|                     |                     |
|                    d}d| j        i}|                     |||||           d{V S )a  
        fetches information on an order made by the user

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/trading-requests#query-order-user_data
        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Query-Order
        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/websocket-api/Query-Order

        :param str id: order id
        :param str [symbol]: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/?id=order-structure>`
        Nr  rM   rc   rd   re   z0 fetchOrderWs only supports spot or swap marketsrk   r,   rg   Frn   r  r"  r#  r  zorder.statusrK  r   )r   r   r   r   rL  r   r   r9  r8  r  r  r   rN  r   r  rP  )r&   r   r   r   r   r   r   r~   rS  rn   rQ  r#  r  r?  s                 r)   fetch_order_wszbinance.fetch_order_ws  s      !!!!!!!!!>TW'IIJJJV$$##NFFCC6>>dh..4:3E3ETW'YYZZZit$X.t4OOC((	)nn #'#@#@Ykmr#s#s &nnV,, 0
 
 **63FXX$+8G'((!%!6!6r!:!:GI$&&t{{7F'C'CDD
 
 d*
 ZZ[';UUUUUUUUUr*   c                   K   |                                   d{V  |t          | j        dz             |                     |          }|                     d||          }|dk    rt          | j        dz             | j        d         d         d         |         }|                     |          }t          |          }	d	}
|                     |d
dd	          \  }
}| 	                    |          |
d}|	d| 
                    |                     ||                    d}d| j        i}|                     ||	||	|           d{V }|                     ||||          S )a  
        fetches information on multiple orders made by the user

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/trading-requests#order-lists

        :param str symbol: unified market symbol of the market orders were made in
        :param int|None [since]: the earliest time in ms to fetch orders for
        :param int|None [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.orderId]: order id to begin at
        :param int [params.startTime]: earliest time in ms to retrieve orders for
        :param int [params.endTime]: latest time in ms to retrieve orders for
        :param int [params.limit]: the maximum number of order structures to retrieve
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nz  fetchOrdersWs requires a symbolrN   rc   z) fetchOrdersWs only supports spot marketsrk   r,   rg   FrM   rn   r  	allOrdersrK  r   )r   r   r   r   rL  r   r   r9  r8  r  rN  r   r  rP  filter_by_symbol_since_limitr&   r   r   r   r   r   r   r   r~   rS  rn   rQ  r  r?  r  s                  r)   fetch_orders_wszbinance.fetch_orders_ws  s       !!!!!!!!!>TW'IIJJJV$$##OVVDD6>>TW'RRSSSit$X.t4OOC((	)nn #'#@#@Ykmr#s#s &nnV,, 0
 

 !&&t{{7F'C'CDD
 
 d+
 zz#{G[,WWWWWWWW00NNNr*   c                    K   |                      ||||           d{V }g }t          dt          |                    D ]+}||         }|d         dk    r|                    |           ,|S )a  
        fetch closed orders

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/trading-requests#order-lists

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nr   statusclosed)r0  r   r   r   )	r&   r   r   r   r   r  closedOrdersr   r  s	            r)   fetch_closed_orders_wszbinance.fetch_closed_orders_ws<  s       ++FE5&IIIIIIIIq#f++&& 	+ 	+A1IEX(**##E***r*   c                   K   |                                   d{V  |                     |          }|                     d||          }|dk    r|dk    rt          | j        dz             | j        d         d         d         |         }|                     |          }t          |          }	d	}
|                     |d
dd	          \  }
}d|
i}|| 	                    |          |d<   |	d| 
                    |                     ||                    d}d| j        i}|                     ||	||	|           d{V }|                     ||||          S )aO  
        fetch all unfilled currently open orders

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/trading-requests#current-open-orders-user_data

        :param str symbol: unified market symbol
        :param int|None [since]: the earliest time in ms to fetch open orders for
        :param int|None [limit]: the maximum number of open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        NrL   rc   rd   z5 fetchOpenOrdersWs only supports spot or swap marketsrk   r,   rg   FrM   rn   r   zopenOrders.statusrK  r   )r   r   rL  r   r   r   r   r9  r8  r  rN  r   r  rP  r.  r/  s                  r)   fetch_open_orders_wszbinance.fetch_open_orders_wsP  s      !!!!!!!!!V$$##$7HH6>>dh..TW'^^___it$X.t4OOC((	)nn #'#@#@Ykmr#s#s & 0
  $v 6 6GH)&&t{{7F'C'CDD
 
 d+
 zz#{G[,WWWWWWWW00NNNr*   c                 H  K   |                                   d{V  d}d}|%|                     |          }|d         }|d|z   z  }d}|                     d||          \  }}d}|                     d||          \  }}|                     ||          rd}n|                     ||          rd}|                     ||||d          }|                     |           d{V  d}	|                     d|          \  }	}|}
|d	k    s|d
k    r|	d
}
d}| 	                    |dddd          \  }}d}|d
k    s|d	k    r | j
        d         d         d         d
         }n+|rd}
|                     |
| j        |         d                   }|                     |          }|                     |||           |                     ||d|           d}|                     ||||           d{V }| j        r|                    ||          }|                     ||||d          S )ag  
        watches information on multiple orders made by the user

        https://developers.binance.com/docs/binance-spot-api-docs/user-data-stream#order-update
        https://developers.binance.com/docs/margin_trading/trade-data-stream/Event-Order-Update
        https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Order-Update
        https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Algo-Order-Update

        :param str symbol: unified market symbol of the market the orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str|None [params.marginMode]: 'cross' or 'isolated', for spot margin
        :param boolean [params.portfolioMargin]: set to True if you would like to watch portfolio margin account orders
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nr  r   r5  r8   rd   re   )r   r   r   rf   rc   rh   r  Fr  rk   r,   rg   r   T)r   r   r   r   r   r   r   r'  r  r  r   r   r   r   r  r  rP  r   r  r.  )r&   r   r   r   r   rS  r   r   r   r  r  r  r   r   r  r  s                   r)   watch_orderszbinance.watch_ordersv  s     " !!!!!!!!![[((FH%F3<'K99-QWXXf99-QWXX==w'' 	DD^^D'** 	DVdfQX%Y%YZZ'''''''''
!??vVV
FH46>>
8NG $($C$CFM[actv{$|$|!66>>TX--)E"4(26:CC  ! ))'4<3Ek3RSSCS!!vt->???  t5FGGGzz#{GTBBBBBBBB? 	3OOFE22E00tTTTr*   c                    |                      |d          }|                      |d          }d|v rdnd}|                     |d d |          }|                     |d          }|                     |d          }d }	|dk    s|d	k    s|d
k    r||}n|dk    r|}	|}
d }|                      |d          }|Et          j        |d          r0|                      |d          }|                     |          }||d}|                      |d          }|                     |          }|                     |dd          }|t          |          dk    r|                      |d          }| 	                    |g d          }|                      |d          }|dk    rd}| 
                    i d|d|d|                     |dd          d|d|d |                     |          d!|	d"|
d#|                     |                     |d$                    d%|d&d d'|                     |d(          d)|                     |d*          d+|                      |d,          d-|d.|d/|                      |d0          |                      |d1          |                      |d2          |                      |d3          d ||d d4          S )5Nr  r  r  r  rc   Or  NEW	AMENDMENTCANCELEDr  r  r  r  r  XrH  caidr   r  )r]  sptpr  GTXPOr  r   r   r   aidr#  r  r  lastTradeTimestamplastUpdateTimestampr   r  timeInForcepostOnly
reduceOnlyRr  r  r  r  r  r  rq  r  Zr  z)r   r^  filled	remainingr2  r  r  )r   r  r   r   	string_gtr  parse_order_statusr  r   r  
safe_orderr   parseOrderTyper  r  )r&   r  r   r  r
  rR  r   r  r  rF  rG  r  r  r  feeCurrency	rawStatusr2  r#  r  rH  s                       r)   parse_ws_orderzbinance.parse_ws_order  s   V ((44##E3//$(EMMZZ
!!(D$
CC%%eS11	eS))!E!!]k%A%A]V`E`E` 	g%%!"""5#..g&7&E&E ,,UC88M11-@@K' C $$UC00	((33**5#v>>!s='9'9Q'>'> ,,UC88M&&u.?.?.?@@	&&uc22%K  
E 
f 
 $$$UC77 
 ]	 

  
 Y// 
 !"4 
 "#6 
 D''(>(>uc(J(JKK 
 ; 
  
 $..44 
 D**5#66 
 T%%eS11 
  
  I! 
" d&&uc22# 
$ $$UC00''t44&&uc221 
  
  
   	r*   c                     |                      |d          }|dk    s|dk    r|                     |d|          }|                     ||           |                     ||           |                     ||           d S )Nrj  ORDER_TRADE_UPDATEALGO_UPDATEr  )r   r   handle_my_tradehandle_orderr+  )r&   r   r  rj  s       r)   handle_order_updatezbinance.handle_order_updateV  s    j Wc**%%%1+=+=nnWc7;;GVW---&'***""6733333r*   c                   K   |                                   d{V  d}d}|                     |          }|                     |          s-|                     |          }dd                    |          z   }d}|                     d||          \  }}|dk    s|dk    rd}d}|                     d||          \  }}|                     ||          rd}n|                     ||          rd	}i }	||	d
<   ||	d<   | 	                    | 
                    |	|                     d{V  |dz   |z   }d}
|                     |dddd          \  }
}|}|
rd}|                     || j        |         d                   }|                     |          }|                     |||
           |                     ||||
           |                     ddd          }|                     ddd          }|                     | j        |          }|r;|r9|7|                    |dz              d{V }|                     ||||d          S |                     ||d|           d{V }| j        r|S |                     ||||d          S )a  
        watch all open positions
        :param str[]|None symbols: list of unified market symbols
        :param number [since]: since timestamp
        :param number [limit]: limit
        :param dict params: extra parameters specific to the exchange API endpoint
        :param boolean [params.portfolioMargin]: set to True if you would like to watch positions in a portfolio margin account
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        Nr  r   r   r:   rc   rf   rd   re   r   r   
:positionsrh   r  Fr   r   Tr   :fetchPositionsSnapshot)r   r   r   r   r   r   r   r   r   r'  r   r  r   r   r   r  r  r~  r   r  rd   r   rP  r   )r&   r   r   r   r   r   rS  r   r   marketTypeObjectr  r  r   r   r   r   r  rg  newPositionss                      r)   watch_positionszbinance.watch_positions  s      !!!!!!!!!%%g..}}W%% 	311'::F'!2!22K99:JFTZ[[f6>>TX--D99:JFTZ[[==w'' 	DD^^D'** 	D!##' &-#,<f E EFFFFFFFFF\)K7 $($C$CFL\^dfwy~$$!6 	G%%gt|D/A+/NOOS!!vt->???  w8IJJJ!%!3!34DF^`d!e!e!%!3!34DF^`d!e!e55! 	]&< 	]#]]42K+KLLLLLLLLH55hPUW[\\\!ZZ[$EEEEEEEE? 	 11%%PTUUUr*   c                 0   |dk    rd S | j         i | _         || j         v rd S |                     ddd          }|rE|dz   }||j        vr5|                    |           |                     | j        ||||           d S d S t                      | j         |<   d S )Nrc   r:   r   Fr_  )r  r~  r  rd   r  load_positions_snapshotr   )r&   r   r   r   r  r   rS  s          r)   r  zbinance.set_positions_cache  s    6>>F>!DN4>!!F!%!3!34DF^`e!f!f! 	>!::K6>11k***

47dTefffff 21 $<#=#=DN4   r*   c                   K   d|i}|rd|d<   |                      d |           d {V }t                      | j        |<   | j        |         }t          dt	          |                    D ]<}||         }	|                     |	dd          }
|
dk    r|                    |	           =||j        v r=|j        |         }|                    |           |                    ||dz              d S d S )Nr   Tr  r   r  z	:position)	fetch_positionsr   r  r   r   r  r   r  r  )r&   r   rS  r   r  r   r  r  r   positionr  rd   s               r)   rd  zbinance.load_positions_snapshot  s     D
  	-(,F$%..tV<<<<<<<<	799tt$q#i..)) 	' 	'A |H((;BBI1}}X&&&&.((^K0FNN5!!!NN5$"455555 )(r*   c                 &   |j         }t          |                                          }|                     |          }| j        i | _        || j        vrt                      | j        |<   | j        |         }|                     |di           }|                     |dg           }g }	t          dt          |                    D ]|}
||
         }| 
                    |          }|                     |d          }||d<   |                     |          |d<   |	                    |           |                    |           }|                     ||dz             }t          dt          |                    D ]}
||
         }|                    d          }|d	         }|                    d
          }|                     |	d|d          }|                     |          s|                    ||           |                    |	|dz              d S )Nrx  r]  r   r{  r  r  z:positions::r   r   r   r   Fr^  )rd  rr  r  r  r  r   r   r  r   r   parse_ws_positionr   r   r   find_message_hashessplitr  r   r  )r&   r   r  rd  r  r  r  datarawPositionsra  r   rawPositionrg  r  r   rS  partssymbolsStringr   r  s                       r)   handle_positionszbinance.handle_positions*  s   < , !3!3!5!566>>?PQQ>!DNt~--*B*D*DDN;'{+~~gsB//~~dC44q#l++,, 	# 	#A&q/K--k::H))'377I$-H[!#'<<	#:#:HZ )))LL""""00~9UVVq#m,,-- 	7 	7A'*K%%d++E!!HM#))#..G,,\8WeTTI==++ 7y+666|[<%?@@@@@r*   c           
         |                      |d          }|                      |d          }t          j        |                      |d                    }|                     |d          }d}|dk    r1d}t          j        |d          st          j        |d          rd}nd	}|                     i d
|dd d|                     |d d d          dd d|                      |d          dd d|                     |d          d|                     |d          dd d| 	                    |          dd dd d|d|dd dd dd d d d d d d d          S ) Nr  par  TbothFr  shortlongr  r   r   r   notionalr  mtliquidationPricer  epunrealizedPnlupr\  r  r  r   r  hedgedr  r  maintenanceMargin)maintenanceMarginPercentage
collateralinitialMargininitialMarginPercentageleveragemarginRatio)
r   r   
string_absr  r  	string_ltsafe_positionr  r  parse_number)r&   rg  r   r
  r  contractsAbspositionSider}  s           r)   ri  zbinance.parse_ws_positionf  s    ##Hc22$$Xt44	)$*:*:8T*J*JKK--h==6!!F$Y44 *$Y44 *#*LL#)L!! #
H#
$#
 d&&xtVDD#
 	#

 $**8T::#
 #
 $**8T::#
 T--h==#
 $#
 **<88#
 D#
 #
 L#
 f#
 #
  !#
"  ##
$ ,0!'+/#
 #
 #
   	r*   c                 ^  K   |                                   d{V  |t          | j        dz             |                     |          }|                     d||          }|dk    r#|dk    rt          | j        dz   |z   dz             | j        d         d	         d
         |         }|                     |          }t          |          }	d}
|                     |ddd          \  }
}| 	                    |          |
d}|||d<   |||d<   | 
                    |d          }||t          | j        dz             |	d|                     |                     ||                    d}d| j        i}|                     ||	||	|           d{V }|                     ||||          S )a  
        fetch all trades made by the user

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/account-requests#account-trade-history-user_data

        :param str symbol: unified market symbol
        :param int|None [since]: the earliest time in ms to fetch trades for
        :param int|None [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.endTime]: the latest time in ms to fetch trades for
        :param int [params.fromId]: first trade Id to fetch
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        Nz" fetchMyTradesWs requires a symbolrI   rc   rd   z" fetchMyTradesWs does not support  marketsrk   r,   rg   Frn   r  r  r   fromIdz_ fetchMyTradesWs does not support fetching by both fromId and since parameters at the same timemyTradesrK  r   )r   r   r   r   rL  r   r   r9  r8  r  r   rN  r   handle_trades_wsrP  r.  )r&   r   r   r   r   r   r   r   r~   rS  rn   rQ  r  r  r?  r  s                   r)   fetch_my_trades_wszbinance.fetch_my_trades_ws  s      !!!!!!!!!>TW'KKLLLV$$##$5vvFF6>>dh..TW'KKdRU__```it$X.t4OOC((	)nn #'#@#@IZ\npu#v#v &nnV,, 0
 
 #(GK $GG""6844%"3TW  (I  I  J  J  J &&t{{7F'C'CDD
 
 d+
 zz#{G[,WWWWWWWW00NNNr*   c                   K   |                                   d{V  |                     |          }|                     d||          }|dk    r#|dk    rt          | j        dz   |z   dz             | j        d         d         d	         |         }|                     |          }t          |          }	d
}
|                     |ddd
          \  }
}| 	                    |          |
d}|||d<   |	d| 
                    ||          d}d| j        i}|                     ||	||	|           d{V }|                     |||          S )a  
        fetch all trades made by the user

        https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/market-data-requests#recent-trades

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve, default=500, max=1000
        :param dict [params]: extra parameters specific to the exchange API endpoint

 EXCHANGE SPECIFIC PARAMETERS
        :param int [params.fromId]: trade ID to begin at
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        NrS   rc   rd   z  fetchTradesWs does not support r  rk   r,   rg   Frn   r  r   ztrades.historicalrK  r   )r   r   rL  r   r   r   r   r9  r8  r  r   r  rP  r  )r&   r   r   r   r   r   r   r   r~   rS  rn   rQ  r  r?  r  s                  r)   fetch_trades_wszbinance.fetch_trades_ws  s      !!!!!!!!!V$$##OVVDD6>>dh..TW'IIDPS]]^^^it$X.t4OOC((	)nn #'#@#@Zlns#t#t &nnV,, 0
 
 $GG)kk'622
 
 d+
 zz#{G[,WWWWWWWW))&%???r*   c                     |                      |d          }|                     |dg           }|                     |          }|                    ||           d S r  )r   r  parse_tradesr  )r&   r   r  rS  rV  r  s         r)   r  zbinance.handle_trades_ws  s\    \ &&w55266""6**v{+++++r*   c                 h  K   |                                   d{V  d}d}||                     |          }|d         }|                     d||          \  }}d}|                     d||          \  }}|                     ||          rd}n|                     ||          rd}d}|<|                     |          }|d|z   z  }|                     ||d         |d	          }|                     |                     ||d
|                     d{V  |}	|dk    rd}	d}
| 	                    |dddd          \  }
}d}|dk    s|dk    r | j
        d         d         d         d         }n+|
rd}	|                     |	| j        |         d                   }|                     |          }|                     |||
           |                     ||d|
           d}|                     ||||           d{V }| j        r|                    ||          }|                     ||||d          S )ag  
        watches information on multiple trades made by the user
        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.portfolioMargin]: set to True if you would like to watch trades in a portfolio margin account
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        Nr   r3   rd   re   r  r5  r   )r   r   )r   r   rf   rc   rh   r  Fr  rk   r,   rg   r   T)r   r   r   r   r   r   r   r   r'  r  r   r   r   r   r  r  rP  r   r  r.  )r&   r   r   r   r   r   r   r   rS  r  r  r   r   r  r  s                  r)   watch_my_tradeszbinance.watch_my_trades&  s      !!!!!!!!![[((FH%F99/6SYZZf99/6SYZZ==w'' 	DD^^D'** 	D [[((F3<'K[[&.F)S)STTFTg,N,NPV W WXXXXXXXXX8G $($C$CFO]cevx}$~$~!66>>TX--)E"4(26:CC  ! ))'4<3Ek3RSSCS!!vt->???  t5FGGGzz#{GTBBBBBBBB? 	3OOFE22E00tTTTr*   c                 <   d}|                      |d          }|dk    r|                     |          }|                      |d          }|                     |di           }|                     i |          }|                      |d          }|||| j        }	|	|                     |	j        |i           }
|                     |
|          }||                     |d          }|                     |d          }|                     |          sd}t          d	t          |                    D ]z}||         }|d
         |d
         k    r^| 
                    |d         |d                   }t          |                     |d
         |                    |d         |         d<   d} n{|r|d                             |           n||d
         |d
         k    rU| 
                    |d         |d                   }t          |                     |d
         |                    |d         d<   n |d
         ||d<   n||g|d<   d |d<   n||d<   |                     |dg           }|                    |           ||d<   | j        0|                     | j        dd          }t%          |          | _        | j        }|                    |           |                    | j        |           |dz   |z   }|                    | j        |           d S d S )Nr  r  r  r  r  r   feesTr   r  r   Fr  r{   ry   r5  )r   r  r   r   r  r   hashmapr   r   r   r   floatcurrency_to_precisionr   r  r  r   r   r   r  )r&   r   r  rS  r  r   r  tradeFeer   cachedOrdersr  r  r  r  insertNewFeeCurrencyr   orderFeer  orderTradesr   r  messageHashSymbols                         r)   rZ  zbinance.handle_my_tradeX  sA    ((#66G##''00E&&ug66G~~eUB77H{{2x00H%%eX66F"x';@R#{+!__\-A62NNF OOFG<<E(#uf=="ooeU;;#}}T22 4370%*1c$ii%8%8 * *+/7#+J#78J;O#O#O.2hhx7GRXIY.Z.ZG?DTE_E_`his`tv}E~E~??E&M!$4V$<;@$8$)E	 $P
  4 ? %f 4 4X > > > _":(:2FFF*.((3v;@P*Q*Q7<T=W=WX`akXlnu=v=v7w7weV 4 4!$Z!8/7e14hf/3e+3E%L&*nnUHb&I&I#**5111*5h }$))$,tLL 6u = =}HOOE"""NN4=+666 +c 1F :NN4=*;<<<<<e $#r*   c                 @   |                      |          }|                     |d          }|                     |d          }|Y| j        0|                     | j        dd          }t          |          | _        | j        }|                     |j        |i           }|                     ||          }	|	|                     |	d          }
|
|
|d<   |                     |	d          }|||d<   |                     |	d          |d<   |                     |d          }|2|                     |	d          |d<   |                     |	d	          |d	<   |                    |           d
}d|z   }|	                    ||           |	                    ||           d S d S )Nr   r   r|   ry   r  r  r  r  r  r  zorders:)
rV  r   r  r   r   r   r   r  r   r  )r&   r   r  r  r   r  r   r  r  r  r  r  r  rS  symbolSpecificMessageHashs                  r)   r[  zbinance.handle_order  s   $$W--!!&(33""6400{"))$,tLL4U;;;L__\%962FFFOOFG44E ooeU33?$'F5Muf55#%)F6N#'??5(#C#Cx  --fkBB	$*.*;*;E;*O*OF;')-)9)9%)L)LF:&'''"K(1F(:%NN<555NN<)BCCCCC/ r*   c                 ^    |                      ||           |                     ||           d S r!   )r  rq  ri  s      r)   handle_acount_updatezbinance.handle_acount_update  s4    FG,,,fg.....r*   c                    |                      |d          }d}|                     |di           }|                     |d          }|                      |d          }	 |                     |||j        di |                     |          |i i 	  	         n# t          $ r}d}|                    ||           t          |j	        
                                          }	t          dt          |	                    D ]r}
|	|
         }|                      |j	        |         d          }|                      |j	        |         d	          }||k    r |                    ||           ||j	        |= sY d }~nd }~ww xY w|s|                    ||           |                      |d          }|#|d         d
k    r|                    |           d S d S d S )Nr   Fr  r  msgr  Tr   r?  5)r   r   r   handle_errorsr   jsonrc  re  rr  rd  r  r   r   ra  )r&   r   r  r   rejectedr  r  r  rj  r  r   r   r  r?  
codeStrings                  r)   handle_ws_errorzbinance.handle_ws_error  s    gt,,w44  //ue,,	?tS&*b"dii>N>NPUWY[]^^^^ 	? 	? 	?HMM!R   #F$8$=$=$?$?@@1c"23344 ? ?#3A#6 !%!1!1&2FGW2XZ^!_!_#//0DEU0VXfgg''MM!%5666#/"0>? ? ? ? ?	?  	'MM'2&&&%%eV44
"A#)=)=LL!!!!! #")=)=s   5B 
E5CE00E5c                     |                      |d          }|j        }t          |                                          }|                     |          }|dk    r |j        |= |                    ||           d S d S )Nrj  eventStreamTerminated)r   rd  rr  r  r  re  )r&   r   r  r  rd  r  r  s          r)   handle_event_stream_terminatedz&binance.handle_event_stream_terminated  s       #.., !3!3!5!566>>?PQQ+++$[1MM';///// ,+r*   c                    |                      |d          }||}|                     |d          }|                     |d          }|||dk    r|                     ||           d S |                     |d          }|                     |j        |          }|                     |d          }| |||           d S i d| j        d| j        d	| j        d
| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j	        | j	        | j
        | j        | j        | j        | j        | j        | j        | j        | j        | j        d}	|                     |d          }
t!          |t"                    r!|d         }|                     |d          dz   }
|                     |	|
          }|X|                     |d          }||                     ||           d S |
 d|v rd|v r| 
                    ||           d S d S d S d S  |||           d S )Nr  r2  r  200r   r   depthUpdater   r   r   r  r  z1hTicker@arrz4hTicker@arrz1dTicker@arrz24hrTicker@arrz24hrMiniTicker@arrr   r   r   r   r   r   )zmarkPriceUpdate@arrr   outboundAccountPositionr  ACCOUNT_UPDATEexecutionReportrX  rY  r   r  externalLockUpdaterj  r   r7  rx  rz  )r   r   r   r  rd  r  r  r  rl  ro  rj  r  r  r\  r  r  rq  rr  r  )r&   r   r  eventMsgr2  r  r   rd  r   methodsr  rl  r~   s                r)   handle_messagezbinance.handle_message  s   >>'733G!!'844116#5&E//  111Fgt,,(<bAA99F67###F
41
T&
 )
 T&	

 t0
  1
 D/
 D/
 D/
 d1
 !$"5
 +
 +
 +
 $-
  d1!
" t6#
$ $(#:/'+':!0"7#7"&":31%)%H"&"59
 
 
<   #..gt$$ 	91:D$$T3//&8E%00>(($77I$//@@@ }#..sg~~%%fg66666 }..~~ F67#####r*   )r   r!   )rc   )F)NF)__name__
__module____qualname__r   r#   r%   r   r   r   r   r   r   r   r   r9  r	   r   r
   r   r   r  r  r#  r"  r+  r   r.  r-  rF  rI  rT  rO  rk  rr  ru  rb  r  r:  r  dictr  r   r  r  r  r  r  r  rr  r  r  r  r  r  r   r
  r  r  r  r  r   r   r  r  r'  r)  r+  r-  r0  boolr  rc  r	  rj  rl  ro  rh  rN  r  r  r  r  r'  r  r  r  r   r  r  r  r   r  r  r  r  r  r  rL  r   r   r  r   r   r  r  r  r  r  r'  r)  r+  r0  r5  r7  r9  rV  r\  rb  r  rd  rq  ri  r  r  r  r  rZ  r[  r  r  r  r  __classcell__)r(   s   @r)   r   r      s       E# E E E E E En
 n
 n
`  Y& Y Y Y Y 3 #    .    
> > >
 BFTXac Y Ys Y3 Yc Yhlmxhy Y Y Y Y UYgktv 4b 4bDI 4bc 4bad 4b{  AL  |M 4b 4b 4b 4bl3A 3A 3A 3A 3AjY Y Y Yv EIW[df V V# Vc VQT Vkop{k| V V V V X\jnwy $\ $\tCy $\QT $\dg $\  C  DO  P $\ $\ $\ $\L;CF ;C ;C ;C ;Cz @DB 6P 6PS 6P 6PS\ 6P 6P 6P 6Pp SW_a A! A!$s) A!C A!fo A! A! A! A!F PR 5x 5xT#Y 5xVY 5x 5x 5x 5xn =? L L L3 L L L L" CGr ' ' 'C 'V_ ' ' ' 'R/f / / / />+* +* +*Z& & &
3 3 3    T. T. T. T. T.lVV V V V V     $'V '4 ' ' ' ' OSaenp 8S 8Sd3i 8S 8S[^ 8Suyz  vA 8S 8S 8S 8St LN 8w 8wc 8wRU 8w 8w 8w 8wt 9; H HC Hs H H H H" <@d[] S S SS S Sbfglbm S S S S&Y YE Y Y Y Yv16 1 1 1 1$ ?CQUdhqs ) ) ) )3 )^a )x|  ~B  yC ) ) ) ). aesw  AC =E =E$tCy/ =EZ] =Emp =E =E =E =E~ ^` >u >uT$s)_ >udg >u >u >u >u@ BFb T T3 T3 TUX T T T T(=16 =1 =1 =1 =1~ 9; # #C #v # # # #J BFTXgktv 0V 0V3 0V3 0Vc 0Vad 0V{  AE  |F 0V 0V 0V 0Vd$, $, $, $, $,L 68   F    * :<  S       :>b E Ew EW E E E E* 6:" E E7 E E E E E0 9=R j jg jC j j j j* =A m m' mPS m m m m =? 
A 
A 
A3 
A 
A 
A 
A 9; = =C =s = = = =" 8<B F FW F7 F F F F& `dln  GL \ \s \U\ \  @D \ \ \ \|r r rh,v , , , ,@Fv F F F FFV F F F F@I I I I I*96 *9 *9 *9 *9X "$    2O Os O O O O>- - - - -* Yaik @S @SRU @S @S @S @SD /1 X X X X )+ 1Q 1Q 1Q 1Qf 24 @ @ @ @D$ $ $ $ $ $B B B -/ %V %V8 %V %V %V %VN4 4 4 4 424v 24 24 24 24h ;= 
? 
?c 
?h 
? 
? 
? 
? ;?r .P .P .PdS[n .P .P .P .P`'/& '/ '/ '/ '/R *, &A &A &A &A &A &APi?V i? i? i? i?Vc s     68 	 	 	 	 pt|~ >V >VC >Vy >V	 >V[` >Vil >V  DI >V >V >V >V@3+f 3+ 3+ 3+ 3+j),v ), ), ), ),V im{  IK *V *Vc *V3 *Vi *Vy *Vbe *Vux *V  PU *V *V *V *VXk+6 k+ k+ k+ k+Z <@ 6V 6V 6VS 6Vu 6V 6V 6V 6Vp 8<B  V  V  V  V  V  VD ;?r *V *Vs *VC *Ve *V *V *V *VX 37TX\eg )O )OC )Os )ORU )Olpqvlw )O )O )O )OV :>D_cln  3 c Y\ swx}s~    ( 8<$]ajl $O $O $OC $OWZ $Oquv{q| $O $O $O $OL 04$UYbd 8U 8U 8UC 8Us 8Uimnsit 8U 8U 8U 8Utd d d dLz4& z4 z4 z4 z4x 8<$]ajl 2V 2VW 2VC 2VWZ 2Vquv~q 2V 2V 2V 2Vh> >& > > > > > 6 6 6(:A :A :Ax1 1 1 1f 6:[_hj .O .Os .O# .OUX .Oostyoz .O .O .O .O` ?CQU^` (@ (@C (@ (@3 (@eijoep (@ (@ (@ (@T1,v 1, 1, 1, 1,f 37TX\eg 0U 0UC 0Us 0URU 0Ulpqvlw 0U 0U 0U 0Ud5=f 5= 5= 5= 5=nD6 D D D D:/ / /$"f $" $" $" $"L0V 0 0 0 0H$V H$ H$ H$ H$ H$ H$ H$ H$r*   r   )%ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   r   r   r  ccxt.base.typesr   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   r   r   ccxt.base.preciser   async_supportr   r   r*   r)   <module>r     s       A  A  A  A  A  A  A  A  A  A  A  A  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y 4 4 4 4 4 4       . . . . . . ' ' ' ' ' ' ) ) ) ) ) ) * * * * * * % % % % % %ZD$ ZD$ ZD$ ZD$ ZD$d ( ZD$ ZD$ ZD$ ZD$ ZD$r*   