
    !:h!O                       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 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    Q/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/async_support/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                    K   | j                  |       d{   }d}| j                  |d      }|rd}nd}|ddd|dS 7 'w)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_statusr  s^      88@@ ..95FF
 	
 As   A?(Ac                 d   K   | j                  |       d{   }| j                  |d      S 7 w)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
        Nt)r   safe_integer)r   r  r  s      r   
fetch_timezdefx.fetch_time  s6      88@@   3// As   0.0c                   K   ddi}| j                  | j                  ||            | j                  | j                  ||            g}t        j                  |  d{   }| j                  |d   d      }| j                  |d      }| j                  |d   d      }t        dt        |            D ]   }||   d   }	d}
|	|v r||	   d   }
|
||   d<   " | j                  |      S 7 w)	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perpsNr   datamarketr   r   )
v1PublicGetCMarketsextendv1PublicGetCMarketsMetadataasynciogather	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
 "..(33	L y|V<"mmM8D..1v>q#o./ 	2A&q)(3HF..,X6x@+1OAx(	2 !!/22_ 4s   AC*C(B
C*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   r6  r7  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_marketH  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                    K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  ||      S 7 W7 w)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>`
        Nr*  r&   )load_marketsr  "v1PublicGetSymbolsSymbolTicker24hrr  parse_tickerr   r*  r  r  r  r  s         r   fetch_tickerzdefx.fetch_ticker  sz      !!!V$fTl
 @@WV\A]^^0   622; 	"
 _"   A2A.A A2A0A20A2Nsymbolsc                   K   | j                          d{    d}|6| j                  |      }| j                  |d      }|| j                  |      }d}| j	                  d||      \  }}|dk(  rt        | j                  dz   |z   dz         | j                  |       d{   }| j                  ||      S 7 7 w)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)	rV  market_symbolsrI  r  handle_market_type_and_paramsr   r&   v1PublicGetTicker24HrAggparse_tickers)r   r\  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66v>>  !!(G447 	" ?s"   B?B;BB?$B=%B?=B?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)
baseVolumerj  r  r  r   )rI  r  r  iso8601safe_ticker)r   rd  r  r  r*  r|  ru  rv  r}  rj  r  r   r  tsrt  rw  rx  ry  rz  s                      r   rX  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                 H  K   | j                          d{    | 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                  ||             d{   }| j                  |||||      S 7 7 w)
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
        Nr   r&   )r*  intervalr   untiltillendTimer   	startTime)rV  r  r9  rI  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?  sQ     !!!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;;wPV;WXX(   69eUKKW 	". Ys"   D"DC,D"D D" D"c           	          | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS )Nstartr|  ru  rv  r}  rk  )r  rM  )r   ohlcvr  s      r   parse_ohlcvzdefx.parse_ohlcvz  sn     eW-UF+UF+UE*UG,UH-
 	
r   c                   K   | j                          d{    | j                  |      }d}||}t        ||      }|d   |d}| j                  | j	                  ||             d{   }| j                  ||||      S 7 l7 w)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>`
        N2   r&   )r*  r   )rV  r  r9  v1PublicGetSymbolsSymbolTradesr  parse_trades)	r   r*  r  r   r  r  r  r  r  s	            r   fetch_tradeszdefx.fetch_trades  s      !!!V$=EHe$Tl
 <<T[[RX=YZZ   65%@@- 	" [s"   BBAB*B+BBc                 F  K   | j                          d{    i }|| j                  |      }|d   |d<   |d}t        ||      }||d<   | j                  | j	                  ||             d{   }| j                  |dg       }	| j                  |	d||      S 7 7 -w)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&   r\  r)   pageSizer  )rV  r  r9  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33DKK4PQQ& ~~h3  tUE::; 	" Rs"   B!BAB!1B2,B!B!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timers  r*  r7  qtyr&   orderIdrole
buyerMakersidesellbuyfeeUSDCr@  currency)r&   rs  rt  r*  r  r7  r6  r@  ordertakerOrMakerr	  r  r   )rI  r  	parse8601safe_marketsafe_string_lowerr   
safe_trader  )r   r  r  r  rs  r  r*  r7  r6  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           	        K   | j                          d{    | j                  |      }|d}| j                  |di       }| j                  |dg       }|d   || j	                  |d      d}| j                  | j                  ||             d{   }| j                  |d      }	| j                  |||	d	d
dd      S 7 7 /w)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
        N
   r   
depthSlabsr&   r   )r*  levelslabrs  bidsasksr7  r  )	rV  r  rL  r  rI  &v1PublicGetSymbolsSymbolDepthLevelSlabr  r  parse_order_book)
r   r*  r   r  r  
marketInfor  r  r  rs  s
             r   fetch_order_bookzdefx.fetch_order_book  s      !!!V$=E^^FFB7
