
    ":h                        d dl Zd dlmZmZmZmZ d dl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 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@                  jB                        Z!y)    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheBySymbolBySideArrayCacheByTimestamp)AsksBids)AnyBalancesIntMarketOrder	OrderBookPositionStrStringsTickerTickersTrade)Client)List)ExchangeError)AuthenticationError)NotSupportedc            
           e Zd Zdef fdZi fdZdi fdededefdZi fde	fd	Z
d
efdZd Zd
ef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i fdedee   defdZ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
efdZd8dZdddi fdedededee   fdZd
efdZd8de de!fdZ"d Z#d  Z$dddi fdedededee%   fd!Z&d
efd"Z'd8de!fd#Z(d
efd$Z)d% Z*d8d&e de!fd'Z+d
efd(Z,d8d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,Z0di fdedede1fd-Z2d. Z3d/ Z4d
efd0Z5d
efd1Z6di fdee   dede1fd2Z7i fd3Z8d
efd4Z9d
efd5Z:d
efd6Z;d
efd7Z< xZ=S )9bitmartreturnc                 $   | j                  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
ddd	dddddddiidd
dddd idd id!d
id"d
id#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3id4      S )5NcreateOrderWsFeditOrderWsfetchOpenOrdersWsfetchOrderWscancelOrderWscancelOrdersWscancelAllOrdersWswsTwatchBalancewatchTickerwatchTickerswatchBidsAskswatchOrderBookwatchOrderBookForSymbolswatchOrderswatchTradeswatchTradesForSymbolsemulated)
watchOHLCVwatchPositionwatchPositionsapiz5wss://ws-manager-compress.{hostname}/api?protocol=1.1z6wss://ws-manager-compress.{hostname}/user?protocol=1.1)publicprivatez/wss://openapi-ws-v2.{hostname}/api?protocol=1.1z0wss://openapi-ws-v2.{hostname}/user?protocol=1.1)spotswapr6   )fetchBalanceSnapshotawaitBalanceSnapshotdepthdepth/increase100ignoreDuplicatesinflate1m3m5m15m30m45m1H2H3H4H1D1W1M)r>   r?   r@   rA   rB   rC   1h2h3h4h1d1wrJ   )defaultTyper&   r*   r+   r-   r%   
timeframes	keepAlivei:  )hasurlsoptions	streaming)deep_extendsuperr   describe)self	__class__s    J/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/pro/bitmart.pyrZ   zbitmart.describe   s   gt = ?u $U 	
   !% $U d  t    !$ +D t  t!" (#$ #!+"&). &]'_!
 'X'Y!	  &,0,1! 0# 0- '  t    -%N UWNB
 N N	    c                   K   | j                  |      }| j                  | j                  d   d   |   d         }i }d }|dk(  rd|z   dz   |d   z   }d|gd	}nBd
