
    ei                        d dl Zd dlmZmZmZm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 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MarketOrder	OrderBookPositionStrStringsTickerTrade)Client)List)
BadRequest)NotSupported)NetworkError)Precisec                       e Zd Zdef fdZi fdedededededed	edefd
Zi fdedefdZ	i fdedefdZ
defdZd<dZd<dedefdZd=dededefdZddi fdedededee         fdZi fdedefdZdefdZdi fdededefdZi fdedefdZd ZdefdZd<defd Zdefd!Zd"ddi fded#edededee         f
d$Zd"i fded#edefd%Z dddi fdedededee!         fd&Z"dddi fdedededee         fd'Z#i fde$fd(Z%defd)Z&d* Z'dddi fd+e(dededee)         fd,Z*d<ded+e(fd-Z+d. Z,d<d/Z-defd0Z.d1 Z/i fd2Z0i fd3Z1d4 Z2d5 Z3defd6Z4defd7Z5defd8Z6defd9Z7ded:e8fd;Z9 xZ:S )>bingxreturnc                 f   |                      t          t          |                                           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iidddddiddddidddd d!d"d#d$d%d&d'd(d)d*d+d,idd-d.d/d0d1d2d3iddd4ddd5d6d7id8did9d:d;id<          S )=NwsTwatchTradeswatchTradesForSymbolsFwatchOrderBookwatchOrderBookForSymbols
watchOHLCVwatchOHLCVForSymbolswatchOrderswatchMyTradeswatchTickerwatchTickerswatchBalancewatchPositionsunWatchOHLCVunWatchOrderBookunWatchTickerunWatchTradeslinearz+wss://vst-open-api-ws.bingx.com/swap-marketz"wss://open-api-ws.bingx.com/marketz)wss://open-api-swap.bingx.com/swap-marketz(wss://open-api-cswap-ws.bingx.com/marketspotr-   inverse)testapii 6 gunzip
timeframes1m3m5m15m30m1h2h4h6h12h1d3d1w1M)r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   1min5min15min30min60min1day)r5   r7   r8   r9   r:   r?   )fetchBalanceSnapshotawaitBalanceSnapshot)fetchPositionsSnapshotawaitPositionsSnapshotdepthd   ignoreDuplicates)listenKeyRefreshRater   swapr/   r'   r(   r   r   	keepAlivei@w )hasurlsoptions	streaming)deep_extendsuperr   describe)self	__class__s    L/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/pro/bingx.pyrY   zbingx.describe   s   eT 2 2 ; ; = =dt ( !$	
 +E d ' t   t   !$  #D   !"  #*  "O  D"M#M   )0d !"""$$""""$""""# #& !$$&&%$# #	 -1,0! !
 /3.3# #
 S#
 ' [0 0d WgV@
 V@
 V V V	    messageHashsubMessageHashsubscribeHashdataTypetopicmarket
methodNamec	                 z  K   d }	d }
d }|                      |||          \  }	}|                     |||d          \  }
}|	dk    r(|                     | j        d         d         |
          }n'|                     | j        d         d         |	          }|                                 }||dd}g }||                    |d                    d||g|g||d	}|                     |d
          }|||d
<   |                     |d
          }|                     ||| 	                    ||          ||           d {V S )Nr-   rQ   r2   r   unsub)idra   reqTypesymbolT)unsubscriberg   subMessageHashesmessageHashessymbolsrb   symbolsAndTimeframes)
handle_market_type_and_paramshandle_sub_type_and_paramssafe_stringrT   uuidappend	safe_listomitwatchextend)rZ   r^   r_   r`   ra   rb   rc   rd   params
marketTypesubTypeurlrg   requestrm   subscriptionrn   s                    r\   un_watchzbingx.un_watchl   s     
!??
FTZ[[
F99*ffV^__""49U#3D#97CCCC""49U#3D#9:FFCYY[[ 
 

 NN6(+,,,!/ 0)]
 
  $~~f6LMM+3GL/0YYv'=>>FZZ[$++gv2N2NP]_klllllllllr]   ri   c                   K   |                                   d{V  |                     |          }d}d}d}|                     d||          \  }}|                     d||d          \  }}|dk    r(|                     | j        d         d         |          }n'|                     | j        d         d         |          }|d         dz   }|                     d	|d
                   }|                                 }	|	|d}
|dk    rd|
d<   d|	d}|                     ||| 	                    |
|          ||           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://bingx-api.github.io/docs-v3/#/en/Spot/Websocket%20Market%20Data/Subscribe%20to%2024-hour%20Price%20Change
        https://bingx-api.github.io/docs-v3/#/en/Swap/Websocket%20Market%20Data/Subscribe%20to%2024-hour%20price%20changes
        https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Websocket%20Market%20Data/Subscribe%20to%2024-Hour%20Price%20Change

        :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>`
        Nr%   r-   rQ   r2   r   rg   @tickertickerri   rg   ra   subrh   Frj   rg   )
