
    i                         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 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)AsksBids)BalancesIntMarketOrder	OrderBookPositionStrStringsTickerTickersTrade)Client)List)ExchangeError)AuthenticationError)ArgumentsRequired)NotSupportedc            
           e Zd Z 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ddi fdedededee         fdZd
e
fdZd3d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"d3defdZ#d
e
fd Z$d! Z%d3defd"Z&d
e
fd#Z'd3defd$Z(d%ddi fdedededee)         fd&Z*d
e
fd'Z+di fdedede,fd(Z-d) Z.d* Z/d
e
fd+Z0d
e
fd,Z1di fdee         dede,fd-Z2i fd.Z3d
e
fd/Z4d
e
fd0Z5d
e
fd1Z6d
e
fd2Z7 xZ8S )4bitmartc                 N   |                      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iidd
dddd idd id!d
id"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2id3          S )4NcreateOrderWsFeditOrderWsfetchOpenOrdersWsfetchOrderWscancelOrderWscancelOrdersWscancelAllOrdersWswsTwatchBalancewatchTickerwatchTickerswatchOrderBookwatchOrderBookForSymbolswatchOrderswatchTradeswatchTradesForSymbols
watchOHLCVemulated)watchPositionwatchPositionsapiz5wss://ws-manager-compress.{hostname}/api?protocol=1.1z6wss://ws-manager-compress.{hostname}/user?protocol=1.1)publicprivatez,wss://openapi-ws.{hostname}/api?protocol=1.1z-wss://openapi-ws.{hostname}/user?protocol=1.1)spotswapr4   )fetchBalanceSnapshotawaitBalanceSnapshotdepthdepth/increase100inflate1m3m5m15m30m45m1H2H3H4H1D1W1M)r;   r<   r=   r>   r?   r@   1h2h3h4h1d1wrG   )defaultTyper%   r(   r)   r$   
timeframes	keepAlivei:  )hasurlsoptions	streaming)deep_extendsuperr   describe)self	__class__s    V/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/pro/bitmart.pyrW   zbitmart.describe   s   gt 4 4 = = ? ?u $U 	
   !% $U d  t  !$ +D t t  (!" d#$ ","&'  , &]'_! !
 'U'V! !	 	  &,0,1! ! 0# 0- t     '" "H UOJB
 JB
 J J J	    c                 j  K   |                      |          }|                     | j        d         d         |         d                   }i }d }|dk    rd|z   dz   |d         z   }d|gd	}nd
|z   dz   |d         z   }d|gd}|                     |||                     ||          |           d {V S )Nr1   r$   r2   r4   spot/:id	subscribeopargsfutures/actionrc   )marketimplode_hostnamerR   watchrU   )	rX   channelsymboltypeparamsrg   urlrequestmessageHashs	            rZ   r`   zbitmart.subscribeb   s      V$$##DIe$4T$:4$@$JKK6>>!G+c1F4L@K!$ GG
 %w.4vd|CK%$ G ZZ[$2B2B7F2S2SU`aaaaaaaaar[   Nrj   rl   symbolsc                 t  K   |                      ||dd          }|                     | j        d         d         |         d                   }|dk    rdnd}|dk    rdnd	}g }g }	t          d