~~j,;Tl$$T1-

 DDT[[QXZ`Eabb, %%h<	$$Xvy&&RY[`aaE 	" cs"   CCA<CC.CCc                    K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  ||      S 7 W7 w)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>`
        Nr*  r&   )rV  r  v1PublicGetSymbolsSymbolPricesr  rX  rY  s         r   fetch_mark_pricezdefx.fetch_mark_priceA  sz      !!!V$fTl
 <<T[[RX=YZZ   622! 	"
 [r[  c                    K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  ||      S 7 W7 w)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>`
        Nr*  r&   )rV  r  r  r  parse_funding_raterY  s         r   fetch_funding_ratezdefx.fetch_funding_rate^  sz      !!!V$fTl
 <<T[[RX=YZZ &&x88! 	"
 [r[  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estimatedSettlePricers  rt  fundingRatefundingTimestampfundingDatetimenextFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimer  )rM  r  r  )r   r2  r  r  r  r  fundingTimes          r   r  zdefx.parse_funding_ratez  s:    $$X{;	%%h=
&&x1DE''2EF
H
fX&
 
 *	

 D
 #D
 
 
 ;
 
 t||K8
 t
 #D
 "4
 "4
  '!
" &t#
$ %
 	
r   c                    K   | j                          d{    | j                  |       d{   }| j                  |d      }| j                  |      S 7 @7 )w)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>`
        Nassets)rV  v1PrivateGetApiWalletBalancer  parse_balancer   r  r  r  s       r   fetch_balancezdefx.fetch_balance  sY      !!!::6BB ~~h1!!$'' 	"Bs   AAAA(AA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  rK  rI  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  r6  r7  c                   K   | j                          d{    | 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                  ||             d{   }| j                  |d      }| j                  ||      S 7 7 +w)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>`
        N
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_LIMITr7  quantity)clOrdIDr  client_order_idpostOnlyr   r  r   r   r  )rV  r  safe_bool_2r  upperrI  safe_string_2safe_string_upperprice_to_precisionamount_to_precisionv1PrivatePostApiOrderr  rL  parse_order)r   r*  r	  r  r6  r7  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  $^  _33DKK4PQQ. ~~h/f--K 	"Z Rs"   GGFG"G#)GGr   c                 @    |dddddd}| j                  |||      S |S )Nr|  canceledrejectedclosed)NEWOPEN	CANCELLEDREJECTEDFILLEDrI  )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*  r7  origQtyr	  r   r  executedQtyavgPricer   take_profitr   r  	createdAt	updatedAtr&   rs  rt  lastTradeTimestamplastUpdateTimestampr  r  r   r   r   totalFeer  r  )r  r6  filled	remainingr@  tradesr  r   )
rI  r  r  	omit_zerofindr  
safe_orderr  r  r   )r   r  r  r  r  r  r*  r7  r6  r  r   r  r#  r  r   r   r   rs  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                   K   | j                          d{    |dd}| j                  |g d      }|du}|r=|t        | j                  dz         | j	                  |      }||d<   d|d<   |d   |d	<   | j                  |g d      }| j                  | j                  ||             d{   }d	|i}	|r||	d<   n||	d<   | j                  | j                  |      |	      S 7 7 8w)
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>`
        Nr  r  idTyper  r  r  z) cancelOrder() requires a symbol argumentr  r+  r&   r*  )	rV  safe_string_nr   r&   r  r  v1PrivateDeleteApiOrderOrderIdr  r  )
r   r&   r*  r  r  r  isByClientOrderr  r  extendParamss
             r   cancel_orderzdefx.cancel_ordert  s     !!!
 **63bc't3~'2](]^^[[(F!.GI /GH &tGH6#RS<<T[[RX=YZZ '/,9L)!#L{{4++H5|DD5 	" [s"   C*C&BC*/C(07C*(C*c                    K   | j                          d{    | j                  |      }d|d   gi}| j                  | j                  ||             d{   }|S 7 H7 w)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>`
        Nr\  r&   )rV  r  v1PrivateDeleteApiOrdersAllOpenr  rY  s         r   cancel_all_orderszdefx.cancel_all_orders  sn      !!!V$t~
 ==dkk'SY>Z[[  	"
 \s"   A#AAA#A!A#!A#c                 h  K   |t        | j                  dz         | j                          d{    | j                  |      }d|d   i}| j	                  | j                  ||             d{   }| j                  |dg       }| j                  |di       }| j                  ||      S 7 }7 >w)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>`
        Nz+ fetchPosition() requires a symbol argumentr*  r&   r  r   )	r   r&   rV  r  v1PrivateGetApiPositionActiver  r  rL  parse_position)r   r*  r  r  r  r  r  firsts           r   fetch_positionzdefx.fetch_position  s      >#DGG.[$[\\!!!V$fTl
 ;;DKKQW<XYY" ~~h3tQ+""5&111 	"
 Zs"   .B2B.A B21B02=B20B2c                    K   | j                          d{    | j                  |       d{   }| j                  |dg       }| j                  ||      S 7 B7 +w)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>`
        Nr  )rV  r6  r  parse_positions)r   r\  r  r  	positionss        r   fetch_positionszdefx.fetch_positions  s]      !!!;;FCC" NN8VR8	##Iw77' 	"Cs   AAAA*AA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&   