load_marketsrc   ro   rp   rq   rT   get_message_hashrr   rv   rw   )rZ   ri   rx   rc   ry   rz   r{   ra   r^   rr   r|   r}   s               r\   watch_tickerzbingx.watch_ticker   s      !!!!!!!!!V$$
!??vW]^^
F99-QWYabb""49U#3D#97CCCC""49U#3D#9:FFC$<)+++HfX6FGGyy{{ 
 
 !&GI 
 
 ZZ[$++gv2N2NP[]ijjjjjjjjjr]   c           
        K   |                                   d{V  |                     |          }|d         dz   }|                     d|d                   }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://bingx-api.github.io/docs-v3/#/en/Spot/Websocket%20Market%20Data/Subscribe%20to%2024-hour%20Price%20Change
        https://bingx-api.github.io/docs-v3/#/en/Swap/Websocket%20Market%20Data/Subscribe%20to%2024-hour%20price%20changes
        https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Websocket%20Market%20Data/Subscribe%20to%2024-Hour%20Price%20Change

        :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>`
        Nrg   r   r   ri   unsubscribe::r+   r   rc   r   r~   	rZ   ri   rx   rc   ra   r_   r^   rb   rd   s	            r\   un_watch_tickerzbingx.un_watch_ticker   s       !!!!!!!!!V$$$<)+..x9IJJ%6$
]];XW\^dfprxyyyyyyyyyr]   clientc                    |                      |di           }|                     |d          }|j                            d          dk    }|rdnd}|                     |d d |          }|d         }|                     ||          }	|	| j        |<   |                    |	|                     d|                     |                     |d          d	k    r+|                    |	|                     d                     d S d S )
NdatasrQ   r   r/   ri   r   ra   z
all@ticker)	
safe_valuerq   r{   findsafe_marketparse_ws_tickertickersresolver   )
rZ   r   messager   marketIdisSwapry   rc   ri   r   s
             r\   handle_tickerzbingx.handle_ticker   s	   n w33##D#..((A-%1VV6
!!(D$
CC!%%dF33%Vvt44XvFFGGGGZ00L@@NN64#8#8#B#BCCCCC A@r]   Nc                    |                      |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|          S ) NCr   cri   	timestampdatetimehighhlowlbidB	bidVolumebaskA	askVolumeavwapopenocloselastpreviousClosechangep
percentageaveragevq)
baseVolumequoteVolumeinfo)safe_integerrq   r   safe_tickeriso8601)rZ   r   rc   r   r   r   s         r\   r   zbingx.parse_ws_ticker  s   . %%gs33	##GS11!!(F33  #.. !
fX&!
!
 Y//!
 D$$Wc22	!

 4##GS11!
 4##GS11!
 ))'377!
 4##GS11!
 ))'377!
 D!
 D$$Wc22!
 U!
 E!
 T!
 d&&w44!
  $!!
" t#!
$ **7C88++GS99)!
 !
 !
* +  	r]   ry   limitc                     |d}nC|dk    s|dk    r|                      g d|          }n|dk    r|                      ddg|          }|S )NrN   rQ   future)   
      2   rN   r/   r   )find_nearest_ceiling)rZ   ry   r   s      r\   #get_order_book_limit_by_market_typez)bingx.get_order_book_limit_by_market_type>  sj    =EEV##zX'='=112F2F2FNNv%%112s)UCCr]   unifiedChannelextrac                 >    |}|	|d|z   z  }n|dz  }||d|z   z  }|S )N::r    )rZ   r   ri   r   hashs        r\   r   zbingx.get_message_hashH  s?    D6M!DDCKDD5L Dr]   sincec                 d  K   |                                   d{V  |                     |          }|d         }d}d}d}|                     d||          \  }}|                     d||d          \  }}|dk    r(|                     | j        d         d         |          }n'|                     | j        d         d         |          }|d         d	z   }	d
|z   }
|                                 }||	d}|dk    rd|d<   d|d}|                     ||
|                     ||          |
|           d{V }| j	        r|
                    ||          }|                     |||dd          }|                     ddd          r-|                     |          }|                     |d          }|S |S )an  
        watches information on multiple trades made in a market

        https://bingx-api.github.io/docs-v3/#/en/Spot/Websocket%20Market%20Data/Subscription%20transaction%20by%20transaction
        https://bingx-api.github.io/docs-v3/#/en/Swap/Websocket%20Market%20Data/Subscribe%20the%20Latest%20Trade%20Detail
        https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Websocket%20Market%20Data/Subscription%20transaction%20by%20transaction

        :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
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nri   r   r-   rQ   r2   r   rg   @tradetrade::r   r   rh   Fr   r   TrO   )r   rc   ro   rp   rq   rT   rr   rv   rw   
newUpdatesgetLimitfilter_by_since_limithandle_option!remove_repeated_trades_from_arraysort_by)rZ   ri   r   r   rx   rc   ry   rz   r{   rawHashr^   rr   r|   r}   tradesresultfiltereds                    r\   watch_tradeszbingx.watch_tradesR  s      !!!!!!!!!V$$!
!??vW]^^
F99-QWYabb""49U#3D#97CCCC""49U#3D#9:FFC,)&(yy{{
 
 !&GI 
 
 zz#{DKK4P4PR]_kllllllll? 	3OOFE22E++FE5+tTTm-?FF 	==fEEH||Hk::HOr]   c           
        K   |                                   d{V  |                     |          }|d         dz   }|                     d|d                   }d|z   }d}d}|                     ||||||||           d{V S )	a'  
        unsubscribes from the trades channel

        https://bingx-api.github.io/docs-v3/#/en/Spot/Websocket%20Market%20Data/Subscription%20transaction%20by%20transaction
        https://bingx-api.github.io/docs-v3/#/en/Swap/Websocket%20Market%20Data/Subscribe%20the%20Latest%20Trade%20Detail
        https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Websocket%20Market%20Data/Subscription%20transaction%20by%20transaction

        :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>`
        Nrg   r   traderi   r   r   r,   r   r   s	            r\   un_watch_tradeszbingx.un_watch_trades  s       !!!!!!!!!V$$$<(*..wx8HII%6$
]];XW\^dfprxyyyyyyyyyr]   c                    |                      |dg           }|                     |d          }|                    d          d         }|j                            d          dk    }|rdnd}|                     |d d |          }|d         }	d|	z   }
d }t          |t                    r|                     ||          }n| 	                    ||          g}|                      | j
        |	          }|5|                     | j        d	d
          }t          |          }|| j
        |	<   t          dt          |                    D ]}|                    ||                    |                    ||
           d S )Nr   ra   @r   rQ   r/   ri   r   tradesLimit  )r   rq   splitr{   r   r   
isinstancelistparse_tradesparse_trader   r   rU   r   rangelenrs   r   )rZ   r   r   r   r   r   r   ry   rc   ri   r^   r   storedr   js                  r\   handle_tradeszbingx.handle_trades  s|   d w33""7J77==%%a(((A-%1VV6
!!(D$
CC!&(dD!! 	6&&tV44FF&&tV445Ff55>%%dlM4HHE&&F"(DKq#f++&& 	% 	%AMM&)$$$$v{+++++r]   c                 r  K   |                                   d{V  |                     |          }d}d}d}|                     d||          \  }}|                     d||d          \  }}|dk    r(|                     | j        d         d         |          }n'|                     | j        d         d         |          }|                     | j        di           }|                     |dd          }	|d	         d
z   dz   | 	                    |	          z   }
| 
                    d|d                   }|                                 }||
d}|dk    rd|d<   i }|d         r|d||d}n|d||d}|                     |||                     ||          |
|           d{V }|                                S )aQ  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://bingx-api.github.io/docs-v3/#/en/Spot/Websocket%20Market%20Data/Subscribe%20Market%20Depth%20Data
        https://bingx-api.github.io/docs-v3/#/en/Swap/Websocket%20Market%20Data/Partial%20Order%20Book%20Depth
        https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Websocket%20Market%20Data/Subscribe%20to%20Limited%20Depth

        :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-   rQ   r2   r   rM   rN   rg   r   	orderbookri   r   r   rh   r0   F)rg   rj   countrx   )rg   rj   levelrx   )r   rc   ro   rp   rq   rT   	safe_dictrU   r   number_to_stringr   rr   rv   rW   r   )rZ   ri   r   rx   rc   ry   rz   r{   rU   rM   subscriptionHashr^   rr   r|   subscriptionArgsr   s                   r\   watch_order_bookzbingx.watch_order_book  s      !!!!!!!!!V$$
!??@PRXZ`aa
F99:JFTZ\dee""49U#3D#97CCCC""49U#3D#9:FFC../?DD!!'7C88!$<#-7$:O:OPU:V:VV++K9IJJyy{{(
 
 !&GI!#) 	$ 	    $ 	    **S+t7G7GQW7X7XZjl|}}}}}}}}	   r]   c           
      h  K   |                                   d{V  |                     |          }|                     | j        di           }|                     |dd          }|d         dz   dz   |                     |          z   }d|z   }d}d	}	|                     |||||||	|           d{V S )
a  
        unWatches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://bingx-api.github.io/docs-v3/#/en/Spot/Websocket%20Market%20Data/Subscribe%20Market%20Depth%20Data
        https://bingx-api.github.io/docs-v3/#/en/Swap/Websocket%20Market%20Data/Partial%20Order%20Book%20Depth
        https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Websocket%20Market%20Data/Subscribe%20to%20Limited%20Depth

        :param str symbol: unified symbol of the market
        :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   rM   rN   rg   r   r   r   r*   )r   rc   r   rU   r   r   r~   )
rZ   ri   rx   rc   rU   rM   r_   r^   rb   rd   s
             r\   un_watch_order_bookzbingx.un_watch_order_book6  s       !!!!!!!!!V$$../?DD!!'7C88+g58M8Me8T8TT%6'
]];^]bdjlvx~r]   c                     |                      |dd          }|                      |dd          }|                    ||           d S )Nr   r      r   )safe_float_2store)rZ   booksidedeltapriceamounts        r\   handle_deltazbingx.handle_deltaL  sJ    !!%C00""5!S11uf%%%%%r]   c           	      ,   |                      |di           }|                     |d          }|                    d          }|d         }|dk    }|                     |d|          }|j                            d          dk    }	|	rdnd}
|                     |d d |
          }|d         }|                     | j        |          }|C|}|j        |         }| 	                    |d	          }| 
                    i |          | j        |<   | j        |         }d }|                     |d
d          }|                     |d
d|          }|d         r|                     |||dddd          }n|                     |||dddd          }| 	                    |d          }||d<   |                    |           |                     d|          }|                    ||           |r-|                     d          }|                    ||           d S d S )Nr   ra   r   r   allri   rQ   r/   r   r   tsr0   bidsasksr   r   r   lastUpdateIdnoncer   )r   rq   r   r{   r   r   r   
orderbookssubscriptionsr   
order_booksafe_integer_2parse_order_bookresetr   r   )rZ   r   r   r   ra   parts	firstPartisAllEndpointr   r   ry   rc   ri   r   r   r}   r   snapshotr   r  r^   messageHashForAlls                         r\   handle_order_bookzbingx.handle_order_bookQ  s?   H ~~gvr22##GZ88s##!H	"e+##D(I>>((A-%1VV6
!!(D$
CC!OODOV<<	'!/0@AL%%lG<<E&*oob%&@&@DOF#OF+	''dCC	''k4KK	) 	\,,T69ffVY[^__HH,,T69ffVWYZ[[H!!$77!!!!++K@@y+... 	9 $ 5 5k B BNN9&788888	9 	9r]   c           	      B   |d         rdnd}|d         r|d         rdnd}|                      ||          |                     |d          |                     |d          |                     |d          |                     |d	          |                     |d
          gS )Nr/   tTrQ   r0   r   r   r   r   r   )r   safe_number)rZ   ohlcvrc   r   s       r\   parse_ws_ohlcvzbingx.parse_ws_ohlcv  s     #6N4CC	&> 	< &y 1;IeY//UC((UC((UC((UC((UC((
 	
r]   c                 l   |j                             d          dk    }|                     |d          }|                    d          }|d         }|dk    }|                     |d|          }|rdnd}	|                     |d d |	          }
d }|r9|
d         r|                     |d	i           g}nG|                     |d	g           }n/|                     |d	i           }|                     |d
i           g}|
d         }|                     | j        |i           | j        |<   |                    d          d         }|                     | j	        |	          }|                     |di           }| 
                    ||          }|                     | j        |         |          B|}|j        |         }|                     |d          }t          |          | j        |         |<   | j        |         |         }t          dt          |                    D ]5}||         }|                     ||
          }|                    |           6|||g}|                     d||          }|                    ||           |r/|                     dd |          }|                    ||           d S d S )NrQ   r   ra   r   r  r   r/   r0   r   Kri   _r   r4   r   r  )r{   r   rq   r   r   r   rt   r   ohlcvsrU   find_timeframer	  r   r   r   r   r  rs   r   r   )rZ   r   r   r   ra   r  r  r  r   ry   rc   candlesr   ri   rawTimeframemarketOptionsr4   unifiedTimeframer   r}   r   r   icandleparsedresolveDatar^   r  s                               r\   handle_ohlcvzbingx.handle_ohlcv  s   B ((A-##GZ88s##!H	"e+##GS)<<%1VV6
!!(D$
CC 	6i  >>>'62>>?..&"==>>'6266D~~dC445G!"oodk62FFF~~c**1-t|Z@@^^M<DD
..|ZHH??4;v.==E'!/0@AL%%lG<<E4I%4P4PDK 01V$%56q#g,,'' 	" 	"AQZF((88FMM&!!!!/8++GV=MNN{K000 	; $ 5 5gtEU V VNN;(9:::::	; 	;r]   r5   	timeframec                   K   |                                   d{V  |                     |          }d}d}d}	|                     d||          \  }}|                     d||d          \  }}|dk    r(|                     | j        d         d         |          }	n'|                     | j        d         d         |          }	|	t          | j        dz   |z   dz             |                     | j	        |i           }
|                     |
d	i           }|                     |||          }| 
                    d
|d         |          }|d         dz   |z   }|                                 }||d}|dk    rd|d<   |d||d}|                     |	||                     ||          ||           d{V }|d         }| 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://bingx-api.github.io/docs-v3/#/en/Spot/Websocket%20Market%20Data/K-line%20Streamst
        https://bingx-api.github.io/docs-v3/#/en/Swap/Websocket%20Market%20Data/Subscribe%20K-Line%20Data
        https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Websocket%20Market%20Data/Subscribe%20to%20Latest%20Trading%20Pair%20K-Line

        :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
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Nr!   r-   rQ   r2   r   z! watchOHLCV is not supported for z	 markets.r4   r  ri   rg   @kline_r   r   rh   F)rg   rj   intervalrx      r   T)r   rc   ro   rp   rq   rT   r   rg   r   rU   r   rr   rv   rw   r   r   r   )rZ   ri   r(  r   r   rx   rc   ry   rz   r{   rU   r4   r   r^   r   rr   r|   r   r   r  s                       r\   watch_ohlcvzbingx.watch_ohlcv<  s>      !!!!!!!!!V$$
!??fV\]]
F99,PVX`aa""49U#3D#97CCCC""49U#3D#9:FFC;TW'JJZWZeefff//$,
B??__WlB??
''
IyII++GVH5EyQQ!$<)3lByy{{(
 
 !&GI $	"
 "
 zz#{DKK4P4PRbdtuuuuuuuuq	? 	2NN6511E))%q$GGGr]   c           
        K   |                                   d{V  |                     |          }|                     | j        |d         i           }|                     |di           }|                     |||          }|d         dz   |z   }d|z   }	d}
