
    !:hԞ                       d dl mZ d dlm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$ d dl%m&Z&  G d dee      Z'y)    )Exchange)ImplicitAPI)AnyBalancesCurrencyGreeksIntLeverage
MarginModeMarketNumOrder	OrderBook	OrderSide	OrderTypePositionStrStringsTickerTickersTradeTransaction)List)ExchangeError)AuthenticationError)PermissionDenied)ArgumentsRequired)
BadRequest)OperationRejected)InvalidOrder)	TICK_SIZE)Precisec                       e Zd Zdef fdZi fdefdZi fdZi fdee	   fdZ
dede	fdZdd	d	i fd
edededee   fdZd_de	defdZd	i fdedefdZi fd
edefdZd_dede	defdZd	i fd
ededefdZd	d	i fd
edededee   fdZd_dede	defdZi fd
efdZd_de	fdZd Zd Zd Z d Z!d`dZ"d Z#i fd Z$i fd!Z%d_d"ede	de&fd#Z'd$e(fd%Z)d&e(fd'Z*d(e(fd)Z+d*efd+Z,d,efd-Z-d	i fd
ed(e.d.e/d/e0d0e1f
d1Z2d	i fd2ed
e(fd3Z3d	i fd
e(fd4Z4d	i fd2ed
e(fd5Z5d	d	d	i fd
e(dededee&   fd6Z6d	d	d	i fd
e(dededee&   fd7Z7i fde8fd8Z9de8fd9Z:d	d	d	i fd
e(dedefd:Z;i fd
efd;Z<d	i fdedee=   fd<Z>d_d=ede	fd>Z?d	d	i fd
ededefd?Z@d_de	fd@ZAd	d	d	i fdAe(dededeeB   fdBZCd	d	d	i fdAe(dededeeB   fdCZDd_dDedEeEdeBfdFZFd&e(fdGZGi fd
edeHfdHZId_dIedeHfdJZJd	i fdKed
e(fdLZKi fd
edeLfdMZMd_dNede	deLfdOZNdP ZOd	i fdNed
e(fdQZPi fd
edeQfdRZRd_dSede	deQfdTZSdUdVi d	d	fdWZTdXeUdYedZed[ed\ed]efd^ZV xZWS )aparadexreturnc                 p   | j                  t        t        |          i dddddg 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d/dd0dd1di d2dd3dd4dd5dd6dd7dd8dd9dd:dd;dd<dd=dd>dd?dd@ddAddBdi dCddDddEddFddGddHddIddJddKddLddMddNddOddPddQddRddSdi dTddUddVddWddXddYddZdd[dd\dd]dd^dd_dd`ddaddbddcdddddddddddedfdgdhdidjdkdldmdndodpdqddriddsidtdudvdwdxdydzi d{dgd|dgd}dgd~dgddgddgddgddgddgddgddgddgddgddgddgddgddgdgdgdii ddgddgddgddgddgddgddgddgddgddgddgddgddgddgddgddgddgdgdgdgdgdgdgdgdgddgdgdgdgdgdgdgdgdgdgd
ddgidgdgdgdgdddd| j	                  d      | j	                  d      d| j	                  d      | j	                  d      dddddddddi dt
        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        i dt        dt
        dt        dt        dt        dt        dt        dt
        dt
        dt
        dt        dt        dt        dt        dt        dt
        dt        i dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        t        t        t
        t
        t        dݜdt
        idߜdt        i d 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ddddddddddddddddddddddddd dd id	ddid dd d ddd      S )Nidr$   nameParadex	countriesversionv1	rateLimit2   	certifiedFproTdexhasCORSspotmarginswapfutureoption	addMarginborrowCrossMarginborrowIsolatedMargincancelAllOrderscancelAllOrdersAftercancelOrdercancelOrderscancelOrdersForSymbolscloseAllPositionsclosePositioncreateMarketBuyOrderWithCostcreateMarketOrderWithCostcreateMarketSellOrderWithCostcreateOrdercreateOrderscreateReduceOnlyOrdercreateStopOrdercreateTriggerOrder	editOrderfetchAccountsfetchBalancefetchBorrowInterestfetchBorrowRateHistoriesfetchBorrowRateHistoryfetchCanceledOrdersfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositAddressesfetchDepositsfetchDepositWithdrawFeefetchDepositWithdrawFeesfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchGreeksfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchLedgerfetchLeveragefetchLeverageTiersfetchLiquidationsfetchMarginModefetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMyLiquidationsfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenInterestHistoryfetchOpenOrders
fetchOrderfetchOrderBookfetchOrdersfetchOrderTradesfetchPositionfetchPositionModefetchPositionsfetchPositionsRiskfetchPremiumIndexOHLCVfetchStatusfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTransferfetchTransfersfetchWithdrawalfetchWithdrawalsreduceMarginrepayCrossMarginrepayIsolatedMargin)sandboxsetLeveragesetMarginModesetPositionModetransferwithdraw
timeframes               <   )1m3m5m15m30m1hhostnamezparadex.tradeurlszOhttps://github.com/user-attachments/assets/84628770-784e-4ec4-a759-ec2fbb2244eazhttps://api.prod.{hostname}/v1z!https://api.testnet.{hostname}/v1zhttps://www.paradex.trade/z'https://docs.api.testnet.paradex.trade/z7https://docs.paradex.trade/getting-started/trading-feesz"https://app.paradex.trade/r/ccxt24)logoapitestwwwdocfeesreferralr   getzbbo/{market}zfunding/datamarketszmarkets/klineszmarkets/summaryzorderbook/{market}	insurancezreferrals/configzsystem/configzsystem/statezsystem/timetradesvaultszvaults/balancezvaults/configzvaults/historyzvaults/positions)zvaults/summaryzvaults/transfersaccountzaccount/infozaccount/historyzaccount/marginzaccount/profilezaccount/subaccountsbalancefillszfunding/payments	positions
tradebuststransactionsliquidationsorderszorders-historyorders/by_client_id/{client_id}orders/{order_id})zpoints_data/{market}/{program}zreferrals/qr-codezreferrals/summary	transfersalgo/orderszalgo/orders-historyalgo/orders/{algo_id}zvaults/account-summary)
zaccount/margin/{market}zaccount/profile/max_slippagezaccount/profile/referral_codezaccount/profile/usernameauth
onboardingr   zorders/batchr   r   )r   r   r   r   )r   postputdelete)publicprivater   z0.0002)takermaker)r6   r4   requiredCredentials)apiKeysecretwalletAddress
privateKey
exceptionsVALIDATION_ERRORBINDING_ERRORINTERNAL_ERROR	NOT_FOUNDSERVICE_UNAVAILABLEINVALID_REQUEST_PARAMETERORDER_ID_NOT_FOUNDORDER_IS_CLOSEDORDER_IS_NOT_OPEN_YETCLIENT_ORDER_ID_NOT_FOUNDDUPLICATED_CLIENT_IDINVALID_PRICE_PRECISIONINVALID_SYMBOLINVALID_TOKENINVALID_ETHEREUM_ADDRESSINVALID_ETHEREUM_SIGNATUREINVALID_STARKNET_ADDRESSINVALID_STARKNET_SIGNATURE&STARKNET_SIGNATURE_VERIFICATION_FAILEDBAD_STARKNET_REQUESTETHEREUM_SIGNER_MISMATCHETHEREUM_HASH_MISMATCHNOT_ONBOARDEDINVALID_TIMESTAMPINVALID_SIGNATURE_EXPIRATIONACCOUNT_NOT_FOUNDINVALID_ORDER_SIGNATUREPUBLIC_KEY_INVALIDUNAUTHORIZED_ETHEREUM_ADDRESS"ETHEREUM_ADDRESS_ALREADY_ONBOARDEDMARKET_NOT_FOUNDALLOWLIST_ENTRY_NOT_FOUNDUSERNAME_IN_USEGEO_IP_BLOCKETHEREUM_ADDRESS_BLOCKEDPROGRAM_NOT_FOUNDINVALID_DASHBOARDMARKET_NOT_OPENINVALID_REFERRAL_CODE PARENT_ADDRESS_ALREADY_ONBOARDEDINVALID_PARENT_ACCOUNTINVALID_VAULT_OPERATOR_CHAIN VAULT_OPERATOR_ALREADY_ONBOARDEDVAULT_NAME_IN_USEBATCH_SIZE_OUT_OF_RANGE ISOLATED_MARKET_ACCOUNT_MISMATCHPOINTS_SUMMARY_NOT_FOUNDz-32700z-32600z-32601z-32602)z-32603100401104011140112zmissing or malformed jwt)exactbroadprecisionModeCCXT)paradexAccountbroker)IOCFOKPOGTD)
marginModetriggerPricetriggerDirectiontriggerPriceTypestopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingleveragemarketBuyByCostmarketBuyRequiresPriceselfTradePreventionicebergd   i )r  limitdaysBack	untilDayssymbolRequired)r  triggerr  r  )r  r  r  r  r  )r  r  r  r  r  r  r  r  )	r   rF   rG   rl   rq   rp   rs   rR   rm   extendsforSwap)linearinverse)r4   r  r6   r7   )commonCurrenciesoptionsfeatures)deep_extendsuperr$   describeparse_numberr   r   r   r   r    r   r!   )self	__class__s    T/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/async_support/paradex.pyr   zparadex.describe   s   gt = ? eB
)eB
IeB
 eB
 t	eB

 eB
 eB
 4eB
 4eB
  \\\ %\ 	\
 %\ %\ U\ $U\ '\ "4\ '\ u\ \ )%\ $U\   !\" /#\$ ,U%\& 0'\( t)\* +\, (-\. "4/\0 %d1\2 U3\4  5\6 7\8 &u9\: +E;\< )%=\> &u?\@ $UA\B 'C\D (E\F "5G\H &uI\J (K\L  M\N *5O\P +EQ\R &uS\T #EU\V *5W\X $UY\Z t[\\ "5]\^ *5_\` +Ea\b uc\d  e\f %eg\h $Ti\j "4k\l +Em\n o\p !%q\r &us\t  u\v dw\x $Ty\z +E{\| "4}\~ d\@ !$A\B tC\D #EE\F  G\H $UI\J !$K\L %eM\N )%O\P tQ\R tS\T U\V TW\X tY\Z "5[\\ #E]\^  _\` !%a\b "5c\d #De\f g\h #Ei\j &uk\l  #!%#(!!w\eB