|z   dz   |d   z   }| j                  |d      }	|	| j	                  |d      }|d|	z   z  }d|gd}| j                  ||| j                  ||      |       d {   S 7 w)Nr3   r%   r4   r6   spot/:id	subscribeopargsfutures/speedactionrf   )marketimplode_hostnamerU   safe_stringomitwatchrX   )
r[   channelsymboltypeparamsrk   urlrequestmessageHashrh   s
             r]   rc   zbitmart.subscribee   s     V$##DIIe$4T$:4$@$JK6>!G+c1F4L@K!$G
 %w.4vd|CK$$VW5E 673sU{*%$G ZZ[$2B2B7F2SU`aaaas   C C	CC	Nrp   rr   symbolsc                   K   | j                  ||dd      }| j                  | j                  d   d   |   d         }|dk(  rdnd}|dk(  rdnd	}g }g }	t        d
t	        |            D ]R  }
| j                  ||
         }|dz   |z   dz   |d   z   }|j                  |       |	j                  |dz   |d   z          T d|i}d||<   | j                  ||	| j                  ||      |       d {   S 7 w)NFTr3   r%   r4   r6   futuresre   rj   r   /ra   rb   rq   rf   rc   )	market_symbolsrl   rU   rangelenrk   appendwatch_multiplerX   )r[   rp   rr   rw   rs   rt   channelType
actionTyperawSubscriptionsmessageHashesirk   messageru   s                 r]   subscribe_multiplezbitmart.subscribe_multiple|   s%    %%gtUDA##DIIe$4T$:4$@$JK!%fi"fnT8
q#g,' 	CA[[,F!C''1C7&,FG##G,  31A!AB		C $
 *
((mT=M=MgW]=^`pqqqqs   C,C5.C3/C5c                   K   | j                          d{    d}| j                  dd|      \  }}| j                  ||       d{    i }|dk(  rddgd}ndg dd}d	|z   }| j                  | j                  d
   d   |   d         }| j                  |      }| j                  |||       d}d}| j                  | j                  ddd      \  }}| j                  | j                  ddd      \  }}|r|r|j                  |dz          d{    | j                  ||| j                  ||      |       d{   S 7 .7 7 57 w)a  

        https://developer-pro.bitmart.com/en/spot/#private-balance-change
        https://developer-pro.bitmart.com/en/futuresv2/#private-assets-channel

        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
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        Nr6   r&   rc   z spot/user/balance:BALANCE_UPDATErd   )zfutures/asset:USDTzfutures/asset:BTCzfutures/asset:ETHri   balance:r3   r%   r5   r8   Tr9   Fz:fetchBalanceSnapshot)load_marketshandle_market_type_and_paramsauthenticaterl   rU   clientset_balance_cachehandle_option_and_paramsrV   futurero   rX   )	r[   rs   rr   ru   rv   rt   r   r8   r9   s	            r]   watch_balancezbitmart.watch_balance   s     !!!99.$PVWff---6>!;<G &XG !4'##DIIe$4T$:4$@$KLS!vt[9##'+'D'DT\\Sacy{  (A$f'+'D'DT\\Sacy  |A  (B$f$8--'> >???ZZ[$2B2B7F2SU`aaa3 	" 	.* @asF   EE1EE	C
EE	+E?E EE	EEr   c                 ,   ||j                   v ry | j                  | j                  d      }| j                  |dd      }|rE|dz   dz   }||j                  vr/|j                  |       | j                  | j                  |||       i | j                  |<   y )Nr&   r8   Tra   )	subscriptions
safe_valuerV   	safe_boolry   r   spawnload_balance_snapshotbalance)r[   r   rr   subscribeHashrV   snapshotrv   s          r]   r   zbitmart.set_balance_cache   s    F000//$,,?>>'+A4H*'==K6>>1k*

455v{DQTr^   c                 <  K   | j                  d|i       d {   }| j                  || j                  | j                  |i             | j                  |<   |j                  |   }|j                          |j                  | j                  |   d|z          y 7 w)Nrr   r   )fetch_balanceextendr   r   ry   resolve)r[   r   rv   rr   responser   s         r]   r   zbitmart.load_balance_snapshot   s     ++VTN;;![[4??4<<QUWY3Z[T,t||D):+<= <s   BBBBc                 X   | j                  |dd      }| j                  |d      }|y |j                  d      dk\  }|rdnd}|| j                  |   d<   |rt	        |t
              sy t        dt        |            D ]  }| j                  |d      }|| j                  |   d	<   | j                  |      | j                  |   d
<   | j                  ||   dg       }	t        dt        |	            D ]v  }
|	|   }| j                         }| j                  |d      }| j                  |      }| j                  |d      |d<   | j                  |d      |d<   || j                  |   |<   x  no| j                  |d      }| j                  |      }| j                         }| j                  |d      |d<   | j                  |d      |d<   || j                  |   |<   | j                  | j                  |         | j                  |<   d|z   }|j                  | j                  |   |       y )Ntablegroupdatar6   r   r7   info
event_time	timestampdatetimebalance_detailsccyav_balfreefz_balusedcurrencyavailable_balancefrozen_balancer   )safe_string_2r   findr   
isinstancelistr|   r}   safe_integeriso8601accountrm   safe_currency_codesafe_balancer   )r[   r   r   rp   r   isSpotrr   r   r   balanceDetailsii
rawBalancer   
currencyIdcoderv   s                   r]   handle_balancezbitmart.handle_balance   s%   < $$Wgw?w/<,,v&!+vV%,T6"dD)1c$i( 7 --g|D	2;T";/15i1HT":.!%a:KR!P3~#67 7B!/!2J"llnG!%!1!1*e!DJ22:>D&*&6&6z8&LGFO&*&6&6z8&LGFO/6DLL&t,77 ))$
;J**:6DllnG"..t5HIGFO"..t5EFGFO'.DLLt$!..t||D/ABT 4't||D);7r^   rq   sincelimitc                 H   K   | j                  |g|||       d{   S 7 w)as  

        https://developer-pro.bitmart.com/en/spot/#public-trade-channel
        https://developer-pro.bitmart.com/en/futuresv2/#public-trade-channel

        get the list of most recent trades for a particular symbol
        :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
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        N)watch_trades_for_symbols)r[   rq   r   r   rs   s        r]   watch_tradeszbitmart.watch_trades  s'      22F8UE6RRRRs   " "c                   K   | j                          d{    d}| j                  d|||      \  }}}d}| j                  ||||       d{   }| j                  r6| j	                  |d      }| j                  |d      }	|j                  |	|      }| j                  |||dd      }
| j                  dd	d      r%| j                  |
      }| j                  |d      }|S |
S 7 7 w)
a'  

        https://developer-pro.bitmart.com/en/spot/#public-trade-channel

        get the list of most recent trades for a list of symbols
        :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
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        Nr.   trader   rq   r   Tr-   r<   )r   get_params_for_multiple_subr   
newUpdates	safe_dictrm   getLimitfilter_by_since_limithandle_option!remove_repeated_trades_from_arraysort_by)r[   rw   r   r   rs   
marketTypechannelNametradesfirsttradeSymbolresultfiltereds               r]   r   z bitmart.watch_trades_for_symbols  s      !!!
&*&F&FG^`ginpv&w#V..{JQWXX??NN61-E**5(;KOOK7E++FE5+tTm-?F==fEH||Hk:HO 	" Ys"   C(C$7C(C&BC(&C(
methodNamec                     | j                  |d dd      }t        |      }|dkD  rt        | j                  dz   |z   dz         | j	                  |d         }d }| j                  |||      \  }}|||gS )NFT    z1() accepts a maximum of 20 symbols in one requestr   )r{   r}   r   rb   rk   r   )r[   r   rw   r   rs   lengthrk   r   s           r]   r   z#bitmart.get_params_for_multiple_sub8  s    %%gtUDAWB;tww}z9<ooppWQZ(
!??
FTZ[
FV,,r^   c                    K   | j                          d{    | j                  |      }| j                  |g|       d{   }||   S 7 57 w)a)  

        https://developer-pro.bitmart.com/en/spot/#public-ticker-channel
        https://developer-pro.bitmart.com/en/futuresv2/#public-ticker-channel

        watches 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
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        N)r   rq   watch_tickers)r[   rq   rs   tickerss       r]   watch_tickerzbitmart.watch_tickerB  sR      !!!V$**F8V<<v 	"<s!   AA+AA
AAc                 6  K   | j                          d{    | j                  |      }d}| j                  d||      \  }}| j                  d|||       d{   }| j                  ri }|||d   <   |S | j                  | j                  d|      S 7 ~7 ;w)a9  

        https://developer-pro.bitmart.com/en/spot/#public-ticker-channel
        https://developer-pro.bitmart.com/en/futuresv2/#public-ticker-channel

        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
        :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(   tickerrq   )r   get_market_from_symbolsr   r   r   filter_by_arrayr   )r[   rw   rs   rk   r   r   r   s          r]   r   zbitmart.watch_tickersR  s      !!!--g6
