
    !:h+M                        d dl mZ d dlmZ d dlZd dlmZmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZ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&  G d dee      Z'y)    )Exchange)ImplicitAPIN)AnyBalancesCurrencyIntLedgerEntryLeverageMarketNumOrder	OrderBook	OrderSide	OrderTypePositionStrStringsTickerTickersFundingRateTradeTransaction)List)ExchangeError)AuthenticationError)ArgumentsRequired)
BadRequest)InvalidOrder)NotSupported)	TICK_SIZE)Precisec                   0    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e	   fdZ
dede	fdZi fdedefd	Zd
i fdedefdZdPdede	defdZdd
d
i fdedededee   fdZdPde	defdZd
d
i fdedededee   fdZd
d
d
i fdedededee   fdZdPdede	defdZd
i fdededefdZi fdedefdZi fdedefdZ dPde	defdZ!i fde"fdZ#de"fdZ$d
i fdede%de&d e'd!e(f
d"Z)d#efd$Z*dPd%ede	de+fd&Z,d
i fd'edefd(Z-d
i fdefd)Z.i fdefd*Z/d
i fdedee0   fd+Z1dPd,ede	fd-Z2d
i fd'edefd.Z3d
d
d
i fdedededee+   fd/Z4d
d
d
i fdedededee+   fd0Z5d
d
d
i fdedededee+   fd1Z6d
d
d
i fdedededee+   fd2Z7d
i fdede&de+fd3Z8i fdee0   fd4Z9d
d
d
i fd5edededee:   fd6Z;dPd7ed8e<de:fd9Z=d: Z>d
i fd5ed e'd;efd<Z?dPd=ed8e<de@fd>ZAd
i fd?edefd@ZBdPd?ede	deCfdAZDdB ZEdCdDi d
d
fdEZFdFeGdGedHedIedJedKefdLZHdM ZIdNeJf fdOZK xZLS )Qdefxreturnc                    | j                  t        t        |          i ddddddddd	d
dd
dddddi dd dd
dd
dddd
dd
dddddd
dddd
dddddd
dd
d d
d!d
i d"d
d#d
d$dd%dd&dd'd
d(d
d)d
d*d
d+dd,d
d-d
d.dd/d
d0dd1dd2d
i d3dd4d
d5d
d6d
d7d
d8d
d9d
d:d
d;d
d<d
d=d
d>d
d?d
d@d
dAddBd
dCd
i dDd
dEddFd
dGd
dHd
dIddJd
dKd
dLd
dMddNddOd
dPd
dQddRddSddTdi dUd
dVddWd
dXd
dYddZd
d[d
d\dd]dd^dd_dd`ddad
dbd
dcd
ddd
ded
d
ddd
d
d
ddfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdwdxdydydxdzd{d|gd}gd~diddddi ddddddddddddddddddddddddddddddddddddddddddii ddddddddddddddddddddddddddddddddddddddddddddddddddddddddidddddddddxidddd| j	                  d      | j	                  d      diddd
idd 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
dd d d
dd
d
d
d
dddd
d
d
dd
dddd
d
d
dd
ddddd
d
d
dddid	ddid dĜd d dĜdŜdi dt
        t        t        t        t        t        t        t        t        t        t        t        dȜdt
        idʜdt        i      S )Nidr#   namezDefx X	rateLimitd   versionv1	certifiedFprohostnamezdefx.comdexThasCORSspotmarginswapfutureoption	addMargincancelAllOrderscancelAllOrdersAftercancelOrdercancelWithdrawcloseAllPositionsclosePositioncreateConvertTradecreateDepositAddresscreateMarketBuyOrderWithCostcreateMarketOrdercreateMarketOrderWithCostcreateMarketSellOrderWithCostcreateOrder$createOrderWithTakeProfitAndStopLosscreateReduceOnlyOrdercreateStopLimitOrdercreateStopLossOrdercreateStopMarketOrdercreateStopOrdercreateTakeProfitOrdercreateTrailingAmountOrdercreateTrailingPercentOrdercreateTriggerOrderfetchAccountsfetchBalancefetchCanceledOrdersfetchClosedOrderfetchClosedOrdersfetchConvertCurrenciesfetchConvertQuotefetchConvertTradefetchConvertTradeHistoryfetchCurrenciesfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsfetchDepositsWithdrawalsfetchFundingHistoryfetchFundingIntervalfetchFundingIntervalsfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchLedgerfetchLeveragefetchMarginAdjustmentHistoryfetchMarginModefetchMarketsfetchMarkOHLCVfetchMarkPricefetchMarkPricesfetchMyTrades
fetchOHLCVfetchOpenInterestHistoryfetchOpenOrderfetchOpenOrders
fetchOrderfetchOrderBookfetchOrdersfetchOrderTradesfetchPositionfetchPositionHistoryfetchPositionModefetchPositionsfetchPositionsHistoryfetchPremiumIndexOHLCVfetchStatusfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTransactionsfetchTransfersfetchWithdrawals)reduceMarginsandboxsetLeverage	setMarginsetPositionModetransferwithdraw
timeframes1m3m5m15m30m1h2h4h12h1d1w1M)r   r   r   r   r   r   r   r   r   r   r   r   urlszOhttps://github.com/user-attachments/assets/4e92bace-d7a9-45ea-92be-122168dc87e4zhttps://api.{hostname})publicprivatezhttps://api.testnet.{hostname}zhttps://defx.com/homezhttps://docs.defx.com/docszhttps://api-docs.defx.com/ urlz https://app.defx.com/join/6I2CZ7)logoapitestwwwdocfeesreferralr   getzhealthcheck/ping   zsymbols/{symbol}/ohlczsymbols/{symbol}/tradeszsymbols/{symbol}/priceszsymbols/{symbol}/ticker/24hrz%symbols/{symbol}/depth/{level}/{slab}zticker/24HrAggz	c/marketszc/markets/metadatazanalytics/market/stats/newUserszanalytics/market/stats/tvlz)analytics/market/stats/volumeByInstrumentz"analytics/market/stats/liquidationz"analytics/market/stats/totalVolumez#analytics/market/stats/openInterestz"analytics/market/stats/totalTradeszanalytics/market/stats/basis)z$analytics/market/stats/insuranceFundz(analytics/market/stats/longAndShortRatioz"analytics/market/stats/fundingRatezanalytics/market/overviewzexplorer/searchzexplorer/transactionszexplorer/blocksapi/order/{orderId}z
api/orderszapi/orders/oco/{parentOrderId}z
api/tradeszapi/position/activeapi/users/metadata/leverage api/users/metadata/feeMultiplierapi/users/metadata/slippageapi/users/referralapi/users/apikeysz connection-signature-message/evmapi/users/profile/walletszapi/notificationszapi/wallet/balancezapi/wallet/transactionszapi/analytics/user/overviewzapi/analytics/user/pnl)zapi/analytics/points/overviewzapi/analytics/points/history)z	api/orderzapi/position/ocozapi/users/socket/listenKeysr   r   r   z'api/users/referral/recordReferralSignupr   r   zapi/transfers/withdrawalzapi/transfers/bridge/withdrawal)z!api/position/updatePositionMargin'api/users/socket/listenKeys/{listenKey}z$api/users/apikeys/{accessKey}/statusr   api/users/apikeys/{accessKey})zapi/orders/allOpenr   zapi/position/{positionId}zapi/position/allr   r   )r   postputpatchdeleter   tradingz0.0002z0.0005)	tierBased
percentagemakertakeroptionssandboxModefeatures)lastmarkindex)IOCFOKPOGTD)
marginModetriggerPricetriggerPriceTypetriggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedselfTradePreventiontrailingicebergleveragemarketBuyByCostmarketBuyRequiresPrice  )r   limitdaysBack	untilDayssymbolRequired)r   triggerr   r   )r   r   r   r   r   i  i )r   r   r   r   r   r   r   )r   r   r   daysBackCanceledr   r   r   r   r   )	r   rD   createOrdersrm   rr   rq   rt   rS   rn   extendsforDerivatives)linearinverse)r2   r   r4   r5   commonCurrencies
exceptions)404missing_auth_signatureorder_rejectedinvalid_order_idfilter_lotsize_maxqtyfilter_notional_min'failed_index_price_up_multiplier_filterno_open_ordersactive_position_not_foundposition_inactiveinvalid_position_idzInternal server errorzBad Request)exactbroadprecisionMode)
deep_extendsuperr#   describeparse_numberr   r   r   r   r    )self	__class__s    C/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/defx.pyr   zdefx.describe   s0
   dD : < W?
&W?
HW?
 	W?

 tW?
 W?
 5W?
 
W?
 4W?
  ]]] %] 	]
 %] %] T] "4] '] t] !%] $T]  ] %e] ']  /!]" $U#]$ ,U%]& 0']( t)]* 7+], (-]. '/]0 &u1]2 (3]4 "55]6 (7]8 ,U9]: -e;]< %d=]>  ?]@ A]B &tC]D #EE]F $TG]H )%I]J $UK]L $UM]N +EO]P "5Q]R &uS]T (U]V 1%W]X  Y]Z +E[]\ &u]]^ '_]` (a]b #Dc]d *5e]f $Ug]h "5i]j tk]l  m]n /o]p "5q]r s]t !%u]v !%w]x "5y]z  {]| d}]~ +E]@ !%A]B "4C]D dE]F !$G]H tI]J #EK]L  M]N 'O]P $UQ]R !$S]T (U]V )%W]X tY]Z t[]\ ]]^ T_]` ta]b "5c]d #Ee]f $Ug]h !%i]j #Ek]l !&#"#(! y]W?
