
    !:hN                       d dl mZ d dlmZ d dlZd dlZd dlmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z# d dl$m%Z% d dl&m'Z' d dl&m(Z( d dl&m)Z) d d	l&m*Z* d d
l&m+Z+ d dl&m,Z, d dl&m-Z- d dl&m.Z. d dl&m/Z/ d dl&m0Z0 d dl&m1Z1 d dl&m2Z2 d dl&m3Z3 d dl4m5Z5 d dl6m7Z7  G d dee      Z8y)    )Exchange)ImplicitAPIN)AccountAnyBalances
CurrenciesCurrencyDepositAddress	IndexTypeIntLeverageLeverageTierLeverageTiersMarginModificationMarketNumOrder	OrderBookOrderRequest	OrderSide	OrderTypePositionStrStringsTickerTickersFundingRateTradeTradingFeeInterfaceTransactionTransferEntry)List)ExchangeError)AuthenticationError)PermissionDenied)AccountSuspended)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidAddress)InvalidOrder)NotSupported)OnMaintenance)InvalidNonce)	TICK_SIZE)Precisec                       e Zd Zdef fdZi fdZi fdefdZi fdefdZ	i fde
e   fdZi fdZi fdZd	i fd
ededefdZddededefdZd	d	i fd
ededede
e   fdZddededefdZddZdd	d	i fd
ededede
e   fdZddedefdZd	i fdedefdZi fd
edefdZ ddededefdZ!d	i fdefdZ"i fd
ed e#fd!Z$i fd
ed e#fd"Z%d	i fd
ed#e&d$e'd%e#d&e(f
d'Z)d	d	i fd(Z*d	d	i fd)Z+d	d	i fd*Z,i fd+e
e-   fd,Z.d	i fd-ed
e/fd.Z0d	d	d	i fd
e/dedede
e1   fd/Z2d	i fd
e/fd0Z3d	d	d	i fd
e/dedede
e1   fd1Z4d	d	d	i fd
e/dedede
e1   fd2Z5d	d	d	i fd
e/dedefd3Z6d	d	d	i fd
e/dedefd4Z7d	i fd-ed
e/fd5Z8d	i fd
e/fd6Z9d	i fd
e/fd7Z:dd8edede1fd9Z;d: Z<d; Z=d<e/fd=Z>d> Z?dd?e/fd@Z@dA ZAi fde
eB   fdBZCi fd
edeDfdCZEdeFfdDZGdE ZHi fdeFfdFZId	d	d	i fd
e/dedefdGZJd	d	d	i fd-ed
e/dedefdHZKi fd
efdIZLi fd
ed%e#deMfdJZNi fd
ed%e#deMfdKZOd	i fdLed
e/fdMZPd	d	d	i fd
e/dedefdNZQddedeRfdOZSi fd
edeRfdPZTi fd
edeRfdQZUd	d	d	i fd
e/dedefdRZVd	i fdedeWfdSZXddede
eY   fdTZZddUe[de\fdVZ]i fdWede
e\   fdXZ^i fdWede\fdYZ_i fdWede\fdZZ`d	d	d	i fdWe/dedede
ea   fd[Zbd	d	d	i fdWe/dedede
ea   fd\Zcdd]edUe[deafd^Zddd_Zei fd
efd`Zfd	i fdede
eg   fdaZhddbedefdcZid	i fd-edWe/dejfddZkd	d	d	i fdWe/dedede
ej   fdeZli fdWed%e#dfedgedejf
dhZmddiedUe[dejfdjZndk Zod<e/de/fdlZpd	i fdWed%e#dmedeafdnZqd	i fdoerd
e/fdpZsd	i fd
e/fdqZtd	i fdrefdsZuddtZvddUe[fduZwd	i fdrefdvZxddUe[fdwZyi fd
edezfdxZ{ddLededezfdyZ|i d	f fdz	Z}d	d	d	i fdededede
eg   fd{Z~d	i fd|ed
e/fd}Zd~ Zddi d	d	fdZdWedededededefdZ xZS )mexcreturnc                 b   | j                  t        t        |          i ddddddgddd	d
dddddi dd dddddddddddddddddddddddd ddddddd di d!dd"dd#dd$dd%dd&dd'dd(dd)dd*dd+d d,d d-dd.dd/dd0dd1di d2dd3dd4dd5dd6dd7d d8dd9dd:dd;dd<d d=dd>d d?dd@ddAdBdCdi dDddEddFddGddHddIddJddKddLddMddNddOd dPd dQddRddSddTdi dUddVdBdWddXddYddZdd[dd\dd]d d^dd_dd`ddad dbddcddddBdedBi dfddgddhddid djddkddlddmddnddoddpddqddrd dsdBdtddud dvddd dddddddd d ddwdxdydzdzd{d|d|d{d}d~d{ddidddgdgddddddddddddddddddii ddddddddddddddddddddddddddddddddddi dddddddddddddddddddddddddddddddddddddddddddd	i ddddddddddddddddddddddddddddddddddidddddddddd{di ddddddddddddddddddddddddddddddddii ddddddddddddddddddddddddړddddddddddddddi dddddddddddddddddddddddddddddddddd{ddddddddddd	iddddddddddddddddddddddddddd{dddddddddddddddddididdt        ddddd ddddddd
dd	dd| j                  d
      | j                  d
      didddddddddddddidddd dddddd	ddddddddddd
ddddd d d!d"d#i d$d%d&d'd(d)d*d+d dd,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAd/d/d/dBdCdDdEdFdGddddddddHddd dddddIddddddddJdKdLidddMd ddNdddddOdd ddddPddQdRdRddddSddQdRdRdRddddTdUdQidV	dWdXidXdddddHdddddddYd dddZdZd[d\diddddd]dddZdZddd^dddZd dZddd_dUd`ida	dWdbidWdbidd d ddcddi dedfdgdhdidjdkdldmdndodpdqdqdrdsdtdududtdvdwdxdydzdxd{d|d}d{d~ddddddddi dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        i dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        i dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        i dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        i dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        t        t        t        t        t        t        t        t        t        t        t        t        t        dܜt        t        t        t        t        t        t        t        t        t        t        dݜdޜ      S (  Nidr3   namezMEXC Global	countriesSC	rateLimit2   versionv3	certifiedTprohasCORSspotmarginswapfutureFoption	addMarginborrowCrossMarginborrowIsolatedMarginborrowMargincancelAllOrderscancelOrdercancelOrderscloseAllPositionsclosePositioncreateDepositAddresscreateMarketBuyOrderWithCostcreateMarketOrderWithCostcreateMarketSellOrderWithCostcreateOrdercreateOrderscreatePostOnlyOrdercreateReduceOnlyOrdercreateStopLimitOrdercreateStopMarketOrdercreateStopOrdercreateTriggerOrderdeposit	editOrderfetchAccountsfetchBalancefetchBidsAsksfetchBorrowInterestfetchBorrowRatefetchBorrowRateHistoriesfetchBorrowRateHistoryfetchBorrowRatesfetchBorrowRatesPerSymbolfetchCanceledOrdersfetchClosedOrderfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsfetchDepositWithdrawFeeemulatedfetchDepositWithdrawFeesfetchFundingHistoryfetchFundingIntervalfetchFundingIntervalsfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchIsolatedPositionsfetchL2OrderBookfetchLedgerfetchLedgerEntryfetchLeveragefetchLeveragesfetchLeverageTiersfetchMarginAdjustmentHistoryfetchMarginModefetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenInterestHistoryfetchOpenOrderfetchOpenOrders
fetchOrderfetchOrderBookfetchOrderBooksfetchOrdersfetchOrderTradesfetchPositionfetchPositionHistoryfetchPositionModefetchPositionsfetchPositionsHistoryfetchPositionsRiskfetchPremiumIndexOHLCVfetchStatusfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTradingLimitsfetchTransactionFeefetchTransactionFeesfetchTransactionsfetchTransfer)fetchTransfersfetchWithdrawalfetchWithdrawalsreduceMarginrepayCrossMarginrepayIsolatedMarginsetLeveragesetMarginModesetPositionModesignIntransferwithdrawurlszdhttps://user-images.githubusercontent.com/1294454/137283979-8b2a818d-8633-461b-bfca-de89e8c446b2.jpgzhttps://api.mexc.com)publicprivatez https://www.mexc.com/open/api/v2z)https://contract.mexc.com/api/v1/contractz(https://contract.mexc.com/api/v1/privater   z"https://api.mexc.com/api/v3/broker)rB   spot2contractbrokerzhttps://www.mexc.com/z&https://mexcdevelop.github.io/apidocs/zhttps://www.mexc.com/feez6https://www.mexc.com/register?inviteCode=mexc-1FQ1GNu1)logoapiwwwdocfeesreferralr   get   
      )pingtimeexchangeInfodepthtradeshistoricalTrades	aggTradesklinesavgPricezticker/24hrzticker/pricezticker/bookTickerzetf/infoorder   
openOrders   	allOrdersaccountmyTradestradeFeesub-account/listsub-account/apiKeyzcapital/config/getallzcapital/deposit/hisreczcapital/withdraw/historyzcapital/withdraw/addresszcapital/deposit/addresszcapital/transferzcapital/transfer/tranIdzcapital/transfer/internalz%capital/sub-account/universalTransferzcapital/convertzcapital/convert/listzmargin/loanzmargin/allOrderszmargin/myTradesmargin/openOrderszmargin/maxTransferablezmargin/priceIndexmargin/orderzmargin/isolated/accountzmargin/maxBorrowablezmargin/repayzmargin/isolated/pairzmargin/forceLiquidationReczmargin/isolatedMarginDatazmargin/isolatedMarginTierzrebate/taxQuery)	zrebate/detailzrebate/detail/kickbackzrebate/referCodezrebate/affiliate/commissionzrebate/affiliate/withdrawz"rebate/affiliate/commission/detailmxDeduct/enableuserDataStreamselfSymbolsz
order/testsub-account/virtualSubAccountsub-account/futureszsub-account/marginbatchOrderscapital/withdraw/applycapital/withdrawr   r   )r   r   r   r   r   r   r   )r   postputdeleter   detaild   support_currencieszdepth/{symbol}zdepth_commits/{symbol}/{limit}zindex_price/{symbol}zfair_price/{symbol}zfunding_rate/{symbol}zkline/{symbol}zkline/index_price/{symbol}zkline/fair_price/{symbol}zdeals/{symbol}tickerrisk_reversezrisk_reverse/historyzfunding_rate/historyzaccount/assetszaccount/asset/{currency}zaccount/transfer_recordzposition/list/history_positionszposition/open_positionszposition/funding_recordszposition/position_modezorder/list/open_orders/{symbol}zorder/list/history_ordersz&order/external/{symbol}/{external_oid}zorder/get/{order_id}zorder/batch_query   zorder/deal_details/{order_id}zorder/list/order_dealszplanorder/list/orderszstoporder/list/ordersz'stoporder/order_details/{stop_order_id})zaccount/risk_limitzaccount/tiered_fee_ratezposition/leveragezposition/change_marginzposition/change_leveragezposition/change_position_modezorder/submitzorder/submit_batch(   order/cancelzorder/cancel_with_externalzorder/cancel_allzaccount/change_risk_levelzplanorder/placezplanorder/cancelzplanorder/cancel_allzstoporder/cancelzstoporder/cancel_allzstoporder/change_pricezstoporder/change_plan_price)r   r   )	zmarket/symbolszmarket/coin/listzcommon/timestampzcommon/pingzmarket/tickerzmarket/depthzmarket/dealszmarket/klinezmarket/api_default_symbols)zaccount/infozorder/open_ordersz
order/listzorder/queryzorder/dealszorder/deal_detailzasset/deposit/address/listzasset/deposit/listzasset/address/listzasset/withdraw/listzasset/internal/transfer/recordzaccount/balancezasset/internal/transfer/infozmarket/api_symbols)zorder/placezorder/place_batchzorder/advanced/place_batchasset/withdrawzasset/internal/transfer)r   zorder/cancel_by_symbolr   )r   r   r   )sub-account/universalTransferr   r   capital/deposit/subAddresszcapital/deposit/subHisrecz capital/deposit/subHisrec/getall)r   r   r   r   r   r   )rB   r   r   r   precisionMode
timeframes1m5m15m30m1h4h8h1d1w1M)
r   r   r   r   r   r   r   r   r   r   r   tradingz0.002)	tierBased
percentagemakertakeroptionsr   )zBTC/USDT:USDTzLTC/USDT:USDTzETH/USDT:USDTtypes)linearinverse)rB   rD   60m1W)	r   r   r   r   r   r   r   r   r   Min1Min5Min15Min30Min60Hour4Hour8Day1Week1Month1ETHERC20BTCLTC)r  USDTUSDCr  r  ZKSYNC	ZKSYNCERATRC20TRXTONTONCOINAVAXCAVAX_CCHAINACAACALABEP20BSCOPTIMISMOPASTRASTARBTMBTM2CRC20CRONOSETHFETFHRC20HECOOASISROSEOKCOKTRSKRBTC)zBNB Smart Chain(BEP20-RACAV1)zBNB Smart Chain(BEP20-RACAV2)zBNB Smart Chain(BEP20)  l   W CCXT)adjustForTimeDifferencetimeDifferenceunavailableContractsr   r   defaultTypedefaultNetworkdefaultNetworksnetworksnetworksById
recvWindowmaxTimeTillEndr   features)lastmarkindex)IOCFOKPOGTD)
marginModetriggerPricetriggerDirectiontriggerPriceTypestopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingleveragemarketBuyByCostmarketBuyRequiresPriceselfTradePreventionicebergmax      )rH  limitdaysBack	untilDayssymbolRequired)rH  triggerrQ  r]  )rH  rZ  r^  rQ  r]       )rH  rZ  r[  r\  r^  rQ  r]  )rH  rZ  r[  daysBackCanceledr\  r^  rQ  r]  rZ  )	sandboxrT   rU   r   r   r   r   ri   r   extendsdefault)rI  rK  rJ  rL  rM  rP  rR  rS  Z   )rH  rZ  r[  r\  rH  )rH  rZ  r^  rQ  )rH  rZ  r[  r\  r^  rQ  )rH  rZ  r[  ra  r\  r^  rQ    )	rc  rT   rU   r   r   r   r   ri   r   	forDerivs)rd  rB   rg  rD   rE   commonCurrenciesBEYONDPROTOCOLBEYONDBIFIBIFIFBYNBEYONDFICOFICOFIXDFI
DFISTARTERDFTDFUTUREDRKEGCEGORASCREDITFLUX1FLUXFREEFREEROSSDAOGASGASDAOGASNEOGMTGMTTOKENSTEPNHEROSTEPHEROMIMOMIMOSAPROSFINANCESINCITYTOKENSOULSWAP)PROSSINSOUL
exceptionsz-1128z-2011z-1121101012009201130004333334444410023001930005200320054006007001188004880098801388015700003266021000110007100151007210073100951009610097100981009910100101021010310200102011020210206102111021210216102191022210232102591026510268200012000222222300003000130002300033001030014300163001830020300213002530026300273002830029300323004160005700001700002700004700005700006700007700008700013730001730002730000730003730100730600)730601730602730700730701730702730703730704730705730706730707730101140001140002)z+Order quantity error, please try to modify.z*Combination of optional parameters invalidzapi market order is disabledzContract not allow place order!OversoldzInsufficient positionzInsufficient balance!z'Bid price is great than max allow pricezInvalid symbol.zParam error!maintenance)exactbroad)deep_extendsuperr3   describer0   parse_numberr(   r)   r*   r,   r%   r#   r/   r$   r&   r.   )self	__class__s    Q/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/async_support/mexc.pyr  zmexc.describe   sj   dD : < p?
&p?
Mp?
 $p?
 	p?

 tp?
 p?
 4p?
  sss $s 	s
 %s %s Ts $Us 's s "4s ts s $Us  s  '!s" /#s$ ,T%s& 0's( t)s* +s, &t-s. (/s0 '1s2 (3s4 "45s6 %d7s8 49s: T;s<  =s> ?s@  AsB &uCsD "5EsF +EGsH )%IsJ #EKsL ,UMsN &tOsP #DQsR $TSsT 'UsV (WsX "4YsZ [s\ &t]s^ (_s` 1$asb  csd *:esf +Dgsh &tisj 'ksl (msn #Dosp *4qsr $Usst "4usv *5wsx +Eysz )%{s| #D}s~ ts@ #DAsB  CsD !%EsF %dGsH /IsJ "5KsL +JMsN OsP !$QsR  SsT dUsV $UWsX +EYsZ !$[s\ "4]s^ d_s` !$asb "4csd tesf #Dgsh  isj '
ksl $Tmsn !$osp (qsr %dsst )%usv twsx tysz {s| T}s~ ts@ "4AsB #ECsD %dEsF &zGsH 'IsJ $TKsL  MsN #'#'$( $$)',#!%#'  esp?
x ~ #9#9
 #E#E
 #N#M!
 "#G" /< / U5yp?
p  $%$%,.%&&'01)*&'()+,,-12() $, #Q, (!,  (,  &r	, 
 ',  ',  /,  1!,  4R,  5a,  7,  7,  6r,  /,  6q,   8!, " DQ#, $ .q%, & 3A', ( *1), * /+, , .q-, . 0/, 0 5a1, 2 03, 4 +A5, 6 6q7, 8 3A9, : +A;, < 3A=, > 9!?, @ 8A, B 8C, D .qE, F ./6701;<9:BC/0./+,W, Z!#Q!(!! <Q! 1!	!
 21! 1!! *2! 5a! /! /! 8! 6q! DQ! .r! .q!  -a!!& -a  &'*+23,-12./01#GL %_D   "A $c  1!  -a	 
 =a  3A  21  4Q  -a  9!  8  -a  %a  +A  3A   3A! * ,a 6  6q  >q	 
 6q  7  5a  >q  8  Ea  3A  0  <Q  5a  4Q   4Q! " Fq# $ 347812) ,!4a!6! <Q! +A	!
 1"! +A! 9!! /! 8! .q! /! 3A! /! 3A! 5a!  :1!!/) +?D ./0101+,-.,-,-,-:;
  -.12*++,+,12:;232334>@/1<>23 " ,-12:;./79! -.67./#1 ,\ =>0123:;9:@A  >?23:;67=>34! 1!## ]eqp?
| Y}p?
~ p?
V !&"&!..w7!..w7	Wp?
f +0"#%)%)%))  $&*',!! #"$$#""""
 %$&&%%%$%&2  &"' ##  $ykyUy 9y ]	y
 Uy 7y Uy y Gy0 61y8 X9yD EEyF VGyJ VKyL 5MyN 6Oyv 6;5:.3!" '"7 AAgp?