!??PVX^_
F..xWfUU??G(.GF8$%N##DLL(GDD 	" Vs"   BBABB:BBc                   K   | j                          d{    | j                  |dd      }| j                  |      }d}| j                  d||      \  }}| j	                  | j
                  d   d   |   d         }|dk(  rdnd}|dk(  rd	nd
}g }g }	t        dt        |            D ]G  }
| j                  ||
         }|j                  |dz   |d   z          |	j                  d||
   z          I |dk7  r|dz   g}d|i}d||<   | j                  ||	||       d{   }| j                  ri }|||d   <   |S | j                  | j                  d|      S 7 B7 <w)a  

        https://developer-pro.bitmart.com/en/spot/#public-ticker-channel
        https://developer-pro.bitmart.com/en/futuresv2/#public-ticker-channel

        watches best bid & ask for symbols
        :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>`
        NFr)   r3   r%   r4   r6   ry   re   rj   r   z/ticker:rb   bidask:z/tickerrf   rc   rq   )r   r{   r   r   rl   rU   r|   r}   rk   r~   r   r   r   bidsasks)r[   rw   rs   firstMarketr   rt   r   r   r   r   r   rk   ru   
newTickersr   s                  r]   watch_bids_askszbitmart.watch_bids_asksh  s     !!!%%gtU;227;
!??Q\^de
F##DIIe$4T$::$Fx$PQ!+v!5fI(F2T
q#g,' 	9A[[,F##K*$<vd|$KL  WQZ!78	9  +i 78$
 *
..sM7L\]]
??G,6GJx()N##DMM8WEE3 	"( ^s"   EEDEE:EEc                 R   | j                  |d      }|d u}g }|r| j                  |dg       }n| j                  |di       g}t        |      sy t	        dt        |            D ]A  }| j                  ||         }|d   }|| j                  |<   d|z   }	|j                  ||	       C y )Nr   r   r   rq   r   )rm   	safe_listr   r}   r|   parse_ws_bid_askr   r   
r[   r   r   r   r   
rawTickersr   r   rq   rv   s
             r]   handle_bid_askzbitmart.handle_bid_ask  s      '2t#
<J//'62>?J:q#j/* 	0A**:a=9FH%F$*DMM&!#f,KNN6;/	0r^   c                 n   | j                  |d      }| j                  ||      }| j                  |d      }| j                  |d      }| j                  ||| j	                  |      | j                  |dd      | j                  |dd      | j                  |dd      | j                  |d	d
      |d|      S )Nrq   ms_task_px	ask_priceask_szask_volbid_px	bid_pricebid_szbid_vol)rq   r   r   ask	askVolumebid	bidVolumer   )rm   safe_marketr   safe_tickerr   r   )r[   r   rk   marketIdrq   r   s         r]   r   zbitmart.parse_ws_bid_ask  s    ##FH5!!(F3!!&(3%%ff5	"Y/%%fhD++FHiH%%fhD++FHiH	!
 	 		r^   c                 L  K   | j                          d{    d}d}|'| j                  |      }| j                  |      }d|z   }d}| j                  d||      \  }}| j	                  ||       d{    d}|dk(  rd}	|	|	|d   z  }	nd}	d	|	gd
}nd	dgd}| j                  | j                  d   d   |   d         }
| j                  |
|| j                  ||      |       d{   }| j                  r|S | j                  | j                  |||d      S 7 7 7 6w)a  
        watches information on multiple orders made by the user

        https://developer-pro.bitmart.com/en/spot/#private-order-progress
        https://developer-pro.bitmart.com/en/futuresv2/#private-order-channel

        :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>`
        Norderszorders::r6   r,   zspot/user/order:rb   zspot/user/orders:ALL_SYMBOLSrc   rd   zfutures/orderri   r3   r%   r5   T)r   rq   rk   r   r   rl   rU   ro   rX   r   filter_by_symbol_since_limitr  )r[   rq   r   r   rs   rk   rv   rr   ru   argsRequestrt   	newOrderss               r]   watch_orderszbitmart.watch_orders  s\     !!![[(F[[(F$v-K99-QWXff---6>,K!vd|+<!$G &()G ##DIIe$4T$:4$@$KL**S+t7G7GQW7XZeff	??00feUTXYY= 	" 	.$ gs5   D$DAD$5D 6A5D$+D",2D$ D$"D$c                 `   | j                  |d      }|y t        |      }g }i }|dkD  r| j                  | j                  dd      }| j                  t        |      | _        | j                  }t        dt        |            D ]B  }	| j                  ||	         }
|j                  |
       |j                  |
       |
d   }d||<   D d}t        |j                               }t        dt        |            D ]!  }	||	   }|dz   |z   }|j                  ||       # |j                  ||       y )	Nr   r   ordersLimit  rq   Tr  ::)r   r}   r   rV   r  r   r|   parse_ws_orderr~   r   keysr   )r[   r   r   r  ordersLengthr  rw   r   storedr   orderrq   rv   
symbolKeyssymbolSpecificMessageHashs                  r]   handle_orderszbitmart.handle_orders  s4   l &1>6{	!%%dllM4HE{{"4U;[[F1c&k* '++F1I6e$  'x"&' ',,.)
q#j/* 	AA]F(3d(:V(C%NN9&?@	A 	y+.r^   r  rk   c                 V   | j                  |d      }|d u }|r/| j                  |d      }| j                  ||dd      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }	| j                  |d	      }
| j                  |d
      }| j                  |d      }| j                  |d
   |      }| j	                  |d      }|d   }| j                  |d      }| j                  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|      S | j                  |d      }| j                  |d      }| j                  ||dd      }| j                  |d      }| j	                  |d      }| j	                  |d       }| j                  |d!      }| j                  }| j                  |j                  |i       }| j                  ||      }d }|| j                  |d"      }||g }|j                  |       | j                  i d|d|d|d| j                  |d#      d|d| j                  |      d|d