t	          |                    D ]g}
|                     ||
                   }|dz   |z   dz   |d         z   }|                    |           |	                    |dz   |d         z              h|dk    r|dk    r	|dz   |z   g}d|i}d||<   |                     ||	|                     ||          |           d {V S )NFTr1   r$   r2   r4   futuresrb   rf   r   /r^   r_   rk   tickerrc   r`   )	market_symbolsrh   rR   rangelenrg   appendwatch_multiplerU   )rX   rj   rl   rq   rm   rn   channelType
actionTyperawSubscriptionsmessageHashesirg   messagero   s                 rZ   subscribe_multiplezbitmart.subscribe_multipleu   s~     %%gtUDAA##DIe$4T$:4$@$JKK!%ffi"fnnTT8
q#g,,'' 	C 	CA[[,,F!C''1C7&,FG##G,,,  31A!ABBBBFNNH!4!4 +c 1G ;<$
 *
((mT=M=MgW]=^=^`pqqqqqqqqqr[   returnc                   K   |                                   d{V  d}|                     dd|          \  }}|                     ||           d{V  i }|dk    rddgd}ndg dd}d	|z   }|                     | j        d
         d         |         d                   }|                     |          }|                     |||           d}d}|                     | j        ddd          \  }}|                     | j        ddd          \  }}|r |r|	                    |dz              d{V  | 
                    |||                     ||          |           d{V S )a  
        :see: https://developer-pro.bitmart.com/en/spot/#private-balance-change
        :see: https://developer-pro.bitmart.com/en/futures/#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>`
        Nr4   r%   r`   z spot/user/balance:BALANCE_UPDATEra   )zfutures/asset:USDTzfutures/asset:BTCzfutures/asset:ETHre   balance:r1   r$   r3   r6   Tr7   Fz:fetchBalanceSnapshot)load_marketshandle_market_type_and_paramsauthenticaterh   rR   clientset_balance_cachehandle_option_and_paramsrS   futureri   rU   )	rX   rm   rl   ro   rp   rn   r   r6   r7   s	            rZ   watch_balancezbitmart.watch_balance   s      !!!!!!!!!99.$PVWWff---------6>>!;< GG &XXX G !4'##DIe$4T$:4$@$KLLS!!vt[999##'+'D'DT\Sacy{  (A  (A$f'+'D'DT\Sacy  |A  (B  (B$f 	@$8 	@--'> >?????????ZZ[$2B2B7F2S2SU`aaaaaaaaar[   r   c                    ||j         v rd S |                     | j        d          }|                     |dd          }|rC|dz   dz   }||j        vr2|                    |           |                     | j        |||           i | j        |<   d S )Nr%   r6   Tr^   )	subscriptions
safe_valuerS   	safe_boolrs   r   spawnload_balance_snapshotbalance)rX   r   rl   subscribeHashrS   snapshotrp   s          rZ   r   zbitmart.set_balance_cache   s    F000F//$,??>>'+A4HH 	R*'==K6>11k***

45v{DQQQTr[   c                 >  K   |                      d|i           d {V }|                     ||                     | j        |i                     | j        |<   |j        |         }|                                 |                    | j        |         d|z              d S )Nrl   r   )fetch_balanceextendr   r   rs   resolve)rX   r   rp   rl   responser   s         rZ   r   zbitmart.load_balance_snapshot   s      ++VTN;;;;;;;;![[4??4<QUWY3Z3Z[[T,t|D):+<=====r[   c                    |                      |dd          }|                     |d          }|d S |                    d          dk    }|rdnd}|| j        |         d<   |rIt	          |t
                    sd S t          dt          |                    D ]}|                     |d          }|| j        |         d	<   | 	                    |          | j        |         d
<   |                     ||         dg           }	t          dt          |	                    D ]}
|	|         }| 
                                }|                     |d          }|                     |          }|                     |d          |d<   |                     |d          |d<   || j        |         |<   n|                     |d          }|                     |          }| 
                                }|                     |d          |d<   |                     |d          |d<   || j        |         |<   |                     | j        |                   | j        |<   d|z   }|                    | j        |         |           d S )Ntablegroupdatar4   r   r5   info
event_time	timestampdatetimebalance_detailsccyav_balfreefz_balusedcurrencyavailable_balancefrozen_balancer   )safe_string_2r   findr   
isinstancelistrw   rx   safe_integeriso8601accountsafe_stringsafe_currency_codesafe_balancer   )rX   r   r   rj   r   isSpotrl   r   r   balanceDetailsii
rawBalancer   
currencyIdcoderp   s                   rZ   handle_balancezbitmart.handle_balance   s   < $$Wgw??w//<F,,v&&!++vvV%,T6" 	/dD)) 1c$ii(( 7 7 --g|DD	2;T";/15i1H1HT":.!%a:KR!P!P3~#6#677 7 7B!/!2J"llnnG!%!1!1*e!D!DJ22:>>D&*&6&6z8&L&LGFO&*&6&6z8&L&LGFO/6DL&t,,77 ))$
;;J**:66DllnnG"..t5HIIGFO"..t5EFFGFO'.DLt$!..t|D/ABBT 4't|D);77777r[   rk   sincelimitc                 D   K   |                      |g|||           d{V S )a{  
        :see: https://developer-pro.bitmart.com/en/spot/#public-trade-channel
        :see: https://developer-pro.bitmart.com/en/futures/#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)rX   rk   r   r   rm   s        rZ   watch_tradeszbitmart.watch_trades  s6       22F8UE6RRRRRRRRRr[   c                 z  K   |                                   d{V  d}|                     d|||          \  }}}d}|                     ||||           d{V }| j        rB|                     |d          }|                     |d          }	|                    |	|          }|                     |||dd          S )a+  
        :see: 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   rk   r   T)r   get_params_for_multiple_subr   
newUpdates	safe_dictr   getLimitfilter_by_since_limit)
rX   rq   r   r   rm   
marketTypechannelNametradesfirsttradeSymbols
             rZ   r   z bitmart.watch_trades_for_symbols  s       !!!!!!!!!