P QW?
l i67
 ?? /00
  =%mW?
X   . 3Q  6q  6q	 
 ;A  DQ  -a  (  1!  >q  9!  H  A!  A!  B1   A!! " ;A# $ EFHIBC9:/056/01 : 11 (!  =a  )!	 
 21  :1  ?  :1  1!  0  ?  8  0  1!  6q   :1! " 5a# $ >?<=' , *+01;<;<@A;<GH129:89?@! BCGHDE23	  <Q" 34349:01GH=>#Y4 ;RTYW?
B !%"&!..x8!..x8	CW?
R uSW?
X #&+(, %)$(%*-
 -2).+06:#'#'"&#(	( #(/4$)#($)+0273$6 %)&+!%$(%)*/& ',#($)*/	# '+!$#($)*/( ',!$$*%+#($)*/$ ',!$$*,-%+#($)*/	*  #KH#V "#3  $	 ##cUYW?
D
 E
W?
F
 %.A&2(4-9+7?K&21=)5+7-: ":G
W?
l
 Ym
W?
 W W	    c                 j    | j                  |      }d}| j                  |d      }|rd}nd}|ddd|dS )aY  
        the latest known information on the availability of the exchange API

        https://api-docs.defx.com/#4b03bb3b-a0fa-4dfb-b96c-237bde0ce9e6

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
        Nsuccessokerror)statusupdatedetar   info)v1PublicGetHealthcheckPing	safe_bool)r   paramsresponser   r   s        r   fetch_statuszdefx.fetch_statusq  sQ     226: ..95FF
 	