L MeB
\ ]eB
^ i: = 4@Q@_eB
x  && "1 )!	
 *1 -a $Q +A ( ' &q !! !! )! (  )!!" +A#$ +,,-'0!1& *1 )!	
 *1 .q "1   +A $Q %a ' ' !! )!  :1!" ,Q#$ ;<-.-.%&'(/0122338 45899:45 !&'"#()'("# ,Q #$;<-.12	W11JyeB
N !..x8!..x8
 "..x8!..x8	OeB
b "!%"	$ceB
n 9&(;9#%69 %m9  	9
 *=9 09 ),9 &|9 ,\9 09 +L9 ./@9 %&79 $%69 /0A9  12C!9" /0A#9$ 12C%9& =>Q'9( +J)9* /
+9, -j-9. $Z/90 (192 34G394 ()<596 ./B798 )*99: 4Z;9< 9*=9> '
?9@ 0A9B &':C9D #$4E9F /0@G9H (I9J ():K9L &zM9N ,->O9P 7
Q9R -.?S9T 34EU9V 78IW9X ():Y9Z ./@[9\ 78I]9^ /0A_9` ja9b jc9d je9f jg9h ,%00-q9v /0Cw>oeB
l YmeB
n! #' 
 #&+(,,0,0).+06:#'#("&#(	( #($)$)+027/3#()$, %)&+!$$*%+*/& ',#($)*/	# ',!$#($)*/( ',!$$*%+#($)*/$ *.#o:z "9  $	 ##GG{eB
 e e	    c                 d   K   | j                  |       d{   }| j                  |d      S 7 w)af  
        fetches the current integer timestamp in milliseconds from the exchange server

        https://docs.api.testnet.paradex.trade/#get-system-time-unix-milliseconds

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        Nserver_time)publicGetSystemTimesafe_integer)r"  paramsresponses      r$  
fetch_timezparadex.fetch_time  s5      11&99   =99 :s   0.0c                    K   | j                  |       d{   }| j                  |d      }|dk(  rdndddd|dS 7 %w)aR  
        the latest known information on the availability of the exchange API

        https://docs.api.testnet.paradex.trade/#get-system-state

        :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statusokmaintenance)r.  updatedetaurlinfo)publicGetSystemStatesafe_string)r"  r*  r+  r.  s       r$  fetch_statuszparadex.fetch_status  sU      226:: !!(H5%~dM
 	
 ;s   ?=&?c                    K   | j                  |       d{   }| j                  |d      }| j                  |      S 7 'w)a  
        retrieves data on all markets for bitget

        https://docs.api.testnet.paradex.trade/#list-available-markets

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        Nresults)publicGetMarkets	safe_listparse_marketsr"  r*  r+  datas       r$  fetch_marketszparadex.fetch_markets  sE      ..v66D ~~h	2!!$''G 7s   A?(Amarketc                 X   | j                  |d      }|dk(  }|rdnd}|dk(  }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }	| j                  |      }
| j                  |d      }| j                  |      }|
d	z   |	z   d
z   |z   }| j                  |d      }| j                  |d      }| j                  |d      }| j                  d      }| j                  d      }|r)|dk(  rdnd}|dz   |z   dz   |z   }| j                  d      }nd }| j	                  i 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||| j                  d%      ||d&k(  rd n| j                  |      | j                  |      | j                  |d      | j                  |d'      | j                  |d(      d)d d d*d | j                  |d+      d*d d d*| j                  |d,      d d*d-d |d.      S )/N
asset_kindPERP_OPTIONr8   r6   symbolquote_currencybase_currencysettlement_currency/:	expiry_atoption_typestrike_pricez0.0003z-0.00005CALLCP-r'   basequotesettlebaseIdquoteIdsettleIdtyper4   Fr5   r7   activeenableTradingcontractTr  1r   order_size_incrementprice_tick_size)amountprice)minmaxmax_order_sizemin_notional)r  r^  r_  cost)r  r   r   contractSizeexpiryexpiryDatetimestrike
optionType	precisionlimitscreatedr4  )	r6  safe_currency_coder)  r!  safe_market_structure	safe_booliso8601safe_string_lowersafe_number)r"  r@  	assetKindisOptionrW  isSwapmarketIdrU  rT  rR  rQ  rV  rS  rD  rf  ri  strikePricetakerFeemakerFeeoptionTypeSuffixs                       r$  parse_marketzparadex.parse_market  s   Z $$V\:	.$x6&.##FH5""6+;<!!&/:''0&&v.##F,AB((2e#c)F2""6;7%%fm<
&&v~>$$X.$$Z0'1V';s#c\K/#58HHF((2HF)) 2+
(2+
f2+
 D2+
 U	2+

 f2+
 f2+
 w2+
 2+
 D2+
 E2+
 d2+
 F2+
 e2+
 h2+
 dnnV_=2+
  !2+
" d#2+
$  --c2'-{df9M''400G**63IJ))&2CD  
  ++F4DE
  
  ++FNC$ c2+
 2 2	r%  r   NrD  sincer  c                   K   | j                          d{    | j                  |      }| j                  | j                  ||      |d   d}| j	                         }| j                  |      }	| j                  |dd|      }
| j                  |ddg      }|/||d<   |"| j                  ||	|dz   z  dz        dz
  |d	<   n3|
|d	<   n-|
|d	<   ||
|	|dz   z  dz  z
  dz   |d<   n|
|	d
z  dz  z
  dz   |d<   | j                  | j                  ||             d{   }| j                  |dg       }| j                  |||||      S 7 17 /w)a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://docs.api.testnet.paradex.trade/#ohlcv-for-a-symbol

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest candle to fetch
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Nr'   )
resolutionrD  untiltillstart_atr     end_ate   r9  )load_marketsr@  r6  r   millisecondsparse_timeframesafe_integer_2omitsumpublicGetMarketsKlinesextendr;  parse_ohlcvs)r"  rD  	timeframer|  r  r*  r@  requestnowdurationr  r+  r>  s                r$  fetch_ohlcvzparadex.fetch_ohlcvn  s     !!!V$**4??IyQTl
 !''	2##FGVSA6GV#45"'GJ $(HHUH	4JT4Q$RUV$V!$)! %GH &+h%!).Dt.K&Ka&O
#&+hnt.C&Ca&G
#44T[[&5QRR ~~h	26  vy%GGM 	", Ss"   EEDEE
-E
Ec           	          | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS )Nr   r      r      r   )r)  rr  )r"  ohlcvr@  s      r$  parse_ohlcvzparadex.parse_ohlcv  sn     eQ'UA&UA&UA&UA&UA&
 	
r%  symbolsc                   K   | j                          d{    | j                  |      }ddi}| j                  | j                  ||             d{   }| j	                  |dg       }| j                  ||      S 7 g7 +w)a"  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://docs.api.testnet.paradex.trade/#list-available-markets-summary

        :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@  ALLr9  )r  market_symbolspublicGetMarketsSummaryr  r;  parse_tickers)r"  r  r*  r  r+  r>  s         r$  fetch_tickerszparadex.fetch_tickers  s      !!!%%g.e
 55dkk'66RSS, ~~h	26!!$009 	"
 Ts!   BA>=BB *B Bc                 4  K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  |dg       }| j                  |di       }| j                  ||      S 7 }7 >w)a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://docs.api.testnet.paradex.trade/#list-available-markets-summary

        :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'   r9  r   )r  r@  r  r  r;  	safe_dictparse_ticker)r"  rD  r*  r@  r  r+  r>  tickers           r$  fetch_tickerzparadex.fetch_ticker  s      !!!V$fTl
 55dkk'66RSS, ~~h	26a,  00; 	"
 T"   BBA BB=BBr  c           	      &   | j                  |d      }|t        j                  |d      }| j                  |d      }| j                  |d      }| j                  ||      }|d   }| j	                  |d      }| j                  i d|d|d| j                  |      dd d	d d
| j                  |d
      dd d| j                  |d      dd dd dd d|d|dd dd d|dd d | j                  |d      | j                  |d      |d|      S )Nprice_change_rate_24hr   last_traded_pricerD  
created_at	timestampdatetimehighlowbid	bidVolumeask	askVolumevwapopencloselastpreviousClosechange
percentageaverage
volume_24h
mark_price)
baseVolumequoteVolume	markPricer4  )r6  r"   
string_mulsafe_marketr)  safe_tickerrp  )r"  r  r@  r  r  rv  rD  r  s           r$  r  zparadex.parse_ticker	  s   $ %%f.EF
! ++J>J(;<##FH5!!(F3!%%fl;	 !
f!
!
 Y/!
 D	!

 4!
 4##FE2!
 !
 4##FE2!
 !
 D!
 D!
 T!
 D!
 T!
 d!
  *!!
" t#!
$ ++FLA))&,?+!
, - 	r%  c                 P  K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }|||d<   | j	                  |d      }| j                  ||d   |      }| j	                  |d      |d<   |S 7 7 Lw)	a:  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://docs.api.testnet.paradex.trade/#get-market-orderbook

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        Nr@  r'   depthlast_updated_atrD  seq_nononce)r  r@  publicGetOrderbookMarketr  r)  parse_order_book)	r"  rD  r  r*  r@  r  r+  r  	orderbooks	            r$  fetch_order_bookzparadex.fetch_order_book;  s      !!!V$!6$<066t{{7F7STT( $GG%%h0AB	))(F84DiP	!..xB	'9 	" Us#   B&B"A B&B$AB&$B&c                 8  K   | j                          d{    d}| j                  |dd      \  }}|r!| j                  d||||dddd	       d{   S | j                  |      }d|d	   i}|||d
<   |||d<   | j	                  d||      \  }}| j                  | j                  ||             d{   }| j                  |dg       }	t        dt        |	            D ]  }
| j                  |d      |	|
   d<    | j                  |	|||      S 7 7 7 aw)a  
        get the list of most recent trades for a particular symbol

        https://docs.api.testnet.paradex.trade/#trade-tape

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch trades for
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        NFr~   paginatenextcursorr  r@  r'   	page_sizer  r  r9  r   )r  handle_option_and_paramsfetch_paginated_call_cursorr@  handle_until_optionpublicGetTradesr  r;  rangelenr6  parse_trades)r"  rD  r|  r  r*  r  r@  r  r+  r   is              r$  fetch_tradeszparadex.fetch_tradesd  s`     !!!88PZ[&99-QVX]_egmowy}  @C  D  D  DV$fTl
 #(GK "'GJ228WfM--dkk'6.JKK$ )R8q#f+& 	CA $ 0 06 BF1If	C  >>G 	" D Ls5   DD:DDA$D6D7ADDDtradec                 ,   | j                  |d      }| j                  ||      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |dd      }	|	dk(  }