&*&F&FG^`ginpv&w&w#V..{JQWXXXXXXXX? 	8NN61--E**5(;;KOOK77E))&%TRRRr[   
methodNamec                    |                      |d dd          }t          |          }|dk    rt          | j        dz   |z   dz             |                     |d                   }d }|                     |||          \  }}|||gS )NFT    z1() accepts a maximum of 20 symbols in one requestr   )rv   rx   r   r_   rg   r   )rX   r   rq   r   rm   lengthrg   r   s           rZ   r   z#bitmart.get_params_for_multiple_sub$  s    %%gtUDAAWB;;tw}z9<oopppWQZ((
!??
FTZ[[
FV,,r[   c                    K   |                                   d{V  |                     |          }|                     |g|           d{V }||         S )a  
        :see: https://developer-pro.bitmart.com/en/spot/#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   rk   watch_tickers)rX   rk   rm   tickerss       rZ   watch_tickerzbitmart.watch_ticker.  sp       !!!!!!!!!V$$**F8V<<<<<<<<vr[   c                 <  K   |                                   d{V  |                     |          }d}|                     d||          \  }}|                     d|||           d{V }| j        ri }|||d         <   |S |                     | j        d|          S )a  
        :see: https://developer-pro.bitmart.com/en/futures/#overview
        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'   ru   rk   )r   get_market_from_symbolsr   r   r   filter_by_arrayr   )rX   rq   rm   rg   r   ru   r   s          rZ   r   zbitmart.watch_tickers;  s       !!!!!!!!!--g66
!??PVX^__
F..xWfUUUUUUUU? 	G(.GF8$%N##DL(GDDDr[   c                   K   |                                   d{V  d}d}|/|                     |          }|                     |          }d|z   }d}|                     d||          \  }}|                     ||           d{V  d}|dk    r)|t          | j        dz             dd|d	         z   gd
}nddgd}|                     | j        d         d         |         d                   }	| 	                    |	|| 
                    ||          |           d{V }
| j        r|
S |                     | j        |||d          S )a  
        :see: https://developer-pro.bitmart.com/en/spot/#private-order-channel
        :see: https://developer-pro.bitmart.com/en/futures/#private-order-channel
        watches information on multiple orders made by the user
        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Norderszorders::r4   r*   z: watchOrders() requires a symbol argument for spot marketsr`   zspot/user/order:r_   ra   zfutures/orderre   r1   r$   r3   T)r   rk   rg   r   r   r   r_   rh   rR   ri   rU   r   filter_by_symbol_since_limitr   )rX   rk   r   r   rm   rg   rp   rl   ro   rn   	newOrderss              rZ   watch_orderszbitmart.watch_ordersN  s      !!!!!!!!![[((F[[((F$v-K99-QWXXff---------6>>~'2n(nooo!+fTl:; GG &() G ##DIe$4T$:4$@$KLL**S+t7G7GQW7X7XZeffffffff	? 	00feUTXYYYr[   c                    |                      |d          }|d S t          |          }g }i }|dk    r|                     | j        dd          }| j        t          |          | _        | j        }t          dt          |                    D ]T}	|                     ||	                   }
|                    |
           |                    |
           |
d         }d||<   Ud}t          |
                                          }t          dt          |                    D ](}	||	         }|dz   |z   }|                    ||           )|                    ||           d S )	Nr   r   ordersLimit  rk   Tr   ::)r   rx   r   rS   r   r   rw   parse_ws_orderry   r   keysr   )rX   r   r   r   ordersLengthr   rq   r   storedr   orderrk   rp   
symbolKeyssymbolSpecificMessageHashs                  rZ   handle_orderszbitmart.handle_ordersv  so   l &11>F6{{	!%%dlM4HHE{"4U;;[F1c&kk** ' '++F1I66e$$$  '''x"&',,..))
q#j//** 	A 	AA]F(3d(:V(C%NN9&?@@@@y+.....r[   rg   c                 v   |                      |d          }|d u }|ri|                     |d          }|                     ||dd          }|                     |d          }|                     |d          }|                     |d          }|                     |d          }	|                     |d	          }
|                     |d
          }|                     |d          }|                     |d
         |          }|                     |d          }|d         }|                     |d          }|                     i d|d|d|d|dd dd d|d