r   c                 H    | j                  |      }| j                  |d      S )a\  
        fetches the current integer timestamp in milliseconds from the exchange server

        https://api-docs.defx.com/#4b03bb3b-a0fa-4dfb-b96c-237bde0ce9e6

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        t)r   safe_integer)r   r  r  s      r   
fetch_timezdefx.fetch_time  s)     226:   3//r   c                    ddi}| j                  | j                  ||            | j                  | j                  ||            g}|}| j                  |d   d      }| j	                  |d      }| j                  |d   d      }t        dt        |            D ]   }||   d   }	d}
|	|v r||	   d   }
|
||   d<   " | j                  |      S )	ae  
        retrieves data on all markets for defx

        https://api-docs.defx.com/#73cce0c8-f842-4891-9145-01bb6d61324d
        https://api-docs.defx.com/#24fd4e5b-840e-451e-99e0-7fea47c7f371

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        typeperpsr   datamarketr   Nr   )v1PublicGetCMarketsextendv1PublicGetCMarketsMetadata	safe_listindex_byrangelenparse_markets)r   r  requestpromises	responsesactiveMarketsactiveMarketsByTypemarketMetadatasimarketIdr   s              r   fetch_marketszdefx.fetch_markets  s     G
 $$T[[&%AB,,T[[&-IJ
 	L y|V<"mmM8D..1v>q#o./ 	2A&q)(3HF..,X6x@+1OAx(	2 !!/22r   r  c                 v   | j                  |d      }|j                  d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |      }|dz   |z   dz   |z   }| j                  |dg       }	| j	                  |di       }
| j                  |	d	      }| j	                  |d
i       }| j	                  |di       }| j	                  |di       }| j	                  |di       }i d|d|d|d|d|d|d|d|ddddddddddddd| j                  |dd       dk(  d!dd"dd| j                  |
d#      | j                  |
d$      | j                  d%      d d d d | j                  |d&      | j                  |d'      d(d | j                  |d)      d*| j                  |d+      | j                  |d,      d*| j                  |d-      | j                  |d.      d*| j                  |d/      d d*| j                  |d+      | j                  |d,      d*d0d |d1S )2Nr  _r   r   /:filtersr   
filterTypePRICE_FILTERLOT_SIZEMARKET_LOT_SIZENOTIONALr&   symbolbasequotesettlebaseIdquoteIdsettleIdr	  r4   r2   Fr3   Tr5   r6   activer   r   contractr   r   r   1stepSizetickSize)amountpricecappedLeverage)minmaxminQtymaxQtyminPricemaxPriceminNotional)r   r4  r5  costr  )r   r   r   contractSizeexpiryexpiryDatetimestrike
optionType	precisionlimitscreatedr   )safe_stringsplitsafe_currency_coder  	safe_dictr  safe_numberr   )r   r  r  partsr,  r-  r)  r*  r(  r"  r   filtersByTypepriceFilter	lotFiltermarketLotFilternotionalFilters                   r   parse_marketzdefx.parse_marketG  s   ##FH5s#!!%+""5!,&&v.''0e#c)E1..B7~~ffb1g|<nn]NBGNN=*bA	..8I2Nz2F6
(6
f6
 D6
 U	6

 e6
 f6
 w6
 6
 F6
 E6
 e6
 D6
 e6
 e6
 d&&vx<H6
  !6
" d#6
$ %%dG4%%dG4 --c2"**9jA))+zB  ++F4DE
  ++Ix@++Ix@
  ++KD++KD
  ++NMJ
  ++OXF++OXF#, k6
 6	
r   r(  c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  ||      S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://api-docs.defx.com/#fe6f81d0-2f3a-4eee-976f-c8fc8f4c5d56

        :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>`
        r(  r&   )load_marketsr  "v1PublicGetSymbolsSymbolTicker24hrr  parse_tickerr   r(  r  r  r  r  s         r   fetch_tickerzdefx.fetch_ticker  sa     	V$fTl
 ::4;;wPV;WX0   622r   Nsymbolsc                 R   | j                          d}|6| j                  |      }| j                  |d      }|| j                  |      }d}| j	                  d||      \  }}|dk(  rt        | j                  dz   |z   dz         | j                  |      }| j                  ||      S )a  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://api-docs.defx.com/#8c61cfbd-40d9-410e-b014-f5b36eba51d1

        :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>`
        Nr   r~   r2   z% fetchTickers() is not supported for z markets)	rT  market_symbolsrG  r  handle_market_type_and_paramsr   r&   v1PublicGetTicker24HrAggparse_tickers)r   rY  r  r  firstSymbolr	  r  s          r   fetch_tickerszdefx.fetch_tickers  s     	))'2G**7A6K&[199.&RXYf6>tww)PPSWWZddee008  !!(G44r   tickerc           
      4   | j                  |d      }|| j                  |      }|d   }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }	| j                  |d      }
| j                  |d      }| j                  |d	      }| j                  |d
      }|dk(  rd }| j                  |      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j	                  i d|d|d|d|d|d|d|d|d|dd d|d|dd dd d|d|dd |