d}|d	         |gg}||d
<   |                     |	||	||
|||           d{V S )a   
        unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://bingx-api.github.io/docs-v3/#/en/Spot/Websocket%20Market%20Data/K-line%20Streamst
        https://bingx-api.github.io/docs-v3/#/en/Swap/Websocket%20Market%20Data/Subscribe%20K-Line%20Data
        https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Websocket%20Market%20Data/Subscribe%20to%20Latest%20Trading%20Pair%20K-Line

        :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
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Ntyper4   rg   r*  r   r  r)   ri   rn   )r   rc   r   rU   rq   r~   )rZ   ri   r(  rx   rc   rU   r4   r   r_   r^   rb   rd   rn   s                r\   un_watch_ohlcvzbingx.un_watch_ohlcvp  s       !!!!!!!!!V$$//$,vCC__WlB??
''
IyII	1L@%6#
!'!19 =>)=%&]];^]bdjlvx~r]   c                 d  K   |                                   d{V  |                                  d{V  d}d}d}||                     |          }|d         }|                     d||          \  }}|                     d||d          \  }}|dk    }d}	d}
|r|	n|
}d}d	}|r|n|}||d
|z   z  }|                                 }d}d}|dk    rE|dk    rt          | j        dz             |                     | j	        d         d         |          }n-|                     | j	        d         d         |          }|ddd}|dz   | j
        d         z   }d|d}|                     |||||           d{V }| j        r|                    ||          }|                     ||||d          S )a/  
        watches information on multiple orders made by the user

        https://bingx-api.github.io/docs-v3/#/en/Spot/Websocket%20Account%20Data/order%20update%20event
        https://bingx-api.github.io/docs-v3/#/en/Swap/Websocket%20Account%20Data/Order%20update%20push
        https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Websocket%20Account%20Data/Order%20update%20push

        :param str [symbol]: unified market symbol of the market orders are made in
        :param int [since]: the earliest time in ms to watch orders for
        :param int [limit]: the maximum number of order 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>`
        Nri   r#   r-   r/   spot:privateswap:private
spot:order
swap:order:rQ   r0   z: watchOrders is not supported for inverse swap markets yetr2   r   r   spot.executionReportrg   rh   ra   ?listenKey=	listenKeyFr   Tr   authenticaterc   ro   rp   rr   r   rg   rq   rT   rU   rv   r   r   filter_by_symbol_since_limit)rZ   ri   r   r   rx   r/  rz   rc   isSpotspotHashswapHashr   spotMessageHashswapMessageHashr^   rr   baseUrlr|   r{   r}   orderss                        r\   watch_orderszbingx.watch_orders  s4      !!!!!!!!!!!!!!!!!![[((FH%F99-QWXXf99-QWYabb&.!!'-;888&&)/Doo_3<'Kyy{{6>>)##"47-i#ijjj&&ty'7'=wGGGG&&ty'7'=tDDG 2 G
 %[(AA 
 
 zz#{G=M|\\\\\\\\? 	3OOFE22E00tTTTr]   c                 d  K   |                                   d{V  |                                  d{V  d}d}d}||                     |          }|d         }|                     d||          \  }}|                     d||d          \  }}|dk    }d}	d}
|r|	n|
}d}d	}|r|n|}||d
|z   z  }|                                 }d}d}|dk    rE|dk    rt          | j        dz             |                     | j	        d         d         |          }n-|                     | j	        d         d         |          }|ddd}|dz   | j
        d         z   }d|d}|                     |||||           d{V }| j        r|                    ||          }|                     ||||d          S )a3  
        watches information on multiple trades made by the user

        https://bingx-api.github.io/docs-v3/#/en/Spot/Websocket%20Account%20Data/order%20update%20event
        https://bingx-api.github.io/docs-v3/#/en/Swap/Websocket%20Account%20Data/Order%20update%20push
        https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Websocket%20Account%20Data/Order%20update%20push

        :param str [symbol]: unified market symbol of the market the trades are made in
        :param int [since]: the earliest time in ms to watch trades for
        :param int [limit]: the maximum number of trade structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        Nri   r$   r-   r/   r2  r3  spot:mytradesswap:mytradesr6  rQ   r0   z< watchMyTrades is not supported for inverse swap markets yetr2   r   r   r7  r8  r9  r:  Fr   Tr;  )rZ   ri   r   r   rx   r/  rz   rc   r>  r?  r@  r   rA  rB  r^   rr   rC  r|   r{   r}   r   s                        r\   watch_my_tradeszbingx.watch_my_trades  s4      !!!!!!!!!!!!!!!!!![[((FH%F99/6SYZZf99/6SY[cdd&.!!'-;888)))/Doo_3<'Kyy{{6>>)##"47-k#klll&&ty'7'=wGGGG&&ty'7'=tDDG 2 G
 %[(AA 
 
 zz#{G=M|\\\\\\\\? 	3OOFE22E00tTTTr]   c                   K   |                                   d{V  |                                  d{V  d}d}|                     dd|          \  }}|                     dd|d          \  }}|dk    }d}d}d}d}|r|n|}	|r|n|}
d}d}|                                 }|dk    rE|d	k    rt          | j        d
z             |                     | j        d         d         |          }n,|                     | j        d         d         |          }|dd}|dz   | j	        d         z   }| 
                    |          }|                     ||||
|           d}d}|                     |ddd          \  }}|                     |ddd          \  }}|r |r|                    |dz              d{V  d|d}|                     ||	||
|           d{V S )a  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://bingx-api.github.io/docs-v3/#/en/Spot/Websocket%20Account%20Data/Subscription%20account%20balance%20push
        https://bingx-api.github.io/docs-v3/#/en/Swap/Websocket%20Account%20Data/Account%20balance%20and%20position%20update%20push
        https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Websocket%20Account%20Data/Account%20balance%20and%20position%20update%20push

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/?id=balance-structure>`
        Nr'   r-   r/   zspot:balancer3  zswap:balancerQ   r0   z; watchBalance is not supported for inverse swap markets yetr2   r   ACCOUNT_UPDATEr   r9  r:  rI   TrJ   F:fetchBalanceSnapshotr   )r   r<  ro   rp   rr   r   rg   rq   rT   rU   r   set_balance_cachehandle_option_and_paramsr   rv   )rZ   rx   r/  rz   r>  spotSubHashswapSubHashrA  rB  r^   r   r|   rC  rr   r{   r   rI   rJ   r}   s                      r\   watch_balancezbingx.watch_balance  sw      !!!!!!!!!!!!!!!!!!99.$PVWWf99.$PVX`aa&.$$(()/Doo_*0A;;kyy{{6>>)##"47-j#jkkk&&ty'7'=wGGGG&&ty'7'=tDDG, G %[(AAS!!vtW6FOOO##'+'D'DV^]suy'z'z$f'+'D'DV^]suz'{'{$f 	@$8 	@--'> >????????? 
 
 ZZ[';K\ZZZZZZZZZr]   c                     ||j         v rd S |                     |ddd          }|rE|dz   }||j        vr5|                    |           |                     | j        ||||           d S d S i | j        |<   d S )Nr'   rI   TrL  )r	  rN  futuresr   spawnload_balance_snapshotbalance)rZ   r   r/  rz   r   rx   rI   r^   s           r\   rM  zbingx.set_balance_cache0  s    v333F#<<V^Ukmqrr 	$!88K6>11k***