j $&*(-,1$)$)%*-
 */+06:#'#'"&#(	( #'$)$(+/27/4#(1$6 r% ',!$$&%)*.& ',#($)*.	# '+!%#($)*.( '+!%$%%&#($)*.$ '+!%$%,-%&#($)*.	*  #MIV y  )(,$($(%)-
 -1).+0"&$(+0$ %)&+!$$&%'	& %e# ',!$#'$)	( ',!$$&%'#'$)$ ',!$$&,0%'#'$)*  #c4n "; "; 	 ##WOkp?
J  ! (!! z! 	!
 |! y! u! ~! ! ! ! x! %! z! !  
!!" #!$ &%")!Kp?
v eZe Ze Y	e
 .e Le Je .e Ze Ze Le Ze \e Le -e  :!e$ :%e& -'e( .)e* ]+e, \-e. ./e0 l1e2 -3e4 .5e6 07e8 Y9e: Z;e< Z=e> Z?e@ \AeB \CeD \EeF \GeH ZIeJ ZKeL \MeN ]OeP ZQeR ZSeT ZUeV ZWeX ZYeZ Z[e\ ]]e^ ]_e` Zaeb Zced ]eef ]geh Ziej ]kel ]men Zoep ]qer \set \uev \wex \yez \{e| \}e~ -e@ 0AeB ZCeD \EeF ZGeH \IeJ \KeL \MeN \OeP \QeR ]SeT 1UeV 1WeX jYeZ l[e\ j]e^ 1_e` jaeb 1ced jeef jgeh miej mkel mmen joep )(((((((((((1IeN DNBL4>7C 1->->?K'0$.#0Otwp?
 p p	    c                   K   | j                  dd|      \  }}d}d}d}|dk(  rS| j                  |       d{   }t        |j                               }t	        |      }|r| j                  |      nd}nU|dk(  rP| j                  |       d{   }| j                  |d      rdn| j                  |      }| j                  |d      }||dd|dS 7 7 Ew)	a  
        the latest known information on the availability of the exchange API

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#test-connectivity
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-the-server-time

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
        r   NrB   okrD   successdata)statusupdatedurletainfo)	handle_market_type_and_paramsspotPublicGetPinglistkeyslenjsoncontractPublicGetPing
safe_valuesafe_integer)	r  params
marketTypequeryresponser  r  r  lengths	            r  fetch_statuszmexc.fetch_status  s      !>>}dTZ[
E!33E::H (DYF,2TYYx(F6!!77>>H "__XyATtyyQYGZF''&9G
 	
 ; ?s#   6CCACCACCc                   K   | j                  dd|      \  }}d}|dk(  r+| j                  |       d{   }| j                  |d      S |dk(  r+| j                  |       d{   }| j                  |d      S y7 G7 w)a  
        fetches the current integer timestamp in milliseconds from the exchange server

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#check-server-time
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-the-server-time

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        r   NrB   
serverTimerD   r  )r  spotPublicGetTimer	  r  )r  r
  r  r  r  s        r  
fetch_timezmexc.fetch_time  s      !>>{DRXY
E!33E::H $$X|<<6!!77>>H $$Xv66 ; ?s!   2B A</B $A>%B >B c                    K   | j                  d      sy| j                  |       d{   }i }t        dt        |            D ]0  }||   }| j	                  |d      }| j                  |      }i }| j                  |dg       }	t        dt        |	            D ]  }
|	|
   }| j                  |dd      }| j                  |      }|||d| j                  |dd      | j                  |d	d      | j                  |d
      dd| j	                  |d      | j	                  |d      di| j	                  |d      d
||<    | j                  |||| j	                  |d      dddddddddid|d      ||<   3 |S 7 Rw)a0  
        fetches all available currencies on an exchange

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#query-the-currency-information

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        FNr   coinnetworkListnetWorknetworkdepositEnablewithdrawEnablewithdrawFeer   withdrawMinwithdrawMaxminrW  r   )
r   r6   r  activer\   r   fee	precisionlimitsr   r7   amountcrypto)r   r6   coder7   r   r\   r   r!  r"  r#  typer<  )check_required_credentials!spotPrivateGetCapitalConfigGetallranger  safe_stringsafe_currency_coder  safe_string_2network_id_to_code	safe_boolsafe_numbersafe_currency_structure)r  r
  r  resulticurrencyr6   r&  r<  chainsjchain	networkIdr  s                 r  fetch_currencieszmexc.fetch_currencies  s     ..u5??GGN q#h-( -	A{H!!(F3B**2.DH__X}bAF1c&k* q	 ..uiK	11)<!#&"#~~e_eL $u6F N++E=A!%"#'#3#3E=#I#'#3#3E=#I% !% 0 0
 C%!	*  77 ((6: !## !$#9 F4L7-	\ m Hs   'E>E;EE>c                   K   | j                   d   r| j                          d{    | j                  |      }| j                  |      }t	        j
                  ||g  d{   \  }}| j                  ||      S 7 W7 w)a  
        retrieves data on all markets for mexc

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#exchange-information
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-the-contract-information

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        r6  N)r   load_time_differencefetch_spot_marketsfetch_swap_marketsasynciogatherarray_concat)r  r
  spotMarketPromiseswapMarketPromise
spotMarket
swapMarkets         r  fetch_marketszmexc.fetch_marketsx  s      <<12++--- 33F; 33F;'.~~8IK\7]'^!^
J  Z88	 . "_s!   #BA==B#A?$B?Bc                 "  K   | j                  |       d{   }| j                  |dg       }g }t        dt        |            D ]  }||   }| j	                  |d      }| j	                  |d      }| j	                  |d      }	| j                  |      }
| j                  |	      }| j	                  |d      }| j                  |d      }d	}|d
k(  r|rd}| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }|j                  i d|d|
dz   |z   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| j                  | j                  | j	                  |d!                  | j                  | j                  | j	                  |d"                  d#ddd$| j                  |d%      dd$ddd$| j                  |d&      |d$d'd|d(        |S 7 w))a2  
 @ignore
        retrieves data on all spot markets for mexc

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#exchange-information

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        Nsymbolsr   symbol	baseAsset
quoteAssetr  isSpotTradingAllowedF1TisMarginTradingAllowedmakerCommissiontakerCommissionmaxQuoteAmountr6   /basequotesettlebaseIdquoteIdsettleIdr'  rB   rC   rD   rE   rF   r   r   r  baseAssetPrecisionquoteAssetPrecisionr$  pricer  baseSizePrecisionquoteAmountPrecisionrR  r$  r[  costr  r   r   contractSizeexpiryexpiryDatetimestrike
optionTyper"  r#  createdr   )
spotPublicGetExchangeInfor  r*  r  r+  r,  r0  appendr  parse_precision)r  r
  r  r  r2  r3  marketr6   rU  rV  rR  rS  r  rK  r   rM  rN  rO  rP  s                      r  r<  zmexc.fetch_spot_markets  s     77??V xB7q#d)$ B	A!WF!!&(3B%%fk:F&&v|<G**62D++G4E%%fh7F#'??6;Q#R F#$8%)__V=U%V""..v7HIO"..v7HIO!--f6FGNMM 2b2$*u,2 2 	2
 $2 &2 72 D2 2 2 02 2 %2 %2 &2  E!2" $#2$  (( $"&""//0D0DTEUEUV\^rEs0tu!..t/C/CDDTDTU[]rDs/tu  $#!
  $//8KL#
  $#
  $//8NO-$  c2 2!B	F a @s   HHG5Hc                 H  K   | j                   }| j                  | dd       | j                  |       d{   }| j                  | d|       | j                  |dg       }g }t	        dt        |            D ]  }||   }| j                  |d      }| j                  |d      }	| j                  |d      }
| j                  |d	      }| j                  |	      }| j                  |
      }| j                  |      }| j                  |d
      }||k(  }|j                  i d|d|dz   |z   dz   |z   d|d|d|d|	d|
d|ddddddddddddd|dk(  ddd|| | j                  |d       | j                  |d!      | j                  |d"      dddd| j                  |d#      | j                  |d$      d%| j                  |d&      | j                  |d'      d(| j                  |d)      | j                  |d*      d(ddd(ddd(d+d|d,        |S 7 w)-a>  
 @ignore
        retrieves data on all swap markets for mexc

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-the-contract-information

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        r:   r   Nr  r   rH  baseCoin	quoteCoin
settleCoinstater6   rQ  :rR  rS  rT  rU  rV  rW  r'  rD   rB   FrC   TrE   rF   r   0r   r  takerFeeRatemakerFeeRatera  volUnit	priceUnitrZ  minLeveragemaxLeverager  minVolmaxVolr^  r`  )
r:   set_propertycontractPublicGetDetailr  r*  r  r+  r,  rh  r0  )r  r
  	currentRlr  r  r2  r3  rj  r6   rU  rV  rW  rR  rS  rT  ro  isLinears                    r  r=  zmexc.fetch_swap_markets  s     !NN	$R055f==$Y7Z x4q#d)$ =	A!WF!!&(3B%%fj9F&&v{;G''=H**62D++G4E,,X6F$$VW5EHMM 2b2$*u,s2V;2 2 	2
 &2 &2 72 H2 2 2 %2 2 %2 %2 5C<2  D!2" (#2$  (<))&.A))&.A $ 0 0 H"&""..vyA!--fkB  $//F#//F!
  $//A#//A
  $#
  $#$  c2 2=	| ] >s   4H"HG)H"NrH  rZ  c                 V  K   | j                          d{    | j                  |      }d|d   i}|||d<   d}|d   re| j                  | j                  ||             d{   }| j	                  |d      }| j                  |||      }| j	                  |d      |d<   |S |d	   ru| j                  | j                  ||             d{   }| j                  |d
      }	| j	                  |	d      }
| j                  |	||
      }| j	                  |	d      |d<   |S 7 7 7 Ww)a  

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#order-book
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-the-contract-s-depth-information

        fetches 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
        NrH  r6   rZ  rB   	timestamplastUpdateIdnoncerD   r  r<   )load_marketsrj  spotPublicGetDepthextendr	  parse_order_bookcontractPublicGetDepthSymbolr  )r  rH  rZ  r
  rj  request	orderbookr  spotTimestampr  r  s              r  fetch_order_bookzmexc.fetch_order_book  sL     !!!V$fTl
 $GG	&>!44T[[&5QRRH !--hDM--hNI!%!2!28^!LIg2 1 F^!>>t{{7TZ?[\\H& ??8V4D))$<I--dFIFI!%!2!24!CIge 	" S$ ]s6   D)D"AD)%D%&A)D)D'AD)%D)'D)priceKey	amountKeycountOrIdKeyc                     d}| j                  ||      }| j                  ||      }| j                  ||      }||||gS ||gS )Nr   )r0  )	r  bidaskr  r  r  countKeyr[  r$  counts	            r  parse_bid_askzmexc.parse_bid_ask  sZ      2!!&)4  265))vr  sincec                   K   | j                          d{    | j                  |      }d|d   i}|||d<   d}|d   r>| j                  |ddg      }|||d<   |t        | j                  d	z         ||t        | j                  d