|	| j                  |d       | j                  |d!      |d"|      S )#Nr(  	openPrice	highPricelowPrice	lastPricequoteVolumevolumepriceChangePercentpriceChange	closeTimer   bestBidPrice
bestBidQtybestAskPrice
bestAskQty	timestampdatetimehighlowbid	bidVolumeask	askVolumevwapopencloser   previousClosechanger   average	markPrice
indexPrice)
baseVolumerg  r~  r  r   )rG  r  r  iso8601safe_ticker)r   ra  r  r  r(  ry  rr  rs  rz  rg  r  r   r|  tsrq  rt  ru  rv  rw  s                      r   rV  zdefx.parse_ticker  sO   f ##FH5[[*F!44vz2  5&&v}=%%fh7
%%f.BC
!!&-8v{37B<<#v~6$$V\:	v~6$$V\:	 !
f!
!
 !
 D	!

 3!
 3!
 !
 3!
 !
 D!
 D!
 U!
 D!
 T!
 f!
  *!!
" t#!
$ %&))&+>**6<@-!
. / 	r   r   sincer   c                    | j                          | j                  |      }d}||}t        ||      }|d   | j                  | j                  ||      |d}| j                  |dd      }	| j                  |ddg      }|	| j                         n|	|d<   |d|d<   n7||d<   |	0| j                  |      }
|
dz  }||z  }| j                  ||      |d<   | j                  | j                  ||            }| j                  |||||      S )	a  

        https://api-docs.defx.com/#54b71951-1472-4670-b5af-4c2dc41e73d0

        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]: max=1000, max=100 when since is defined and is less than(now - (999 * (timeframe in ms)))
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch orders for
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        r   r&   )r(  intervalr   untiltillendTimer   	startTime)rT  r  r7  rG  r   safe_integer_2omitmillisecondsparse_timeframesumv1PublicGetSymbolsSymbolOhlcr  parse_ohlcvs)r   r(  	timeframer  r   r  r  maxLimitr  r  timeframeInSecondstimeframeInMillisecondstotalTimeframeInMillisecondsr  s                 r   fetch_ohlcvzdefx.fetch_ohlcv>  s6    	V$=EHe$Tl(()YO

 ##FGV<6GV#455:]T..0	=#$GK #(GK }%)%9%9)%D"*<t*C'/47N/N,%)XXe5Q%R	"44T[[&5QR(   69eUKKr   c           	          | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS )Nstartry  rr  rs  rz  rh  )r  rK  )r   ohlcvr  s      r   parse_ohlcvzdefx.parse_ohlcvy  sn     eW-UF+UF+UE*UG,UH-
 	
r   c                     | j                          | j                  |      }d}||}t        ||      }|d   |d}| j                  | j	                  ||            }| j                  ||||      S )a'  
        get the list of most recent trades for a particular symbol

        https://api-docs.defx.com/#5865452f-ea32-4f13-bfbc-03af5f5574fd

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        2   r&   )r(  r   )rT  r  r7  v1PublicGetSymbolsSymbolTradesr  parse_trades)	r   r(  r  r   r  r  r  r  r  s	            r   fetch_tradeszdefx.fetch_trades  s     	V$=EHe$Tl
 66t{{7F7ST   65%@@r   c                    | j                          i }|| j                  |      }|d   |d<   |d}t        ||      }||d<   | j                  | j	                  ||            }| j                  |dg       }	| j                  |	d||      S )a  
        fetch all trades made by the user

        https://api-docs.defx.com/#06b5b33c-2fc6-48de-896c-fc316f5871a7

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        Nr&   rY  r)   pageSizer  )rT  r  r7  v1PrivateGetApiTradesr  r  r  )
r   r(  r  r   r  r  r  r  r  r  s
             r   fetch_my_tradeszdefx.fetch_my_trades  s     	[[(F!'GIH%(E"'GJ--dkk'6.JK& ~~h3  tUE::r   tradec                 N   | j                  |d      }| j                  |d| j                  |            }| j                  |d      }| j                  ||      }|d   }| j                  |d      }| j                  |d      }| j                  |d      }	| j                  |d      }
| j	                  |d      }| j                  |d	      }| j	                  |d
      }||rd}nd}| j                  |	|| j                  |      ||||d |
|d | j                  |d      dd|d|      S )Ntimerp  r(  r5  qtyr&   orderIdrole
buyerMakersidesellbuyfeeUSDCr>  currency)r&   rp  rq  r(  r  r5  r4  r>  ordertakerOrMakerr	  r  r   )rG  r  	parse8601safe_marketsafe_string_lowerr   
safe_trader  )r   r  r  r  rp  r  r(  r5  r4  r&   oidr  r  r  s                 r   parse_tradezdefx.parse_trade  sR   2 v.%%e[$..:NO	##E84!!(F3!  0!!%/eT*ui0--eV<^^E<8
%%eV4!"Y/(((6" ! 
" # 	r   c           	      ^   | j                          | j                  |      }|d}| j                  |di       }| j                  |dg       }|d   || j	                  |d      d}| j                  | j                  ||            }| j                  |d      }	| j                  |||	dd	d
d      S )a  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://api-docs.defx.com/#6c1a2971-8325-4e7d-9962-e0bfcaacf9c4

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.slab]: slab from market.info.depthSlabs
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        
   r   
depthSlabsr&   r   )r(  levelslabrp  bidsasksr5  r  )	rT  r  rJ  r  rG  &v1PublicGetSymbolsSymbolDepthLevelSlabr  r  parse_order_book)
r   r(  r   r  r  
marketInfor  r  r  rp  s
             r   fetch_order_bookzdefx.fetch_order_book  s     	V$=E^^FFB7
~~j,;Tl$$T1-

 >>t{{7TZ?[\, %%h<	$$Xvy&&RY[`aar   c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  ||      S )a  
        fetches mark price for the market

        https://api-docs.defx.com/#12168192-4e7b-4458-a001-e8b80961f0b7

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.subType]: "linear" or "inverse"
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        r(  r&   )rT  r  v1PublicGetSymbolsSymbolPricesr  rV  rW  s         r   fetch_mark_pricezdefx.fetch_mark_price@  s`     	V$fTl
 66t{{7F7ST   622r   c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  ||      S )ag  
        fetch the current funding rate

        https://api-docs.defx.com/#12168192-4e7b-4458-a001-e8b80961f0b7

        :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>`
        r(  r&   )rT  r  r  r  parse_funding_raterW  s         r   fetch_funding_ratezdefx.fetch_funding_rate]  s`     	V$fTl
 66t{{7F7ST &&x88r   c                 (   | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }i d|d|d   d|d|dd dd d	d d
d d|d|d| j                  |      dd dd dd dd dd dd dd iS )Nr~  r  payoutFundingRatenextFundingPayoutr   r(  interestRateestimatedSettlePricerp  rq  fundingRatefundingTimestampfundingDatetimenextFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimer  )rK  r  r  )r   r0  r  r~  r  r  fundingTimes          r   r  zdefx.parse_funding_ratey  s:    $$X{;	%%h=
&&x1DE''2EF
H
fX&
 
 *	

 D
 #D
 
 
 ;
 
 t||K8
 t
 #D
 "4
 "4
  '!
" &t#
$ %
 	
r   c                     | j                          | j                  |      }| j                  |d      }| j                  |      S )ak  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://api-docs.defx.com/#26414338-14f7-40a1-b246-f8ea8571493f

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        assets)rT  v1PrivateGetApiWalletBalancer  parse_balancer   r  r  r  s       r   fetch_balancezdefx.fetch_balance  sC     	44V< ~~h1!!$''r   c                     d|i}t        dt        |            D ]R  }||   }| j                  | j                  |d            }| j	                         }| j                  |d      |d<   |||<   T | j                  |      S )Nr   r   assetbalancetotal)r  r  rI  rG  accountsafe_balance)r   balancesresultr  r  coder  s          r   r  zdefx.parse_balance  s    H
 q#h-( 	#AqkG**4+;+;GW+MNDllnG#//CGG"F4L	#   ((r   r	  r  r4  r5  c                 r   | j                          | j                  |      }| j                  |dd      }| j                  |ddg      }|j	                         }	|j	                         }