|
rdnd	}| j                  |d
      }| j	                  |      }| j                  ||| j                  |d      || j                  |      |d   d ||||d | j                  |d      |d dd|      S )Nr@  r'   r  r_  sizeside	liquidityr   r   fee_currencyorder_idrD  fee)rd  currencyrate)r4  r'   orderr  r  rD  rW  takerOrMakerr  r_  r^  rd  r  )r6  r  r)  rq  rm  
safe_traderp  )r"  r  r@  rv  r'   r  priceStringamountStringr  	liabilityisTakerr  
currencyIdcodes                 r$  parse_tradezparadex.parse_trade  sA   @ ##E84!!(F3eT*%%e\:	&&ug6''v6%%eV4**5+wG	w&#*w%%e^<
&&z2%%eZ8"Y/X&( "((6  
$ % 	r%  c                 n  K   | j                          d{    | j                  |      }|d   st        | j                  dz         d|d   i}| j	                  | j                  ||             d{   }| j                  |dg       }| j                  |di       }| j                  ||      S 7 7 >w)aw  
        retrieves the open interest of a contract trading pair

        https://docs.api.testnet.paradex.trade/#list-available-markets-summary

        :param str symbol: unified CCXT market symbol
        :param dict [params]: exchange specific parameters
        :returns dict} an open interest structure{@link https://docs.ccxt.com/#/?id=open-interest-structure:
        NrZ  z3 fetchOpenInterest() supports contract markets onlyr@  r'   r9  r   )	r  r@  r   r'   r  r  r;  r  parse_open_interest)r"  rD  r*  r@  r  r+  r>  interests           r$  fetch_open_interestzparadex.fetch_open_interest  s      !!!V$j!TWW'\\]]fTl
 55dkk'66RSS, ~~h	26>>$2.''&99? 	" Ts"   B5B1AB54B35=B53B5c           	          | j                  |d      }| j                  |d      }| j                  ||      }|d   }| j                  || j                  |d      d || j	                  |      |d|      S )Nr  rD  open_interest)rD  openInterestAmountopenInterestValuer  r  r4  )r)  r6  r  safe_open_interestrp  )r"  r  r@  r  rv  rD  s         r$  r  zparadex.parse_open_interest  s    $ %%h=	##Hh7!!(F3!&&"&"2"28_"M!%"Y/(
  	r%  c                 .    d| j                  |dd      z   S )N0xkeccakhex)hash)r"  messages     r$  hash_messagezparadex.hash_message!  s    dii5999r%  c                     | j                  |dd  |dd  dd       }|d   }|d   }| j                  | j                  d|d               }d|j                  dd	      z   |j                  dd	      z   |z   S )