z         ||d<   | j                  | j                  dd      }	| j                  |d|	      }	| j                  |dg      }|	dk(  r*| j                  | j                  ||             d{   }n|	dk(  r*| j                  | j                  ||             d{   }n|	dk(  r*| j                  | j                  ||             d{   }nXt        | j                  dz         |d   r;| j                  | j                  ||             d{   }
| j                  |
d      }| j                  ||||      S 7 7 7 7 x7 3w)aU  

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#recent-trades-list
        https://mexcdevelop.github.io/apidocs/spot_v3_en/#compressed-aggregate-trades-list
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-contract-transaction-data

        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
        :param int [params.until]: *spot only* *since must be defined* the latest time in ms to fetch entries for
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        NrH  r6   rZ  rB   endTimeuntil	startTimezA fetchTrades() requires an until parameter when since is providedz@ fetchTrades() requires a since parameter when until is providedfetchTradesMethodspotPublicGetAggTradesmethodspotPublicGetHistoricalTradesspotPublicGetTradesz& fetchTrades() not support self methodrD   r  )r  rj  safe_integer_nr'   r6   r+  r   omitr  r  r  r  r-   contractPublicGetDealsSymbolr  parse_trades)r  rH  r  rZ  r
  rj  r  r   r  r  r  s              r  fetch_tradeszmexc.fetch_trades  s     !!!V$fTl
 $GG&>''G0DEE ',$=+DGG6y,yzz =+DGG6x,xyy%*	"%%dll4GIabF%%fh?FYYvz2F11#::4;;wPV;WXX::#AA$++gW]B^__00#77GV8TUU"477-U#UVV> F^!>>t{{7TZ?[\\H" __Xv6F  >>] 	", Y_UD ]sY   GGC-GG.G3G4.G"G#AG)G*+GGGGGtraderj  c                    d }d }d }d }d }d }d }	d }
d }d }d }d|v rr| j                  |d      }| j                  d |      }|d   }| j                  |d      }| j                  |d      }| j                  | j                  |d            }	d}
n| j                  |d      }| j                  ||      }|d   }| j	                  |dd      }| j	                  |d	d      }| j                  |d
      }d|v r| j                  |d      }| j                  |d      }| j                  | j                  |d            }	| j                  |d      | j                  | j                  |d            d}| j                  |d      rdnd}
n| j                  |dd      }| j	                  |dd      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |dd      }||rdnd}
||rdnd}	||rdnd}	d}
| j                  |d      }|$| j                  |d      | j                  |      d}|| j                  |||	||||
      }| j                  |||| j                  |      |||	|
|||||d|      S ) NvtrH  pTr   r6   ar[  orderIdpositionModer  volsider!  feeCurrencyr_  r4  r   r   qtyqquoteQtyisBuyerisMakerisBuyerMakermbuysellcommissionAsset
commission)r6   r   r  datetimerH  r'  r  takerOrMakerr[  r$  r_  r!  r   )r	  safe_marketr+  parse_order_sider-  r,  r  safe_integer_2safe_value_2synthetic_trade_id
safe_tradeiso8601)r  r  rj  r6   r  r  rH  r!  r'  r  r  priceStringamountString
costStringmarketIdr  r  
buyerMakerfeeAssets                      r  parse_tradezmexc.parse_trade)  s   	
%< ))%5I%%dF3FH%F**5#6K++E37L(()9)9%)EFD"Lh ''x8H%%h7FH%F##E45B,,UGSAK&&ui8G& --e[A	#//u=,,T-=-=eV-LM ,,UE: $ 7 78H8HP]8^ _ +///%*Iww //vsC	#11%D!--eZ@
//%;//%;!..uncJ
&.577L&$+5D)%/6UD#*L++E3DE' $ 0 0 E$($;$;H$EC :((D,P[]acopB"Y/( " 
  	r  c                     d}|x| j                  |      dz   | j                  |dd      z   }||d|z   z  }||d| j                  |      z   z  }||d| j                  |      z   z  }||d|z   z  }||d|z   z  }|S )N -r6   _)number_to_stringr+  )	r  rj  r  r  r$  r[  	orderTyper  r6   s	            r  r  zmexc.synthetic_trade_id  s     &&y1C7$:J:J6SWY\:]]BcDj !cD11&999 cD11%888'cL(($cIo%	r  r   c           	        K   | j                          d{    | j                  |      }|d   rdnd}d}| j                  |ddd      \  }}|r| j                  d||||||       d{   S | j	                  | j
                  di       }	| j	                  |	|d	   i       }
| j                  |
|      }| j                  |      dz  }|d
   |d}d}|d   r| j                  |ddg      }|;||d<   |4| j                  |||z        }| j                         }t        ||      |d<   |||d<   || j                  |dg      }||d<   | j                  | j                  ||             d{   }|}nC|d   r=| j                  |ddgd      }|| j!                  |dz        |d<   || j                  |dg      }||d<   | j                  |dd      }| j                  |d      }d}|dk(  r*| j#                  | j                  ||             d{   }nv|dk(  r*| j%                  | j                  ||             d{   }nG|dk(  r*| j'                  | j                  ||             d{   }nt)        | j*                  dz         | j	                  |d      }| j-                  |dddddd      }| j/                  |||||      S 7 7 g7 g7 7 7 hw) a1  

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#kline-candlestick-data
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#k-line-data

        fetches 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
        :param int [params.until]: timestamp in ms of the latest candle to fetch
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        NrB   r_  rf  Fr   paginater   r'  r6   )rH  intervalr  r  r  rZ  rD   gMbP?startendr[  rd  rC  rB  zA fetchOHLCV() not support self price type, [default, index, mark]r  r   openhighlowcloser  )r  rj  handle_option_and_params"fetch_paginated_call_deterministicr  r   r+  parse_timeframer  summillisecondsr  r  spotPublicGetKlinesr  safe_integer_product_nparse_to_intcontractPublicGetKlineSymbol&contractPublicGetKlineIndexPriceSymbol%contractPublicGetKlineFairPriceSymbolr-   r6   convert_trading_view_to_ohlcvparse_ohlcvs)r  rH  	timeframer  rZ  r
  rj  maxLimitr  r   r   timeframeValuedurationr  candlesr  r  nowr  	priceTyper  s                        r  fetch_ohlcvzmexc.fetch_ohlcv  s5      !!!V$"6N488z[`a&@@vW\^cenpv  yA  B  B  B//$,,bA__WfVnbA
))*i@''	2T9Tl&
 &>'')0DEE ',$=((5(X*=>C++-C),S#GI& #(  6G95%*	"!55dkk'66RSSH GF^//)8LeTE #'#4#4UT\#B  6G95!&(()DIYYvw/FHI%!%!B!B4;;wX^C_!``g%!%!L!LT[[Y`bhMi!jjf$!%!K!KDKKX_agLh!ii"477-p#pqq  ??8V4D88vvvW\^eglmG  &)UEJJc 	" B0 T6 ajism   KKAK*K+DK-K.B&KK.KK.K2K3AKKKKKKc           	          | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS )Nr   r   r   r      r   )r	  r0  )r  ohlcvrj  s      r  parse_ohlcvzmexc.parse_ohlcv'  sl    eQ'UA&UA&UA&UA&UA&
 	
r  rG  c                   K   | j                          d{    i }d}d}|3t        |      }|dk(  }| j                  |d      }| j                  |      }| j	                  d||      \  }}	d}
|r|d   |d<   |dk(  r*| j                  | j                  ||	             d{   }
nA|d	k(  r<| j                  | j                  ||	             d{   }| j                  |d
g       }
|r|
g}
| j                  |
|      S 7 7 _7 2w)a  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#24hr-ticker-price-change-statistics
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-contract-trend-data

        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        NFr   r   r   r6   rH  rB   rD   r  )
r  r  r+  rj  r  spotPublicGetTicker24hrr  contractPublicGetTickerr  parse_tickers)r  rG  r
  r  rj  isSingularMarketr  firstSymbolr  r  tickersr  s               r  fetch_tickerszmexc.fetch_tickers1  s&     !!! \F%{**7A6K[[-F >>~vW]^
E &tGH 88We9TUUG2 6!!99$++gu:UVVH8 ooh;GiG!!'733Q 	" V4 Ws4   DC?B
D!D".DD/DDDc                   K   | j                          d{    | j                  |      }| j                  d||      \  }}d}d|d   i}|dk(  r*| j                  | j	                  ||             d{   }nA|dk(  r<| j                  | j	                  ||             d{   }| j                  |di       }| j                  ||      S 7 7 Z7 -w)aF  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#24hr-ticker-price-change-statistics
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-contract-trend-data

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        Nr   rH  r6   rB   rD   r  )r  rj  r  r  r  r  r  parse_ticker)	r  rH  r
  rj  r  r  r   r  r  s	            r  fetch_tickerzmexc.fetch_ticker  s      !!!V$ >>}fV\]
EfTl
 77GU8STTF. 6!!99$++gu:UVVH4 __Xvr:F  00y 	" U0 Ws4   CCAC4C5.C#C$*CCCr   c                 Z   | j                  |d      }| j                  ||      }d }d }d }d }d }d }	d }
d }d }d }d }d }d }| j                  |d      }|sd|v r| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }	| j                  |d      }
| j                  |d      }| j                  |d	      }| j                  |d
      }| j                  |d      }t	        j
                  |d      }n0| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }t	        j                  |d      rd }t	        j                  |d      rd }| j                  |d      }	| j                  |d      }
| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }t	        j
                  |d      }| j                  i d|d   d|d| j                  |      d|d|d|d| j                  |d       d!|d"|d#|d$|d%d d&|d'|d(|d)d d*|	|
|d+|      S ),NrH  rD   r  bid1ask1volume24amount24high24Pricelower24PriceriseFallValueriseFallRate100	closeTimebidPriceaskPricebidQtyaskQtyrq  volumequoteVolume	openPrice	highPricelowPriceprevClosePricepriceChangepriceChangePercentr  r  r  r  r  	lastPricebid	bidVolumeask	askVolumevwappreviousClosechanger   average
baseVolume)r  r   )	r+  r  r  r	  r1   
string_mul	string_eqsafe_tickerr  )r  r   rj  r  r  r  r  r  r  r  r  r  r  r  
changePcntchangeValue	prevCloseisSwaps                     r  r  zmexc.parse_ticker  sn   ##FH5!!(F3			

	0kV+, ))&+>I""662C""662C))&*=J**6:>K##FM:D""6>:C**6?CK))&.AJ ++J>J0 ))&+>I""6:6C""6:6C((:I((:I  C0 	  C0 	))&(;J**6=AK##FK8D##FK8D""6:6C((1ABI**6=AK))&2FGJ ++J>J !
fX&!
!
 Y/!
 D	!

 D!
 3!
 T%%fk:!
 3!
 !
 3!
 !
 D!
 Y!
 k!
 *!
  t!!
" *#!
$ ''!
( ) 	r  c                 x  K   | j                          d{    d}d}|$t        |      }|dk(  }| j                  |d         }| j                  d||      \  }}d}|dk(  r| j	                  |       d{   }n#|dk(  rt        | j                  dz   |z   d	z         |r|g}| j                  ||      S 7 7 Aw)
a  
        fetches the bid and ask price and volume for multiple markets

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#symbol-order-book-ticker

        :param str[]|None symbols: unified symbols of the markets to fetch the bids and asks for, all markets are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        NFr   r   r`   rB   rD   z& fetchBidsAsks() is not available for z markets)r  r  rj  r  spotPublicGetTickerBookTickerr-   r6   r  )	r  rG  r
  rj  r  r  r  r  r  s	            r  fetch_bids_askszmexc.fetch_bids_asks@  s      !!! \F%{[[,F >>PVX^_
E >>uEEG 6!tww)QQT^^akklliG!!'7337 	" Fs#   B:B6AB:6B87A B:8B:r_  c                   K   | j                          d{    | j                  |      }|d   st        | j                  dz         d|i}| j	                  |dddd| j                  ||             d{   S 7 d7 w)a  
        create a market buy order by providing the symbol and cost

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#new-order

        :param str symbol: unified symbol of the market to create an order in
        :param float cost: how much you want to trade in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NrB   9 createMarketBuyOrderWithCost() supports spot orders onlyr_  rj  r  r   r  rj  r-   r6   create_orderr  r  rH  r_  r
  rj  reqs         r  !create_market_buy_order_with_costz&mexc.create_market_buy_order_with_costg  s      !!!V$f~tww)ddeeD
 &&vx4UXZ`Iabbb 	" c"   A?A;AA?6A=7A?=A?c                   K   | j                          d{    | j                  |      }|d   st        | j                  dz         d|i}| j	                  |dddd| j                  ||             d{   S 7 d7 w)a  
        create a market sell order by providing the symbol and cost

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#new-order

        :param str symbol: unified symbol of the market to create an order in
        :param float cost: how much you want to trade in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NrB   r)  r_  rj  r  r   r*  r,  s         r  "create_market_sell_order_with_costz'mexc.create_market_sell_order_with_cost{  s      !!!V$f~tww)ddeeD
 &&vxD$++VY[aJbccc 	" dr/  r'  r  r$  r[  c           	        K   | j                          d{    | j                  |      }| j                  d|      \  }}	|d   r| j                  |||||||	       d{   S | j	                  |||||||	       d{   S 7 m7 %7 w)a  
        create a trade order

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#new-order
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#order-under-maintenance
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#trigger-order-under-maintenance

        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: only 'isolated' is supported for spot-margin trading
        :param float [params.triggerPrice]: The price at which a trigger order is triggered at
        :param bool [params.postOnly]: if True, the order will only be posted if it will be a maker order
        :param bool [params.reduceOnly]: *contract only* indicates if self order is to reduce the size of a position
        :param bool [params.hedged]: *swap only* True for hedged mode, False for one way mode, default is False
        :param str [params.timeInForce]: 'IOC' or 'FOK', default is 'GTC'
 EXCHANGE SPECIFIC PARAMETERS
        :param int [params.leverage]: *contract only* leverage is necessary on isolated margin
        :param long [params.positionId]: *contract only* it is recommended to hasattr(self, fill) parameter when closing a position
        :param str [params.externalOid]: *contract only* external order ID
        :param int [params.positionMode]: *contract only*  1:hedge, 2:one-way, default: the user's current config
        :param boolean [params.test]: *spot only* whether to use the test endpoint or not, default is False
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NrT   rB   )r  rj  handle_margin_mode_and_paramscreate_spot_ordercreate_swap_order)
r  rH  r'  r  r$  r[  r
  rj  rH  r  s
             r  r+  zmexc.create_order  s     8 !!!V$ >>}fU