|d   |
|	d}| j                  |d      }| j                  |dd      }|	dk(  }|	d	k(  }| j                  |d
      }|||d
<   n|rd|d
<   |r||d<   | j                  |d      }|||d<   ||Ld|d<   |#| j                  ||      |d<   |rd|d<   n(d|d<   n"| j                  ||      |d<   |rd|d<   nd|d<   |r|| j                  ||      |d<   | j                  ||      |d<   | j                  |g d      }| j                  | j                  ||            }| j                  |d      }| j                  ||      S )a  
        create a trade order

        https://api-docs.defx.com/#ba222d88-8856-4d3c-87a9-7cec07bb2622

        :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 float [params.triggerPrice]: The price a trigger order is triggered at
        :param str [params.reduceOnly]: for swap and future reduceOnly is a string 'true' or 'false' that cant be sent with close position set to True or in hedge mode. For spot margin and option reduceOnly is a boolean.
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        
reduceOnlyreduce_onlyr&   )r(  r  r	  r   	stopPricer   MARKETLIMITr   GTCclientOrderIdnewClientOrderId
MARK_PRICEworkingTypeTAKE_PROFIT_MARKETr	  TAKE_PROFIT_LIMITSTOP_MARKET
STOP_LIMITr5  quantity)clOrdIDr  client_order_idpostOnlyr   r  r   r   r  )rT  r  safe_bool_2r  upperrG  safe_string_2safe_string_upperprice_to_precisionamount_to_precisionv1PrivatePostApiOrderr  rJ  parse_order)r   r(  r	  r  r4  r5  r  r  r  	orderType	orderSider  r   r   isMarketisLimitr   r  r  r  s                       r   create_orderzdefx.create_order  s     	V$%%flMJ
6L-#@AJJL	JJL	Tl

 **63DE))&+~N(w&,,V]C"%0GM").&$.GL!((A$*7G&'#'B%1GM"*'+'>'>v'W$&:GFO&9GFO'+'>'>v|'T$&3GFO&2GFOu(#66vuEGG"66vvF
6  $^  _--dkk'6.JK. ~~h/f--r   r   c                 @    |dddddd}| j                  |||      S |S )Nry  canceledrejectedclosed)NEWOPEN	CANCELLEDREJECTEDFILLEDrG  )r   r   statusess      r   parse_order_statuszdefx.parse_order_status  s:    '&"H ##Hff==r   r  c                 <   | j                  |d      }| j                  |d      }| j                  |d      }| j                  ||      }|d   }| j                  |d      }| j                  |d      }| j                  |d      }	| j                  |d      }
| j                  |d      }| j                  | j                  |d	            }| j                  | j                  |d
            }| j                  |d      }d }d }|	9|	j	                  d      dk\  r| j                  |d      }n| j                  |d      }| j                  | j                  |d            }| j                  | j                  |d            }| j                  i d|d|d|d| j                  |      d|d|d| j                  |
      d|d|	d|d| j                  |d      d| j                  |d      d|d|d|d|dd |||d d d | j                  |d      dd|d|      S )Nr  r  r(  r5  origQtyr	  r   r  executedQtyavgPricer   take_profitr   r  	createdAt	updatedAtr&   rp  rq  lastTradeTimestamplastUpdateTimestampr  r  r   r   r   totalFeer  r  )r}  r4  filled	remainingr>  tradesr  r   )
rG  r  r  	omit_zerofindr  
safe_orderr  r  r   )r   r  r  r  r  r  r(  r5  r4  r  r   r  r   r}  r   r   r   rp  r  s                      r   r  zdefx.parse_order$  s   4 ""5)4((@##E84!!(F3!  0!!%3**5&9	!!%2%%eV4 0 0 FG..!1!1%!DE,,UMB#  ~~m,1"&"2"25+"F#//{CNN4#3#3E;#GH	!^^D,<,<UK,PQ  
' 
] 
  
 Y/	 

 !"4 
 "#5 
 d--f5 
 f 
 I 
 ; 
 uj9 
 $..= 
 D 
 U 
 L 
  ! 
" T# 
$ ((
;" 9 
: ; 	r   r&   c                    | j                          |dd}| j                  |g d      }|du}|r=|t        | j                  dz         | j	                  |      }||d<   d|d<   |d   |d	<   | j                  |g d      }| j                  | j                  ||            }d	|i}	|r||	d<   n||	d<   | j                  | j                  |      |	      S )
a  

        https://api-docs.defx.com/#09186f23-f8d1-4993-acf4-9974d8a6ddb0

        cancels an open order
        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  r  idTyper  r  r  Nz) cancelOrder() requires a symbol argumentr  r(  r&   r(  )	rT  safe_string_nr   r&   r  r  v1PrivateDeleteApiOrderOrderIdr  r  )