| j                  |d
      dd dd d| j                  | j                  |d            d| j                  |d      dd dd d| j                  |d	      dd d| j                  |d$      | j                  |d%      d | j                  | j                  |d            d |d|      S )&Nrj   rq   _r6   order_id	clientOidpricefilled_sizesizerr   stater   sider   rb   clientOrderIdr   r   lastTradeTimestamptimeInForcepostOnly	stopPricetriggerPriceamountcostaverage)filled	remainingstatusfeer   r   r7   create_timeupdate_time
last_trader   client_order_iddeal_avg_price	deal_size)safe_numberrm   r   parse_order_status_by_typer   safe_string_lower
safe_orderr   safe_symbolr  hashmapr~   r   parse_ws_order_sideparse_ws_order_status)r[   r  rk   rj   r   r   rb   r  r  r$  r!  rr   rawStater&  r   rq   r  	orderInfoorderIdupdatedTimestamp	lastTradecachedOrdersr  cachedOrderr   s                            r]   r
  zbitmart.parse_ws_order+  sr   X !!%2D.''x8H%%hVDF!!%4B ,,UK@M$$UG4E%%e];F%%eV4F##E62D''w7H44VF^XNF))%8IH%F))%8D?? $$&$ b$  	$
 T$ D$ %i$ $ t$ D$ $ $ T$ $ &$  !$" 4#$$ !! -$. / 2 w7I''	8<H%%hFCF&&y*=G)))]CI#00MJ	<@I;;L__\%9%962FF//&':KF&9$>Fi(?? $$&$ g$  !1!1)=N!O	$
 Y$ DLL3$ %&6$ ((F;$ t$ D$ 001A1A)V1TU$ )))W=$ T$ $ $**9f=$  !$" 4++I7GH#$$ **9kB!44T5E5EeX5VW -$. / r^   c           
      @    dddddddddd	}| j                  |||      S )Nclosedopencanceled)	123456789rm   )r[   statusIdstatusess      r]   r6  zbitmart.parse_ws_order_status  s;    

 (H==r^   c                 6    ddddd}| j                  |||      S )Nbuysell)rB  rC  rD  rE  rK  )r[   sideIdsidess      r]   r5  zbitmart.parse_ws_order_side  s,    	
 vv66r^   c                   K   | j                          d{    d}| j                  ||       d{    | j                  |dddd      }d}||ddj                  |      z   z  }d}d	dgd
}| j	                  | j
                  d   d   |   d         }	| j                  |	|| j                  ||      |       d{   }