E&>//dFES]_deee//dFES]_deee 	" fes4   B
BA	B
 B!B
?B B
B
B
c                    |d   }|j                         }	|d   |	|j                         d}
|dk(  r| j                  |dd      }| j                  |d      }||}| j                  ||      |
d<   n}|| j	                  ||      |
d<   ne| j                  |      }| j                  |      }t        j                  ||      }|}| j                  ||      |
d<   n| j	                  ||      |
d<   || j                  ||      |
d<   | j                  |d	      }|||
d
<   | j                  |dd	g      }|#|dk7  rt        | j                  dz   |z   dz         d }| j                  |dk(  |dk(  |      \  }}|rd|
d<   | j                  |d      }|'| j                  |d      }|dk(  rd|
d<   n
|dk(  rd|
d<   | j                  |
|      S )NrH  r6   )rH  r  r'  rj  r_  quoteOrderQtyquantityr[  clientOrderIdnewClientOrderIdr'  isolatedz+ createOrder() does not support marginMode  for spot-margin tradingLIMIT_MAKERrO  rD  IMMEDIATE_OR_CANCELrE  FILL_OR_KILL)uppersafe_number_2r  cost_to_precisionamount_to_precisionr  r1   r  price_to_precisionr+  r(   r6   handle_post_onlyr  )r  rj  r'  r  r$  r[  rH  r
  rH  	orderSider  r_  r  r  quoteAmountr9  postOnlytifs                     r  create_spot_order_requestzmexc.create_spot_order_request  s    !JJL	TlJJL

 8%%ffoFDYYvv.F+/+A+A&&+Q(=*.*B*B66*RGJ'#'#8#8#@L"&"7"7">K")"4"4\;"OK(F/3/E/Eff/UGO,"&":":66"JGJ#66vuEGG((A$*7G&'YYv'@AF!Z' +X!X[e!e  iC  "C  D  D001A4=CXZ`a&+GFOv}5?YYv}5Fe|"7"0{{7F++r  c           	        K   | j                          d{    | j                  |dd      }| j                  |d      }| j                  |||||||      }	d}
|r| j	                  |	       d{   }
n| j                  |	       d{   }
| j                  |
|      }||d<   ||d<   | j                  |d      ||d<   | j                  |d      ||d<   |S 7 7 l7 Tw)an  
 @ignore
        create a trade order

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#new-order

        :param str market: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param str [marginMode]: only 'isolated' is supported for spot-margin trading
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param bool [params.postOnly]: if True, the order will only be posted if it will be a maker order
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NtestFr  r'  r[  r$  )r  r/  r  rJ  spotPrivatePostOrderTestspotPrivatePostOrderparse_orderr+  )r  rj  r'  r  r$  r[  rH  r
  rL  r  r  r   s               r  r4  zmexc.create_spot_order  s     " !!!~~ffe466*00tVUT^`fg!::7CCH!66w??H(   62ffE7+3"E'NE8,4$E(OG 	" D?s5   C CAC /C0C 	C
AC C C c                   K   | j                          d{    |d   }| j                  | j                  di       }	| j                  |	|d      }
|
rt	        | j
                  dz   |z         d}|(|dk(  rd}n3|dk(  rd	}n+t        | j
                  d
z         | j                  |dd      }|dk7  r;|dk7  r6|d	k7  r1|dk7  r,|dk7  r'|dk7  r"|dk7  r|dk7  rt        | j
                  dz         d}| j                  |dk(  |dk(  |      \  }}|rd}n|dk(  rd	}n|dk(  rd}|d   t        | j                  ||            ||d}|dk7  r(|dk7  r#|dk7  rt        | j                  ||            |d<   |d	k(  r,| j                  |d      }|t        | j
                  dz         | j                  |dd      }| j                  |dd      }d}|r,|r| j                  |d      }|dk(  rdnd}|dk(  rd	nd}d	|d<   n|r
|dk(  rdnd}n	|dk(  rd	nd}||d<   | j                  |dd      }|||d<   | j                  |d d!      }| j                  |g d"      }d}|r| j                  ||      |d <   | j                  |d#d	      |d#<   | j                  |d$d	      |d$<   | j                  |d%d	      |d%<   | j                  |d&d	      |d&<   | j!                  | j#                  ||             d{   }n)| j%                  | j#                  ||             d{   }| j'                  |d'      }| j)                  d|i|      S 7 $7 W7 /w)(a  
 @ignore
        create a trade order

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#new-order
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#order-under-maintenance
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#trigger-order-under-maintenance

        :param str market: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param str [marginMode]: only 'isolated' is supported for spot-margin trading
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param float [params.triggerPrice]: The price at which a trigger order is triggered at
        :param bool [params.postOnly]: if True, the order will only be posted if it will be a maker order
        :param bool [params.reduceOnly]: indicates if self order is to reduce the size of a position
        :param bool [params.hedged]: *swap only* True for hedged mode, False for one way mode, default is False

 EXCHANGE SPECIFIC PARAMETERS
        :param int [params.leverage]: leverage is necessary on isolated margin
        :param long [params.positionId]: it is recommended to hasattr(self, fill) parameter when closing a position
        :param str [params.externalOid]: external order ID
        :param int [params.positionMode]: 1:hedge, 2:one-way, default: the user's current config
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NrH  r8  Fz4 createSwapOrder() does not support yet self symbol:crossr   r;  r   zN createSwapOrder() marginMode parameter should be either "cross" or "isolated"openTyperZ  rj  r   r  r      z createSwapOrder() order type must either limit, market, or 1 for limit orders, 2 for post-only orders, 3 for IOC orders, 4 for FOK orders, 5 for market orders or 6 to convert market price to current pricer6   )rH  r  r'  rR  r[  rR  zK createSwapOrder() requires a leverage parameter for isolated margin orders
reduceOnlyrP  r  r  r  r  r9  externalOidrI  	stopPrice)r9  rU  rH  rV  rI  rP  triggerTypeexecuteCycletrendr  r  )r  r  r   r/  r-   r6   r'   r	  r,   rE  floatrC  rD  r  r-  rA  !contractPrivatePostPlanorderPlacer  contractPrivatePostOrderSubmitr+  
safe_order)r  rj  r'  r  r$  r[  rH  r
  rH  r8  isContractUnavaiablerR  rH  r  rR  rT  rP  sideIntegerr9  rI  r  r  s                         r  r5  zmexc.create_swap_order	  s    8 !!!!#t||=SUWX#~~.BFERtww)__bhhii!W$z)'  3C  )C  D  D((Q?HGO$("2QRY]abYbimqriry}  BC  zC  JN  RS  JStww  *y   y  z  z001A419fU&DW_DXDTl11&&AB  #
4 AIDAIDH,<$T%<%<VU%KLGGq=((<H'2(  A  A^^FL%@
%86<8"&%-ve $!AK&'GN#$(EMa$(EMa%**6?MR$%2GM"))&.+N6#vw&*&=&=fl&SGN#%)%6%6v}a%PGM"&*&7&7PQ&RGN##00!DGG#'#4#4V[!#LGK !CCDKKPWY_D`aaH!@@WV\A]^^H &1d|V44A 	"j b^s4   ML:KM%L=&)ML?+M=M?Mordersc           
         K   | j                          d{    g }d}t        dt        |            D ]  }||   }| j                  |d      }| j	                  |      }|d   st        | j                  dz         ||}n||k7  rt        | j                  dz         | j                  |d      }	| j                  |d      }
| j                  |d	      }| j                  |d
      }| j                  |di       }d}| j                  d|      \  }}| j                  ||	|
||||      }|j                  |        d| j                  |      i}| j                  |       d{   }| j                  |      S 7 c7 w)a  
        *spot only*  *all orders must have the same symbol* create a list of trade orders

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#batch-orders

        :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
        :param dict [params]: extra parameters specific to api endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   rH  rB   z2 createOrders() is only supported for spot marketsz; createOrders() requires all orders to have the same symbolr'  r  r$  r[  r
  rT   r   )r  r*  r  r+  rj  r-   r6   r(   r  r3  rJ  rh  r  spotPrivatePostBatchOrdersparse_orders)r  r`  r
  ordersRequestsrH  r3  rawOrderr  rj  r'  r  r$  r[  orderParamsrH  orderRequestr  r  s                     r  create_orderszmexc.create_orders	  s     !!!q#f+& 	0AayH''(;H[[*F&>"477-a#abb~!X%$TWW/l%lmm##Hf5D##Hf5D__Xx8FOOHg6E//(HbAKJ!%!C!CMSY!ZJ99&$fV[]gituL!!,/'	0* 499^4
 88AA*   **_ 	"4 Bs"   E>E9EE>#E<$E><E>r6   c                   K   |t        | j                  dz         | j                          d{    | j                  |      }d|d   i}d}|d   r| j	                  |d      }|| j                  |d      }||d<   n||d<   | j                  d	|      \  }}	|M|d
k7  rt        | j                  dz   |z   dz         | j                  | j                  ||	             d{   }no| j                  | j                  ||	             d{   }nE|d   r@||d<   | j                  | j                  ||             d{   }
| j                  |
d      }| j                  ||      S 7 :7 7 a7 /w)am  
        fetches information on an order made by the user

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#query-order
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#query-the-order-based-on-the-order-number

        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: only 'isolated' is supported, for spot-margin trading
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nz( fetchOrder() requires a symbol argumentrH  r6   rB   r9  origClientOrderIdr  r   r;  z* fetchOrder() does not support marginMode r<  rD   order_idr  )r'   r6   r  rj  r+  r  r3  r(   spotPrivateGetMarginOrderr  spotPrivateGetOrder!contractPrivateGetOrderGetOrderIdr  rO  )r  r6   rH  r
  rj  r  r  r9  rH  r  r  s              r  fetch_orderzmexc.fetch_order	  s     >#DGG.X$XYY!!!V$fTl
 &> ,,V_EM(6?;/<+,%'	" $ B B<QW XJ%+$TWW/[%[^h%h  lF  &F  G  G!;;DKKQV<WXX!55dkk'56QRRZ F^"$GJ!CCDKKPWY_D`aaHB ??8V4Df--I 	"" YR^ bsF   .E3E*B2E3#E-$)E3E/3E3E1)E3-E3/E31E3c                   K   | j                          d{    i }d}|| j                  |      }|d   |d<   | j                  |d      }| j                  |d      }| j	                  d||      \  }}	|dk(  r|t        | j                  dz         | j                  d|      \  }
}|||d<   |||d	<   |||d
<   d}|
M|
dk7  rt        | j                  dz   |
z   dz         | j                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  ||||      S |p||d<   | j                  |d|      }|#| j                  || j                  d         |d<   n_||z
  | j                  d   kD  rt        | j                  dz         ||d<   n,|*| j                  || j                  d   dz        |d<   ||d<   |||d<   | j                  | j                  dd      }| j                  |	d|      }g }g }|dk(  r<| j!                  | j                  ||	             d{   }| j#                  |d      }n;| j%                  | j                  ||	             d{   }| j#                  |d      }| j'                  ||      }| j                  |||||      S 7 7 7 7 7 Hw)a  
        fetches information on multiple orders made by the user

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#all-orders
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-all-of-the-user-39-s-historical-orders
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#gets-the-trigger-order-list

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch orders for
        :param str [params.marginMode]: only 'isolated' is supported, for spot-margin trading
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr6   rH  r  r   rB   z9 fetchOrders() requires a symbol argument for spot marketr  r  rZ  r;  z+ fetchOrders() does not support marginMode r<  
start_timeend_timer?  z. end is invalid, i.e. exceeds allowed 90 days.	page_size(contractPrivateGetOrderListHistoryOrdersr  r  )r  rj  r	  r  r  r'   r6   r3  r(   spotPrivateGetMarginAllOrdersr  spotPrivateGetAllOrdersrc  r  r   r+  ru  r  %contractPrivateGetPlanorderListOrdersr@  )r  rH  r  rZ  r
  r  rj  r  r  r  rH  
queryInnerr  r  r  ordersOfRegularordersOfTriggermergeds                     r  fetch_orderszmexc.fetch_ordersF
  s;      !!![[(F &tGH!!&'267+ >>}fV\]
E~'2m(mnn%)%G%GW]%^"J
 ',$ %*	" #( H%+$TWW/\%\_i%i  mG  &G  H  H!%!C!CDKKPWYcDd!ee!%!=!=dkk'S]>^!__b $$XvueDD (-%''
EB;*.((5$,,GW:X*YGJ'et||4D'EE(3c)cdd.3
+"(,EU8VY[8[(\%&+
# ',$%%dllMCmnF%%eXv>F O OCC!%!N!Nt{{[bdiOj!kkF #'//(F"C "&!K!KDKKX_afLg!hh6 #'//(F"C&&HF$$VVUE6JJG 	". f_N lL isY   KKC1KK
	)K2K3DKK;K	K
>K
KKKKc                   K   | j                          d {    i }d }|| j                  |      }|d   |d<   | j                  d||      \  }}|dk(  rt        | j                  dz   |z         dj                  |      |d<   | j                  | j                  ||             d {   }| j                  |d      }	| j                  |	|      S 7 7 *w)	Nr6   rH  fetchOrdersByIdsrB   z) fetchOrdersByIds() is not supported for ,	order_idsr  )
r  rj  r  r(   r6   join!contractPrivateGetOrderBatchQueryr  	safe_listrc  )
r  idsrH  r
  r  rj  r  r  r  r  s
             r  fetch_orders_by_idszmexc.fetch_orders_by_ids
  s     !!![[(F &tGH >>?QSY[ab
ETWW'RRU__``#&88C=GK !CCDKKPWY^D_``HF >>(F3D$$T622_ 	" as"   CCBC(C))CCc                 x  K   | j                          d{    i }d}d}|| j                  |      }| j                  d||      \  }}|dk(  r|t        | j                  dz         |d   |d<   | j                  d|      \  }}	d}
|M|dk7  rt        | j                  dz   |z   d	z         | j                  | j                  ||	             d{   }
n)| j                  | j                  ||	             d{   }
| j                  |
|||      S | j                  d
||||       d{   S 7 7 b7 :7 w)a9  
        fetch all unfilled currently open orders

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#current-open-orders
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-all-of-the-user-39-s-historical-orders
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#gets-the-trigger-order-list

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of  open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: only 'isolated' is supported, for spot-margin trading
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   rB   z= fetchOpenOrders() requires a symbol argument for spot marketr6   rH  r;  z/ fetchOpenOrders() does not support marginMode r<  r   )r  rj  r  r'   r6   r3  r(   spotPrivateGetMarginOpenOrdersr  spotPrivateGetOpenOrdersrc  fetch_orders_by_state)r  rH  r  rZ  r
  r  rj  r  rH  r  r  s              r  fetch_open_orderszmexc.fetch_open_orders-  ss     !!!
[[(F!??@QSY[ab
F~'2q(qrr &tGH $ B BCTV\ ]JH%+$TWW/`%`cm%m  qK  &K  L  L!%!D!DT[[QXZ_E`!aa!%!>!>t{{7TY?Z![[b $$XvueDD 33AvueVTTTM 	"  b[h UsF   D:D1B:D:D4)D:;D6<0D:,D8-D:4D:6D:8D:c                 H   K   | j                  d||||       d{   S 7 w)a  
        fetches information on multiple closed orders made by the user

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#all-orders
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-all-of-the-user-39-s-historical-orders
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#gets-the-trigger-order-list

        :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 Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r   Nr  r  rH  r  rZ  r
  s        r  fetch_closed_orderszmexc.fetch_closed_orders  '      //65%PPPP   " "c                 H   K   | j                  d||||       d{   S 7 w)a  
        fetches information on multiple canceled orders made by the user

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#all-orders
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-all-of-the-user-39-s-historical-orders
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#gets-the-trigger-order-list

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: timestamp in ms of the earliest order, default is None
        :param int [limit]: max number of orders to return, default is None
        :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>`
        r  Nr  r  s        r  fetch_canceled_orderszmexc.fetch_canceled_orders  r  r  c           	      8  K   | j                          d {    i }d }|| j                  |      }| j                  d||      }|dk(  rt        | j                  dz   |z         ||d<   | j                  |||| j                  ||             d {   S 7 7 w)NfetchOrdersByStaterB   z+ fetchOrdersByState() is not supported for states)r  rj  r  r-   r6   r}  r  )	r  ro  rH  r  rZ  r
  r  rj  r  s	            r  r  zmexc.fetch_orders_by_state  s     !!![[(F778LfV\]
tww)VVYccdd %GH**65%WV\A]^^^ 	" _s"   BBA:BBBBc                   K   | j                          d{    i }d}|| j                  |      }|d   |d<   d}| j                  d||      \  }}| j                  d|      \  }}d}	|dk(  r|t	        | j
                  dz         d|d   i}
| j                  |d      }|| j                  |d      }||
d<   n||
d	<   |N|d
k7  rt        | j
                  dz   |z   dz         | j                  | j                  |
|             d{   }	n| j                  | j                  |
|             d{   }	n| j                  | j                  dd      }| j                  |d|      }d}|dk(  r| j                  |g       d{   }n8|dk(  r| j                  |g       d{   }nt        | j
                  dz         | j!                  |d      }	| j!                  |	d      }| j!                  |dd      }|dk7  r!t#        | j
                  dz   |z   dz   |z         | j%                  |	|      S 7 7 -7 7 7 w)a  
        cancels an open order

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#cancel-order
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#cancel-the-order-under-maintenance
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#cancel-the-stop-limit-trigger-order-under-maintenance

        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: only 'isolated' is supported for spot-margin trading
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr6   rH  rL   rB   z) cancelOrder() requires a symbol argumentr9  rj  r  r;  z+ cancelOrder() does not support marginMode r<  contractPrivatePostOrderCancelr  "contractPrivatePostPlanorderCancelz& cancelOrder() not support self methodr  r   errorMsgr  r  z! cancelOrder() the order with id z cannot be cancelled: )r  rj  r  r3  r'   r6   r+  r  r(   spotPrivateDeleteMarginOrderr  spotPrivateDeleteOrderr   r  r  r-   r  r,   rO  )r  r6   rH  r
  r  rj  r  rH  r  r  requestInnerr9  r  r  r   r  s                   r  cancel_orderzmexc.cancel_order  s     !!![[(F &tGH
!??vW]^
F >>}fU
E~'2](]^^&,"L !,,V_EM(5/:4A01*,Y'%+$TWW/\%\_i%i  mG  &G  H  H!>>t{{<Y^?_``!88\SX9YZZJ %%dllMCcdF%%eXv>FH99!%!D!DbT!JJ??!%!H!H"!NN"477-U#UVV ??8V4DOOD!,Euj"=H9$"477-P#PSU#UXp#ps{#{||f--w 	"2 aZR KNsZ   I H3C2I 	H6
*I 4H95AI H<I &H>'BI 6I 9I <I >I c                 L  K   | j                          d{    || j                  |      nd}| j                  d||      }|dk(  rt        | j                  dz   |z         | j                  |       d{   }| j                  |d      }| j                  ||      S 7 7 *w)a  
        cancel multiple orders

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#cancel-the-order-under-maintenance

        :param str[] ids: order ids
        :param str symbol: unified market symbol, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        NrM   rB   z% cancelOrders() is not supported for r  )r  rj  r  r(   r6   r  r  rc  )r  r  rH  r
  rj  r  r  r  s           r  cancel_orderszmexc.cancel_orders  s      !!!)/);V$$77PVW
TWW'NNQ[[\\!@@EEH >>(F3D$$T622+ 	" Fs"   B$B A B$7B"8)B$"B$c                   K   | j                          d{    || j                  |      nd}i }d}| j                  d||      \  }}| j                  d|      \  }}|dk(  r|t	        | j
                  dz         |d   |d<   d}|M|dk7  rt        | j
                  dz   |z   d	z         | j                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  ||      S ||d   |d<   | j                  | j                  dd
      }	| j                  |d|	      }	d}|	d
k(  r*| j                  | j                  ||             d{   }n.|	dk(  r)| j                  | j                  ||             d{   }| j                  |dg       }
| j                  |
|      S 7 7 7 7 `7 3w)a  
        cancel all open orders

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#cancel-all-open-orders-on-a-symbol
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#cancel-all-orders-under-a-contract-under-maintenance
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#cancel-all-trigger-orders-under-maintenance

        :param str symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: only 'isolated' is supported for spot-margin trading
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        NrK   rB   z5 cancelAllOrders() requires a symbol argument on spotr6   rH  r;  z/ cancelAllOrders() does not support marginMode r<  !contractPrivatePostOrderCancelAllr  %contractPrivatePostPlanorderCancelAllr  )r  rj  r  r3  r'   r6   r(   !spotPrivateDeleteMarginOpenOrdersr  spotPrivateDeleteOpenOrdersrc  r+  r   r  r  r  )r  rH  r
  rj  r  r  rH  r  r  r  r  s              r  cancel_all_orderszmexc.cancel_all_orders>  s     !!!)/);V$$
!??@QSY[ab
F >>?PRXY
E~'2i(ijj &tGHH%+$TWW/`%`cm%m  qK  &K  L  L!%!G!GT[]bHc!dd!%!A!A$++gW\B]!^^J $$Xv66!$*4L! %%dll4EGjkF%%eXv>FH<<!%!G!GT[]bHc!ddBB!%!K!KDKKX_afLg!hh >>(FB7D$$T622S 	" e^^ ehsY   GGB:GG)G;G<A;G7G8.G&G'*GGGGGr   c                    | j                  |d      }|%| j                  |d| j                  |d      d      S d }t        |t              r|}n| j                  |dd      }| j                  | j                  |d            }| j                  |d      }|| j                  |      }| j                  |d	      }| j                  ||      }| j                  |g d
      }d }	| j                  |d      }