r   r&   r(  r  r  r  isByClientOrderr  r  extendParamss
             r   cancel_orderzdefx.cancel_orders  s     	
 **63bc't3~'2](]^^[[(F!.GI /GH &tGH6#RS66t{{7F7ST '/,9L)!#L{{4++H5|DDr   c                     | j                          | j                  |      }d|d   gi}| j                  | j                  ||            }|S )a  
        cancel all open orders

        https://api-docs.defx.com/#db5531da-3692-4a53-841f-6ad6495f823a

        :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
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        rY  r&   )rT  r  v1PrivateDeleteApiOrdersAllOpenr  rW  s         r   cancel_all_orderszdefx.cancel_all_orders  sT     	V$t~
 77GV8TU r   c                 8   |t        | j                  dz         | j                          | j                  |      }d|d   i}| j	                  | j                  ||            }| j                  |dg       }| j                  |di       }| j                  ||      S )a  
        fetch data on a single open contract trade position

        https://api-docs.defx.com/#d89dbb86-9aba-4f59-ac5d-a97ff25ea80e

        :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>`
        z+ fetchPosition() requires a symbol argumentr(  r&   r  r   )	r   r&   rT  r  v1PrivateGetApiPositionActiver  r  rJ  parse_position)r   r(  r  r  r  r  r  firsts           r   fetch_positionzdefx.fetch_position  s     >#DGG.[$[\\V$fTl
 55dkk'66RS" ~~h3tQ+""5&11r   c                     | j                          | j                  |      }| j                  |dg       }| j                  ||      S )aq  
        fetch all open positions

        https://api-docs.defx.com/#d89dbb86-9aba-4f59-ac5d-a97ff25ea80e

        :param str[] [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>`
        r  )rT  r3  r  parse_positions)r   rY  r  r  	positionss        r   fetch_positionszdefx.fetch_positions  sG     	55f=" NN8VR8	##Iw77r   positionc                    | j                  |d      }| j                  ||      }t        j                  | j                  |d            }| j	                  |d      }| j                  | j                  |d            }| j                  | j                  |d            }| j                  |d      }| j                  i d|d| j                  |d	      d|d   d
d dd dd d| j                  |      dd dd dd d| j                  |      dd dd d| j                  |      dd d| j                  |      d| j                  |d      d d d d d d |d d d d d      S )Nr(  r  positionSidepnl
entryPricemarginAmountr   r&   
positionIdrp  rq  r  initialMargininitialMarginPercentagemaintenanceMarginmaintenanceMarginPercentagenotionalr   unrealizedPnlrealizedPnl	contractsr?  )marginRatioliquidationPricer~  rf  
collateralr   r  r   r   r   r   )	rG  r  r!   
string_absr  r#  safe_positionr   rK  )	r   r;  r  r  sizer  unrealisedPnlr?  rB  s	            r   r4  zdefx.parse_position  s    ##Hh7!!(F3!!$"2"28Z"HI%%h?t'7'7%'HI^^D$4$4X|$LM
((>B!! #
H#
$""8\:#
 fX&#
 	#

 #
 "4#
 T..}=#
 &t#
  #
 *4#
 $++J7#
 #
 #
 T..}=#
 4#
  **40!#
" D,,V^D##
$   $!#9#
  	r   c                    | j                          |dd}| j                  |g d      }| j                  |g d      }|=|t        | j                  dz         | j                  |      }||d<   d|d<   |d   |d<   | j                  | j                  ||            }| j                  |d	      }| j                  |      S )
a  
        fetches information on an order made by the user

        https://api-docs.defx.com/#44f82dd5-26b3-4e1f-b4aa-88ceddd65237

        :param str id: the order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  r'  r)  z( fetchOrder() requires a symbol argumentr  r(  r&   r(  r  )
rT  r*  r  r   r&   r  v1PrivateGetApiOrderOrderIdr  rJ  r  )	r   r&   r(  r  r  r  r  r  r  s	            r   fetch_orderzdefx.fetch_order+  s     	
 **63bc6#RS$~'2\(\]][[(F!.GI /GH &tGH33DKK4PQ4 ~~h/%%r   c                    | j                          i }|| j                  |      }|d   |d<   | j                  |d      }|&| j                  |d      }| j	                  |      |d<   || j	                  |      |d<   |d}t        ||      }||d<   | j                  | j                  ||            }	| j                  |	d	g       }
| j                  |
d||      S )
al  
        fetches information on multiple orders made by the user

        https://api-docs.defx.com/#ab200038-8acb-4170-b05e-4fcb4cc13751

        :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 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
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr&   rY  r  endr  r)   r  r  )
rT  r  r  r  r  r7  v1PrivateGetApiOrdersr  r  parse_orders)r   r(  r  r   r  r  r  r  r  r  r  s              r   fetch_orderszdefx.fetch_ordersa  s     	[[(F!'GI!!&'2YYvw/F!\\%0GEN#||E2GGH%(E"'GJ--dkk'6.JK< ~~h3  tUE::r   c           	      R    ddi}| j                  |||| j                  ||            S )a]  
        fetch all unfilled currently open orders

        https://api-docs.defx.com/#ab200038-8acb-4170-b05e-4fcb4cc13751

        :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 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
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r  r  rX  r  r   r(  r  r   r  reqs         r   fetch_open_orderszdefx.fetch_open_orders  s4     
   t{{37OPPr   c           	      R    ddi}| j                  |||| j                  ||            S )as  
        fetches information on multiple closed orders made by the user

        https://api-docs.defx.com/#ab200038-8acb-4170-b05e-4fcb4cc13751

        :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 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
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r  r  rZ  r[  s         r   fetch_closed_orderszdefx.fetch_closed_orders  s4     
   t{{37OPPr   c           	      R    ddi}| j                  |||| j                  ||            S )au  
        fetches information on multiple canceled orders made by the user

        https://api-docs.defx.com/#ab200038-8acb-4170-b05e-4fcb4cc13751

        :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 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
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r  CANCELEDrZ  r[  s         r   fetch_canceled_orderszdefx.fetch_canceled_orders  s4     

   t{{37OPPr   c                    | j                          | j                  |d      }|t        | j                  dz         | j	                  |d      }|t        | j                  dz         | j                  |d      }|t        | j                  dz         |||d}|dk7  r1| j                  |d	      }|t        | j                  d
z         ||d	<   | j                  |g d      }| j                  | j                  ||            }	|	S )a1  
        closes an open position for a market

        https://api-docs.defx.com/#b2c08074-c4d9-4e50-b637-0d6c498fa29e

        :param str symbol: unified CCXT market symbol
        :param str [side]: one-way mode: 'buy' or 'sell', hedge-mode: 'long' or 'short'
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.positionId]: the position id you want to close
        :param str [params.type]: 'MARKET' or 'LIMIT'
        :param str [params.quantity]: how much of currency you want to trade in units of base currency
        :param str [params.price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        rA  z& closePosition() requires a positionIdr	  z  closePosition() requires a typer  z$ closePosition() requires a quantity)rA  r	  r  r  r5  z! closePosition() requires a price)rA  r	  r  r5  )rT  rG  r   r&   r   r  $v1PrivateDeleteApiPositionPositionIdr  )