45v{DRYZZZZZ 21 "$DLr]   c                 V  K   |                      ||d           d {V }|                     ||                     | j        |i                     | j        |<   ||j        v rG|j        |         }|                                 |                    | j        |         |dz              d S d S )Nr/  rz   :balance)fetch_balancerw   r   rV  rS  r   )rZ   r   r^   r/  rz   responser   s          r\   rU  zbingx.load_balance_snapshot<  s      ++Tg,N,NOOOOOOOO![[4??4<QUWY3Z3Z[[T&.((^K0FNNNN4<-tj/@AAAAA )(r]   rm   c                   K   |                                   d{V  |                                  d{V  d}d}|                     |          }|                     |          s-|                     |          }dd                    |          z   }d}d}|                     d||d          \  }}|                     d||d          \  }}|dk    rt          | j	        d	z             |d
k    rt          | j	        dz             d}	d|z   }| 
                    | j        d         d         |          }
|
dz   | j        d         z   }|                     |          }|                     |||           d}d}|                     |ddd          \  }}|                     |ddd          \  }}|                                 }d|d}|r@|r>| j        7|                    |dz              d{V }|                     ||||d          S |                     ||d|	|           d{V }| j        r|S |                     | j        |||d          S )aZ  
        watch all open positions

        https://bingx-api.github.io/docs/#/en-us/swapV2/socket/account.html#Account%20balance%20and%20position%20update%20push

        :param str[]|None [symbols]: list of unified market symbols
        :param int [since]: the earliest time in ms to fetch positions for
        :param int [limit]: the maximum number of position structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        N r   ,r(   rQ   r-   r/   z1 watchPositions is not supported for spot marketsr0   z= watchPositions is not supported for inverse swap markets yetr3  swap:positionsr2   r   r9  r:  rK   TrL   Fr   :fetchPositionsSnapshot)r   r<  market_symbolsis_emptyget_market_from_symbolsjoinro   rp   r   rg   rq   rT   rU   r   set_positions_cacherN  rr   	positionsr   filter_by_symbols_since_limitrv   r   )rZ   rm   r   r   rx   rc   r^   r/  rz   r   rC  r{   r   rK   rL   rr   r}   r  newPositionss                      r\   watch_positionszbingx.watch_positionsE  s      !!!!!!!!!!!!!!!!!!%%g..}}W%% 	311'::F'!2!22K99:JFTZ\bccf99:JFTZ\dee6>>tw)\\]]]itw)hhiii)&4""49U#3D#97CC%[(AAS!!  w777!%!%)-)F)FvO_ay{  *A  *A&)-)F)FvO_ay  |A  *B  *B&yy{{ 
 
 " 	]&< 	]AW#]]42K+KLLLLLLLLH55hPUW[\\\!ZZ[$@PR^________? 	 11$.'5RWY]^^^r]   c                     | j         d S |                     ddd          }|rD|dz   }||j        vr4|                    |           |                     | j        |||           d S d S t                      | _         d S )Nr(   rK   Tr`  )rf  r   rS  r   rT  load_positions_snapshotr   )rZ   r   r/  rm   rK   r^   s         r\   re  zbingx.set_positions_cachex  s    >%F!%!3!34DF^`d!e!e! 	8!::K6>11k***