|dd dd d|d|dd dd d|
dd dd |	d |d d d|          S |                     |d          }|                     |d          }|                     ||dd          }|                     |d          }|                     |d          }|                     |d           }|                     |d!          }| j	        }|                     |j
        |i           }|                     ||          }d }||                     |d"          }||g }|                    |           |                     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 )&Nrf   rk   _r4   order_id	clientOidpricefilled_sizesizerl   statems_tsider   r_   clientOrderIdr   r   lastTradeTimestamptimeInForcepostOnly	stopPricetriggerPriceamountcostaverage)filled	remainingstatusfeer   r    r5   create_timeupdate_time
last_trader   client_order_iddeal_avg_price	deal_size)safe_numberr   safe_marketparseOrderStatusByTyper   safe_string_lower
safe_orderr   safe_symbolr   hashmapry   r   parse_ws_order_sideparse_ws_order_status)rX   r   rg   rf   r   marketIdr_   r   r   r   r   rl   rawStater   r   rk   r   	orderInfoorderIdupdatedTimestamp	lastTradecachedOrdersr   cachedOrderr   s                            rZ   r   zbitmart.parse_ws_order  s   X !!%22D. O	''x88H%%hVDDF!!%44B ,,UK@@M$$UG44E%%e];;F%%eV44F##E622D''w77H00JJF))%88IH%F))%88D?? $$&$ b$  	$
 T$ D$ %i$ $ t$ D$ $ $ T$ $ &$  !$" 4#$$ !! -$ $ $. /  2 w77I''	8<<H%%hFCCF&&y*==G)))]CCI#00MJJ	<@@I;L__\%962FFF//&'::KF&99$>Fi(((?? $$&$ g$  !1!1)=N!O!O	$
 Y$ DLL33$ %&6$ ((F;;$ t$ D$ 001A1A)V1T1TUU$ )))W==$ T$ $ $**9f==$  !$" 4++I7GHH#$$ **9kBB!44T5E5EeX5V5VWW -$ $ $. /  r[   c           
      H    dddddddddd	}|                      |||          S )Nclosedopencanceled)	123456789r   )rX   statusIdstatusess      rZ   r  zbitmart.parse_ws_order_statusD  sC    

 

 (H===r[   c                 >    ddddd}|                      |||          S )Nbuysell)r  r  r   r!  r'  )rX   sideIdsidess      rZ   r  zbitmart.parse_ws_order_sideR  s4    	
 
 vv666r[   c                 
  K   |                                   d{V  d}|                     ||           d{V  |                     |dddd          }d}||dd                    |          z   z  }d}d	dgd
}|                     | j        d         d         |         d                   }	|                     |	||                     ||          |           d{V }
| j        r|
S | 	                    | j
        |||          S )a  
        :see: https://developer-pro.bitmart.com/en/futures/#private-position-channel
        watch all open positions
        :param str[]|None symbols: list of unified market symbols
        :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>`
        Nr5   TF	positionsr   ,zfutures/positionr`   re   r1   r$   r3   )r   r   rv   joinrh   rR   ri   rU   r   filter_by_symbols_since_limitr0  )rX   rq   r   r   rm   rl   rp   subscriptionHashro   rn   newPositionss              rZ   watch_positionszbitmart.watch_positions[  sH      !!!!!!!!!f---------%%gvtT5II!4#((7"3"333K-!'(
 
 ##DIe$4T$:4$@$KLL!ZZ[$:J:J7TZ:[:[]mnnnnnnnn? 	 11$.'5RWXXXr[   c                    |                      |dg           }| j        t                      | _        | j        }g }t          dt	          |                    D ]I}||         }|                     |          }|                    |           |                    |           J|                     |d          }	t          dt	          |	                    D ]}|	|         }
|
                    d          }|d         }|                    d          }| 	                    |d|d          }| 
                    |          s|                    ||
           |                    |d	           d S )
Nr   r   zpositions::r      r1  rk   Fr0  )r   r0  r   rw   rx   parse_ws_positionry   find_message_hashessplitr   is_emptyr   )rX   r   r   r   cacher5  r   rawPositionpositionr~   rp   partssymbolsStringrq   r0  s                  rZ   handle_positionszbitmart.handle_positionsu  sj   H w33>!577DNq#d))$$ 	# 	#Aq'K--k::H)))LL""""00GGq#m,,-- 	7 	7A'*K%%d++E!!HM#))#..G,,\8WeTTI==++ 7y+666|[11111r[   c                    |                      |d          }|                     ||d d          }|d         }|                     |d          }|                     |d          }|                     |d          }|                     |d          }|                     i d|dd d|d	|d
|                     |          d|dd d|dk    rdn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k    rdndd d d d d           S )!Nrk   r5   r  r  position_type	open_typer   r_   r   r   lastUpdateTimestamphedgedr   r8  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)r   r
  r   r	  safe_positionr   )	rX   r?  rg   r  rk   openTimestampr   r   marginModeIds	            rZ   r9  zbitmart.parse_ws_position  s    " ##Hh77!!(FD&AA!))(MBB%%h>>	/::''+>>!! #