| j                  r|
S | j                  | j                  |||      S 7 7 7 4w)a  

        https://developer-pro.bitmart.com/en/futures/#private-position-channel

        watch all open positions
        :param str[]|None symbols: list of unified market symbols
        :param int [since]: the earliest time in ms to fetch positions
        :param int [limit]: the maximum number of positions 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>`
        Nr7   TF	positionsr	  ,zfutures/positionrc   ri   r3   r%   r5   )r   r   r{   joinrl   rU   ro   rX   r   filter_by_symbols_since_limitrT  )r[   rw   r   r   rs   rr   rv   subscriptionHashru   rt   newPositionss              r]   watch_positionszbitmart.watch_positions  s     !!!f---%%gvtT5I!4#((7"333K-!'(
 ##DIIe$4T$:4$@$KL!ZZ[$:J:J7TZ:[]mnn??11$..'5RWXX! 	"- os2   C4C.C4C0B
C4=C2>1C40C42C4c                 d   | j                  |dg       }| j                  t               | _        | j                  }g }t        dt	        |            D ]:  }||   }| j                  |      }|j                  |       |j                  |       < | j                  |d      }	t        dt	        |	            D ]f  }|	|   }
|
j                  d      }|d   }|j                  d      }| j                  |d|d      }| j                  |      rU|j                  ||
       h |j                  |d	       y )
Nr   r   zpositions::r	     rU  rq   FrT  )r   rT  r   r|   r}   parse_ws_positionr~   find_message_hashessplitr   is_emptyr   )r[   r   r   r   cacherY  r   rawPositionpositionr   rv   partssymbolsStringrw   rT  s                  r]   handle_positionszbitmart.handle_positions  s(   H w3>>!57DNq#d)$ 	#Aq'K--k:H)LL"		#
 00Gq#m,- 	7A'*K%%d+E!!HM#))#.G,,\8WeTI==+y+6	7 	|[1r^   c                 f   | j                  |d      }| j                  ||d d      }|d   }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  i d|dd d|d	|d
| j	                  |      d|dd d|dk(  rdndd| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      dd dd dd dd dd d d d d d | j                  |d      |dk(  rdndd d d d d       S )!Nrq   r7   r)  r*  position_type	open_typer   rb   r   r   lastUpdateTimestamphedgedr  r\  longshort	contractshold_volumecontractSize
entryPriceopen_avg_price	markPricehold_avg_price	lastPricenotionalleverage
collateralinitialMarginliquidate_priceisolatedcross)initialMarginPercentagemaintenanceMarginmaintenanceMarginPercentageunrealizedPnlrealizedPnlliquidationPrice
marginMode
percentagemarginRatiostopLossPricetakeProfitPrice)rm   r   r   safe_positionr   r/  )	r[   rc  rk   r   rq   openTimestampr   r  marginModeIds	            r]   r]  zbitmart.parse_ws_position  s   " ##Hh7!!(FD&A!))(MB%%h>	  ?;((;?!! #
H#
$#
 f#
 	#

 ]3#
 "9#
 d#
 tqyFw#
 ))(MB#
 D,,V^D#
 $**85EF#
 ))(4DE#
 #
 #
 #
  $!#
" T##
$ (,!%+/! $ 0 0;L M)5):*!#9#
  	r^   c                 >   | j                  |d      }|y d }t        |      }d|v }|r.t        d|      D ]  }||z
  dz
  }| j                  ||         }  n%t        d|      D ]  }| j                  ||         } |j	                  | j
                  |   d|z          y )Nr   r   r   r\  ztrade:)r   r}   r|   handle_trade_loopr   r   )	r[   r   r   r   rq   r   isSwapr   indexs	            r]   handle_tradezbitmart.handle_tradeO  s    @ w/<TW$1f% =
Q//U<=
 1f% 9//Q89t{{6*Hv,=>r^   c                    | j                  |      }|d   }| j                  | j                  dd      }| j                  | j                  |      t        |      | j                  |<   | j                  |   }|j                  |       |S )Nrq   tradesLimitr  )parse_ws_trader   rV   r   r   r   r~   )r[   entryr   rq   r  r  s         r]   r  zbitmart.handle_trade_loop  sz    ##E*x''mTJ??4;;/7",["9DKKV$er^   r   c                    | j                  |d      }| j                  ||      }| j                  |d      }d }|$| j                  |d      }| j                  |      }n| j	                  |      }d }| j                  |d      }| j                  |d      }|||rd}nd}d}| j                  || j                  |d	      d |||d   d || j                  |d
d      | j                  |dd      d |d d|      S )Nrq   r   
created_atr  mrP  rO  takertrade_idr  
deal_pricer  deal_vol)r   rb   r  r   r   rq   rr   r  r  r!  r"  takerOrMakerr'  )rm   r   r   	parse8601r   r   
safe_trader   )	r[   r   rk   r   r   r   r  r  
buyerMakers	            r]   r  zbitmart.parse_ws_trade  s)   . ##E84!!(F3%%eV4	''|<Hx0I||I.Hv.^^E3/
!|!D D"L""5*5" X&''wE((
C( 
  	r^   c                    | j                  ||       | j                  |d      }|d u}g }|r| j                  |dg       }n| j                  |di       g}t	        |      sy t        dt	        |            D ]W  }|r| j                  ||         n| j                  ||         }|d   }|| j                  |<   d|z   }	|j                  ||	       Y y )Nr   r   r   rq   zticker:)
r   rm   r   r   r}   r|   parse_tickerparse_ws_swap_tickerr   r   r   s
             r]   handle_tickerzbitmart.handle_ticker  s    B 	FG,  '2t#
<J//'62>?J:q#j/* 	0A9?T&&z!}5TE^E^_ijk_lEmFH%F#)DLL #f,KNN6;/	0r^   c                    | j                  |d      }| j                  i d| j                  ||dd      dd dd dd dd d| j                  |d	      d
| j                  |d      d| j                  |d      d| j                  |d      dd dd dd d| j                  |d      dd dd dd dd d | j                  |d      || j                  |d      | j                  |d      d|      S )Nrq   r(  r7   r   r   highlowr   r   r   r   r   r   r   r   vwapr@  closelast
last_pricepreviousClosechanger  r#  	volume_24
mark_priceindex_price)
baseVolumequoteVolumer   rs  
indexPrice)rm   r   r3  )r[   r   rk   r   s       r]   r  zbitmart.parse_ws_swap_ticker  s    ##FH5 !
d&&xVD!
!
 !
 D	!

 4!
 4##FK8!
 ))&)<!
 4##FK8!
 ))&)<!
 D!
 D!
 T!
 D$$V\:!
 T!
 d!
  $!!
" t#!
$ ++FK@))&,?**6=A-!
. / 	r^   r>   c                   K   | j                          d{    | j                  |      }| j                  |      }d}| j                  d||      \  }}| j	                  | j
                  di       }| j                  ||      }	d}
|dk(  rd|	z   }
nd|	z   }
| j                  |
|||       d{   }| j                  r|j                  ||      }| j                  |||dd      S 7 7 9w)	a  

        https://developer-pro.bitmart.com/en/spot/#public-kline-channel
        https://developer-pro.bitmart.com/en/futuresv2/#public-klinebin-channel

        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :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
        Nr6   r*   rR   klineklineBinr   T)r   rq   rk   r   r   rV   rm   rc   r   r   r   )r[   rq   	timeframer   r   rs   rk   rr   rR   intervalnameohlcvs               r]   watch_ohlcvzbitmart.watch_ohlcv  s      !!!V$V$99:JFTZ[f__T\\<D
##J	:6>X%D(DnnT64@@??NN651E))%q$GG 	" As"   C)C%BC)-C'.8C)'C)c                    | j                  |dd      }|j                  d      dk\  }| j                  |d      }|y |j                  d      }| j	                  |dd      }|j                  d	d      }|j                  d
d      }|j                  d      }	| j	                  |	d      }| j                  | j                  di       }
| j                  ||
      }| j                  |      }|dz  }|r<t        dt        |            D ]"  }| j	                  ||   d      }| j                  |      }|d   }| j                  ||   d      }| j                  ||      }| j                  |d   |z        |z  |d<   | j                  | j                  |i       | j                  |<   | j                  | j                  |   |      }|:| j                  | j                  dd      }t!        |      }|| j                  |   |<   |j#                  |       |dz   |z   }|j%                  ||       % y | j	                  |d      }| j                  |d d d      }|d   }| j                  |dg       }| j                  | j                  |i       | j                  |<   | j                  | j                  |   |      }|:| j                  | j                  dd      }t!        |      }|| j                  |   |<   t        dt        |            D ]*  }||   }| j                  ||      }|j#                  |       , |j%                  ||       y )Nr   r   r6   r   r   rz   r\  r(  r  Binra   rR   r  rq   candle
OHLCVLimitr7   items)r   r   r   r_  rm   replacerV   find_timeframeparse_timeframer|   r}   r   parse_ohlcvparse_to_intohlcvsr   r   r~   r   )r[   r   r   rp   r   r   rd  part1r  intervalPartsrR   r  durationdurationInMsr   r   rk   rq   rawOHLCVparsedr  r   rv   r  r  s                            r]   handle_ohlcvzbitmart.handle_ohlcv>  s!   H $$Wgw?,,v&!+w/<c"  2.=="-##E2. s+##M15__T\\<D
''*=	''	2$1c$i( 4++DGX>))(3)??47H=))(F; --fQi,.FG,Vq	&*oodkk62&NF#V)<iH> --dllL$OE259F5;DKK'	2f%%mh6v{34" ''h7H%%hdFCFH%FOOD'26E"&//$++vr"JDKK__T[[%8)DF~))$,,dK.u517F#I.1c%j) &q))&&9f%& NN67+r^   c                   K   | j                          d{    | j                  | j                  di       }| j                  |dd      }| j	                  |      }| j                  |      }d}| j                  d||      \  }}|dk(  r|dk(  rd}| j                  ||||       d{   }|j                         S 7 7 w)a$  

        https://developer-pro.bitmart.com/en/spot/#public-depth-all-channel
        https://developer-pro.bitmart.com/en/spot/#public-depth-increase-channel
        https://developer-pro.bitmart.com/en/futuresv2/#public-depth-channel

        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :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
        :param str [params.speed]: *futures only* '100ms' or '200ms'
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        Nr*   r:   r;   r6   r7   depth50)	r   r   rV   rm   rq   rk   r   rc   r   )	r[   rq   r   rs   rV   r:   rk   rr   	orderbooks	            r]   watch_order_bookzbitmart.watch_order_book  s      !!!//$,,0@"E  '3FGV$V$99:JFTZ[f6>e'::E..fEE	   	" Fs"   CB=BC(B?)C?Cc                 p    | j                  |d      }| j                  |d      }|j                  ||       y )Nr   r\  )
safe_floatstore)r[   booksidedeltar  r!  s        r]   handle_deltazbitmart.handle_delta  s0    q)*uf%r^   c                 b    t        dt        |            D ]  }| j                  |||           y )Nr   )r|   r}   r  )r[   r  deltasr   s       r]   handle_deltaszbitmart.handle_deltas  s0    q#f+& 	3Ahq	2	3r^   c                 L   | j                  |dg       }| j                  |dg       }| j                  |d   |       | j                  |d   |       | j                  |d      }| j                  |d      }| j	                  |      }||d<   ||d<   | j                  |      |d<   |S )Nasksbidsr   rq   r   r   )r   r  r   rm   r3  r   )	r[   r   r   r  r  r  r   r   rq   s	            r]   handle_order_book_messagez!bitmart.handle_order_book_message  s    * ~~gvr2~~gvr29V,d39V,d3%%gv6	##GX6!!(+$	(!*	+ $Y 7	*r^   c                 ~   d|v }g }|r| j                  |d|      }n%| j                  |d      }||j                  |       t        |      }|dk  ry | j	                  |dd      }g d}d}	t        dt        |            D ].  }
||
   }|j                  |      dk\  s| j                  |      }	 n |rM|j                  dd      }t        dt        |            D ]!  }
||
   }| j                  |d      }| j                  |      }|| j                  vr&| j                  i |	      }||d<   || j                  |<   | j                  |   }| j                  |d	      }|d
k(  s|j                  d      dk\  s|j                  i        | j                  |||       | j                  |d      }|d   ||d<   | j!                  |      |d<   |dz   |z   }|j#                  ||       |dz   |z   }|j#                  ||       $ y |j%                  d      }|d   j                  dd      }|d   }|d   }| j                  |d      }| j                  |      }|| j                  vr&| j                  i |	      }||d<   || j                  |<   | j                  |   }| j                  |d      }|dk(  rdnd}|dk(  rt'        g |	      ||<   nt)        g |	      ||<   t        dt        |            D ]O  }
||
   }| j+                  |d      }| j+                  |d      }| j-                  ||      }|j/                  ||       Q t        |d         }t        |d         } |dk(  s| dk(  ry | j                  |d      }||d<   | j!                  |      |d<   |}|j#                  ||       |dz   |z   }|j#                  ||       y )Nr   r   r   r   )100502010rF  r`   r(  rq   rr   r   increaser   r   r   ra   rg   depthswayr\  r  r  r  vol)r   r   r~   r}   r   r|   r   r  r  rm   r3  