47dSSSSS 21 677DNNNr]   c                   K   |                      d |dd           d {V }t                      | _        | j        }t          dt	          |                    D ]<}||         }|                     |dd          }|dk    r|                    |           =||j        v r:|j        |         }	|	                    |           |                    |d           d S d S )Nr-   rX  r   	contractsr_  )	fetch_positionsr   rf  r   r   r  rs   rS  r   )
rZ   r   r^   r/  rf  cacher#  positionrm  r   s
             r\   rk  zbingx.load_positions_snapshot  s      ..tdx5X5XYYYYYYYY	133q#i..)) 	' 	'A |H((;BBI1}}X&&&&.((^K0FNN5!!!NN5"233333 )(r]   c           
         |                      |d          }|                      |d          }t          j        |          }|                     |d          }d}|dk    r1d}t          j        |d          st          j        |d          rd}nd	}|                      |d
          }|dk    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!          S )"Nr   papsTbothF0shortlongmtisolatediwr   rg   ri   rQ   notional
marginModeliquidationPrice
entryPriceepunrealizedPnlupr   rm  contractSize	markPricesidehedgedr   r   maintenanceMargin)maintenanceMarginPercentage
collateralinitialMargininitialMarginPercentageleveragemarginRatio)
rq   r   
string_abssafe_string_lower	string_eq	string_ltr  safe_positionsafe_symbolparse_number)
rZ   rp  rc   r   rm  contractsAbspositionSider  r|  r  s
             r\   parse_ws_positionzbingx.parse_ws_position  s"    ##Hc22$$Xt44	))44--h==6!!F$Y44 *$Y44 *#*LL#)L%%h55