H#
$#
 f#
 	#

 ]33#
 "9#
 d#
 tqyyFFw#
 ))(MBB#
 D,,V^DD#
 $**85EFF#
 ))(4DEE#
 #
 #
 #
  $!#
" T##
$ (,!%+/! $ 0 0;L M M)5):):**!#9#
 #
 #
   	r[   c                 z   |                      |d          }|d S d }t          |          }d|v }|r7t          d|          D ]%}||z
  dz
  }|                     ||                   }&n.t          d|          D ]}|                     ||                   }|                    | j        |         d|z              d S )Nr   r   r   r8  ztrade:)r   rx   rw   handle_trade_loopr   r   )	rX   r   r   r   rk   r   isSwapr   indexs	            rZ   handle_tradezbitmart.handle_trade  s    F w//<FTW$ 	91f%% = =
Q//U<<=
 1f%% 9 9//Q88t{6*Hv,=>>>>>r[   c                     |                      |          }|d         }|                     | j        dd          }|                     | j        |          t          |          | j        |<   | j        |         }|                    |           |S )Nrk   tradesLimitr   )parse_ws_trader   rS   r   r   r   ry   )rX   entryr   rk   rm  r   s         rZ   rh  zbitmart.handle_trade_loop  s    ##E**x''mTJJ??4;//7",["9"9DKV$er[   c                    |                      |d          }|dnd}|dk    rdnd}|                     |d|                     |d                    }|                      |d          }|                     ||                      |d	          d ||                     |          |                     ||||          d |                      |d
          |                     |dd          |                     |dd          d d d d|          S )Ncontract_idr4   r5   r   r  create_time_mills_trk   trade_idr   r   
deal_pricer   deal_vol)r   r_   r   r   r   rk   rl   r   r   r   r   takerOrMakerr  )r   r   safe_timestamp
safe_trader   r  r   )rX   r   rg   
contractIdr   marketDelimiterr   r  s           rZ   rn  zbitmart.parse_ws_trade#  s)   . %%e];;
 * 2VV
","6"6##R%%e-?ATATUZ\aAbAbcc	##E844""5*55"Y//&&x*UU$$UF33''wEE((
CC  
  
   	r[   c                    |                      |d          }|d u}g }|r|                     |dg           }n|                     |di           g}t          |          sd S t	          dt          |                    D ]g}|r|                     ||                   n|                     ||                   }|d         }|| j        |<   d|z   }	|                    ||	           hd S )Nr   r   r   rk   zticker:)	r   	safe_listr   rx   rw   parse_tickerparse_ws_swap_tickerr   r   )
rX   r   r   r   r   
rawTickersr   ru   rk   rp   s
             rZ   handle_tickerzbitmart.handle_tickerO  s	   >   '22t#
 	@<<JJ//'62>>?J: 	Fq#j//** 	0 	0A9?mT&&z!}555TE^E^_ijk_lEmEmFH%F#)DL #f,KNN6;////	0 	0r[   c           
         |                      |d          }|                     i d|                     ||dd          dd dd dd dd d|                      |d	          d
|                      |d          d|                      |d          d|                      |d          dd dd dd d|                      |d          dd dd dd d|                      |d          d |                      |d          |d|          S )Nrk   r  r5   r   r   highlowbid	bid_price	bidVolumebid_volask	ask_price	askVolumeask_volvwapr  closelast
last_pricepreviousClosechanger`  r   
fair_price	volume_24)
baseVolumequoteVolumer   )r   safe_tickerr  )rX   ru   rg   r  s       rZ   r  zbitmart.parse_ws_swap_ticker~  s    ##FH55 !
d&&xVDD!
!
 !
 D	!

 4!
 4##FK88!
 ))&)<<!
 4##FK88!
 ))&)<<!
 D!
 D!
 T!
 D$$V\::!
 T!
 d!
  $!!
" t''==#!
$ ++FK@@)!
 !
 !
* +  	r[   r;   c                   K   |                                   d{V  |                     |          }|                     |          }d}|                     d||          \  }}|                     | j        di           }|                     ||          }	d}
|dk    rd|	z   }
nd|	z   }
|                     |
|||           d{V }| j        r|	                    ||          }| 
                    |||dd          S )	a  
        :see: https://developer-pro.bitmart.com/en/spot/#public-kline-channel
        :see: https://developer-pro.bitmart.com/en/futures/#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
        Nr4   r(   rO   klineklineBinr   T)r   rk   rg   r   r   rS   r   r`   r   r   r   )rX   rk   	timeframer   r   rm   rg   rl   rO   intervalnameohlcvs               rZ   watch_ohlcvzbitmart.watch_ohlcv  s"      !!!!!!!!!V$$V$$99:JFTZ[[f__T\<DD