positionIdrs  rt  r!  initialMargininitialMarginPercentagemaintenanceMarginmaintenanceMarginPercentagenotionalr   unrealizedPnlrealizedPnl	contractsrA  )marginRatioliquidationPricer  ri  
collateralr   r  r   r   r   r   )	rI  r  r!   
string_absr  r&  safe_positionr   rM  )	r   r>  r  r  sizer  unrealisedPnlrB  rE  s	            r   r7  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                   K   | j                          d{    |dd}| j                  |g d      }| j                  |g d      }|=|t        | j                  dz         | j                  |      }||d<   d|d<   |d   |d	<   | j                  | j                  ||             d{   }| j                  |d
      }| j                  |      S 7 7 )w)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>`
        Nr  r*  r,  z( fetchOrder() requires a symbol argumentr  r+  r&   r*  r  )
rV  r-  r  r   r&   r  v1PrivateGetApiOrderOrderIdr  rL  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99$++gv:VWW4 ~~h/%%S 	" Xs"   CCBC+C,(CCc                   K   | j                          d{    i }|| j                  |      }|d   |d<   | j                  |d      }|&| j                  |d      }| j	                  |      |d<   || j	                  |      |d<   |d}t        ||      }||d<   | j                  | j                  ||             d{   }	| j                  |	d	g       }
| j                  |
d||      S 7 7 -w)
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&   r\  r  endr  r)   r  r  )
rV  r  r  r  r  r9  v1PrivateGetApiOrdersr  r  parse_orders)r   r*  r  r   r  r  r  r  r  r  r  s              r   fetch_orderszdefx.fetch_ordersb  s     !!![[(F!'GI!!&'2YYvw/F!\\%0GEN#||E2GGH%(E"'GJ33DKK4PQQ< ~~h3  tUE::] 	" Rs"   C1C-B*C1C/,C1/C1c           	      n   K   ddi}| j                  |||| j                  ||             d{   S 7 w)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  Nr[  r  r   r*  r  r   r  reqs         r   fetch_open_orderszdefx.fetch_open_orders  s>      
 &&vueT[[f=UVVVV   ,535c           	      n   K   ddi}| j                  |||| j                  ||             d{   S 7 w)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  Nr]  r^  s         r   fetch_closed_orderszdefx.fetch_closed_orders  s>      
 &&vueT[[f=UVVVVra  c           	      n   K   ddi}| j                  |||| j                  ||             d{   S 7 w)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  CANCELEDNr]  r^  s         r   fetch_canceled_orderszdefx.fetch_canceled_orders  s>      

 &&vueT[[f=UVVVVra  c                 B  K   | j                          d{    | 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                  ||             d{   }	|	S 7 7 	w)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>`
        NrD  z& closePosition() requires a positionIdr	  z  closePosition() requires a typer  z$ closePosition() requires a quantity)rD  r	  r  r  r7  z! closePosition() requires a price)rD  r	  r  r7  )rV  rI  r   r&   r  r  $v1PrivateDeleteApiPositionPositionIdr  )
r   r*  r  r  rD  r	  r  r  r7  r  s
             r   close_positionzdefx.close_position  s3     !!!%%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BB4;;wX^C_`` 3 	"* as"   DDC<DDDDc                    K   | j                          d{    | j                  |       d{   }| j                  |dg       }| j                  |d|      S 7 C7 ,w)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>`
        Nr  )rV  v1PrivateDeleteApiPositionAllr  r;  r  s       r   close_all_positionszdefx.close_all_positions  s_      !!!;;FCC ~~h3##D$77 	"Cs   AAAA+AAr  c                   K   | j                          d{    d}| j                  |dd      \  }}|r| j                  d||||       d{   S i }|||d<   nd|d<   | j                  |d      }|| j	                  |d      }||d<   n| j                         |d<   | j                  | j                  ||             d{   }| j                  |d	g       }	| j                  |	d||      S 7 7 7 /w)
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>`
        NFre   paginater  r   r  rX  transactions)