:D
:R:RT%%h555Y]
!! #
H#
$#
 d&&xtVDD#
 	#

 *#
 #
 $**8T::#
 T--h==#
 $#
 **<88#
 D#
 #
 L#
 f#
 #
  !#
"  ##
$ ,0$!'+/#
 #
 #
   	r]   c                    | j         t                      | _         | j         }|                     |di           }|                     |dg           }g }t	          dt          |                    D ]}||         }|                     |          }	|                     |	d          }
|
8|                     |d          }||	d<   | 	                    |          |	d<   |
                    |	           |
                    |	           |                     |d          }t	          dt          |                    D ]}||         }|                    d	          }|d
         }|                    d          }|                     |d|d          }|                     |          s|                    ||           |                    |d           d S )Nr   Pr   ri   Er   r   zswap:positions::r   r   r^  Fr_  )rf  r   r   rt   r   r   r  rq   r   r   rs   find_message_hashesr   filter_by_arrayrb  r   )rZ   r   r   ro  r   rawPositionsrh  r#  rawPositionrp  ri   r   rl   r^   r  symbolsStringfilteredSymbolsrf  s                     r\   handle_positionszbingx.handle_positions  s   , >!577DN~~gsB//~~dC44q#l++,, 
	# 
	#A&q/K--k::H%%h99F~))'377I$-H[!#'<<	#:#:HZ )))LL""""009KLLq#m,,-- 	7 	7A'*K%%d++E!!HM+11#66O,,\8_V[\\I==++ 7y+666|%566666r]   c                    |                      |d          }	 |B| j        dz   |                     |          z   }|                     | j        d         ||           n,# t
          $ r}|                    |           Y d }~nd }~ww xY wdS )Ncode exactT)rq   rg   jsonthrow_exactly_matched_exception