##J	::6>>X%DD(DnnT64@@@@@@@@? 	2NN6511E))%q$GGGr[   c                 ~   |                      |dd          }|                    d          dk    }|                     |d          }|d S |                    d          }|                     |dd          }|                    d	d          }|                    d
d          }|                    d          }	|                     |	d          }|                     | j        di           }
|                     ||
          }|                     |          }|dz  }|rht          dt          |                    D ]G}|                     ||         d          }|                     |          }|d         }|                     ||         d          }|                     ||          }|                     |d         |z            |z  |d<   |                     | j        |i           | j        |<   |                     | j        |         |          }|;|                     | j        dd          }t!          |          }|| j        |         |<   |                    |           |dz   |z   }|                    ||           Id S |                     |d          }|                     |d d d          }|d         }|                     |dg           }|                     | j        |i           | j        |<   |                     | j        |         |          }|;|                     | j        dd          }t!          |          }|| j        |         |<   t          dt          |                    D ]5}||         }|                     ||          }|                    |           6|                    ||           d S )Nr   r   r4   r   r   rt   r8  r  r  Binr^   rO   r   rk   candle
OHLCVLimitr5   items)r   r   r   r;  r   replacerS   find_timeframeparse_timeframerw   rx   r
  parse_ohlcvparse_to_intohlcvsr   r   ry   r   )rX   r   r   rj   r   r   r@  part1r  intervalPartsrO   r  durationdurationInMsr   r  rg   rk   rawOHLCVparsedr   r   rp   r  r  s                            rZ   handle_ohlcvzbitmart.handle_ohlcv  s   H $$Wgw??,,v&&!+w//<Fc""  2..=="--##E2.. s++##M155__T\<DD