|
N| j                  |d      }| j                  |d      }t        j                  ||      }|
| j                  |      d}	| j                  i d|d| j                  |d      d|d| j                  |      dd d| j                  | j                  |dd            d	|d	   d| j                  |      d|d| j!                  | j                  |d            d| j#                  |d      d| j%                  |dd      d| j#                  |d      d| j%                  |dd      d| j#                  |d      d | j%                  |d!d"      d#d |	d |d$|      S )%Nr&  rejectedr:  )r   r  r9  r  r6   rO  r'  rH  )r   
createTimetransactTimer  takerFeemakerFee)r4  r_  r9  r  r  lastTradeTimestampr  ro  r  r[  rI  rV  r  dealAvgPricer$  origQtyr  r_  cummulativeQuoteQtyfilledexecutedQtydealVol	remaining)r!  r   r   )r	  r]  r+  
isinstancestrr-  parse_order_time_in_forceget_tif_from_raw_order_typer  r  r1   
string_addr  r  parse_order_statusparse_order_typer  r0  rA  )r  r   rj  r&  r6   rO  typeRawr  r  r!  r  r  r  feeSums                 r  rO  zmexc.parse_order  s   V   /??$!%!1!1%9K!L$  
 eS!B##E9d;B44T5E5Ee]5[\""5&1::7CK##E84!!(F3''/UV	&&um<"''z:H''z:H''(;F'))&1C   
" 
T--e_E 
  
 Y/	 

 !$ 
 d--d.@.@RY.Z[ 
 fX& 
 D))'2 
 ; 
 D))$*:*:5&*IJ 
 T%%eW5 
 D..uk>R 
 t''~> 
 d((	5A 
 D$$U,AB 
  d((yI! 
" # 
$ ) 
* + 	r  c                 6    ddddd}| j                  |||      S )Nr  r  )BUYSELLrL  2r+  r  r  statusess      r  r  zmexc.parse_order_sidev  s,    	
 &&99r  c                 8    dddddd}| j                  |||      S )Nrj  rZ  )MARKETLIMITr=  r>  r?  r  r  s      r  r  zmexc.parse_order_type  s/    "#*#
 &&99r  r  c           	      >    ddddddddd}| j                  |||      S )Nr  closedcanceled)NEWFILLEDCANCELEDPARTIALLY_FILLEDPARTIALLY_CANCELEDr  34r  r  s      r  r  zmexc.parse_order_status  s:    " &", 
 &&99r  c                 4    dddd}| j                  |||      S )NGTCrE  rD  )r  rE  rD  r  r  s      r  r  zmexc.parse_order_time_in_force  s)    

 &&99r  r  c                 8    dddddd}| j                  |||      S )Nr  	POST_ONLYrD  rE  )r  r=  r>  r?  r  r  )r  r  r  s      r  r  z mexc.get_tif_from_raw_order_type  s/    &#(!
 )Y??r  c                    K   |dk(  r| j                  |       d {   S |dk(  r+| j                  |       d {   }| j                  |d      S y 7 57 w)NrB   rD   r  )spotPrivateGetAccountcontractPrivateGetAccountAssetsr  )r  r'  r
  r  s       r  fetch_account_helperzmexc.fetch_account_helper  s`     6>33F;;;: V^!AA&IIH& ??8V44e << Js   AAAAAAc                   K   | j                  dd|      \  }}| j                          d{    | j                  ||       d{   }| j                  |dg       }g }t	        dt        |            D ]a  }||   }| j                  |dd      }	| j                  |	      }
|j                  | j                  |d      | j                  |d      |
|d	       c |S 7 7 w)
a  
        fetch all the accounts associated with a profile

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#account-information
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-all-informations-of-user-39-s-asset

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `account structures <https://docs.ccxt.com/#/?id=account-structure>` indexed by the account type
        r^   Nbalancesr   assetr4  r6   r'  )r6   r'  r&  r   )
r  r  r  r  r*  r  r-  r,  rh  r+  )r  r
  r  r  r  r  r2  r3  r   
currencyIdr&  s              r  fetch_accountszmexc.fetch_accounts  s      !>>PTV\]
E!!!22:uEExR8q#d)$ 		A1gG++GWjIJ**:6DMM&&w5((&9	 			  	"Es"   *CCCCBCCc                 v  K   | j                          d{    | j                  |      }|d   st        | j                  dz         d|d   i}| j	                  | j                  ||             d{   }| j                  |di       }||| j                  |d      | j                  |d      ddd	S 7 7 Bw)
ac  
        fetch the trading fees for a market

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#query-mx-deduct-status

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/#/?id=fee-structure>`
        NrB   z- fetchTradingFee() supports spot markets onlyrH  r6   r  rN  rO  )r   rH  r   r   r   r   )r  rj  r(   r6   spotPrivateGetTradeFeer  	safe_dictr0  r  rH  r
  rj  r  r  r  s          r  fetch_trading_feezmexc.fetch_trading_fee  s      !!!V$f~TWW'VVWWfTl
 44T[[&5QRR ~~h3%%d,=>%%d,=>
 	
) 	" Ss#   B9B5AB94B75AB97B9c                    d }|dk(  r| j                  |dg       }n,|dk(  r| j                  |dg       }n| j                  |dg       }d|i}|dk(  rt        dt        |            D ]  }||   }| j                  |d      }| j	                  |d       }| j                  |d	i       }	| j                  |d
i       }
| j                  | j                  |	d            }| j                  | j                  |
d            }i }| j                  |	      ||<   | j                  |
      ||<   | j                  |      ||<    |S |dk(  rt        dt        |            D ]i  }||   }| j                  |d      }| j                  |      }| j                         }| j                  |d      |d<   | j                  |d      |d<   |||<   k | j                  |      S t        dt        |            D ]i  }||   }| j                  |d      }| j                  |      }| j                         }| j                  |d      |d<   | j                  |d      |d<   |||<   k | j                  |      S )NrC   assetsrD   r  r  r   r   rH  rI  rJ  r  r4  availableBalancefreefrozenBalanceusedlocked)	r  r*  r  r+  safe_symbolr,  parse_balance_helpersafe_balancer   )r  r  r  walletr2  r3  entryr  rH  rR  rS  baseCode	quoteCode	subResultr  r&  r   s                    r  custom_parse_balancezmexc.custom_parse_balance&  s   z !__Xx<F6!__Xvr:F__Xz2>F(#!1c&k* >q	++E8<))(D9uk2>|R@2243C3CD'3RS 33D4D4DUG4TU	"$	&*&?&?&E	(#'+'@'@'G	)$!%!2!29!=v> M6!1c&k* 'q	!--eZ@
..z:,,."&"2"25:L"M"&"2"25/"J&t' $$V,,1c&k* 'q	!--eW=
..z:,,."&"2"25&"A"&"2"25("C&t' $$V,,r  c                    | j                         }| j                  |d      |d<   | j                  |d      |d<   | j                  |d      |d<   | j                  |d      }| j                  |d      }t        j                  ||      |d<   |S )	Nr  r  r  
totalAssettotalborrowedinterestdebt)r   r+  r1   r  )r  r  r   r  r  s        r  r  zmexc.parse_balance_helper  s    ,,.**5(;**5&9++E<@z2##E:6!,,T8<r  c                   K   | j                          d{    d}i }| j                  dd|      \  }}| j                  |d      }| j                  |dd      }| j	                  |ddg      }d}||s|dk(  rd}| j                  |d      }|5| j                  |d      }	|	7dj                  | j                  |	            }n| j                  |      }
|
d	   }| j                  d|d
       d}||d<   | j	                  |ddg      }| j                  | j                  ||             d{   }nv|dk(  r*| j                  | j                  ||             d{   }nG|dk(  r*| j                  | j                  ||             d{   }nt        | j                  dz         | j!                  ||      S 7 7 7 c7 6w)a  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#account-information
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-all-informations-of-user-39-s-asset
        https://mexcdevelop.github.io/apidocs/spot_v3_en/#isolated-account

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.symbols]:  # required for margin, market id's separated by commas
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        Nr_   rH  rC   FrH  rG  r  r6   zsymbol or symbolsrB   rD   z' fetchBalance() not support self method)r  r  r+  r/  r  r  r  
market_idsrj  check_required_argument#spotPrivateGetMarginIsolatedAccountr  r  r  r-   r6   r  )r  r
  r  r  rH  isMarginr  parsedSymbolsrH  rG  rj  s              r  fetch_balancezmexc.fetch_balance  s     !!!