exceptions	Exceptionreject)rZ   r   r   r  feedbackes         r\   handle_error_messagezbingx.handle_error_message  s     00	7S=499W+=+==44T_W5MtU]^^^ 	 	 	MM!	ts   AA 
B'BBc                   K   |                      | j        d          }|d S 	 |                     d|i           d {V  n# t          $ r}g d}t	          dt          |                    D ]}||         }|                      | j        d         d         |          }|4|dz   |z   }|                     |          }	t          |	j	        
                                          }
t	          dt          |
                    D ] }|
|         }|	                    ||           !d | j        d<   d| j        d<   Y d }~d S d }~ww xY w|                     | j        dd	          }|                     || j        |           d S )
Nr:  r.   r   r2   r   r9  lastAuthenticatedTimerP   6 )rq   rU    userAuthPrivatePutUserDataStreamr  r   r   rT   r   r   rS  keysr  r   delaykeep_alive_listen_key)rZ   rx   r:  errortypesr#  r/  rC  r{   r   rl   r   r^   rP   s                 r\   r  zbingx.keep_alive_listen_key  s     $$T\;??	F	77i8PQQQQQQQQQQ 	 	 	111E1c%jj)) 
6 
6Qx**49U+;D+A4HH?-	9S)) $V^%8%8%:%: ; ;q#m"4"455 6 6A"/"2KMM%55556 )-DL%45DL01FFFFF	"  $00?UW^__

')CVLLLLLs   A 
EC+D==Ec                 t  K   |                                  }|                     | j        dd          }|                     | j        dd          }||z
  |k    r`|                                  d {V }|                     |d          | j        d<   || j        d<   |                     || j        |           d S d S )Nr  r   rP   r  r:  )millisecondsr   rU   !userAuthPrivatePostUserDataStreamrq   r  r  )rZ   rx   timer  rP   r[  s         r\   r<  zbingx.authenticate'  s        "" $ 1 1$,@WYZ [ [#00?UW^__''*>>>!CCEEEEEEEEH(,(8(8;(O(ODL%48DL01JJ+T-GPPPPP	 ?>r]   c                   K   	 |dk    r|                     d           d {V  d S |                     |d          }|                     |d          }|                     ||d           d {V  d S # t          $ rM}t          | j        dz   |                     |          z             }|                    |           Y d }~d S d }~ww xY w)NPingPongpingr  )pongr  z pong failed with error )sendrq   r  r   rg   exception_messager  )rZ   r   r   r  r  r  r  s          r\   r  z
bingx.pong1  s&     	 &  kk&)))))))))))''88''88kk  # #             	  	  	  +E!EH^H^_`HaHa!abbELL	 s   !A3 A
A3 3
C
=ACC
c                    d|v }|                      |ddi           }| j        0|                     | j        dd          }t	          |          | _        | j        }|                     |          }|                    |           |d         }d}	d}
|r|	n|
}|                    ||           |                    ||d	z   |z              d S )
Nra   r   r   ordersLimitr   ri   r4  r5  r6  )safe_value_2rD  r   rU   r   parse_orderrs   r   )rZ   r   r   r>  r   r   r   parsedOrderri   r?  r@  r^   s               r\   handle_orderzbingx.handle_orderI  s    h '  &#r::;%%dlM4HHE077DK&&t,,k"""X&#)8hhv{+++v{S069:::::r]   c                    d|v }|                      |ddi           }| j        }|2|                     | j        dd          }t	          |          }|| _        |rdnd}|                     |d          }|                     |d d	|          }	|                     ||	          }
|
d
         }d}d}|r|n|}|                    |
           |	                    ||           |	                    ||dz   |z              d S )Nra   r   r   r   r   r/   rQ   r   -ri   rG  rH  r6  )
safe_dict_2myTradesr   rU   r   rq   r   r   rs   r   )rZ   r   r   r>  r   cachedTradesr   r/  r   rc   r%  ri   r?  r@  r^   s                  r\   handle_my_tradeszbingx.handle_my_trades  s!   r '!!'63;;}%%dlM4HHE1%88L(DM+vvV##FC00!!(D#t<<!!&&11!"""(6hhhF###|[111|[3%6%?@@@@@r]   c                 @   |                      |di           }|                     |dg           }|                     |dd          }d|v rdnd}|| j        vr
i | j        |<   || j        |         d<   || j        |         d	<   |                     |          | j        |         d
<   t          dt          |                    D ]}||         }|                     |d          }	|                     |	          }
| 	                                }||d<   |                     |d          |d<   |                     |d          |d<   || j        |         |
<   | 
                    | j        |                   | j        |<   |                    | j        |         |dz              d S )Nr   r   r  r  r  rQ   r/   r   r   r   r   lkusedwbfreerY  )r   rt   r  rV  r   r   r   rq   safe_currency_codeaccountsafe_balancer   )rZ   r   r   r   r   r   r/  r#  rV  