N	secp256k1rs   vr  @   0)ecdsaint_to_base16r  rjust)r"  r  r   	signaturer  r   r  s          r$  	sign_hashzparadex.sign_hash$  s    JJtCDz:cd+;[$O	cNcNtxxIcN;<aggb#&&S)99A==r%  c                 J    | j                  | j                  |      |dd        S )Nr  )r	  r  )r"  r  r   s      r$  sign_messagezparadex.sign_message+  s%    ~~d//8*ST:JKKr%  c                    K   | j                  | j                  d      }||S | j                          d {   }|| j                  d<   |S 7 w)NsystemConfig)r  r  publicGetSystemConfig)r"  cachedConfigr+  s      r$  get_system_configzparadex.get_system_config.  sQ     !^^DLL.I#3355: (0^$= 6s   4AAAc                 r   K   | j                          d {   }|du rd|d   dd}|S d|d   dd}|S 7 w)NTr)   l1_chain_idr[  )r(   chainIdr+   starknet_chain_idr   )r  )r"  l1r  l1Ddomains        r$  prepare_paradex_domainzparadex.prepare_paradex_domainR  s\     !3355:!'6C
 J#$78

  6s   757c                   K   | j                  | j                  d      }||S | j                          | j                          d {   }| j	                  d       d {   }ddddgi}ddi}| j                  |||      }| j                  || j                        }| j                  ||d   |d	         }|| j                  d<   |S 7 7 kw)
Nr   TConstantactionstringr(   rW  z	STARK Keyparaclear_account_hashparaclear_account_proxy_hash)	r  r  check_required_credentialsr  r  eth_encode_structured_datar  r   retrieve_stark_account)	r"  cachedAccountr  r  messageTypesr  msgr  r   s	            r$  retrieve_accountzparadex.retrieve_accountb  s     "nnT\\;KL$  '')!335522488!84
 k
 --flGL%%c4??;	--1278

 *1%&% 68s%   ACC	CC A*CCc                 F  K   | j                          d {   }ddi}| j                          d {   }ddddgi}| j                  ||||d         }| j                  ||d         }||d<   |d   |d	<   |d
   |d<   | j	                  |       d {   }|S 7 7 j7 
w)Nr  
Onboardingr  feltr  addressr   r  r   	publicKey
public_key)r&  r  starknet_encode_structured_datastarknet_signprivatePostOnboarding)	r"  r*  r   reqr  r$  r%  r  r+  s	            r$  r   zparadex.onboarding{  s     --//l
 2244!62

 226<gV_N`a&&sGL,AB	'{#I.y&{3|33F;;! 0 5 <s2   B!BB!BA!B!BB!B!B!c                   K   | j                  | j                  d      }| j                         }|#| j                  | j                  d      }||k  r|S | j	                          d {   }|dz   }ddd||d}| j                          d {   }dd	d
ddd
ddd
ddd
ddd
dgi}	| j                  ||	||d         }
| j                  |
|d         }||d<   |d   |d<   |d   |d<   |d   |d<   | j                  |       d {   }| j                  |d      }|| j                  d<   || j                  d<   |S 7 7 7 :w)N	authTokenexpires   POSTz/v1/auth )methodpathbodyr  
expirationRequestr7  r)  r  r8  r9  r  r:  r*  r   r  r   	jwt_token)	r6  r  r  r)  r&  r  r-  r.  privatePostAuth)r"  r*  cachedTokenr  cachedExpiresr   r3  r0  r  r$  r%  r  r+  tokens                 r$  authenticate_restzparadex.authenticate_rest  s    &&t||[Ajjl" --dllIFM]"""--//)!
 2244!6200$f5%v6
 226<gV_N`a&&sGL,AB	'{#I.y!+.{"<0|--f55   ;7$)[!")YG 0 5  6s7   A%E'D=($ED?A9EE7E?EEr  c                    | j                  |d      }| j                  |d      }| j                  | j                  |d            }| j                  |d      }| j                  ||      }|d   }| j                  |d      }| j                  |d      }	| j                  |d      }
| j                  |d	      }| j                  |d
      }|d}| j	                  |d      }| j                  | j                  |d            }| j                  | j                  |d            }| j                  |d      }| j                  |dg       }d }d|v rd}| j                  i d|d|d|d| j                  |      dd d|d
| j                  |      d|d| j                  |
      d| j                  | j                  |d            dd d|d|d|d| j                  |d      dd dd ||	d |d d d d d |d!|      S )"Nr  r'   	client_idr@  rD  r_  r  rW  cancel_reasonr.  canceledr  avg_fill_priceremaining_sizer  flagsREDUCE_ONLYTclientOrderIdr  r  lastTradeTimestamplastUpdateTimestampr	  instructionpostOnly
reduceOnlyr  trigger_pricer  r  )rd  r  )r  r^  filled	remainingrd  r   r  r4  )r)  r6  	omit_zeror  rq  r;  
safe_orderrp  parse_order_statusparse_order_typeparse_time_in_force)r"  r  r@  r  orderIdrJ  rv  rD  r_  r^  	orderTypecancelReasonr.  r  r  rR  rL  rH  rO  s                      r$  parse_orderzparadex.parse_order  s   : %%e\:	""5$/t'7'7{'KL##E84!!(F3!  0!!%0$$UF3	''?!!%2#F%%eV4..!1!1%9I!JKNN4#3#3E;K#LM	"//7HIugr2
E!J  
' 
] 
  
 Y/	 

 !$ 
 "#6 
 d--f5 
 f 
 D)))4 
 433D4D4DUM4Z[ 
  
 * 
 D 
 U 
 D,,UOD 
  t! 
" T# 
$ "  9 
: ; 	r%  r	  c                 4    dddd}| j                  ||d       S )Nr   GTCr   )r   r]  	POST_ONLYr6  )r"  r	  timeInForcess      r$  rW  zparadex.parse_time_in_force  s)    

 k4@@r%  r.  c                 >    |ddddd}| j                  |||      S |S )Nr  closed)NEWUNTRIGGEREDOPENCLOSEDr_  r"  r.  statusess      r$  rU  zparadex.parse_order_status  s7    %"	H ##Hff==r%  rW  c                 6    ddddd}| j                  |||      S )Nr  r@  )LIMITMARKET