!??PTV\]
F%%fl;
>>&(E:6Hl#;<"jH6L M%%fh7F~//&)<&$'HHT__W-E$FMV, &t((H[\!J!.GIYYv)'<=F!EEdkkRY[aFbccH6!!77GV8TUUH6!!AA$++gW]B^__Htww)RRSSj ((:>>c 	", dU_sF   GF:DG,F=-.GF?.G
G0G=G?GGc                   K   |t        | j                  dz         | j                          d{    | j                  |      }d}| j	                  d||      \  }}d|d   i}d}|dk(  rc|||d<   |||d<   | j                  |d	      }	|	| j                  |d	      }|	|d
<   | j                  | j                  ||             d{   }n|;||d<   | j                  |d      }
|
"| j                  || j                  d         |d<   |||d<   | j                  | j                  ||             d{   }| j                  |d      }| j                  ||||      S 7 27 7 /w)a  
        fetch all trades made by the user

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#account-trade-list
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-all-transaction-details-of-the-user-s-order

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch trades for
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Nz+ fetchMyTrades() requires a symbol argumentr   rH  r6   rB   r  rZ  r  r  rq  rr  r?  rt  r  )r'   r6   r  rj  r  r	  r  spotPrivateGetMyTradesr  r  r   %contractPrivateGetOrderListOrderDealsr  r  )r  rH  r  rZ  r
  rj  r  r  r   r  r  r  s               r  fetch_my_tradeszmexc.fetch_my_trades  s     >#DGG.[$[\\!!!V$
!??QWY_`
FfTl
  ',$ #( %%fg6E 673%*	"66t{{7F7STTF.  (-%''
;;*.((5$,,GW:X*YGJ' ',$!GGT[]cHdeeH0 __Xv6F  >>Q 	"" U< fs5   .E)E"BE)	E%
A-E)7E'8+E)%E)'E)c                   K   | j                          d{    i }d}|| j                  |      }| j                  d||      \  }}	d}
|dk(  rQ|t        | j                  dz         |d   |d<   ||d<   | j                  | j                  ||	             d{   }
n@||d<   | j                  | j                  ||	             d{   }| j                  |d	      }
| j                  |
||||	      S 7 7 \7 /w)
a  
        fetch all the trades made from a single order

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#account-trade-list
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#query-the-order-based-on-the-order-number

        :param str id: order id
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Nr   rB   z. fetchOrderTrades() requires a symbol argumentr6   rH  r  rk  r  )
r  rj  r  r'   r6   r  r  )contractPrivateGetOrderDealDetailsOrderIdr  r  )r  r6   rH  r  rZ  r
  r  rj  r  r  r   r  s               r  fetch_order_tradeszmexc.fetch_order_tradesq  s     !!![[(F >>?QSY[ab
E~'2b(bcc &tGH!#GI66t{{7E7RSSF. #%GJ!KKDKKX_afLghhH0 __Xv6F  uEE{ 	" T0 is4   C;C5BC;C7.C;	C9
,C;7C;9C;c                    K   | j                  |d      }|t        | j                  dz         | j                          d {    |||d}| j	                  | j                  ||             d {   }|S 7 57 w)N
positionIdz5 modifyMarginHelper() requires a positionId parameter)r	  r$  r'  )r	  r'   r6   r  'contractPrivatePostPositionChangeMarginr  )r  rH  r$  addOrReducer
  r	  r  r  s           r  modify_margin_helperzmexc.modify_margin_helper  s     &&v|<
#DGG.e$eff!!!$

 EEdkkRY[aFbcc  	" ds$   A A<A8.A<1A:2A<:A<c                 F   K   | j                  ||d|       d{   S 7 w)a  
        remove margin from a position

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#increase-or-decrease-margin

        :param str symbol: unified market symbol
        :param float amount: the amount of margin to remove
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=reduce-margin-structure>`
        SUBNr  r  rH  r$  r
  s       r  reduce_marginzmexc.reduce_margin  %      ..vvufMMMM   !!c                 F   K   | j                  ||d|       d{   S 7 w)a  
        add margin

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#increase-or-decrease-margin

        :param str symbol: unified market symbol
        :param float amount: amount of margin to add
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=add-margin-structure>`
        ADDNr  r  s       r  
add_marginzmexc.add_margin  r  r  rR  c                   K   | j                          d{    d|i}| j                  |d      }|j| j                  |d      }| j                  |d      }|| j                  |      nd}|||t	        | j
                  dz         ||d<   |d   |d<   ||d<   n||d<   | j                  | j                  ||             d{   S 7 7 w)	at  
        set the level of leverage for a market

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#switch-leverage

        :param float leverage: the rate of leverage
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        NrR  r	  rR  positionTypez setLeverage() requires a positionId parameter or a symbol argument with openType and positionType parameters, use openType 1 or 2 for isolated or cross margin respectively, use positionType 1 or 2 for long or short positionsr6   rH  )r  r	  r0  rj  r'   r6   )contractPrivatePostPositionChangeLeverager  )	r  rR  rH  r
  r  r	  rR  r  rj  s	            r  set_leveragezmexc.set_leverage  s     !!!
 &&v|<
''
;H++FNCL-3-?T[[(dF l&:'  3V  )V  W  W&.
#$*4L!*6'$.GL!CCDKKPWY_D`aaa# 	"" bs"   CCB/CCCCc                 &  K   | j                          d{    d}i }|| j                  |      }|d   |d<   |||d<   | j                  | j                  ||             d{   }| j	                  |di       }| j	                  |dg       }	g }
t        dt        |	            D ]a  }|	|   }| j                  |d      }|
j                  ||d|| j                  |      | j                  |d      | j                  |d	      d
       c |
S 7 7 w)aY  
        fetch the history of funding payments paid and received on self account

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-details-of-user-s-funding-rate

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch funding history for
        :param int [limit]: the maximum number of funding history structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding history structure <https://docs.ccxt.com/#/?id=funding-history-structure>`
        Nr6   rH  rt  r  
resultListr   
settleTimefunding)r   rH  r&  r  r  r6   r$  )r  rj  (contractPrivateGetPositionFundingRecordsr  r  r*  r  r	  rh  r  r0  )r  rH  r  rZ  r
  rj  r  r  r  r  r2  r3  r  r  s                 r  fetch_funding_historyzmexc.fetch_funding_history  s8     !!!
 [[(F &tGH#(GK FFt{{SZ\bGcddB x4__T<<
q#j/* 	AqME))%>IMM & LL3&&ud3**5)< 	 { 	" es#   DDAD%D&B(DDc                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  ||d d      }| j                  |d      }| j                  |d      }d }	||dz   }	i d|d|d	d d
d dd dd d|d| j	                  |      d|d|d| j	                  |      dd dd dd dd dd dd d|	iS )NfundingRatenextSettleTimerH  r   r  collectCyclehr   	markPrice
indexPriceinterestRateestimatedSettlePricer  fundingTimestampfundingDatetimenextFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimer  )r0  r	  r+  r  r  )
r  r   rj  r,  r-  r  rH  r  r  intervalStrings
             r  parse_funding_ratezmexc.parse_funding_rateS  s|    **8]C#00;KL##Hh7!!(FD*E%%h<	##Hn=%^N
H
f
 
 $	

 D
 #D
 
 Y/
 ?
  4
 t||,@A
 t
 #D
 "4
 "4
  '!
" &t#
$ %
 	
r  c                 B   K   | j                  ||       d{   S 7 w)a  
        fetch the current funding rate interval

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-contract-funding-rate

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        N)fetch_funding_rate)r  rH  r
  s      r  fetch_funding_intervalzmexc.fetch_funding_interval}  s!      ,,VV<<<<s   c                   K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  |di       }| j                  ||      S 7 j7 +w)aw  
        fetch the current funding rate

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-contract-funding-rate

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        NrH  r6   r  )r  rj  "contractPublicGetFundingRateSymbolr  r  r3  )r  rH  r
  rj  r  r  r2  s          r  r5  zmexc.fetch_funding_rate  s      !!!V$fTl
 @@WV\A]^^  626&&vv66- 	"
 _"   BBA BB*BBc           
        K   |t        | j                  dz         | j                          d{    | j                  |      }d|d   i}|||d<   | j	                  | j                  ||             d{   }| j                  |d      }| j                  |dg       }	g }
t        dt        |	            D ]r  }|	|   }| j                  |d      }| j                  |      }| j                  |d	      }|
j                  ||| j                  |d
      || j                  |      d       t | j                  |
d      }| j!                  ||d   ||      S 7 '7 w)ad  
        fetches historical funding rate prices

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-contract-funding-rate-history

        :param str symbol: unified symbol of the market to fetch the funding rate history for
        :param int [since]: not used by mexc, but filtered internally by ccxt
        :param int [limit]: mexc limit is page_size default 20, maximum is 100
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
        Nz5 fetchFundingRateHistory() requires a symbol argumentrH  r6   rt  r  r  r   r  r"  )r   rH  r"  r  r  r  )r'   r6   r  rj  #contractPublicGetFundingRateHistoryr  r  r*  r  r+  r  r	  rh  r0  r  sort_byfilter_by_symbol_since_limit)r  rH  r  rZ  r
  rj  r  r  r  r2  ratesr3  r  r  symbolInnerr  sorteds                    r  fetch_funding_rate_historyzmexc.fetch_funding_rate_history  su     >#DGG.e$eff!!!V$fTl

 #(GK AA$++gW]B^__2 x0|R8q#f+& 	A1IE''x8H**84K))%>ILL%#//}E& LL3 	 e[1009I5RWXXe 	" `s#   .EEAE8E9CEEc                    K   | j                          d{    | j                  |ddd      }| j                  |       d{   }| j                  |d      }| j	                  ||d      S 7 V7 +w)a`  
        retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes, if a market has a leverage tier of 0, then the leverage tiers cannot be obtained for self market

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-the-contract-information

        :param str[] [symbols]: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `leverage tiers structures <https://docs.ccxt.com/#/?id=leverage-tiers-structure>`, indexed by market symbols
        NrD   Tr  rH  )r  market_symbolsr{  r  parse_leverage_tiersr  rG  r
  r  r  s        r  fetch_leverage_tierszmexc.fetch_leverage_tiers  su      !!!%%gvtTB55f==\ ~~h/((wAAc 	"=s!   A1A-,A1A/*A1/A1c                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }	d}
g }| j                  |d	      }|dk(  r=d
| j                  ||d d      | j                  |      d d d | j                  |d      |dgS t	        j
                  |
|      r
t	        j                  |
|      }|j                  | j                  t	        j                  ||            | j                  ||d d      | j                  |      | j                  |
      | j                  |      | j                  |      | j                  t	        j                  d|            |d       t	        j                  ||	      }t	        j                  ||      }|}
t	        j
                  |
|      r
|S )NrH  maintenanceMarginRateinitialMarginRatery  riskIncrVolriskIncrMmrriskIncrImrrq  rm  r   r   rw  )tierrH  r4  minNotionalmaxNotionalrH  rw  r   rL  )
r+  r  r,  r0  r1   	string_ltr  rh  r  
string_div)r  r   rj  r  rH  rI  ry  rJ  rK  rL  floortiersrV  caps                 r  parse_market_leverage_tiersz mexc.parse_market_leverage_tiers*  s   N ##D(3 $ 0 07N O ,,T3FG!!$1&&t];&&t];&&t];""45# "..xzR $ 7 7 @#'#'-1#'#3#3D-#H 	  v.$$UK8CLL))'*<*<S+*NO**8VT:N 33G<#007#005)-):):;P)Q#001C1CCIZ1[\	 	 !( 2 23Dk R$+$6$67Lk$Z!E v. r  r4  c                     | j                  |d      }| j                  |d      }| j                  |d      }| j                  |       || j                  ||      | j                  ||      || j                  |d      dS )Naddressr  r  memo)r   r4  r  rW  tag)r+  check_addressr,  r.  )r  depositAddressr4  rW  r  r8  s         r  parse_deposit_addresszmexc.parse_deposit_addressy  s     "">9=%%nf=
$$^Y?	7#"//
HE..y*E##NF;
 	
r  r&  c                 V  K   | j                          d{    | j                  |      }d|d   i}| j                  |d      }d}|t| j                  ||      }| j	                  |di       }||v r9| j	                  ||i       }	| j                  |	di       }
| j                  |
d      }n| j                  ||      }|||d<   | j                  |d      }| j                  | j                  ||             d{   }| j                  |dd      }| j                  |d      S 7 7 ,w)a  
        fetch a dictionary of addresses for a currency, indexed by network

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#deposit-address-supporting-network

        :param str code: unified currency code of the currency for the deposit address
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `address structures <https://docs.ccxt.com/#/?id=address-structure>` indexed by the network
        Nr  r6   r  r<  r   F)r  r4  r+  r.  r  r  network_code_to_idr  #spotPrivateGetCapitalDepositAddressr  parse_deposit_addressesindex_by)r  r&  r
  r4  r  networkCoder8  networkUnifiedr<  r  networkInfor  addressStructuress                r  "fetch_deposit_addresses_by_networkz'mexc.fetch_deposit_addresses_by_network  s@     !!!==&HTN
 &&vy9	"!44[$GN~~h