orderbooks
order_bookresetr  r   r   r   r_  r   r   r/  r   r  )!r[   r   r   r   datasorderBookEntryr   r   limitsToCheckr   r   limitStringrp   updater   rq   obr  rr   r   rv   messageHashForMulti
tablePartsr   r  r  r  r:   r  r!  orderbookSide
bidsLength
asksLengths!                                    r]   handle_order_bookzbitmart.handle_order_book  s   H W$NN7FE:E!^^GV<N)^,UQ;(('7C6q#m,- 	A'*K,1))+6		
 !))'26G1c%j) ?q++FH=))(3$//1U3B#)BxL.0DOOF+ OOF3	''7J&0@0@0LPQ0QOOB'..vvyI --ff=	[)1-6Ik*,0LL,CIj))C/(:y+6&-mf&<#y*=>+?. %**3/J m++J;G8D(^F''h7H%%h/Fdoo-__R/%8*,'/I##D%0C!Qh6VDax"&r5/	$"&r5/	$1c&k* 3q	((8))%7 $	4 @##E623 Yv./JYv./JaZ1_))$7I%.Ik"$(LL$;Ij!%KNN9k2")C-&"8NN9&9:r^   c                   K   | j                          d{    d}| j                  d|||      \  }}}d}| j                  |ddd      \  }}|dk(  r|dk(  rd}| j                  ||||       d{   }|j	                         S 7 o7 w)a  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://developer-pro.bitmart.com/en/spot/#public-depth-increase-channel

        :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 str [params.depth]: the type of order book to subscribe to, default is 'depth/increase100', also accepts 'depth5' or 'depth20' or depth50
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        Nr+   r:   r;   r7   r  )r   r   r   r   r   )r[   rw   r   rs   rr   rp   r  s          r]   watch_order_book_for_symbolsz$bitmart.watch_order_book_for_symbolsm  s      !!! $ @ @A[]dfkms tv77@Z\cexy6>g)<<G11'4&QQ	   	" Rs"   B
BAB
1B2B
B
c                   K   | j                          | j                  | j                  d   d   |   d         }d}| j                  |      }|j	                  |      }| j                  |j                  |      }|t        | j                               }| j                  }	d}
|dz   |	z   dz   |
z   }| j                  | j                  |      | j                  | j                        t        j                        }d }|dk(  rd| j                  ||gd	}nd
| j                  ||dgd}| j!                  ||      }| j#                  ||||       | d {   S 7 w)Nr3   r%   r5   authenticatedzbitmart.WebSocket#r6   loginrd   accesswebri   )check_required_credentialsrl   rU   r   r   r   r   strmillisecondsuidhmacencodesecrethashlibsha256apiKeyr   ro   )r[   rr   rs   rt   rv   r   r   r  r   memopathauth	signatureru   r   s                  r]   r   zbitmart.authenticate  sS    '')##DIIe$4T$:4$@$KL%S!{+(<(<kJ D--/0I88D&Ds?T)C/$6D		$++d"3T[[5Mw~~^IGv~!!! '!!	 kk'62GJJsK+>||s   EEEEc                     |S N )r[   r   r   s      r]   handle_subscription_statusz"bitmart.handle_subscription_status  s	     r^   c                 b    d}| j                  |j                  |      }|j                  d       y )Nr  T)r   ry   r   )r[   r   r   rv   r   s        r]   handle_authenticatezbitmart.handle_authenticate  s)     &=tr^   c                 d   | j                  |d      }| j                  |d      }	 ||| j                  dz   | j                  |      z   }| j                  | j                  d   ||       | j                  |d|      }| j                  | j                  d   ||       | j                  |d      }|dk(  rt        |      t        |      y	# t        $ rZ}t        |t              r/d
}	|j                  ||	       |	|j                  v r|j                  |	= |j                  |       Y d }~yd }~ww xY w)N	errorCodeerrorr   exactr   broadrj   r  Fr  T)rm   rb   jsonthrow_exactly_matched_exception
exceptionsr   throw_broadly_matched_exceptionr   r   	Exceptionr   rejectr   )
r[   r   r   r  r  feedbackmessageStringrj   erv   s
             r]   handle_error_messagezbitmart.handle_error_message  s)    $$Wk:	  '2	$(977S=499W+==44T__W5MyZbc $E J44T__W5M}^fg))'8<X%-h77#H-- 	112-a-&"6"66,,[9MM!	s   B%C 	D/AD**D/c           	         | j                  ||      ry d|v }|sY| j                  |dd      }|C| j                  | j                  | j                  d}| j	                  ||      }|
 |||       y y y | j                  |dd      }| j
                  | j                  | j                  | j                  | j                  | j                  | j                  | j                  d}t        |j                               }t        dt        |            D ]7  }	||	   }