''*==	''	22$  	,1c$ii(( 4 4++DGX>>))(33)??47H==))(F;; --fQi,.FGG,Vq	&*oodk62&N&NF#V)<iHH> --dlL$OOE2599F5;DK'	2f%%%%mh6v{33334 4" ''h77H%%hdFCCFH%FOOD'266E"&//$+vr"J"JDK__T[%8)DDF~))$,dKK.u5517F#I.1c%jj)) & &q))&&99f%%%%NN67+++++r[   c                   K   |                                   d{V  |                     | j        di           }|                     |dd          }|                     |          }|                     |          }d}|                     d||          \  }}|dk    r|dk    rd}|                     ||||           d{V }|                                S )a  
        :see: https://developer-pro.bitmart.com/en/spot/#public-depth-all-channel
        :see: https://developer-pro.bitmart.com/en/spot/#public-depth-increase-channel
        :see: https://developer-pro.bitmart.com/en/futures/#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
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        Nr(   r8   r9   r4   r5   depth50)	r   r   rS   r   rk   rg   r   r`   r   )	rX   rk   r   rm   rS   r8   rg   rl   	orderbooks	            rZ   watch_order_bookzbitmart.watch_order_book  s       !!!!!!!!!//$,0@"EE  '3FGGV$$V$$99:JFTZ[[f6>>e':::E..fEEEEEEEE	   r[   c                     |                      |d          }|                      |d          }|                    ||           d S )Nr   r8  )
safe_floatstore)rX   booksidedeltar   r   s        rZ   handle_deltazbitmart.handle_delta-  sB    q))**uf%%%%%r[   c                 ~    t          dt          |                    D ]}|                     |||                    d S )Nr   )rw   rx   r  )rX   r  deltasr   s       rZ   handle_deltaszbitmart.handle_deltas2  sH    q#f++&& 	3 	3Ahq	2222	3 	3r[   c                    |                      |dg           }|                      |dg           }|                     |d         |           |                     |d         |           |                     |d          }|                     |d          }|                     |          }||d<   ||d<   |                     |          |d<   |S )Nasksbidsr   rk   r   r   )r}  r  r   r   r  r   )	rX   r   r   r  r  r  r   r  rk   s	            rZ   handle_order_book_messagez!bitmart.handle_order_book_message6  s    * ~~gvr22~~gvr229V,d3339V,d333%%gv66	##GX66!!(++$	(!*	+ $Y 7 7	*r[   c                    d|v }g }|r|                      |d|          }n-|                     |d          }||                    |           t          |          }|dk    rd S |                     |dd          }g d}d}	t          dt          |                    D ]:}
||
         }|                    |          dk    r|                     |          }	 n;|r|                    dd          }t          dt          |                    D ]I}
||
         }| 	                    |d          }| 
                    |          }|| j        vr%|                     i |	          }||d<   || j        |<   | j        |         }| 	                    |d	          }|d
k    s|                    d          dk    s|                    i            |                     |||           |                     |d          }|d         ||d<   |                     |          |d<   |dz   |z   }|                    ||           |dz   |z   }|                    ||           Kd S |                    d          }|d                             dd          }|d         }|d         }| 	                    |d          }| 
                    |          }|| j        vr%|                     i |	          }||d<   || j        |<   | j        |         }|                     |d          }|dk    rdnd}|dk    rt)          g |	          ||<   nt+          g |	          ||<   t          dt          |                    D ]b}
||
         }|                     |d          }|                     |d          }|                     ||          }|                    ||           ct          |d                   }t          |d                   } |dk    s| dk    rd S |                     |d          }||d<   |                     |          |d<   |}|                    ||           |dz   |z   }|                    ||           d S )Nr   r   r   r   )100502010r"  r]   r  rk   rl   r   increaser   r   r   r^   rd   depthswayr8  r  r  r   vol)r}  r   ry   rx   r   rw   r   r  r  r   r  
orderbooks
order_bookresetr  r   r   r   r;  r	  r   r   r   r  )!rX   r   r   r   datasorderBookEntryr   r   limitsToCheckr   r   limitStringrj   updater  rk   obr  rl   r   rp   messageHashForMulti
tablePartsr   r  r  r   r8   r   r   orderbookSide
bidsLength
asksLengths!                                    rZ   handle_order_bookzbitmart.handle_order_bookW  s   H W$ 	-NN7FE::EE!^^GV<<N)^,,,UQ;;F(('7CC666q#m,,-- 	 	A'*K,,11))+66 2  ;	;!))'266G1c%jj)) ? ?q++FH==))(33$/11U33B#)BxL.0DOF+ OF3	''77J&&0@0@0L0LPQ0Q0QOOB'''..vvyIII --ff==	[)1-6Ik*,0LL,C,CIj))C/(:y+666&-mf&<#y*=>>>>+? ?. %**3//J m++J;;G8D(^F''h77H%%h//Fdo--__R//%8*,'/I""4//C!Qhh66VDaxx"&r5//	$"&r5//	$1c&kk** 3 3q	((88))%77 $	4 @ @##E62222Yv.//JYv.//JaZ1__))$77I%.Ik"$(LL$;$;Ij!%KNN9k222")C-&"8NN9&9:::::r[   c                 0  K   |                                   d{V  d}|                     d|||          \  }}}d}|                     |ddd          \  }}|dk    r|dk    rd}|                     ||||           d{V }|                                S )a  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: 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)   r8   r9   r5   r  )r   r   r   r   r   )rX   rq   r   rm   rl   rj   r  s          rZ   watch_order_book_for_symbolsz$bitmart.watch_order_book_for_symbols  s       !!!!!!!!! $ @ @A[]dfkms t tv77@Z\cexyy6>>g)<<<G11'4&QQQQQQQQ	   r[   c                   K   |                                   |                     | j        d         d         |         d                   }d}|                     |          }|                    |          }|                     |j        |          }|t          |                                           }| j	        }	d}
|dz   |	z   dz   |
z   }| 
                    |                     |          |                     | j                  t          j                  }d }|dk    rd| j        ||gd	}nd
| j        ||dgd}|                     ||          }|                     ||||           | d {V S )Nr1   r$   r3   authenticatedzbitmart.WebSocket#r4   loginra   accesswebre   )check_required_credentialsrh   rR   r   r   r   r   strmillisecondsuidhmacencodesecrethashlibsha256apiKeyr   ri   )rX   rl   rm   rn   rp   r   r   r  r   memopathauth	signaturero   r   s                  rZ   r   zbitmart.authenticate   s     '')))##DIe$4T$:4$@$KLL%S!!{++(<kJJ D--//00I8D&Ds?T)C/$6D		$++d"3"3T[[5M5Mw~^^IGv~~!!!  '!!	  kk'622GJJsK+>>>||||||r[   c                     |S N )rX   r   r   s      rZ   handle_subscription_statusz"bitmart.handle_subscription_status%  s	     r[   c                 j    d}|                      |j        |          }|                    d           d S )Nr  T)r   rs   r   )rX   r   r   rp   r   s        rZ   handle_authenticatezbitmart.handle_authenticate+  s6     &==tr[   c                    |                      |d          }|                      |d          }	 ||| j        dz   |                     |          z   }|                     | j        d         ||           |                     |d|          }|                     | j        d         ||           |                      |d          }|dk    rt          |          t          |          d	S # t          $ r^}t          |t                    r)d
}	|                    ||	           |	|j        v r|j        |	= |                    |           Y d }~dS d }~ww xY w)N	errorCodeerrorr   exactr   broadrf   r  Fr  T)r   r_   jsonthrow_exactly_matched_exception
exceptionsr   throw_broadly_matched_exceptionr   r   	Exceptionr   rejectr   )
rX   r   r   r  r  feedbackmessageStringrf   erp   s
             rZ   handle_error_messagezbitmart.handle_error_message6  ss    $$Wk::	  '22	$(97S=499W+=+==44T_W5MyZbccc $E J J44T_W5M}^fggg))'8<<X%%-h777#H---5 	 	 	1122 :-a---&"666,[9MM!44444	s   B9C) )
E3AEEc           	         |                      ||          rd S d|v }|sX|                     |dd          }|;| j        | j        | j        d}|                     ||          }| |||           d S d S d S |                     |dd          }| j        | j        | j        | j        | j	        | j
        | j        | j        d}t          |                                          }t          dt          |                    D ]E}	||	         }
|                    |
          dk    r"|                     ||
          } |||           Fd S )	Nr   eventrf   )r  r  r`   r   r   )r8   ru   r   r  r   r?  r   assetr   )r  r   r  r  r   r  r  rk  r  r   rB  r   r   r   rw   rx   r   )rX   r   r   isDataUpdater  methodsmethodrj   r   r   keys              rZ   handle_messagezbitmart.handle_messageX  s   $$VW55 	F^ ') 	,&&wBBE  "5"6!%!@	  %88%F67+++++ !  &% (('7CCG/,**+ 1.,	 	G ''D1c$ii(( , ,1g<<$$))!__Wc::FF67+++	, ,r[   r  )9__name__