r   r(  r  r  rA  r	  r  r  r5  r  s
             r   close_positionzdefx.close_position  s    	%%fl;
#DGG.V$VWW%%ff5<#DGG.P$PQQ##FJ7#DGG.T$TUU$ 

 8$$VW5E}'2U(UVV$GG6#NO<<T[[RX=YZ r   c                     | j                          | j                  |      }| j                  |dg       }| j                  |d|      S )aF  
        closes all open positions for a market type

        https://api-docs.defx.com/#d6f63b43-100e-47a9-998c-8b6c0c72d204

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: A list of `position structures <https://docs.ccxt.com/#/?id=position-structure>`
        r  N)rT  v1PrivateDeleteApiPositionAllr  r8  r  s       r   close_all_positionszdefx.close_all_positions  sI     	55f= ~~h3##D$77r   r  c                    | j                          d}| j                  |dd      \  }}|r| j                  d||||      S i }|||d<   nd|d<   | j                  |d      }|| j	                  |d      }||d<   n| j                         |d<   | j                  | j                  ||            }| j                  |d	g       }	| j                  |	d||      S )
ai  
        fetch the history of changes, actions done by the user or operations that altered the balance of the user

        https://api-docs.defx.com/#38cc8974-794f-48c0-b959-db045a0ee565

        :param str [code]: unified currency code
        :param int [since]: timestamp in ms of the earliest ledger entry
        :param int [limit]: max number of ledger entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest ledger entry
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger>`
        Fre   paginateNr  r   r  rU  transactions)
rT  handle_option_and_paramsfetch_paginated_call_dynamicr  r  r  !v1PrivateGetApiWalletTransactionsr  r  parse_ledger)
r   r  r  r   r  rj  r  r  r  r  s
             r   fetch_ledgerzdefx.fetch_ledger  s     	88PZ[&44]D%QVX^__$GG GG!!&'2YYvw/F"GEN!..0GEN99$++gv:VW~~h;  tUE::r   itemr  c                    | j                  |d      }| j                  |d      }| j                  ||      }| j                  ||      }| j                  |d      }| j                  |d      }| j	                  || j                  |d      d d d d | j                  |      || j                  |      || j                  |      d d d d d|      S )Nr4  r  rp  r	  r&   )r   r&   	directionr  referenceAccountreferenceIdr	  r  r4  rp  rq  beforeafterr   r  )rG  rI  safe_currencyr  safe_ledger_entryparse_ledger_entry_typer   r  )r   rq  r  r4  
currencyIdr  rp  r	  s           r   parse_ledger_entryzdefx.parse_ledger_entry8  s     !!$1%%dG4
&&z8<%%j(;%%dK8	f-%%""4. $006''/"Y/'
  ! 	r   c           	      >    ddddddddd}| j                  |||      S )Nr  r  r   r   
commission)
FundingFee	FeeRebateFeeKickbackRealizedPnlLiquidationClearanceTransferReferralPayout
Commissionr  )r   r	  
ledgerTypes      r   rz  zdefx.parse_ledger_entry_type[  s8     "$+"(&	

 
D$77r   addressc                     | j                          | j                  |      }| j                  ||      |d   d}| j                  | j	                  ||            }| j                  ||      S )a  
        make a withdrawal

        https://api-docs.defx.com/#2600f503-63ed-4672-b8f6-69ea5f03203b

        :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>`
        r&   )r4  r  )rT  r  currency_to_precision)v1PrivatePostApiTransfersBridgeWithdrawalr  parse_transaction)	r   r  r4  r  tagr  r  r  r  s	            r   r   zdefx.withdrawh  so     	==&00v>d^
 AA$++gW]B^_ %%h99r   transactionc                     | j                  |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| j                  d |      dd dd d d d dS )NtransactionIdr   r&   txidrp  rq  networkr  	addressToaddressFromr  tagTotagFromr	  r4  r  r   r   )internalcommentr  )rG  rI  )r   r  r  r  s       r   r  zdefx.parse_transaction  s    _=
K
$
 D
 	

 
 t
 t
 
 4
 4
 T
 t
 D
 d
 //h?
  d!
" t#
$ )
 	