STOP_LIMITSTOP_MARKET)rq  )r"  rW  typess      r$  rV  zparadex.parse_order_type  s,    !#	
 %%eT488r%  strc                 f    d| j                  | j                  | j                  |                  z   S )Nr  )binary_to_base16base64_to_binarystring_to_base64)r"  ro  s     r$  convert_short_stringzparadex.convert_short_string'  s/    d++D,A,A$BWBWX[B\,]^^^r%  numc                 .    t        j                  |d      S )N	100000000)r"   r  )r"  ru  s     r$  scale_numberzparadex.scale_number+  s    !!#{33r%  r  r^  r_  c           	        K   | j                          d{    | j                          d{    | j                  |      }| j                  |dd      }|j	                         }	|j	                         }
|d   |
|	d}| j                  |dd      }| j                  |d      }| j                  |d	      }|	d
k(  }|du}|du}|duxs |xs |}| j                  |d      }| j                  |d|      }|s|rd|d<   n
|dk(  rd|d<   || j                  ||      |d<   | j                  |g d      }|||d<   d}d}|r|rb|r| j                  ||      }d}d|d<   n|r| j                  ||      }d}d|d<   n| j                  ||      }| j                  ||      }d|d<   nt|r| j                  ||      }d}d|d<   nX|r| j                  ||      }d}d|d<   n<| j                  ||      }| j                  ||      }d|d<   n| j                  ||      }|||d<   ||d<   |rdg|d<   | j                  |g d       }| j                          d{   }| j                         }|d!z  | j                  |d"         |
d#k(  rd$nd%| j                  |d         | j!                  |d         |rdn| j!                  |d         d&}| j#                          d{   }d'd(d)d*d"d)d*d+d)d*d,d)d*dd)d*dd)d*gi}| j%                  ||||d-         }| j'                  ||d.         }||d/<   |d(   |d0<   | j)                  | j+                  ||             d{   }| j-                  ||      } | S 7 \7 G7 $7 7 #w)1a  
        create a trade order

        https://docs.api.prod.paradex.trade/#create-order

        :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 fullfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param float [params.stopPrice]: alias for triggerPrice
        :param float [params.triggerPrice]: The price a trigger order is triggered at
        :param float [params.stopLossPrice]: the price that a stop loss order is triggered at
        :param float [params.takeProfitPrice]: the price that a take profit order is triggered at
        :param str [params.timeInForce]: "GTC", "IOC", or "POST_ONLY"
        :param bool [params.postOnly]: True or False
        :param bool [params.reduceOnly]: Ensures that the executed order does not flip the opened position.
        :param str [params.clientOrderId]: a unique id for the order
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NrO  reduce_onlyr'   )r@  r  rW  r  	stopPricer  r  rk  r	  r^  rM  iocr   r_  clOrdIDrJ  client_order_idrC  r  TSTOP_LOSS_MARKETrW  TAKE_PROFIT_MARKETrm  STOP_LOSS_LIMITTAKE_PROFIT_LIMITrl  rP  r  rI  rH  )rO  rz  r~  rJ  r  rN  r	  r{  r  r  r  r  r@  BUYr[  2)r  r@  r  rY  r  r_  r   r  r)  r  r  rY  r*  r   r  signature_timestamp)rA  r  r@  safe_bool_2uppersafe_string_2r6  safe_string_upperis_post_onlyprice_to_precisionsafe_string_namount_to_precisionr  r&  r  rt  rx  r  r-  r.  privatePostOrdersr  r[  )!r"  rD  rW  r  r^  r_  r*  r@  rO  rY  	orderSider  r  r  r  isMarketisTakeProfitOrderisStopLossOrderisStopOrderr	  rN  rJ  
sizeStringr{  r   r  orderReqr  r$  r%  r  r+  r  s!                                    r$  create_orderzparadex.create_order.  s6    , $$&&&!!!V$%%flMJ
JJL	JJL	Tl

 ))&.+N((A**63DE(,D8(4#4/X4EX,,V]C$$XtV<)4&%).&#66vuEGG**63bc$#0GK 
	" $ 7 7 NI!%J&8GFO& $ 7 7 PI!%J&:GFO $ 7 7 MI!%!9!9&&!IJ&3GFO" $ 7 7 NI!%J&7GFO& $ 7 7 PI!%J&9GFO $ 7 7 MI!%!9!9&&!IJ&2GFO11&&AJ '0GO$$ GG 6  $L  M--//jjlt//0AB%.CS2276?C%%gfo6%SD,=,=gg>N,O
 2244$f5!620$f50 &1	
 226<SZ[dSef&&sGL,AB	()1+)>%&//GV0LMM:   62{ 	'!J 0 5 NsX   M?M2M?M5H%M?M8BM?M;A=M?M=M?5M?8M?;M?=M?r'   c                   K   | j                          d{    | j                          d{    i }| j                  |g d      }d}|/||d<   | j                  | j	                  ||             d{   }n.||d<   | j                  | j	                  ||             d{   }| j                  |      S 7 7 7 H7 w)a  
        cancels an open order

        https://docs.api.prod.paradex.trade/#cancel-order
        https://docs.api.prod.paradex.trade/#cancel-open-order-by-client-order-id

        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.clientOrderId]: a unique id for the order
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr}  rC  r  )rA  r  r  %privateDeleteOrdersByClientIdClientIdr  privateDeleteOrdersOrderIdr[  r"  r'   rD  r*  r  rJ  r+  s          r$  cancel_orderzparadex.cancel_order  s      $$&&&!!!**63bc$#0GK !GGT[]cHdeeH"$GJ!<<T[[RX=YZZH )) 	'! f [sD   CB;CB=AC6B?7.C%C&C=C?CCc                 0  K   |t        | j                  dz         | j                          d{    | j                          d{    | j	                  |      }d|d   i}| j                  | j                  ||             d{   }|S 7 _7 I7 
w)a  
        cancel all open orders in a market

        https://docs.api.prod.paradex.trade/#cancel-all-open-orders

        :param str symbol: unified market symbol of the market to cancel orders in
        :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>`
        Nz- cancelAllOrders() requires a symbol argumentr@  r'   )r   r'   rA  r  r@  privateDeleteOrdersr  )r"  rD  r*  r@  r  r+  s         r$  cancel_all_orderszparadex.cancel_all_orders  s      >#DGG.]$]^^$$&&&!!!V$fTl
 11$++gv2NOO  	'!
 Ps4   .BBBB	A B	B
BBBc                   K   | j                          d{    | j                          d{    i }| j                  |g d      }| j                  |g d      }d}|/||d<   | j	                  | j                  ||             d{   }n.||d<   | j                  | j                  ||             d{   }| j                  |      S 7 7 7 H7 w)a%  
        fetches information on an order made by the user

        https://docs.api.prod.paradex.trade/#get-order
        https://docs.api.prod.paradex.trade/#get-order-by-client-id

        :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
        :param str [params.clientOrderId]: a unique id for the order
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr}  rC  r  )rA  r  r  r  "privateGetOrdersByClientIdClientIdr  privateGetOrdersOrderIdr[  r  s          r$  fetch_orderzparadex.fetch_order  s      $$&&&!!!**63bc6#RS$#0GK !DDT[[QXZ`EabbH"$GJ!99$++gv:VWWH6 ))M 	'! c XsD   CCCCAC
C.C9C:CCCCc                   K   | j                          d{    | j                          d{    d}| j                  |dd      \  }}|r!| j                  d||||dddd	       d{   S i }d}|| j	                  |      }|d   |d	<   |||d
<   |||d<   | j                  d||      \  }}| j                  | j                  ||             d{   }| j                  |dg       }	| j                  |d      }
t        |	      }|
|dkD  r|	d   }|
|d<   ||	d<   | j                  |	|||      S 7 7 	7 7 fw)a  
        fetches information on multiple orders made by the user

        https://docs.api.prod.paradex.trade/#get-orders

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.side]: 'buy' or 'sell'
        :param boolean [params.paginate]: set to True if you want to fetch orders with pagination
        :param int params['until']: timestamp in ms of the latest order to fetch
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        NFrs   r  r  r  r.   r'   r@  r  r  r  r9  r   )rA  r  r  r  r@  r  privateGetOrdersHistoryr  r;  r6  r  parse_orders)r"  rD  r|  r  r*  r  r  r@  r+  r   paginationCursorordersLengthfirsts                r$  fetch_orderszparadex.fetch_orders-  s     $$&&&!!!88PZ[&99-QVX]_egmowy}  @B  C  C  C[[(F &tGH"'GJ#(GK 228WfM55dkk'66RSSF )R8++Hf=6{(|a/?1IE,E&MF1I  >>u 	'! C TsE   D>D4D>D7:D>)D:*A+D>D<AD>7D>:D><D>c                 T  K   | j                          d{    | j                          d{    i }d}|| j                  |      }|d   |d<   | j                  | j	                  ||             d{   }| j                  |dg       }| j                  ||||      S 7 7 u7 /w)a4  
        fetches information on multiple orders made by the user

        https://docs.api.prod.paradex.trade/#paradex-rest-api-orders

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr'   r@  r9  )rA  r  r@  privateGetOrdersr  r;  r  )	r"  rD  r|  r  r*  r  r@  r+  r   s	            r$  fetch_open_orderszparadex.fetch_open_ordersx  s      $$&&&!!![[(F &tGH..t{{7F/KLLB )R8  >>S 	'! Ms2   B(B"B(B$AB(6B&7,B($B(&B(c                    K   | j                          d{    | j                          d{    | j                          d{   }| j                  |dg       }| j	                  |      S 7 X7 B7 ,w)a^  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://docs.api.prod.paradex.trade/#list-balances

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        Nr9  )rA  r  privateGetBalancer;  parse_balancer=  s       r$  fetch_balancezparadex.fetch_balance  so      $$&&&!!!//11 ~~h	26!!$'' 	'!1s1   A5A/A5A1A5A3)A51A53A5c                     d|i}t        dt        |            D ]b  }| j                  ||i       }| j                  |d      }| j	                  |      }| j                         }| j                  |d      |d<   |||<   d | j                  |      S )Nr4  r   r@  r  total)r  r  r  r6  rm  r   safe_balance)r"  r+  resultr  r   r  r  r   s           r$  r  zparadex.parse_balance  s    )q#h-( 	#AnnXq"5G))'7;J**:6DllnG#//@GG"F4L	#   ((r%  c                 ~  K   | j                          d{    | j                          d{    d}| j                  |dd      \  }}|r!| j                  d||||dddd	       d{   S i }d}|| j	                  |      }|d   |d	<   |||d
<   |||d<   | j                  d||      \  }}| j                  | j                  ||             d{   }| j                  |dg       }	t        dt        |	            D ]  }
| j                  |d      |	|
   d<    | j                  |	|||      S 7 7 7 7 ew)a1  
        fetch all trades made by the user

        https://docs.api.prod.paradex.trade/#list-fills

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param 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)
        :param int [params.until]: the latest time in ms to fetch entries for
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        NFrl   r  r  r  r  r'   r@  r  r  r  r9  r   )rA  r  r  r  r@  r  privateGetFillsr  r;  r  r  r6  r  )r"  rD  r|  r  r*  r  r  r@  r+  r   r  s              r$  fetch_my_tradeszparadex.fetch_my_trades  s     $$&&&!!!88R\]&99/6SXZ_agioqy{  BE  F  F  F[[(F &tGH#(GK "'GJ228WfM--dkk'6.JKK0 )R8q#f+& 	CA $ 0 06 BF1If	C  >>W 	'! F LsE   D=D3D=D6:D=)D9*A+D=D;AD=6D=9D=;D=c                    K   | j                          d{    | j                          d{    | j                  |      }| j                  |d   g|       d{   }| j	                  |di       S 7 ^7 H7 w)a~  
        fetch data on an open position

        https://docs.api.prod.paradex.trade/#list-open-positions

        :param str symbol: unified market symbol of the market the position is held in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        NrD  r   )rA  r  r@  fetch_positionsr  )r"  rD  r*  r@  r   s        r$  fetch_positionzparadex.fetch_position  sw      $$&&&!!!V$..x0@/A6JJ	~~iB//	 	'!Js1   A;A5A;A7.A;A9A;7A;9A;c                   K   | j                          d{    | j                          d{    | j                  |      }| j                          d{   }| j	                  |dg       }| j                  ||      S 7 j7 T7 -w)aj  
        fetch all open positions

        https://docs.api.prod.paradex.trade/#list-open-positions

        :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>`
        Nr9  )rA  r  r  privateGetPositionsr;  parse_positions)r"  r  r*  r+  r>  s        r$  r  zparadex.fetch_positions  s      $$&&&!!!%%g.11334 ~~h	26##D'22= 	'!3s1   BBBB(BB*BBBpositionc           
      L   | j                  |d      }| j                  ||      }|d   }| j                  |d      }| j                  |d      }|dk7  rt        j                  d|      }| j                  |d      }| j                  i d|d	| j                  |d	      d|d
| j                  |d      dd dd d| j                  |d      d| j                  |d      d|d| j                  |      dd d|d| j                  |      dd dd dd dd d d d d d d d      S )Nr@  rD  r  r  longz-1timer4  r'   
entryPriceaverage_entry_pricer  notional
collateralrd  unrealizedPnlunrealized_pnl	contractsre  r  r  r
  maintenanceMarginmaintenanceMarginPercentageinitialMargin)initialMarginPercentager  liquidationPricemarginRatior  r  )	r6  r  rq  r"   r  r)  safe_positionr!  rp  )r"  r  r@  rv  rD  r  quantityr  s           r$  parse_positionzparadex.parse_positionI  s   , ##Hh7!!(F3!%%h7##Hf56>))$9H%%h7	!! #
H#
$""8T2#
 f#
 $**85JK	#

 #
 #
 $**8V<#
 T--h8HI#
 D#
 **84#
 D#
 #
 Y/#
 d#
  #
  *4!#
" T##
$ (, $/#
  	r%  c                 N  K   | j                          d{    i }|||d<   nd|d<   | j                  |      }| j                  d||      \  }}| j                  | j	                  ||             d{   }| j                  |dg       }| j                  ||||      S 7 7 -w)ar  
        retrieves the public liquidations of a trading pair

        https://docs.api.prod.paradex.trade/#list-liquidations

        :param str symbol: unified CCXT market symbol
        :param int [since]: the earliest time in ms to fetch liquidations for
        :param int [limit]: the maximum number of liquidation structures to retrieve
        :param dict [params]: exchange specific parameters for the huobi api endpoint
        :param int [params.until]: timestamp in ms of the latest liquidation
        :returns dict: an array of `liquidation structures <https://docs.ccxt.com/#/?id=liquidation-structure>`
        Nfromr   tor9  )rA  r@  r  privateGetLiquidationsr  r;  parse_liquidations)	r"  rD  r|  r  r*  r  r@  r+  r>  s	            r$  fetch_liquidationszparadex.fetch_liquidations  s      $$&&&#GFOGFOV$224&I44T[[&5QRR ~~h	26&&tVUEBB) 	' Ss"   B%B!AB%5B#6,B%#B%c                 z    | j                  |d      }| j                  |d d d d d d || j                  |      d	      S )Nr  )	r4  rD  r  re  r_  	baseValue