rV  handle_option_and_paramsfetch_paginated_call_dynamicr  r  r  !v1PrivateGetApiWalletTransactionsr  r  parse_ledger)
r   r  r  r   r  rn  r  r  r  r  s
             r   fetch_ledgerzdefx.fetch_ledger  s     !!!88PZ[&::=$PUW\^deee$GG GG!!&'2YYvw/F"GEN!..0GEN??GU[@\]]~~h;  tUE::% 	" f ^s4   C6C06C6C2A6C6C4,C62C64C6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 )Nr6  r  rs  r	  r&   )r   r&   	directionr  referenceAccountreferenceIdr	  r  r6  rs  rt  beforeafterr   r  )rI  rK  safe_currencyr  safe_ledger_entryparse_ledger_entry_typer   r  )r   ru  r  r6  
currencyIdr  rs  r	  s           r   parse_ledger_entryzdefx.parse_ledger_entry9  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   r~  zdefx.parse_ledger_entry_type\  s8     "$+"(&	

 
D$77r   addressc                 
  K   | j                          d{    | j                  |      }| j                  ||      |d   d}| j                  | j	                  ||             d{   }| j                  ||      S 7 h7 w)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>`
        Nr&   )r6  r  )rV  r  currency_to_precision)v1PrivatePostApiTransfersBridgeWithdrawalr  parse_transaction)	r   r  r6  r  tagr  r  r  r  s	            r   r   zdefx.withdrawi  s      !!!==&00v>d^
 GGT[]cHdee %%h99 	" fs"   BA?AB(B)BB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&   txidrs  rt  networkr  	addressToaddressFromr  tagTotagFromr	  r6  r  r   r   )internalcommentr  )rI  rK  )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                 j  K   |t        | j                  dz         | j                          d{    d| j                  |      i}| j	                  |      }|d   |d<   | j                  | j                  ||             d{   }| j                  |di       }| j                  ||      S 7 ~7 +w)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
        Nz) setLeverage() requires a symbol argumentr   r&   r*  r  )	r   r&   rV  number_to_stringr  %v1PrivatePostApiUsersMetadataLeverager  rL  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CCDKKPWY_D`aa ~~h3""400# 	" bs"   .B3B/AB3B1*B31B3c                 z    | j                  |d      }| j                  |d      }|| j                  ||      d ||dS )Nr*  r   )r   r*  r   longLeverageshortLeverage)rI  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   rL  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  dictrT  r  r   rZ  r   r   rc  rX  r  r  r  r   r  r   r  r  r   r  r  r   r  r  r   r  r  r   r   floatr   r  r  r   r  r1  r4  r9  r   r=  r7  rV  r[  r`  rc  rf  ri  rl  r	   rt  r   r  r~  r   r   r  r  r
   r  r  r  intr  r  boolr  __classcell__)r   s   @r   r#   r#      sY   X# Xt
 )+ 
@ ') 0S 0( *, `3V `3DE
4 E
F E
N 68 '3 '3F '3R 6:" %57 %5 %5N^4 ^ ^6 ^@ 8<$]ajl 9L 9LC 9LWZ 9Lquvzq{ 9Lv	
 	
4 	
 <@d[] "A "AS "A "Abfglbm "AH 37TX\eg );C );s );RU );lpqvlw );V; ;v ; ;z @DB .bS .b .bS\ .b` :< 3S 3 3: <> 9s 9+ 98"
6 "
[ "
H *, ( (0
) 
) mqy{ U. U.I U.Y U.X] U.fi U.n
 
M Mv M M^ 9=R %ES %E# %EN 59 c 2 8: $23 $2L 8<B 8W 84PX> 8>1t 1V 1f 8<B 4&C 4& 4&l 04$UYbd ;; ;;C ;;s ;;imnsit ;;z 59tZ^gi Wc W WTW Wnrsxny W$ 7;\`ik W W3 WVY Wptuzp{ W$ 9=4^bkm W# WS WX[ Wrvw|r} W$ CGr (3 (i (V[ (T 02 8d8n 80 .2SW`b  ;s  ;#  ;S  ;gklwgx  ;D!t !x !; !F8 JNVX :3 : : ::
T 
X 
Q\ 
@ ?C2 13 1 1@
t 
V 
x 
"# "*%DW[ PBc 3 S # X\ dg 	/-t - -r   r#   )) ccxt.async_support.base.exchanger   ccxt.abstract.defxr   r  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     sb    6 *   O  O  O  O  O  O  * 0 . ' ) ) 4 %A -8[ A -r   