r   r   c                 :   |t        | j                  dz         | j                          d| j                  |      i}| j	                  |      }|d   |d<   | j                  | j                  ||            }| j                  |di       }| j                  ||      S )an  
        set the level of leverage for a market

        https://api-docs.defx.com/#4cb4ecc4-6c61-4194-8353-be67faaf7ca7

        :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
        z) setLeverage() requires a symbol argumentr   r&   r(  r  )	r   r&   rT  number_to_stringr  %v1PrivatePostApiUsersMetadataLeverager  rJ  parse_leverage)r   r   r(  r  r  r  r  r  s           r   set_leveragezdefx.set_leverage  s     >#DGG.Y$YZZ--h7
 V$"4L==dkk'SY>Z[ ~~h3""400r   c                 z    | j                  |d      }| j                  |d      }|| j                  ||      d ||dS )Nr(  r   )r   r(  r   longLeverageshortLeverage)rG  r  safe_symbol)r   r   r  r  leverageValues        r   r  zdefx.parse_leverage  sN     ##Hh7))(J?&&x8)*
 	
r   c                 "    | j                         S N)r  )r   s    r   noncez
defx.nonce  s      ""r   r   GETc                 0   |d   }|d   }| j                  ||      }	| j                  | j                  d   |         }
|
d|z   dz   z  }
| j                  || j	                  |            }| j                  |      }|dk(  r#|
d|	z   z  }
|r|
d| j                  |      z   z  }
n| j                          dd	i}|
d
|	z   z  }
t        | j                               }|}|dk(  s|dk(  r.|| j                  |      z  }|r5|
d| j                  |      z   z  }
n|| j                  |      }||z  }d|d<   | j                  | j                  |      | j                  | j                        t        j                        }| j                   |d<   ||d<   ||d<   |
|||dS )Nr   r   r   r   r   zopen/?zX-DEFX-SOURCEccxtzauth/r  r   zapplication/jsonzContent-TypezX-DEFX-APIKEYzX-DEFX-TIMESTAMPzX-DEFX-SIGNATURE)r   methodbodyheaders)implode_paramsimplode_hostnamer   r  extract_paramskeysort	rawencodecheck_required_credentialsstrr  jsonhmacencodesecrethashlibsha256apiKey)r   pathsectionr  r  r  r  r*   accesspathWithParamsr   r  payload	signatures                 r   signz	defx.sign  s   !*,,T6:##DIIe$4V$<=sW}s""64#6#6t#<=f%X7^++CsT^^F333++-&/G7^++C))+,EG$*?"?4>>&113!777C%99V,DtOG*<'		$++g"6DKK8PRYR`R`aI'+{{GO$*/G&'*3G&'fdwOOr   httpCodereasonr   r  r  r  c
                 @   |sy | j                  |d      }
| j                  |d|      }| j                  |dd      }|
sa| j                  dz   | j	                  |      z   }| j                  | j                  d   ||       | j                  | j                  d   ||       y )Nr   err	errorCoder   r   r   )r   rJ  r  r&   r  throw_broadly_matched_exceptionr   throw_exactly_matched_exception)r   r  r  r   r  r  r  r  requestHeadersrequestBodyr   r  r  feedbacks                 r   handle_errorszdefx.handle_errors  s     ..95nnXuh7&&sK@	ww}tyy'::H001I4QYZ001I9V^_r   c                     | j                  |      }|d   }t        |j                               }t        dt	        |            D ]  }||   }|dk(  s|c S  | j                  |d      S )Nnetworksr   ETH)r  listkeysr  r  
safe_value)r   r  currencyItemr  networkKeysr  r  s          r   !default_network_code_for_currencyz&defx.default_network_code_for_currency	  sn    }}T*
+8==?+q#k*+ 	A!!nG%	
 {A..r   enablec                 J    t         t        |   |       || j                  d<   y )Nr   )r   r#   set_sandbox_moder   )r   r  r   s     r   r  zdefx.set_sandbox_mode  s     dD*62&,]#r   r  )M__name__
__module____qualname__r   r   r  r   r  r   r   r  dictrR  r  r   rX  r   r   r`  rV  r  r  r  r   r  r   r  r  r   r  r  r   r  r  r   r  r  r   r   floatr   r	  r  r   r  r.  r1  r6  r   r:  r4  rS  rX  r]  r_  rb  re  rh  r	   rp  r   r|  rz  r   r   r  r  r
   r  r  r  intr  r  boolr  __classcell__)r   s   @r   r#   r#      sN   X# Xt
 #% 
@ !# 0s 0( $& `3$v, `3DE
4 E
F E
N 02 '33 '3f '3R 04B %5W %57 %5N^4 ^ ^6 ^@ 26DW[df 9L# 9Lc 9LQT 9Lkoptku 9Lv	
 	
4 	
 6:UW "A3 "As "A# "A\`af\g "AH -1tRV_a );c ); );C );fjkpfq );V; ;v ; ;z :>b .bs .b3 .bY .b` 46 3s 3& 3: 68 9 9K 98"
6 "
[ "
H $& (( (0
) 
) gksu U.3 U.i U.y U.RW U.`c U.n
 
M Mv M M^ 37r %Es %EC %EN /32  2 24 $2S $2L 26b 8w 8T(^ 8>1t 1V 1f 26b 4&c 4&3 4&l *.Dt\^ ;;3 ;;c ;; ;;cghmcn ;;z /3TXac Q Q3 Qc Qhlmrhs Q$ 154VZce Q# QS QPS Qjnotju Q$ 37TX\eg QC Qs QRU Qlpqvlw Q$ =A (S (	 (PU (T *, 8X 80 (,$TZ\  ;  ;C  ;s  ;aefqar  ;D!t !x !; !F8 DHPR :S :% :# ::
T 
X 
Q\ 
@ 9=R 1S 1# 1@
t 
V 
x 
"# "*%DW[ PBc 3 S # X\ dg 	/-t - -r   r#   )(ccxt.base.exchanger   ccxt.abstract.defxr   r  ccxt.base.typesr   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   ccxt.base.decimal_to_precisionr    ccxt.base.preciser!   r#    r   r   <module>r     s_    ( *  O  O  O  O  O  O  * 0 . ' ) ) 4 %A -8[ A -r   