quoteValuer  r  )r)  safe_liquidationrp  )r"  liquidationr@  r  s       r$  parse_liquidationzparadex.parse_liquidation  sR     %%k<@	$$ "Y/
&
 
 
	r%  r  c                 T  K   | j                          d{    | j                          d{    d}| j                  |dd      \  }}|r!| j                  d||||dddd	       d{   S i }|||d<   |||d	<   | j	                  d
||      \  }}| j                  | j                  ||             d{   }| j                  |dg       }g }	t        dt        |            D ]!  }
||
   }|d   dk(  s|	j                  |       # | j                  |	d||      S 7 	7 7 7 mw)aQ  
        fetch all deposits made to an account

        https://docs.api.prod.paradex.trade/#paradex-rest-api-transfers

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch entries for
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        NFrX   r  r  r  r  r  r  r  r9  r   kindDEPOSITrA  r  r  r  r  privateGetTransfersr  r;  r  r  appendparse_transactionsr"  r  r|  r  r*  r  r  r+  rowsdepositsr  rows               r$  fetch_depositszparadex.fetch_deposits  sf     $$&&&!!!88R\]&99/4QVX]_egmowy}  @C  D  D  D#(GK "'GJ228WfM11$++gv2NOO, ~~h	26q#d)$ 	%Aq'C6{i'$	% &&xueDDQ 	'! D PJ   D(DD(D":D()D$*AD(8D&9>D(8(D("D($D(&D(c                 T  K   | j                          d{    | j                          d{    d}| j                  |dd      \  }}|r!| j                  d||||dddd	       d{   S i }|||d<   |||d	<   | j	                  d
||      \  }}| j                  | j                  ||             d{   }| j                  |dg       }g }	t        dt        |            D ]!  }
||
   }|d   dk(  s|	j                  |       # | j                  |	d||      S 7 	7 7 7 mw)a`  
        fetch all withdrawals made from an account

        https://docs.api.prod.paradex.trade/#paradex-rest-api-transfers

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of withdrawals structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch withdrawals for
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        NFr   r  r  r  r  r  r  r  r9  r   r  
WITHDRAWALr  r  s               r$  fetch_withdrawalszparadex.fetch_withdrawals  sl     $$&&&!!!88ASU_`&99:LdTY[`bhjprz  }A  CF  G  G  G#(GK "'GJ228WfM11$++gv2NOO, ~~h	26q#d)$ 	%Aq'C6{l*$	% &&xueDDQ 	'! G Pr  transactionr  c                 .   | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  ||      }| j                  |d      }| j                  |d      }	| j                  |d      }
|
dk(  rd	nd
}
| j                  | j                  |d            }| j	                  |d      }i d|d|d|d|d| j                  |      dd d|d|dd dd dd dd d|
d|d|d|d|	d d d dS )Nr'   r   txn_hashr@  r  r  r  r  deposit
withdrawalr.  r^  r4  txidr  r  networkr*  	addressToaddressFromtagtagTotagFromrW  r  r1  )internalcommentr  )r6  rm  r)  parse_transaction_statusrr  rp  )r"  r  r  r'   r*  r  r  r  r  r1  rW  r.  r^  s                r$  parse_transactionzparadex.parse_transaction(  s   $ k40"";	:Z8%%k7;
&&z8<%%k<@	##K1BCV4!Y.y\..t/?/?X/VW!!+x8
K
"
 D
 	

 Y/
 t
 w
 
 4
 4
 T
 t
 D
 f
 
  f!