B?H)..>2F"oogvrB ,,[)D	 33KF	 !*GI69-AA$++gW]B^__ !884O}}.	::C 	"( `s"   D)D$C#D):D';*D)'D)c                 `  K   | j                          d{    | j                  |      }d|d   i}| j                  |d      }|t        | j                  dz         d}| j                  ||      }| j                  |di       }||v r9| j                  ||i       }	| j                  |	di       }
| j                  |
d      }n| j                  ||      }|||d<   | j                  |d      }| j                  | j                  ||             d{   }| j                  ||      S 7 7 w)a  
        create a currency deposit address

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#generate-deposit-address-supporting-network

        :param str code: unified currency code of the currency for the deposit address
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.network]: the blockchain network name
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        Nr  r6   r  z4 createDepositAddress requires a `network` parameterr<  r   )r  r4  r+  r'   r6   r.  r  r  r^  r  $spotPrivatePostCapitalDepositAddressr  r\  )r  r&  r
  r4  r  rb  r8  rc  r<  r  rd  r  s               r  create_deposit_addresszmexc.create_deposit_address  s@     !!!==&HTN
 &&vy9#DGG.d$dee	00dC>>(J;X%nnX~rBG//'62>K((i@I//TBI !*GI69-BB4;;wX^C_`` ))(H==9 	"* as"   D.D)C;D.D,D.,D.c                   K   | j                  |d      }| j                  ||       d{   }d}|#| j                  || j                  ||            }n| j                  | j                  d      }| j                  ||      }|| j                  ||      }n=t        |j                               }| j                  |d      }	| j                  ||	      }|$t        | j                  dz   |z   dz   |z   dz         |S 7 ӭw)a-  
        fetch the deposit address for a currency associated with self account

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#deposit-address-supporting-network

        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.network]: the chain of currency, self only apply for multi-chain currency, and there is no need for single chain currency
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        r  Nr;  r   z9 fetchDepositAddress() cannot find a deposit address for z, and networkzMconsider creating one using .createDepositAddress() method or in MEXC website)	r+  rf  r  r.  r   r  r  r+   r6   )
r  r&  r
  r  re  r2  r   defaultNetworkForCurrencyr  keys
             r  fetch_deposit_addresszmexc.fetch_deposit_address  s#     ""695"&"I"I$PV"WW^^$5t7N7NwX\7]^FnnT\\3DEG(,(8(8$(G%(4(9;TU-2245&&tQ/(93?> +f!fim!mp!  CJ  "J  M\  "\  ]  ] Xs   (D C>CD c                   K   | j                          d{    i }d}|M| j                  |      }|d   |d<   | j                  |d      }| | j                  |d      }|d   dz   |z   |d<   |||d<   ||dkD  rt	        d      ||d	<   | j                  | j                  ||             d{   }| j                  ||||      S 7 7 w)
a&  
        fetch all deposits made to an account

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#deposit-history-supporting-network

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr6   r  r  r  r  r_  .This exchange supports a maximum limit of 1000rZ  )r  r4  r+  r  r#   "spotPrivateGetCapitalDepositHisrecr  parse_transactions)	r  r&  r  rZ  r
  r  r4  
rawNetworkr  s	            r  fetch_depositszmexc.fetch_deposits  s     !!!
 }}T*H&tnGFO ))&)<J%695")&/C"7*"D#(GK t|#$TUU$GG@@WV\A]^^" &&x5%HHS 	"0 _s"   CC	BC0C1CCc                 6  K   | j                          d{    i }d}|| j                  |      }|d   |d<   |||d<   ||dkD  rt        d      ||d<   | j                  | j	                  ||             d{   }| j                  ||||      S 7 ~7 w)a2  
        fetch all withdrawals made from an account

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#withdraw-history-supporting-network

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of withdrawals structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr6   r  r  r_  ro  rZ  )r  r4  r#   $spotPrivateGetCapitalWithdrawHistoryr  rq  )r  r&  r  rZ  r
  r  r4  r  s           r  fetch_withdrawalszmexc.fetch_withdrawals8  s      !!!
 }}T*H&tnGFO#(GK t|#$TUU$GGBB4;;wX^C_``( &&x5%HHM 	"$ as"   BBA%B<B=BBtransactionc                 *   | j                  |d      }|dnd}| j                  |dd      }d }| j                  |d      }||j                  d      d   }d }| j                  |d	      }	|	| j                  |	      }| j	                  ||      }
| j                  | j                  |d
      |      }| j                  |d      }| j                  |d      }| j                  |d      }d }| j                  |d      }|| j                  |      |
d}|dk(  rt        j                  ||      }i d|d|d|d|d| j                  |      d	|d|d|dd d| j                  |d      dd dd d|d| j                  |      d|
d
|dd d d |dS )Nr6   r\   
withdrawal
insertTime	applyTimer  r  r   r  r  r$  rW  txIdtransactionFeer  r   txidr  r  	addressToaddressFromrY  rX  tagTotagFromr'  r4  r  )commentinternalr!  )
r+  r  splitr.  r,   parse_transaction_status_by_typer  r1   
string_subr  )r  rw  r4  r6   r'  r  r  currencyWithNetworkr  rr  r&  r  r  rW  r~  r!  feeCostStrings                    r  parse_transactionzmexc.parse_transactionl  sT   R k40Zyl''\;O	
"..{FC*,2237:J%%k9=
!--j9G&&z8<66t7G7GU]7^`de''X>"";	:V4((6FG$))-8 C <"--lMJL
K
"
 D
 	

 Y/
 w
 w
 
 4
 4##K8
 T
 t
 D
 d''5
 
  f!
" t#
$ )
 	
r  c                 ~    ddddddddddddddddddd
d}| j                  ||i       }| j                  |||      S )Nfailedpendingr  )rL  r  r  r  567r  )
rL  r  r  r  r  r  r  8910)r\   ry  )r  r+  )r  r  r'  statusesByTyper  s        r  r  z%mexc.parse_transaction_status_by_type  ss       
. ??>4<&&99r  c                    K   | j                          d{    | j                  |      }d|d   i}| j                  d| j                  ||             d{   }| j	                  |d      S 7 X7 w)a  
        fetch data on a single open contract trade position

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-the-user-s-history-position-information

        :param str symbol: unified market symbol of the market the position is held in, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        NrH  r6   r   )r  rj  fetch_positionsr  r  )r  rH  r
  rj  r  r  s         r  fetch_positionzmexc.fetch_position  sw      !!!V$fTl
 --dDKK4PQQx++ 	"
 Rs"   A3A/AA3A1A31A3c                    K   | j                          d{    | j                  |       d{   }| j                  |dg       }| j                  ||      S 7 B7 +w)a  
        fetch all open positions

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-the-user-s-history-position-information

        :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/#/?id=position-structure>`
        Nr  )r  'contractPrivateGetPositionOpenPositionsr  parse_positionsrE  s        r  r  zmexc.fetch_positions  s^      !!!EEfMM> ~~h3##D'22C 	"Ms   AAAA*AApositionc                    | j                  | j                  |d      |      }|d   }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }|dk(  rdnd}| j                  |d	      }	|	dk(  rd
nd}
| j                  |d      }| j                  |d      }| j                  |d      }| j	                  i d|dd d|d| j                  |      dd d|dd d|dd d| j                  |      dd d|
dd dd dd d|d| j                  |      d d d d || j                  |      d d d d d
      S )NrH  holdVolopenAvgPriceimr  rL  longshortmargin_moder;  rQ  rR  liquidatePrice
updateTimer   r6   	contractsra  
entryPrice
collateralr  unrealizedPnlr   rH  notionalr&  r  liquidationPriceinitialMargin)
initialMarginPercentagemaintenanceMarginmaintenanceMarginPercentagemarginRatior  r  rP  rL  rM  lastUpdateTimestamp)r  r+  r0  r	  safe_positionr  r  )r  r  rj  rH  r  r  r  rawSider  rR  
marginTyperR  r  r  s                 r  parse_positionzmexc.parse_position   s
   z !!$"2"28X"FO!$$Xy9	%%h?
((48""8^<!S.vw##Hm<$,OZ'
##Hj9++H6FG%%h=	!! #
H#
$#
 f#
 **95	#

 D#
 *#
 $#
 D#
 T#
 ))(3#
 $#
 *#
 #
 #
 #
   0!#
" T..}=##
$ (,!%+/"Y/!##'7#
  	r  c                 \  K   | j                  dd|      \  }}| j                          d{    |dk(  rQd|i}| j                  | j                  ||             d{   }| j	                  |di       }| j                  |      S |dk(  rt        | j                  dz   |z         y7 {7 Kw)a  
        fetches a transfer

        https://mexcdevelop.github.io/apidocs/spot_v2_en/#internal-assets-transfer-order-inquiry

        :param str id: transfer id
        :param str [code]: not used by mexc fetchTransfer
        :param dict params: extra parameters specific to the exchange api endpoint
        :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
        r   NrB   transact_idr  rD   z& fetchTransfer() is not supported for )r  r  (spot2PrivateGetAssetInternalTransferInfor  r  parse_transferr(   r6   )	r  r6   r&  r
  r  r  r  r  r  s	            r  fetch_transferzmexc.fetch_transfer  s      !>>PTV\]
E!!!rG "JJ4;;W^`eKfggH >>(FB7D&&t,,6!TWW'OOR\\]]/ 	"
 hs"   *B,B(1B,B*A
B,*B,c                 v  K   | j                  dd|      \  }}| j                          d{    i }d}d}	|| j                  |      }|d   |d<   |dk(  rn|||d<   ||dkD  rt        d      ||d	<   | j	                  | j                  ||             d{   }
| j                  |
d
i       }| j                  |dg       }	nY|dk(  rT|||d<   | j                  | j                  ||             d{   }
| j                  |
d
      }| j                  |d      }	| j                  |	|||      S 7 7 7 Aw)a  
        fetch a history of internal transfers made on an account

        https://mexcdevelop.github.io/apidocs/spot_v2_en/#get-internal-assets-transfer-records
        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-the-user-39-s-asset-transfer-records

        :param str code: unified currency code of the currency transferred
        :param int [since]: the earliest time in ms to fetch transfers for
        :param int [limit]: the maximum number of  transfers structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transfer structures <https://docs.ccxt.com/#/?id=transfer-structure>`
        r   Nr6   r4  rB   rq  r;   z,This exchange supports a maximum limit of 50z	page-sizer  result_listrD   rt  r  )	r  r  r4  r#   *spot2PrivateGetAssetInternalTransferRecordr  r  'contractPrivateGetAccountTransferRecordparse_transfers)r  r&  r  rZ  r
  r  r  r  r4  r  r  r  s               r  fetch_transferszmexc.fetch_transfers  sm     !>>?OQUW]^
E!!!
}}T*H"*4.GJ (-% 2:'(VWW',$!LLT[[Y`bgMhiiH( ??8VR8D}bAJ6! ',$!II$++V]_dJeffH??8V4D|<J2 ##J%GGE 	" j2 gs5   *D9D2A,D9D5AD95D76=D95D97D9fromAccount	toAccountc                 F  K   | j                          d{    | j                  |      }dddd}| j                  ||      }| j                  ||      }	|Ct        |j	                               }
t        | j                  dz   dj                  |
      z         |	Ct        |j	                               }
t        | j                  dz   dj                  |
      z         |d	   |||	d
}|dk(  s|	dk(  rW| j                  |d      }| j                  |d      }|t        | j                  dz         | j                  |      }|d	   |d<   | j                  | j                  ||             d{   }| j                  ||      }| j                  ||||d      S 7 7 /w)a  
        transfer currency internally between wallets on the same account

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#user-universal-transfer

        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: account to transfer from
        :param str toAccount: account to transfer to
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.symbol]: market symbol required for margin account transfers eg:BTCUSDT
        :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
        NSPOTFUTURESISOLATED_MARGIN)rB   rD   rC   z fromAccount must be one of z, z toAccount must be one of r6   )r  r$  fromAccountTypetoAccountTyperH  z: transfer() requires a symbol argument for isolated margin)r$  r  r  )r  r4  r+  r  r  r#   r6   r  r  r'   rj  spotPrivatePostCapitalTransferr  r  )r  r&  r$  r  r  r
  r4  accountsfromIdtoIdr  r  rH  rj  r  rw  s                   r  r   zmexc.transfer  s     !!!==&'

 !!(K8)4>(D*H H499UY? Z[[<(D*F FSW XYYd^%!	
 ''T5F-F%%fh7FYYvx0F~'2n(noo[[(F &tGH<<T[[RX=YZZ ))(H={{;&")
  	G 	"8 [s"   F!FEF!/F0-F!F!r   c                    | j                  |d      }| j                  |g d      }| j                  |d      }|| j                  |      nd }| j                  |d      }d }d }	||dk(  rdnd}|dk(  rdnd}	n$| j                  |d      }| j                  |d	      }	||||| j	                  ||      | j                  |d
      | j                  |      | j                  |	      | j                  | j                  |dd            d	S )Nr4  )r  r~  tranIdr  r'  INMAINCONTRACTfromtor$  transact_statero  )	r   r6   r  r  r4  r$  r  r  r  )	r+  safe_string_nr	  r  r,  r0  parse_account_idparse_transfer_statusr-  )
r  r   r4  r  r6   r  r  	directionaccountFrom	accountTos
             r  r  zmexc.parse_transfer5  s$   @ %%h
;
*KL%%h=	/8/D4<<	*4$$Xv6		 %.$%6&ZK'0D'8
vI**8V<K((48I" //
HE&&x:00=..y9001C1CHN^`g1hi

 
	
r  c                 2    ddd}| j                  |||      S )NrB   rD   )r  r  r  r  s      r  r  zmexc.parse_account_idn  s&    
 &&99r  c                 4    dddd}| j                  |||      S )Nr  r  r  )SUCCESSFAILEDWAITr  r  s      r  r  zmexc.parse_transfer_statusu  s)    

 &&99r  rW  c                 ,  K   | j                          d{    | j                  |      }| j                  ||      \  }}| j                  | j                  di       }| j                  |dd      }| j                  |||      }| j                  ||d         }| j                  |       |d   ||d}	|||	d<   |||	d<   | j                  |ddg      }| j                  | j                  |	|             d{   }
| j                  |
|      S 7 7 w)	a  
        make a withdrawal

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#withdraw-new

        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr<  r  r  r&  r6   )r  rW  r$  rX  )r  r4  handle_withdraw_tag_and_paramsr  r   r-  r+  r^  rZ  r  spotPrivatePostCapitalWithdrawr  r  )r  r&  r$  rW  rY  r
  r4  r<  r  r  r  s              r  r   zmexc.withdraw}  s*     !!!==&99#vFV>>$,,
B?$$VY	B""8Wg>))'8F3CD7#TN

 ?!GFO!(GIYYv	9'=>F<<T[[RX=YZZ %%h991 	"$ [s"   DDC"D9D:DDrP  c                 t   K   d|rdndi}| j                  | j                  ||             d{   }|S 7 w)a  
        set hedged to True or False for a market

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#change-position-mode

        :param bool hedged: set to True to use dualSidePosition
        :param str symbol: not used by mexc setPositionMode()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        r  r   r   N)-contractPrivatePostPositionChangePositionModer  )r  rP  rH  r
  r  r  s         r  set_position_modezmexc.set_position_mode  sG      AQ
 KKDKKX_agLhii  js   -868c                 t   K   | j                  |       d{   }| j                  |d      }||dk(  dS 7 w)a  
        fetchs the position mode, hedged or one way, hedged for binance is set identically for all linear markets or all inverse markets

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-position-mode

        :param str symbol: not used by mexc fetchPositionMode
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an object detailing whether the market is in hedged or one-way mode
        Nr  r   )r   rP  )&contractPrivateGetPositionPositionModer	  )r  rH  r
  r  r  s        r  fetch_position_modezmexc.fetch_position_mode  sJ      DDVLL ((6:#q(
 	
 Ms   868codesc                    K   | j                          d{    | j                  |       d{   }| j                  ||      S 7 /7 w)  
        fetch deposit and withdrawal fees

        https://mexcdevelop.github.io/apidocs/spot_v3_en/#query-the-currency-information

        :param str[]|None codes: returns fees for all currencies if None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>`
        N)r  r)  parse_transaction_feesr  r  r
  r  s       r  fetch_transaction_feeszmexc.fetch_transaction_fees  sK      !!!??GG< **8U;;? 	"Gs   A