__module____qualname__rW   r`   r  r   r   r	   r   r   r   r   r   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r6  rB  r9  rk  rh  rn  r  r  r   r  r  r   r  r  r  r  r  r  r   r  r  r  r  __classcell__)rY   s   @rZ   r   r      s       K K K K KZ =? b b b b& TX`b r r r3 r r r r r* *, !b !b !b !b !b !bF
  
  
  
  
 > > >>8V >8 >8 >8 >8@ <@d[] S S SS S Sbfglbm S S S S OSaenp S Sd3i S S[^ Suyz  vA S S S S* ]aik - -c -DI -VY - - - - 68   F     6:" E E7 E E E E E& 04$UYbd &Z &Z &ZC &Zs &Zimnsit &Z &Z &Z &ZPM/F M/ M/ M/ M/^} }F } } } }~> > >7 7 7 8<$]ajl Y YW YC YWZ Yquv~q Y Y Y Y472v 72 72 72 72r5 5& 5 5 5 5n2?6 2? 2? 2? 2?h  * *F * * * *X-0F -0 -0 -0 -0^# #6 # # # #J 8<$]ajl H H HC HWZ Hquvzq{ H H H H:T,6 T, T, T, T,l @DB ! !S ! !S\ ! ! ! !.& & &
3 3 3    BS; S; S; S; S;j SW_a ! !$s) !C !fo ! ! ! !( /1 # # # #J    	& 	 	 	 	 6        DO,V O, O, O, O, O, O, O, 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   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   r   r   async_supportr   r  r[   rZ   <module>r     sz       A  A  A  A  A  A  A  A  A  A  A  A A A A A A A A A  s s s s s s s s s s s s s s s s s s s s s s s s s s 4 4 4 4 4 4       * * * * * * 0 0 0 0 0 0 . . . . . . ) ) ) ) ) )T, T, T, T, T,d ( T, T, T, T, T,r[   