" w#
$ )
 	
r%  c                 6    ddddd}| j                  |||      S )Npendingr/  failed)PENDING	AVAILABLE	COMPLETEDFAILEDr_  rg  s      r$  r  z paradex.parse_transaction_status\  s,     "	
 &&99r%  c                 `  K   | j                          d{    | j                          d{    | j                  |      }d|d   i}| j                  | j	                  ||             d{   }| j                  |d      }| j                  | j                  |d      |      S 7 7 {7 <w)a  
        fetches the margin mode of a specific symbol

        https://docs.api.testnet.paradex.trade/#get-account-margin-configuration

        :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: a `margin mode structure <https://docs.ccxt.com/#/?id=margin-mode-structure>`
        Nr@  r'   configsr   )rA  r  r@  privateGetAccountMarginr  r;  parse_margin_moder  r"  rD  r*  r@  r  r+  r  s          r$  fetch_margin_modezparadex.fetch_margin_modee  s      $$&&&!!!V$fTl
 55dkk'66RSS ..95%%dnnWa&@&II) 	'!
 T2   B.B(B.B*A B./B,09B.*B.,B.rawMarginModec                     | j                  |d      }| j                  ||      }| j                  |d      }||d   |dS )Nr@  margin_typerD  )r4  rD  r  )r6  r  rq  )r"  r  r@  rv  r  s        r$  r	  zparadex.parse_margin_mode  sP    ##M8<!!(F3++M=I
!X&$
 	
r%  r  c                 r  K   | j                  d|d       | j                          d{    | j                          d{    | j                  |      }d}| j	                  |ddd      \  }}|d   || j                  |      d}| j                  | j                  ||             d{   S 7 7 q7 w)a  
        set margin mode to 'cross' or 'isolated'

        https://docs.api.testnet.paradex.trade/#set-margin-configuration

        :param str marginMode: 'cross' or 'isolated'
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param float [params.leverage]: the rate of leverage
        :returns dict: response from the exchange
        r   rD  Nr  r   r'   r@  r  r  )check_required_argumentrA  r  r@  r  encode_margin_modeprivatePostAccountMarginMarketr  )r"  r  rD  r*  r@  r  r  s          r$  set_margin_modezparadex.set_margin_mode  s      	$$_fhG$$&&&!!!V,88R\^_`&Tl 22:>

 88Wf9UVVV 	'! Ws4   'B7B1B7B3A*B7,B5-B73B75B7c                 `  K   | j                          d{    | j                          d{    | j                  |      }d|d   i}| j                  | j	                  ||             d{   }| j                  |d      }| j                  | j                  |d      |      S 7 7 {7 <w)am  
        fetch the set leverage for a market

        https://docs.api.testnet.paradex.trade/#get-account-margin-configuration

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `leverage structure <https://docs.ccxt.com/#/?id=leverage-structure>`
        Nr@  r'   r  r   )rA  r  r@  r  r  r;  parse_leverager  r
  s          r$  fetch_leveragezparadex.fetch_leverage  s      $$&&&!!!V$fTl
 55dkk'66RSS ..95""4>>'1#=vFF) 	'!
 Tr  r  c                     | j                  |d      }| j                  ||      }| j                  |d      }|| j                  ||      || j	                  |d      | j	                  |d      dS )Nr@  r  r  )r4  rD  r  longLeverageshortLeverage)r6  r  rq  safe_symbolr)  )r"  r  r@  rv  r  s        r$  r  zparadex.parse_leverage  sx    ##Hh7!!(F3++HmD
&&x8$ --h
C!..xD
 	