AA
AA
A
c                    i }t        dt        |            D ]f  }||   }| j                  |d      }| j                  |      }| j                  |d      }|| j	                  ||      sR| j                  ||      ||<   h |i |dS )Nr   r  r&  )r   r\   r   )r*  r  r+  safe_currencyin_arrayparse_transaction_fee)	r  r  r  withdrawFeesr3  r  r  r4  r&  s	            r  r  zmexc.parse_transaction_fees  s    q#h-( 	QAQKE))%8J))*5H##Hf5D4==u#=%)%?%?x%PT"	Q %
 	
r  c                     | j                  |dg       }i }t        dt        |            D ]P  }||   }| j                  |d      }| j                  | j                  d   ||      }| j                  |d      }	|	||<   R |S )Nr  r   r  r<  r  )r  r*  r  r+  r   r0  )
r  rw  r4  r  r2  r6  networkEntryr8  rb  r!  s
             r  r  zmexc.parse_transaction_fee  s    6 ook="Eq#k*+ 	&A&q>L((yAI**4<<
+CYPYZK""<?C"%F;	& r  c                    K   | j                          d{    | j                  |       d{   }| j                  ||d      S 7 07 w)r  Nr  )r  r)  parse_deposit_withdraw_feesr  s       r  fetch_deposit_withdraw_feesz mexc.fetch_deposit_withdraw_fees2  sM      !!!??GG< //%HH? 	"Gs   AAAA	A	Ac                 T   | j                  |dg       }| j                  |      }t        dt        |            D ]\  }||   }| j	                  |d      }| j                  || j	                  |d            }| j                  |d      d dd d dd|d   |<   ^ | j                  |      S )	Nr  r   r  r&  r  )r!  r   )r   r\   r<  )r  deposit_withdraw_feer*  r  r+  r.  r0  $assign_default_deposit_withdraw_fees)	r  r!  r4  r  r2  r6  r  r8  rb  s	            r  parse_deposit_withdraw_feezmexc.parse_deposit_withdraw_fee]  s    6 ooc="=**3/q#k*+ 	A&q>L((yAI11)T=M=MhX^=_`K  ++L-H"&
  "&	/F:{+		 88@@r  c                   K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  |dg       }| j                  ||      S 7 j7 +w)ag  
        fetch the set leverage for a market

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-leverage

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `leverage structure <https://docs.ccxt.com/#/?id=leverage-structure>`
        NrH  r6   r  )r  rj  "contractPrivateGetPositionLeverager  r  parse_leverager  s          r  fetch_leveragezmexc.fetch_leverage  s      !!!V$fTl
 @@WV\A]^^> ~~h3""400K 	"
 _r9  c                    d }d }d }t        dt        |            D ]c  }||   }| j                  |d      }| j                  |d      }	|	dk(  r| j                  |d      }n|	dk(  r| j                  |d      }|dk(  rdnd}e ||d	   |||d
S )Nr   rR  r  r   rR  r   r;  rQ  rH  )r   rH  rH  longLeverageshortLeverage)r*  r  r	  )
r  rR  rj  rH  r  r  r3  r  rR  r  s
             r  r  zmexc.parse_leverage  s    
q#h-( 	DAQKE((
;H,,UNCLq #00
C" $ 1 1% D(0AGJ	D X&$(*
 	
r  c                     | j                  | j                  d      }| j                  |dd      }d}t        t        |   |||      \  }}|dk(  s|du rd}||gS )a  
 @ignore
        marginMode specified by params["marginMode"], self.options["marginMode"], self.options["defaultMarginMode"], params["margin"] = True or self.options["defaultType"] = 'margin'
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param bool [params.margin]: True for trading spot-margin
        :returns Array: the marginMode in lowercase
        r9  rC   FNTr;  )r+  r   r/  r  r3   r3  )r  
methodNamer
  defaultValuer9  r  rH  r  s          r  r3  z"mexc.handle_margin_mode_and_params  sm     &&t||]C>>&(E:
"4LZY_amn
F8#T)9#JF##r  c                 r  K   | j                          d{    i }|,t        |      }|dk(  r| j                  |d         }|d   |d<   |||d<   | j                  | j	                  ||             d{   }| j                  |d      }	| j                  |	||      }
| j                  |
||      S 7 7 >w)u  
        fetches historical positions

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#get-the-user-s-history-position-information

        :param str[] [symbols]: unified contract symbols
        :param int [since]: not used by mexc fetchPositionsHistory
        :param int [limit]: the maximum amount of candles to fetch, default=1000
        :param dict [params]: extra parameters specific to the exchange api endpoint

 EXCHANGE SPECIFIC PARAMETERS
        :param int [params.type]: position type，1: long, 2: short
        :param int [params.page_num]: current page number, default is 1
        :returns dict[]: a list of `position structures <https://docs.ccxt.com/#/?id=position-structure>`
        Nr   r   r6   rH  rt  r  )r  r  rj  .contractPrivateGetPositionListHistoryPositionsr  r  r  filter_by_since_limit)r  rG  r  rZ  r
  r  symbolsLengthrj  r  r  	positionss              r  fetch_positions_historyzmexc.fetch_positions_history  s       !!!LM!WQZ0$*4L!#(GK LLT[[Y`bhMijjR ~~h/((w?	)))UEBBi 	" ks"   B7B3AB76B57=B75B7rH  c                 d  K   | j                          d{    | j                  |      }|d   rt        | j                  dz         |j	                         }|dk7  r|dk7  rt        | j                  dz         | j                  |d      }|t        | j                  dz         | j                  |d	d
      }||dk(  rdndd}||d   |d<   ||dk(  rdnd|d<   | j                  |d	      }| j                  | j                  ||             d{   }| j                  ||      S 7 7 w)aM  
        set margin mode to 'cross' or 'isolated'

        https://mexcdevelop.github.io/apidocs/contract_v1_en/#switch-leverage

        :param str marginMode: 'cross' or 'isolated'
        :param str [symbol]: required when there is no position, else provide params["positionId"]
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.positionId]: required when a position is set
        :param str [params.direction]: "long" or "short" required when there is no position
        :returns dict: response from the exchange
        NrB   z/ setMarginMode() supports contract markets onlyr;  rQ  z@ setMarginMode() marginMode argument should be isolated or crossrR  z. setMarginMode() requires a leverage parameterr  r	  r   r   )rR  rR  r6   rH  r  r  )r  rj  r)   r6   lowerr(   r	  r'   safe_string_lower_2r  r  r  r  )	r  rH  rH  r
  rj  rR  r  r  r  s	            r  set_margin_modezmexc.set_margin_mode&  sM     !!!V$&>DGG&WWXX%%'
#
g(=TWW'iijj$$VZ8#DGG.^$^__,,V[,O	 (J6Q
  &tGH ,5,@aqGN#6;/GGT[]cHdee ""8V441 	"( fs"   D0D+C=D0D.D0.D0c                 ^    | j                         | j                  | j                  dd      z
  S )Nr7  r   )r  r	  r   )r  s    r  r  z
mexc.nonceM  s+      "T%6%6t||EUWX%YYYr  r   GETc                    | j                  |d      }| j                  |d      }| j                  ||      \  }}d }	|dk(  s|dk(  r|dk(  r| j                  d   |   |   dz   |z   }	n+| j                  d   |   |   dz   | j                  z   dz   |z   }	|}
|dk(  r|dk(  rO|d	k(  s
|d
k(  s|dk(  r@| j	                         | j                  | j                  dd      d}
| j                  |      }n3| j	                         |
d<   | j                  | j                  dd      |
d<   d}|
r| j                  |
      }|	d|z   z  }	|dk(  r| j                          | j                  | j                  |      | j                  | j                        t        j                        }|	d|z   z  }	| j                  | j                  | j                  dd      d}|d	k(  s|d
k(  s|dk(  r}d|d<   nv|dk(  s|dk(  rk| j                  d   |   |   dz   | j!                  ||      z   }	| j#                  || j%                  |            }|dk(  r|r|	d| j                  |      z   z  }	n| j                          t'        | j	                               }d}| j                  |d| j                  | j                  dd      d}|d	k(  r| j                  |      }|}n/| j)                  |      }|r|| j                  |      z  }|	d|z   z  }	| j                  |z   |z   }| j                  | j                  |      | j                  | j                        t        j                        }||d<   |	|||dS )Nr   r   rB   r   r   rQ  z/api/r   POSTPUTDELETEr>  r4  )r  r>  r  r  ?z&signature=r5  )zX-MEXC-APIKEYsourcezapplication/jsonContent-Typer   r   r   )ApiKeyzRequest-Timer  r  	Signature)r  r  bodyheaders)r+  resolve_pathr   r<   r  r	  r   r  	urlencoder(  hmacencodesecrethashlibsha256apiKeyimplode_paramsr  extract_paramsr  keysort)r  pathr   r  r
  r  r  sectionaccessr  	urlParamsparamsEncoded	signaturer  auths                  r  signz	mexc.signP  sl   ""3*!!#q)((v6ff8 3("ii&w/7#=Dii&w/7'ADLLPSVVY]]I"h&Vv-=6U?X^bjXj%)ZZ\&*&7&7lTX&Y!I  99V,D-1ZZ\Ik*.2.?.?l\`.aIl+M $y 9s]**"//1 IIdkk-&@$++dkkBZ\c\j\jk	)I55%)[["..t||XvN & fo6X;M*<'
"g&8))E"7+F3c9D<O<OPTV\<]]CYYvt':':4'@AF!3!777C//1

-	"kk$-$6"..t||XvN	 V#99V,DD!\\&1Fv 66sTz){{Y.5 IIdkk$&7T[[9QSZSaSab	'0$fdwOOr  reasonr  r  r  r  c
                 2   |y | j                  |dd      }
|
du ry | j                  |dd       }|g|dk7  rb|dk7  r]| j                  dz   |z   }| j                  | j                  d   ||       | j                  | j                  d	   ||       t        |      y )
Nr  FTr&  200rq   r  r  )r/  r+  r6   throw_broadly_matched_exceptionr  throw_exactly_matched_exceptionr#   )r  r&  r0  r  r  r  r  r  requestHeadersrequestBodyr  responseCodefeedbacks                r  handle_errorszmexc.handle_errors  s     ..9e<d?''&$?$<5+@|WZGZww}t+H001I4QYZ001I<Yab))r  )r   r   r   )N)NNNNNNN)__name__
__module____qualname__r   r  r  r   r  r   r9  r"   r   rE  r<  r=  r  r   r  r   r  r   r  dictr  r  r  r  r  r   r   r  r   r  r  r'  rZ  r.  r1  r   r   r   r+  rJ  r4  r5  r   rh  r   ro  r   r}  r  r  r  r  r  r  r  r  rO  r  r  r  r  r  r  r   r  r   r  r   r  r  r   r  r  r  r   r  r  r  r   r   r3  r6  r5  rA  r   rF  r   rU  r	   r
   r\  rf  ri  rm  r    rs  rv  r  r  r  r   r  r  r!   r  r  r   r  r  r  r   boolr  r  r  r  r  r  r  r   r  r  r3  r  r  r  r/  intr:  __classcell__)r  s   @r  r3   r3      sK
   q# qf )+ #
J ') S 4 -/ e: eN *, 9V 9" /1 zx /1 zx @DB >S > >S\ >@i 	 en  <@d[] ]? ]?S ]? ]?bfglbm ]?~H Hv H HT" 8<$]ajl aK aKC aKWZ aKquvzq{ aKF
 
4 
 6:" S47 S4 S4j 68 G1 G1F G1Ro4 o o6 ob 8<B %4W %4N XZ cc c c( Y[ ds d% d( mqy{ "f "fI "fY "fX] "ffi "fH KO[_hj -,^ IMY]fh 4l IMY]fh |5| FH 9+$|*< 9+v 8<B s.C s. s.j 04$UYbd sK sKC sKs sKimnsit sKj <@ 03S 03d 59tZ^gi UUc UU UUTW UUnrsxny UUn 7;\`ik Q Q3 QVY Qptuzp{ Q  9=4^bkm Q# QS QX[ Q  @DRVeirt _ _C __b _ 9=R i.S i.# i.V 6:"  3s  3D 59 V3c V3p^ ^v ^ ^@:	:: : :@S @4l +- g 8 ;= %
c %
AT %
Nf-H f-P *, }? }?~ 37TX\eg X?C X?s X?RU X?t ?CQUdhqs KF3 KF KF3 KF^a KFZ SU  $ FH N# Nu NL^ N CE Ns NE NI[ N ?C2 b3 b b< 9=4^bkm I# IS IX[ IV(
6 (
[ (
T @B 
=3 
=k 
= <>  7s  7+  7D >BPTcgpr @Ys @Y# @Y]` @YD =A ;B' ;BP] ;BzM M$|J\ M^
h 
R` 
* JL +;S +;PTUcPd +;Z >@ '> '>N '>R =?  > : 04$UYbd 5I 5IC 5Is 5Iimnyiz 5In 37TX\eg 2IC 2Is 2IRU 2Ilpq|l} 2IhX
T X
X X
Q\ X
t:6 8: ,3 ,$ 8<B +3W +34PX> +3Zet eV eN 9=R #s ## #M #J 154VZce PH# PHS PHPS PHjno|j} PHd ac 53 5 5C 5TW 5gt 5n7
t 7
x 7
= 7
r::C :C : JNVX %:3 %: %: %:]h %:N CGr d C . 7;2 
 
0 =A )<' )<V
#8 #J BFb )Iw )IV+A +AZ 8: /13 /1h /1b
t 
V 
x 
* @BPT $  @DRVeirt DCW DCC DC_b DCy}  G  zH DCL DHPR %5 %5S %5NZ &eBSW >P@# s  c TX `c r  r3   )9 ccxt.async_support.base.exchanger   ccxt.abstract.mexcr   r>  r"  ccxt.base.typesr   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!   typingr"   ccxt.base.errorsr#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   ccxt.base.decimal_to_precisionr0   ccxt.base.preciser1   r3    r  r  <module>rJ     s    6 *   U  U  U  U  U  U  U  U  * 0 - - . ' & . + ) ) * ) 4 %IZ8[ IZr  