|j!                  |
      dk\  s| j	                  ||
      } |||       9 y )	Nr   eventrj   )r  r  rc   r   r   )r:   r   r   r  r  rc  r   assetr   )r  r   r  r  r   r  r  r  r  r  rf  r   r   r  r|   r}   r   )r[   r   r   isDataUpdater!  methodsmethodrp   r  r   keys              r]   handle_messagezbitmart.handle_message  sT   $$VW5^ ')&&wBE  "55"66!%!@!@	! %8%67+ & ! (('7CG//,,****++ 11..,,	G 'D1c$i( ,1g<<$)!__Wc:F67+	,r^   r  )>__name__
__module____qualname__r	   rZ   rc   r  r   r   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  dictr   r
  r6  r5  r   rZ  rf  r]  r  r  r  r  r  r   r  r  r   r  r  r  r  r  r  r   r  r  r  r'  __classcell__)r\   s   @r]   r   r      su   O# Ob =? b. TX`b r r3 r r. *, #b #bJ
  
 >>8V >8@ <@d[] S SS S Sbfglbm S OSaenp d3i  [^ uyz  vA 8 ]aik -c -DI -VY - 68  F   6:" E7 E E, 8<B $FW $F7 $FL0V 0"  04$UYbd +Z +ZC +Zs +Zimnsit +ZZM/F M/^}D }& }~>7 8<$]ajl YW YC YWZ Yquv~q Y<72v 72r5& 5n/?6 /?b8D 8& 8t00F 00d'6 'R 8<$]ajl H HC HWZ Hquvzq{ H>T,6 T,l @DB !S ! !S\ !4&
3 BS; S;j SW_a !$s) !C !fo !, /1 #J 	& 	 6  DO,V O,r^   r   )"ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   r   r   *ccxt.async_support.base.ws.order_book_sider   r   r  ccxt.base.typesr	   r
   r   r   r   r   r   r   r   r   r   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   r   async_supportr   r  r^   r]   <module>r6     sQ     A  A A  x x x x 4  * 0 )X,d  (( X,r^   