r%  c                 2    ddd}| j                  |||      S )NCROSSISOLATED)crossisolatedr_  )r"  modemodess      r$  r  zparadex.encode_margin_mode  s&    "
 tT22r%  c                 p  K   | j                  d|d       | j                          d{    | j                          d{    | j                  |      }d}| j	                  d|d      \  }}|d   || j                  |      d}| j                  | j                  ||             d{   S 7 7 p7 w)a  
        set the level of leverage for a market

        https://docs.api.testnet.paradex.trade/#set-margin-configuration

        :param float leverage: the rate of leverage
        :param str [symbol]: unified market symbol(is mandatory for swap markets)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: 'cross' or 'isolated'
        :returns dict: response from the exchange
        r   rD  Nr   r'   r  )r  rA  r  r@  handle_margin_mode_and_paramsr  r  r  )r"  r  rD  r*  r@  r  r  s          r$  set_leveragezparadex.set_leverage  s      	$$]FHE$$&&&!!!V,
!??vW^_
FTl 22:>

 88Wf9UVVV 	'! Ws4   'B6B0B6B2A)B6+B4,B62B64B6c                 4  K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  |dg       }| j                  |di       }| j                  ||      S 7 }7 >w)a  
        fetches an option contracts greeks, financial metrics used to measure the factors that affect the price of an options contract

        https://docs.api.testnet.paradex.trade/#list-available-markets-summary

        :param str symbol: unified symbol of the market to fetch greeks for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `greeks structure <https://docs.ccxt.com/#/?id=greeks-structure>`
        Nr@  r'   r9  r   )r  r@  r  r  r;  r  parse_greeks)r"  rD  r*  r@  r  r+  r>  greekss           r$  fetch_greekszparadex.fetch_greeks  s      !!!V$fTl
 55dkk'66RSSF ~~h	26a,  00U 	"
 Tr  r)  c                    | j                  |d      }| j                  ||d d      }|d   }| j                  |d      }| j                  |di       }i d|d|d| j	                  |      d| j                  |d      d| j                  |d      d	d d
| j                  |d
      d| j                  |d      d| j                  |d      d| j                  |d      dd dd d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      | j                  |d      | j                  |d      | j                  |d      |dS )NrD  r8   r  r)  r  r  deltagammathetavegarhovannavolgabidSizeaskSizebidImpliedVolatilitybid_ivaskImpliedVolatilityask_ivmarkImpliedVolatilitymark_ivbidPricer  askPricer  r  r  underlying_price)r  	lastPriceunderlyingPricer4  )r6  r  r)  r  rp  rr  )r"  r)  r@  rv  rD  r  
greeksDatas          r$  r(  zparadex.parse_greeks*	  s    > ##FH5!!(FD(C!%%fl;	^^FHb9

f

 Y/
 T%%j':	

 T%%j':
 T
 D$$Z8
 4##J6
 T%%j':
 T%%j':
 t
 t
 #D$4$4VX$F
 #D$4$4VX$F
 $T%5%5fi%H
  ((7!
" ((7#
$ ))&,?))&2EF#//8JK+
 	
r%  r   GETc                    | j                  | j                  d   | j                           dz   | j                  ||      z   }| j	                  || j                  |            }|dk(  r|r|d| j                  |      z   z  }n|dk(  rd| j                  | j                  dd      d	}|d
k(  r3|d   |d<   |d   |d<   t        |d         |d<   t        |d         |d<   n|dk(  rW| j                  |d<   |d   |d<   |d   |d<   t        | j                               |d<   d|d<   | j                  d|d   i      }nJ| j                  d   }	d|	z   |d<   |dk(  rd|d<   | j                  |      }n|dz   | j                  |      z   }||||dS )Nr   rH  r   ?r   zapplication/jsonr   r   )AcceptzPARADEX-PARTNERr   r   zPARADEX-STARKNET-ACCOUNTr  zPARADEX-STARKNET-SIGNATUREr  zPARADEX-TIMESTAMPr:  zPARADEX-SIGNATURE-EXPIRATIONr   zPARADEX-ETHEREUM-ACCOUNTzContent-Typer,  r2  zBearer Authorizationr5  )r3  r7  r9  headers)implode_hostnamer   r+   implode_paramsr  extract_params	urlencoder6  r  ro  r   r  json)
r"  r8  r   r7  r*  rF  r9  r3  queryr@  s
             r$  signzparadex.signf	  s   ##DIIe$4T\\$BCcIDL_L_`dflLmm		&$"5"5d";<(?sT^^E222I,#'#3#3DLL(F#SG
 v~6;I6F238=k8J45/253E/F+,:=eL>Q:R67%6:6H6H236;I6F238=k8J45/24::</@+,*<'yy %"5"  [1+4u+<(V#.@GN+99U+D)dnnU&;;C fdwOOr%  httpCodereasonr3  r7  rF  r9  c
                     |sy | j                  |d      }
|
]| j                  dz   |z   }| j                  | j                  d   ||       | j	                  | j                  d   |
|       t        |      y )Nerror r   r   )r6  r'   throw_broadly_matched_exceptionr   throw_exactly_matched_exceptionr   )r"  rN  rO  r3  r7  rF  r9  r+  requestHeadersrequestBody	errorCodefeedbacks               r$  handle_errorszparadex.handle_errors	  sz     $$Xw7	 ww}t+H001I4QYZ001I9V^_))r%  )N)F)X__name__
__module____qualname__r   r   r	   r,  r7  r   r   r?  dictr{  ro  listr  r  r   r   r  r   r  r  r   r  r   r  r  r  r  r  r	  r  r  r  r&  r   rA  r   r[  r   rW  rU  rV  rt  rx  r   r   floatr   r  r  r  r  r  r  r   r  r  r  r  r   r  r  r  r  r   r  r  r   r  r  r   r  r	  r  r
   r  r  r  r&  r   r*  r(  rM  intrY  __classcell__)r#  s   @r$  r$   r$      s   f# fP ') :S :" )+ 
0 *, ,(V ,(\V4 VF Vp 8<$]ajl 4H 4HC 4HWZ 4Hquvzq{ 4Hl
 
4 
( 6:" &17 &1 &1P 68 '1 '1F '1R04 0 06 0d @DB 'S ' 'S\ 'R <@d[] 1? 1?S 1? 1?bfglbm 1?f> >v > >@ =? ): ):VF >:>L"H 2 ') & .0 *XO Ov O ObAs A	 	9S 9_ _4 4 mqy{ S SI SY SX] Sfi Sj 9=R *S *# *: 59 c 0 8<B 3*C 3* 3*j 04$UYbd I? I?C I?s I?imnsit I?V 59tZ^gi 5?c 5? 5?TW 5?nrsxny 5?n *, ( (4	) 	) 37TX\eg 9?C 9?s 9?RU 9?v 8: 03 0  8<B (3W (34PX> (3T6t 6V 6p BFTXac !Cs !C3 !Cc !CFV ( 04$UYbd 6E 6EC 6Es 6Eimnyiz 6Ep 37TX\eg 6EC 6Es 6ERU 6Elpq|l} 6Ep2
T 2
X 2
Q\ 2
h:s : ;= Jc J J@
t 
Z 
 DHPR W WS W2 8: G3 Gh G@

t 

V 

x 

3 ?C2 W3 W W2 68 41 41F 41l:
4 :
 :
6 :
x &eBSW .P`c 3 S # X\ dg r%  r$   N)( ccxt.async_support.base.exchanger   ccxt.abstract.paradexr   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   r    ccxt.base.decimal_to_precisionr!   ccxt.base.preciser"   r$    r%  r$  <module>rj     s_    6 - I  I  I  I  I  I  * 0 - . ' . ) 4 %Q&h Q&r%  