currencyIdr  r  s               r\   handle_balancezbingx.handle_balance  s   J NN7C,,~~ab))''c::	((vv$$!#DL%)T6"*3T;')-i)@)@T:&q#d))$$ 	/ 	/A1gG))'377J**:66DllnnG%GFO"..w==GFO"..w==GFO'.DLt$$!..t|D/ABBTt|D)4*+<=====r]   c                    |                      ||          sd S |dk    sd|v r|                     | j        ||           d S |                     |dd          }|                    d          dk    r|                     ||           d S |                    d          dk    r|                     ||           d S |                    d          dk    r|                     ||           d S |                    d	          dk    r|                     ||           d S |                    d
          dk    ra| 	                    |di           }|                     |d          }|dk    r| 
                    ||           |                     ||           d S |                     |d          }|dk    r,|                     ||           |                     ||           |dk    r{|                     ||           | 	                    |di           }|                     |d          }|                     |d          }|dk    r|dk    r| 
                    ||           | 	                    |d          }|                     |d          }	|	dk    r|                     ||           |dk    r|	||                     ||           d S d S d S d S )Nr  r  ra   r]  z@depthr   r   r   z@klineexecutionReportr   xTRADEr  rK  ORDER_TRADE_UPDATEr   XFILLED	24hTicker)r  rT  r  rq   r   r  r   r   r'  r   r  r  r  r  handle_subscription_status)
rZ   r   r   ra   r   r/  r  statusmsgDatamsgEvents
             r\   handle_messagezbingx.handle_message2  s   ((99 	Fv6W#4#4JJty&'222F##GZ<<==""a''""67333F==##q((vw///F==""a''vw///F==""a''fg...F==*++q00??7FB77D##D#..Dw%%fg666fg...FWc**   000!!&'222$$$fg...??7C44D##D#..D%%dC00Ff&8&8%%fg666//'622##GS11{""vw///r>>h.19++FG<<<<< >..99r]   c                     |                      |d          }|                     |j        d          }|                     ||i           }|                     |dd          }|r|                     ||           |S )Nrg   rj   F)rq   index_byr	  r   	safe_boolhandle_un_subscription)rZ   r   r   rg   subscriptionsByIdr}   isUnSubMessages          r\   r  z bingx.handle_subscription_status_  s~     gt,, MM&*>EE~~&7R@@mUKK 	>''===r]   r}   c                    |                      |dg           }|                      |dg           }t          dt          |                    D ])}||         }||         }|                     |||           *|                     |           d S )Nrl   rk   r   )rt   r   r   clean_unsubscriptionclean_cache)rZ   r   r}   rl   rk   r#  	unsubHashsubHashs           r\   r  zbingx.handle_un_subscriptionp  s    |_bII>>,8JBOOq#m,,-- 	B 	BA%a(I&q)G%%fgyAAAA&&&&&r]   )N)NN);__name__
__module____qualname__r   rY   strr
   r~   r   r   r   r   r   r   r	   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r  r'  r-  r0  r   rE  rI  r   rQ  rM  rU  r   r   ri  re  rk  r  r  r  r  r<  r  r  r  r  r  r  dictr  __classcell__)r[   s   @r\   r   r      s       W# W W W W W Wr \^ m m# ms mSV mbe mnq m  |B m  PS m  cf m m m mB 68 $k $k $kF $k $k $k $kL 9; z zC zs z z z z*BDF BD BD BD BDH0 0 0 0d c #     s C s     <@d[] / / /S / /bfglbm / / / /b 9; z zC zs z z z z,f,F f, f, f, f,P @DB 3! 3!S 3! 3!S\ 3! 3! 3! 3!j =? @ @ @3 @ @ @ @,& & &
e9 e9 e9 e9 e9N
 
D 
 
 
 
4h;6 h; h; h; h;T ?CQUdhqs 2H 2H 2H 2H3 2H^a 2Hx|  ~B  yC 2H 2H 2H 2Hh BFb @ @3 @3 @UX @ @ @ @4 04$UYbd 7U 7U 7UC 7Us 7Uimnsit 7U 7U 7U 7Ur 37TX\eg 7U 7UC 7Us 7URU 7Ulpqvlw 7U 7U 7U 7Ur *, 2[ 2[ 2[ 2[ 2[ 2[h
$ 
$ 
$ 
$ 
$B B B 8<$]ajl 1_ 1_W 1_C 1_WZ 1_quv~q 1_ 1_ 1_ 1_f
8 
8& 
8 
8 
8 
8 
84 4 42 2 2 2h07v 07 07 07 07d  & 24 M M M M6 )+ Q Q Q Q     0a; a; a;FJAv JA JA JA JAX8>V 8> 8> 8> 8>t+=V += += += +=Z    "'V '4 ' ' ' ' ' ' ' 'r]   r   )ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   r   r   ccxt.base.typesr   r   r	   r
   r   r   r   r   r   r   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   r   ccxt.base.preciser   async_supportr   r   r]   r\   <module>r     sY       A  A  A  A  A  A  A  A  A  A  A  A o o o o o o o o o o o o o o o o o o o o o o o o o o 4 4 4 4 4 4       ' ' ' ' ' ' ) ) ) ) ) ) ) ) ) ) ) ) % % % % % %f' f' f' f' f'D$ f' f' f' f' f'r]   