
    E#i                        S SK Jr  S SKJr  S SKrS SKJrJrJrJ	r	J
r
JrJrJrJrJrJrJrJrJrJrJrJrJr  S SKJr  S SKJr  S SKJr  S SKJr  S S	KJr  S S
KJr  S SKJ r   S SK!J"r"  S SK#J$r$   " S S\\5      r%g)    )Exchange)ImplicitAPIN)AccountAnyBalancesCurrencyIntLedgerEntryMarketNumOrder	OrderBook	OrderSide	OrderTypePositionStrStringsTradeTransactionTransferEntry)List)ExchangeError)ArgumentsRequired)
BadRequest)InsufficientFunds)InvalidOrder)NotSupported)	TICK_SIZE)Precisec                     ^  \ rS rSrS\4U 4S jjr0 4S\4S jjrS\S\	4S jr
0 4S\\	   4S jjrSmS	\S\	S\4S
 jjrSS0 4S\S\S\S\\   4S jjrSmS\	S\4S jjrSSS0 4S\S\S\S\\   4S jjrSSS0 4S\S\S\4S jjrS\S\4S jrSmS\S\	S\4S jjrS\4S jrS\4S jrS0 4S\S\4S jjrSSS0 4S\S\S\S\\   4S jjrSSS0 4S\S\S\S\\   4S jjrSSS0 4S\S\S\S\\   4S  jjrSmS!\S\	4S" jjr0 4S\4S# jjr S0 4S$\!S\\"   4S% jjr#S& r$S' r%S( r&S\'4S) jr(SmS*\S+\S,\S-\S.\S/\S\4S0 jjr)S\4S1 jr*S2 r+S3\S4\4S5 jr,S0 4S\S\-S6\.S7\/S8\04
S9 jjr1S:\S;\/S<\/S=\/S>\/S\4S? jr20 4S\34S@ jjr4S0 4S\S\-S6\.S7\/S8\0S\4SA jjr5S0 4S\S\S\4SB jjr6S0 4SC\\   S\4SD jjr7S0 4S\S\S\84SE jjr9SmSF\SG\:S\;4SH jjr<SI r=SSS0 4SJ\S\S\S\\;   4SK jjr>S+\S,\S.\S\4SL jr?0 4SJ\S7\/SM\SN\S\@4
SO jjrASmSP\SG\:S\@4SQ jjrBSSS0 4SJ\S\S\S\\@   4SR jjrCSmSS\SG\:S\D4ST jjrES0 4SJ\S7\/S:\SU\S\D4
SV jjrFSSS0 4SJ\S\S\S\\D   4SW jjrGSSS0 4SJ\S\S\S\\D   4SX jjrHSSS0 4SJ\S\S\S\\D   4SY jjrISSS0 4SJ\S\S\4SZ jjrJ0 4S\\K   4S[ jjrL0 4S\M4S\ jjrNS\M4S] jrOS^ rPS_ rQS`Sa0 SS4Sb jrRSc\3Sd\Se\Sf\Sg\Sh\4Si jrSSj\T4U 4Sk jjrUSlrVU =rW$ )ndydx   returnc                 x  > U R                  [        [        U ]  5       0 SS_SS_SS/_SS_S	S
_SS_SS_SS_S0 SS _SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_S S_S!S_0 S"S_S#S_S$S_S%S_S&S_S'S_S(S_S)S_S*S_S+S_S,S_S-S_S.S_S/S_S0S_S1S_S2S_E0 S3S_S4S_S5S_S6S_S7S_S8S_S9S_S:S_S;S_S<S_S=S_S>S_S?S_S@S_SAS_SBS_SCS_E0 SDS_SES_SFS_SGS_SHS_SIS_SJS_SKS_SLS_SMS_SNS_SOS_SPS_SQS_SRS_SSS_STS_E0 SUS_SVS_SWS_SXS_SYS_SZS_S[S_S\S_S]S_S^S_S_S_S`S_SaS_SbS_ScS_SdS_SeS_ESSSSSSSf.E_SgShSiSjSkSlSmSnSo._SpSqSrSsStSu.SvSwSxSu.SySz/S{/S|S}._S~S0 SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_0 SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_ESSSSSSSSSSSSS.E0SSSSSSS.0SS0SSS.S.Su._SSSSU R	                  S5      U R	                  S5      S.0_SSSSS._SS SSSSSSSSSSSSS.S._SSSSSSSS.SSSS SSSSS.SSSSSSSS.S SSSSSS.SSSSS.SSSSSS.SSS SSSSS.SSS S SSSSS.SS0S.	SSS0S.SS0S S.S S S.S._S0 _0 S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _0 S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _E0 S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[
        _S[        _S[        _S[        _GS [
        _GS[
        _GS[
        _GS[
        _GS[
        _GS[
        _GS[
        _E0 GS[
        _GS[
        _GS	[
        _GS
[
        _GS[
        _GS[
        _GS[
        _GS[
        _GS[
        _GS[
        _GS[
        _GS[
        _GS[
        _GS[
        _GS[
        _GS[
        _GS[
        _E0 GS[
        _GS[
        _GS[
        _GS[
        _GS[
        _GS[
        _GS[
        _GS[
        _GS [
        _GS![
        _GS"[
        _GS#[
        _GS$[
        _GS%[
        _GS&[
        _GS'[
        _GS([
        _E0 GS)[
        _GS*[
        _GS+[
        _GS,[
        _GS-[
        _GS.[
        _GS/[
        _GS0[
        _GS1[
        _GS2[
        _GS3[
        _GS4[
        _GS5[
        _GS6[
        _GS7[
        _GS8[
        _EGS9[        0GS:.[        GS;.E5      $ (<  Nidr!   namedYdX	countriesUS	rateLimitd   versionv4	certifiedFdexTprohasCORSspotmarginswapfutureoption	addMargincancelAllOrderscancelAllOrdersAftercancelOrdercancelOrders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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1MIN5MINS15MINS30MINS1HOUR4HOURS1DAY)1m5m15m30m1h4h1durlszOhttps://github.com/user-attachments/assets/617ea0c1-f05a-4d26-9fcb-a0d1d4091ae1zhttps://indexer.dydx.trade/v4z"https://dydx-ops-rpc.kingnodes.comz https://dydx-rest.publicnode.com)indexernodeRpcnodeRestz*https://indexer.v4testnet.dydx.exchange/v4z#https://test-dydx-rpc.kingnodes.comz$https://test-dydx-rest.kingnodes.comzhttps://www.dydx.xyzzhttps://docs.dydx.xyzz4https://docs.dydx.exchange/introduction-trading_feeszdydx.trade?ref=ccxt)logoapitestwwwdocfeesreferralr   getzaddresses/{address}   z3addresses/{address}/parentSubaccountNumber/{number}z7addresses/{address}/subaccountNumber/{subaccountNumber}assetPositionsz%assetPositions/parentSubaccountNumberz!candles/perpetualMarkets/{market}zcompliance/screen/{address}fillszfills/parentSubaccountNumberfundingPaymentsz fundingPayments/parentSubaccountheightg?zhistorical-pnlz%historical-pnl/parentSubaccountNumberz'historicalBlockTradingRewards/{address}zhistoricalFunding/{market}z-historicalTradingRewardAggregations/{address}z#orderbooks/perpetualMarket/{market}orderszorders/parentSubaccountNumberzorders/{orderId}perpetualMarketsperpetualPositionsz)perpetualPositions/parentSubaccountNumberscreen
sparklinestimeztrades/perpetualMarket/{market}	transfersztransfers/betweenz transfers/parentSubaccountNumberz vault/v1/megavault/historicalPnlzvault/v1/megavault/positionszvault/v1/vaults/historicalPnl)perpetualMarketSparklineszperpetualMarkets/{ticker}z#perpetualMarkets/{ticker}/orderbookztrades/perpetualMarket/{ticker}zhistoricalFunding/{ticker}zcandles/{ticker}/{resolution}zaddresses/{address}/subaccountszFaddresses/{address}/subaccountNumber/{subaccountNumber}/assetPositionszJaddresses/{address}/subaccountNumber/{subaccountNumber}/perpetualPositionsz>addresses/{address}/subaccountNumber/{subaccountNumber}/orderszfills/parentSubaccountzhistorical-pnl/parentSubaccount)	abci_infoblockbroadcast_tx_asyncbroadcast_tx_synctxz.cosmos/auth/v1beta1/account_info/{dydxAddress})zcosmos/tx/v1beta1/encodezcosmos/tx/v1beta1/simulate)r   postr   tradingz0.0001z0.0005)	tierBased
percentagemakertakerrequiredCredentials)apiKeysecret
privateKeyoptionszdydx-mainnet-1uusdcz1.6zDibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5   z0.025adydx   25000000000)
USDC_DENOMUSDC_GAS_DENOMUSDC_DECIMALSUSDC_GAS_PRICECHAINTOKEN_DENOMCHAINTOKEN_DECIMALSCHAINTOKEN_GAS_PRICE)mnemonic	chainNamechainIdsandboxModedefaultFeeDenomdefaultFeeMultiplierfeeDenomfeatures)lastmarkindex)IOCFOKPOGTD)
marginModetriggerPricetriggerPriceTypetriggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingleveragemarketBuyByCostmarketBuyRequiresPriceselfTradePreventionicebergi  Z   i'  )r   limitdaysBack	untilDayssymbolRequired)r   triggerr   r   )r   r   r   r   r   i )r   r   r   r   r   r   r   )r   r   r   daysBackCanceledr   r   r   r   r     )	r   rF   createOrdersrm   rr   rq   rt   rU   rn   defaultr   )extendsrF   r   forSwap)linearinverse)r   r   r5   r6   commonCurrencies910111213141516171819202122232425262728293031323334353637394041424344454647484950100010011002100310041005100610071008100910101011101210131014101510171018101910201021102220002001200220032004200530003001300230033004300530063007300830093010400040014002400340044005400640074008500050016000600160029000900190029003100001000111000zinsufficient funds)exactbroad)
exceptionsprecisionMode)	deep_extendsuperr!   describeparse_numberr   r   r   r   )self	__class__s    C/home/james-whalen/.local/lib/python3.13/site-packages/ccxt/dydx.pyri  dydx.describe   s   dD : < t?
&t?
Ft?
 $t?
 	t?

 tt?
 t?
 4t?
 4t?
  \\\ %\ 	\
 %\ %\ U\ "5\ '\ t\ \ !%\ $U\  \ %e\  '!\" /#\$ $U%\& ,U'\( 0)\* t+\, 7-\. (/\0 '1\2 &u3\4 (5\6 "57\8 (9\: ,U;\< -e=\> %e?\@  A\B C\D &uE\F #EG\H $TI\J )%K\L $UM\N $UO\P +EQ\R "5S\T &uU\V (W\X 1%Y\Z  [\\ +D]\^ &u_\` 'a\b (c\d #Ee\f *4g\h $Ui\j "5k\l tm\n  o\p /q\r "5s\t u\v !%w\x  y\z d{\| +E}\~ !%\@ "4A\B dC\D !$E\F tG\H #EI\J  K\L 'M\N $UO\P !$Q\R (S\T )%U\V uW\X uY\Z [\\ T]\^ t_\` "5a\b #Ec\d $Ue\f !$g\h #Di\j k\l !$"#(  w\t?
L Mt?
^ i>C B  LD F
 .+ K 2'_t?
H  0-q0Mq0 RST0 )!	0
 @0 <Q0 6q0  0 70 *10 ;A0 !#0 )!0 @0 B10  5a!0" H#0$ >q%0& !!'0( 8)0* +A+0, +A-0. -a/00 DQ102 !!304 %a506 708 :190: $Q;0< ,Q=0> ;A?0@ ;AA0B 7C0D 8E0H 6756?@;<679:;<bcfgZ[23;<_02h %&!"./-. I! 5667	{FIt?
V !%"&!..x8!..x8	Wt?
f "#$gt?
p  -$#*(-"h&-%&&-(/+-,9qt?
R #&+(,$($(%*-
 -2).+06:#'#'"&#'	( #($)$)+027/4#(1$4 %)&+!$$&%**/& ',#'$)*/	# ',!$#'$(*/( ',!$$(%+#'$(*/$ ',!$$(,0%+#'$(*/	*  #IGR  ) $$ "9  $	 ##kYSt?
F
 G
t?
J
i 	i
 ,i ,i ,i ,i ,i ,i ,i ,i ,i ,i ,i  ,!i" ,#i$ ,%i& ,'i( ,)i* ,+i, ,-i. ,/i0 ,1i2 ,3i4 ,5i6 ,7i8 ,9i: ,;i< ,=i> ,?i@ ,AiB ,CiD ,EiF ,GiH ,IiJ ,KiL ,MiN ,OiP ,QiR ,SiT ,UiV ,WiX ,YiZ J[i\ J]i^ J_i` Laib Lcid Leif Lgih Liij Lkil Lmin Loip Lqir Lsit Luiv Lwix Lyiz L{i| L}i~ Li@ LAiB LCiD LEiF LGiH LIiJ LKiL LMiN LOiP LQiR LSiT LUiV LWiX LYiZ L[i\ L]i^ L_i` Laib Lcid Leif Lgih Liij Lkil Lmin Loip Lqir Lsit Luiv Lwix Lyiz L{i| L}i~ Li@ LAiB LCiD LEiF LGiH LIiJ LKiL \MiN \OiP \QiV )*;Wn^ 'gt?
 t t	    c                 H    U R                  U5      nU R                  US5      $ )a'  
fetches the current integer timestamp in milliseconds from the exchange server

https://docs.dydx.xyz/indexer-client/http#get-time

:param dict [params]: extra parameters specific to the exchange API endpoint
:returns int: the current integer timestamp in milliseconds from the exchange server
epoch)indexerGetTimesafe_integer)rk  paramsresponses      rm  
fetch_timedydx.fetch_time  s)     &&v.   733ro  marketc                    SnU R                  US5      nUR                  S5      nU R                  US5      nU R                  U5      nU R                  U5      nU R                  US5      nSn	U R                  U	5      n
US-   U-   S-   U
-   nSnSnU R                  US	5      nU R                  US
5      nU R                  US5      nSnUS:w  a  SnU R                  0 SU R                  US5      _SU_SU_SU_SU
_SU_SU_SU_SU	_SS_SS_SS _SU_SS_SS_SU_SU_SSS S S S S S S U R	                  U5      U R	                  U5      S.S S S.S S S.S S S.S S S.S .S US!.E5      $ )"NUSDCticker-r   baseId/:TstepSizetickSizestatusACTIVEFr%   symbolbasequotesettlebaseNamequoteIdsettleIdtyper5   r3   r4   r6   r7   activecontract)amountprice)minmax)r   r  r  cost)r   r   r   r   contractSizeexpiryexpiryDatetimestrike
optionType	precisionlimitscreatedinfo)safe_stringsplitsafe_currency_codesafe_market_structurerj  )rk  rx  r  marketIdpartsr  r  r  r}  r  r  r  r  r5   amountPrecisionStrpricePrecisionStrr  r  s                     rm  parse_marketdydx.parse_market  sb   6 ##FH5s###E1-&&x0''0!!&(3((2e#c)F2!--fjA ,,VZ@!!&(3XF)) 3+
$""6843+
f3+
 D3+
 U	3+

 f3+
 f3+
 3+
 w3+
 3+
 F3+
 E3+
 d3+
 D3+
 e3+
 e3+
  f!3+
" #3+
$  "++,>?**+<=  
  
  
  $ e3+
 3 3	ro  c                     0 nU R                  U R                  X!5      5      nU R                  US0 5      n[        UR	                  5       5      nU R                  U5      $ )z
retrieves data on all markets for hyperliquid

https://docs.dydx.xyz/indexer-client/http#get-perpetual-markets

:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: an array of objects representing market data
markets)indexerGetPerpetualMarketsextend	safe_dictlistvaluesparse_markets)rk  rt  requestru  datar  s         rm  fetch_marketsdydx.fetch_marketsB  sY    
 224;;w3OP> ~~h	26t{{}%!!'**ro  Ntradec                 <   U R                  U R                  US5      5      nUS   nU R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  UUU R	                  U5      UUUUS S S S S US.U5      $ )N	createdAtr  r  sizesider%   )r%   	timestampdatetimer  r  r  r  r  ordertakerOrMakerr  feer  )	parse8601r  safe_string_lower
safe_tradeiso8601)	rk  r  rx  r  r  r  r  r  r%   s	            rm  parse_tradedydx.parse_tradeq  s     NN4#3#3E;#GH	!  0!!%0%%eV4eT*"Y/  
  	ro  r  sincer   c                     U R                  5         U R                  U5      nSUS   0nUb  X6S'   U R                  U R                  Xd5      5      nU R	                  US/ 5      nU R                  XX#5      $ )a  
get the list of most recent trades for a particular symbol

https://developer.woox.io/api-reference/endpoint/public_data/marketTrades

: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>`
rx  r%   r   trades)load_marketsrx  %indexerGetTradesPerpetualMarketMarketr  	safe_listparse_trades)	rk  r  r  r   rt  rx  r  ru  rowss	            rm  fetch_tradesdydx.fetch_trades  s~     	V$fTl
 $G==dkk'>Z[  ~~h"5  u<<ro  c           	          U R                  U R                  US5      5      U R                  US5      U R                  US5      U R                  US5      U R                  US5      U R                  US5      /$ )N	startedAtopenhighlowclosebaseTokenVolume)r  r  safe_number)rk  ohlcvrx  s      rm  parse_ohlcvdydx.parse_ohlcv  sx    & NN4++E;?@UF+UF+UE*UG,U$56
 	
ro  r   c                    U R                  5         U R                  U5      nUS   U R                  U R                  X"5      S.nUb  [	        US5      US'   Ub  U R                  U5      US'   U R                  US5      nU R                  US5      nUb  U R                  U5      US'   U R                  U R                  Xu5      5      n	U R                  U	S/ 5      n
U R                  XX#U5      $ )	a  

https://docs.dydx.xyz/indexer-client/http#get-candles

fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
:param str symbol: unified symbol of the market to fetch OHLCV data for
:param str timeframe: the length of time each candle represents
:param int [since]: timestamp in ms of the earliest candle to fetch
:param int [limit]: the maximum amount of candles to fetch
:param dict [params]: extra parameters specific to the exchange API endpoint
:param int [params.until]: the latest time in ms to fetch entries for
:returns int[][]: A list of candles ordered, open, high, low, close, volume
r%   )rx  
resolutionr   r   fromIsountiltoIsocandles)r  rx  r  r   r  r  rs  omit'indexerGetCandlesPerpetualMarketsMarketr  r  parse_ohlcvs)rk  r  	timeframer  r   rt  rx  r  r  ru  r  s              rm  fetch_ohlcvdydx.fetch_ohlcv  s     	V$Tl**4??IQ
 "5$/GG!%e!4GI!!&'267+#||E2GG??G@\], ~~h	26  yGGro  c           
         Uc  [        U R                  S-   5      eU R                  5         U R                  U5      nSUS   0nUb  X6S'   U R	                  US5      nUb  U R                  U5      US'   U R                  U R                  Xd5      5      n/ n	U R                  US/ 5      n
[        S[        U
5      5       H  nX   nU R                  U R                  US	5      5      nU R                  US
5      nU	R                  UU R                  X5      U R                  US5      UU R                  U5      S.5        M     U R!                  U	S5      nU R#                  XX#5      $ )a  
fetches historical funding rate prices

https://docs.dydx.xyz/indexer-client/http#get-historical-funding

:param str symbol: unified symbol of the market to fetch the funding rate history for
:param int [since]: timestamp in ms of the earliest funding rate to fetch
:param int [limit]: the maximum amount of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>` to fetch
:param dict [params]: extra parameters specific to the exchange API endpoint
:param int [params.until]: timestamp in ms of the latest funding rate
:returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
z5 fetchFundingRateHistory() requires a symbol argumentrx  r%   r   r  effectiveBeforeOrAthistoricalFundingr   effectiveAtr{  rate)r  r  fundingRater  r  r  )r   r%   r  rx  rs  r  !indexerGetHistoricalFundingMarketr  r  rangelenr  r  appendsafe_symbolr  sort_byfilter_by_symbol_since_limit)rk  r  r  r   rt  rx  r  r  ru  ratesr  ientryr  r  sorteds                   rm  fetch_funding_rate_historydydx.fetch_funding_rate_history	  sf    >#DGG.e$effV$fTl
 $G!!&'2-1\\%-@G)*99$++g:VW ~~h(;R@q#d)$AGEt'7'7}'MNI''x8HLL**8<#//v>& LL3 	 % e[100NNro  
methodNamert  c                    S nU R                  X!S5      u  p2UnU R                  X!SU5      u  pBUb	  US:w  a  XB/$ U R                  b  U R                  S:w  a  U R                  U/$ [        U R                  S-   U-   S-   5      e)Nuseraddress  zE() requires a user parameter inside 'params' or the walletAddress set)handle_option_and_paramswalletAddressr   r%   )rk  r  rt  userAuxr  s        rm  handle_public_addressdydx.handle_public_address@  s    77FS44VT[\42:>!*1C1Cr1I&&//#
 :  >G  !G  H  	Hro  r  c           
         U R                  U R                  US5      5      nU R                  US5      nU R                  XB5      nU R                  US5      nU R	                  U R                  US5      5      nU R                  US5      nU R                  US5      n	U R                  U R                  US5      5      n
U R                  US5      nU R                  US	5      nU R                  0 S
U_SU R                  US5      _SU R                  US5      _SU_SU R                  U5      _SS _SU_SU_SU
_S	U_SU R                  US5      _SU R                  US5      _SU_SU_SS _SU	_SS _S US US S S.EU5      $ )Nr  r{  totalFilled	updatedAtr  r  r  r  r   r  r%   clientOrderIdclientIdr  r  lastTradeTimestamplastUpdateTimestampr  postOnly
reduceOnlyr   r  r  )averagefilled	remainingr  r  r  )
parse_order_statussafe_string_upperr  r  r  parse_order_typer  
safe_orderr  	safe_bool)rk  r  rx  r  r  r  r  r  r  r  r  r  r   s                rm  parse_orderdydx.parse_orderK  s
   4 (()?)?x)PQ##E84!!(3!!%7NN4#3#3E;#GH	  0!!%0$$T%;%;E6%JK%%eV4,,UMB  
E 
$""5$/ 
 T--eZ@ 
 	 

 Y/ 
 !$ 
 "9 
 f 
 D 
 ; 
 uj9 
 $..= 
 D 
 U 
 D 
  f! 
" D# 
$ / 
0 1 	ro  r  c                 6    SSSSSS.nU R                  X!U5      $ )Nr  closedcanceled	canceling)UNTRIGGEREDOPENFILLEDCANCELEDBEST_EFFORT_CANCELEDr  )rk  r  statusess      rm  r  dydx.parse_order_status  s-    !"$/
 &99ro  r  c                 :    SSSSSSSS.nU R                  X!U5      $ )NLIMITMARKET)r!  
STOP_LIMITTAKE_PROFIT_LIMITr"  STOP_MARKETTAKE_PROFIT_MARKETTRAILING_STOP)r  )rk  r  typess      rm  r  dydx.parse_order_type  s3    !!(#"*%
 %%e488ro  r%   c                     U R                  5         SU0nU R                  U R                  XC5      5      nU R                  U5      $ )ai  
fetches information on an order made by the user

https://docs.dydx.xyz/indexer-client/http#get-order

: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>`
orderId)r  indexerGetOrdersOrderIdr  r  )rk  r%   r  rt  r  r  s         rm  fetch_orderdydx.fetch_order  sH     	r
 ,,T[[-IJ&&ro  c                 6   SnSnU R                  SU5      u  pTU R                  USSS5      u  pdU R                  5         UUS.nSnUb  U R                  U5      nUS   US'   Ub  X7S'   U R	                  U R                  Xt5      5      n	U R                  XX#5      $ )	ac  
fetches information on multiple orders made by the user

https://docs.dydx.xyz/indexer-client/http#list-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.address]: wallet address that made trades
:param str [params.subAccountNumber]: sub account number
:returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
Nrt   subAccountNumber0r  subaccountNumberr%   r{  r   )r  r  r  rx  indexerGetOrdersr  parse_orders)
rk  r  r  r   rt  userAddressr0  r  rx  ru  s
             rm  fetch_ordersdydx.fetch_orders  s     "88O#'#@#@Xjlo#p " 0
 [[(F &tGH$G((W)EF8   5@@ro  c           	      L    SS0nU R                  XX0R                  XT5      5      $ )aT  
fetch all unfilled currently open orders

https://docs.dydx.xyz/indexer-client/http#list-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.address]: wallet address that made trades
:param str [params.subAccountNumber]: sub account number
:returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
r  r  r7  r  rk  r  r  r   rt  r  s         rm  fetch_open_ordersdydx.fetch_open_orders  s.     f
   {{77STTro  c           	      L    SS0nU R                  XX0R                  XT5      5      $ )aj  
fetches information on multiple closed orders made by the user

https://docs.dydx.xyz/indexer-client/http#list-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.address]: wallet address that made trades
:param str [params.subAccountNumber]: sub account number
:returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
r  r  r:  r;  s         rm  fetch_closed_ordersdydx.fetch_closed_orders  s.     h
   {{77STTro  positionc           
      ,   U R                  US5      nU R                  X25      nUS   nU R                  US5      nU R                  US5      nUS:w  a  [        R                  " SU5      nU R                  U R                  US5      5      nU R                  0 SU_S	S _SU_S
U R                  US
5      _SS _SS _SS _SU R                  US5      _SU_SU R                  U5      _SS _SU_SU R                  U5      _SS _SS _SS _SS _S S S S S S S.E5      $ )Nrx  r  r  r  longz-1r  r  r%   
entryPrice	markPricenotional
collateralunrealizedPnl	contractsr  r  r  r   maintenanceMarginmaintenanceMarginPercentageinitialMargin)initialMarginPercentager   liquidationPricemarginRatior   r   )
r  safe_marketr  r   
string_mulr  safe_positionr  rj  r  )rk  rA  rx  r  r  r  quantityr  s           rm  parse_positiondydx.parse_position  s   * ##Hh7!!(3!%%h7##Hf56>))$9HNN4#3#3Hk#JK	!! #
H#
$#
 f#
 $**8\B	#

 #
 #
 $#
 T--hH#
 D#
 **84#
 D#
 #
 Y/#
 d#
  #
  *4!#
" T##
$ (, $/#
  	ro  c                 N    U R                  U/U5      nU R                  US0 5      $ )a  
fetch data on an open position

https://docs.dydx.xyz/indexer-client/http#list-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
:param str [params.address]: wallet address that made trades
:param str [params.subAccountNumber]: sub account number
:returns dict: a `position structure <https://docs.ccxt.com/#/?id=position-structure>`
r   )fetch_positionsr  )rk  r  rt  	positionss       rm  fetch_positiondydx.fetch_positionI  s+     ((&6:	~~iB//ro  symbolsc                    SnSnU R                  SU5      u  p2U R                  USSS5      u  pBU R                  5         UUSS.nU R                  U R	                  XR5      5      nU R                  US/ 5      nU R                  Xq5      $ )	a  
fetch all open positions

https://docs.dydx.xyz/indexer-client/http#list-positions

:param str[] [symbols]: list of unified market symbols
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.address]: wallet address that made trades
:param str [params.subAccountNumber]: sub account number
:returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
Nry   rt   r0  r1  r  )r  r3  r  rX  )r  r  r  indexerGetPerpetualPositionsr  r  parse_positions)rk  r[  rt  r6  r0  r  ru  r  s           rm  rW  dydx.fetch_positionsX  s     "889I6R#'#@#@Xjlo#p " 0

 44T[[5QR2 ~~hR8##D22ro  c                 (    U R                  USS5      $ )Nkeccakhex)hash)rk  messages     rm  hash_messagedydx.hash_message  s    yy(E22ro  c                     U R                  USS  USS  SS 5      nUS   nUS   nUR                  SS5      UR                  SS5      U R                  SUS   5      S	.$ )
N	secp256k1rs@   r1     v)rj  rk  rn  )ecdsarjustsum)rk  rc  r   	signaturerj  rk  s         rm  	sign_hashdydx.sign_hash  sm    JJtCDz:cd+;[$O	cNcNS!S!"in-
 	
ro  c                 J    U R                  U R                  U5      USS  5      $ )Nrh  )rs  re  )rk  rd  r   s      rm  sign_messagedydx.sign_message  s%    ~~d//8*ST:JKKro  c                 
   SS0nU R                   S   nUSS.nSSSS./0nU R                  X4U5      nU R                  b  U R                  S	:X  a  [        U R                  S
-   5      eU R                  XPR                  5      nU$ )NactionzdYdX Chain Onboardingr   z
dYdX Chain)r   r&   r'   string)r&   r  r  z8 signOnboardingAction() requires a privateKey to be set.)r   eth_encode_structured_datar   r   r%   rv  )rk  rd  r   domainmessageTypesmsgrr  s          rm  sign_onboarding_actiondydx.sign_onboarding_action  s    45,,y) 

 !84

 --fGL??"doo&;#DGG.h$hii%%c??;	ro  r   rd  memor   accountauthenticatorsc                     U R                  X#XEXg5      u  pU R                  X5      n
U R                  XS   U
S   -   5      $ )Nrj  rk  )encode_dydx_tx_for_signingrs  encode_dydx_tx_raw)rk  r   rd  r  r   r  r  r  	encodedTxsignDocrr  s              rm  sign_dydx_txdydx.sign_dydx_tx  sF    !<<WG^lr	NN99	&&w#30OPPro  c                    U R                  U R                  S5      nUb  U$ U R                  U R                  S5      nUc9  U R                  5       nU R	                  U R                  US   US   -   5      5      nU R                  U5      nU R                  US   5      US'   U R                  US   5      US'   XR                  S'   U$ )NdydxCredentialsr   rj  rk  r   	publicKey)r  r   r  r  re  base16_to_binaryretrieve_dydx_credentialsbinary_to_base16)rk  credentialsentropyrr  s       rm  retrieve_credentialsdydx.retrieve_credentials  s    nnT\\3DE"""4<<<?335I''(=(=inyY\~>](^_G44W=$($9$9+l:S$TL!#'#8#8[9Q#RK *5&'ro  c                    U R                  5         U R                  U R                  S5      nUb  U$ U R                  c  [	        U R
                  S-   5      eU R                  R                  S5      (       d  [	        U R
                  S-   5      eSU R                  0nU R                  U5      nU R                  US5      nSUS   S   0US'   X@R                  S'   U$ )	NdydxAccountz fetchDydxAccount() requires the walletAddress to be set using the dydx chain address eg: dydx1cpb4tedmwq304c2kc9pwzjwq0sc6z2a4tasxrzr!   z` fetchDydxAccount() requires a valid dydx chain address, starting with dydx, not the l1 address.dydxAddressr  keypub_key)load_dydx_protosr  r   r  r   r%   
startswith2nodeRestGetCosmosAuthV1beta1AccountInfoDydxAddress)rk  r  r  ru  r  s        rm  fetch_dydx_accountdydx.fetch_dydx_account  s    nnT\\=A"%#DGG  /v  %v  w  w!!,,V44#DGG  /Q  %Q  R  R4--
  JJ7S..62 79%e,
	 '.]#ro  nmc                     [         R                  " US5      nU R                  U5      n[        SU5       H  n[         R                  " X15      nM     U$ )N1r   )r   rQ  parse_to_intr  )rk  r  r  rj  cr  s         rm  powdydx.pow  sI    q#&a q!A""1(A ro  r  r  r  c                    U R                  USSS5      nUR                  5       nU R                  U5      n	UR                  5       n
SnU R                  USSU5      u  pU R	                  USS5      nU R                  US	U5      nU R                  US
5      nUS L=(       d    US L=(       d    US LnUS:H  nU R                  USS5      nU R                  US U5      nU R                  X5      nU R                  X5      nU R                  U	S5      nUS   nU R                  S[        R                  " U5      5      n[        R                  " UU5      nUS   nU R                  S[        R                  " [        R                  " UU5      S5      5      n[        R                  " UU5      nSnSnSnS nS n US:X  a  [!        U R"                  S-   5      eUS:X  a
  SnSnUb  Sn O1US:X  a+  US:X  a  SnU(       a  Sn OSn OSnUS:X  a  Sn O[!        S5      eU(       aF  SnUb  SnU R                  X5      nOUb  SnU R                  X5      n[        R                  " UU5      nU R%                  US5      n!U R%                  US5      n"S n#Sn$U R                  USS U$5      u  n$nUS:X  a	  U"c  U!S!-   n"O!U$c  ['        S"5      eU R)                  5       U$-   n#U
S#:X  a  SOSn%U R+                  S$5      n&U R%                  US%U&5      n'S&U R-                  5       US'.U'UUS(   S).U%U R/                  U5      U R/                  U5      U"U#U UUUU R/                  U5      U R1                  U R2                  S*S+5      S,.0n(S-U(S..n)U R5                  U/ S/Q5      nU R7                  U R-                  5       UU'UUS(   5      n*U*U R9                  U)U5      /$ )0Nr	  reduce_onlyFr   rF   subAccountIdr   	stopPricer   r   r"  r   GTTr  atomicResolutionr   quantumConversionExponentz-6r1  r   z$ timeInForce fok has been deprecatedr   r!  rl     r   z!unexpected code path: timeInForce    latestBlockHeightgoodTillBlock ' goodTillBlockTimeInSeconds   z'goodTillBlockTimeInSeconds is required.BUY	   r  r  ownernumber
clobPairIdsubaccountIdr  
orderFlagsr  routerAddress+dydx165sfn2k3vucvq7gklauy2r3agyjw4c3m60ascn)r+  r  quantumssubticksgoodTilBlockgoodTilBlockTimer   r	  clientMetadataconditionTypeconditionalOrderTriggerSubticksorderRouterAddressz /dydxprotocol.clob.MsgPlaceOrdertypeUrlvalue)r	  r  r  r  r   r  r   stopLoss
takeProfitr  r  r  r  )safe_bool_2upperrx  r  safe_string_2
safe_valuer  is_post_onlyamount_to_precisionprice_to_precisionr  r  r   
string_negrQ  
string_subr   r%   rs  r   secondsrand_numberget_wallet_addressto_dydx_longr  r   r  create_order_id_from_partsr  )+rk  r  r  r  r  r  rt  r	  	orderTyperx  	orderSider  r   r   r   isConditionalisMarketr   r  	amountStrpriceStr
marketInfor  quantumScaler  r  
priceScaler  r  conditionalTyper  	orderFlagtimeInForceNumberr  r  goodTillBlockTimer  
sideNumberdefaultClientOrderIdr  orderPayloadsigningPayloadr+  s+                                              rm  create_order_requestdydx.create_order_request  s^   %%flM5Q
JJL	V$JJL	#<<V]Tbdpq))&.+NN//&2CD$D0lM4MlQ`hlQl(,,V]EJ$$XtV<,,V<	**69^^FF3
%&89xxg&8&89I&JK%%i>$./J$K!XXdG$6$6w7I7IJZ\u7vx|$}~
%%h
;*-'	 %tww)OOPP IN&$%!'!e#	()%()%	%'()%&'JKKI("#262I2I&2`/ ,"#262I2I&2b/.5.@.@A`bl.m+ --f6IJ))&/B %,"-1-J-J6S`b~  A[  .\*"F>$ 1B 6)1'(QRR $1K K$-QA
#//2))&/CWX "&!8!8!:".% !."+",\": # --h7 --h7 -$50("0!0373D3DEd3e&*&6&6t||_  WD  'E)
2 :!
 6  $x  y11$2I2I2K\[hjsu  AM  vN  O^V<==ro  r  r0  r  r  r  c                 $   U R                  U R                  SS5      nUS-   [        U5      -   nU R                  Xg5      nUS-   U R	                  U5      -   S-   U R	                  U5      -   S-   U R	                  U5      -   n	U R                  Xi5      $ )N	namespacez$0f9da948-a6fb-4c45-9edc-4685c3f3317dr|  )r  r   struuid5number_to_string)
rk  r  r0  r  r  r  nameSpprefixAddressprefix	orderInfos
             rm  r  dydx.create_order_id_from_partsW  s    !!$,,=cd#,<(==F2SL4#8#8#GG#MPTPePefpPqqtwwz~  {P  {P  Q[  {\  \	zz&,,ro  c                     U R                  U5      nU R                  US5      nU R                  US5      nU R                  US5      $ )Nresultru  last_block_height)nodeRpcGetAbciInfor  rs  )rk  rt  ru  r  r  s        rm  fetch_latest_block_heightdydx.fetch_latest_block_height^  sH    **62 (3~~fj1  ':;;ro  c                    U R                  5         U R                  5       nU R                  5       nU R                  5       n	U R	                  USU	05      n
U R                  XX4XZ5      nUS   nUS   nU R                  S   nU R                  US   USXS5      nSU0nU R                  U5      nU R                  US	5      nU R                  UUUS
   S   S   S   S.5      $ )au  

https://docs.dydx.xyz/interaction/trading#place-an-order

create a trade 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 fulfilled, in units of the quote currency, ignored in market orders
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.timeInForce]: "GTT", "IOC", or "PO"
:param float [params.triggerPrice]: The price a trigger order is triggered at
:param float [params.stopLossPrice]: price for a stoploss order
:param float [params.takeProfitPrice]: price for a takeprofit order
:param str [params.clientOrderId]: a unique id for the order
:param bool [params.postOnly]: True or False whether the order is post-only
:param bool [params.reduceOnly]: True or False whether the order is reduce-only
:param float [params.goodTillBlock]: expired block number for the order, required for market order and non limit GTT order, default value is latestBlockHeight + 20
:param float [params.goodTillBlockTimeInSeconds]: expired time elapsed for the order, required for limit GTT order and conditional, default value is 30 days
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
r  r   r   r   r   r  Nr   r  r  r  r+  r  )r  r%   r  )r  r  r  r  r  r  r   r  nodeRpcGetBroadcastTxSyncr  r  )rk  r  r  r  r  r  rt  r  r  lastBlockHeight	newParamsorderRequestResr+  orderRequestr   signedTxr  ru  r  s                      rm  create_orderdydx.create_orderr  s	   . 	//1))+88:KK)<o(NO	33F$PUa!!$&q)LL-	$$[%>bR[fjk(
 11': (3)'27;IFzR 
  	ro  c                    U R                  USSS5      nU R                  USS/5      nU(       d  Uc  [        U R                  S-   5      eU R	                  5         U R                  U5      nU R                  USSU5      nUc  [        U R                  S-   5      e[        U5      nUb-  UR                  S	5      S
:  a  [        U R                  S-   5      eU R                  US5      nSn	U R                  USSU	5      u  pSn
U(       a  SOSnU R                  USU5      nSnU R                  USSU5      u  pU R                  U/ SQ5      nUS:w  a$  US:w  a  US:w  a  [        U R                  S-   5      eUS:  aP  U	c  [        U R                  S-   5      eUb  US:  a  [        U R                  S-   5      eU R                  5       U	-   n
OUc  U R                  5       nUS-   nU R                  5       nU R!                  5       nU R#                  5       US.UUUS   S   S.UU
S.nSUS .nU R$                  S!   nU R'                  US"   US#UUS5      nS$U0nU R)                  U5      nU R+                  US%5      nU R-                  SU05      $ )&a_  
cancels an open order

https://docs.dydx.xyz/interaction/trading/#cancel-an-order

:param str id: it should be the hasattr(self, clientOrderId) case
: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]: client order id used when creating the order
:param boolean [params.trigger]: whether the order is a trigger/algo order
:param float [params.orderFlags]: default is 64, orderFlags for the order, market order and non limit GTT order is 0, limit GTT order is 64 and conditional order is 32
:param float [params.goodTillBlock]: expired block number for the order, required for market order and non limit GTT order(orderFlags = 0), default value is latestBlockHeight + 20
:param float [params.goodTillBlockTimeInSeconds]: expired time elapsed for the order, required for limit GTT order and conditional(orderFlagss > 0), default value is 30 days
:param int [params.subAccountId]: sub account id, default is 0
:returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
r   stopFNz) cancelOrder() requires a symbol argumentr  r  zb cancelOrder() requires a clientOrderId parameter, cancelling using id is not currently supported.r|  zn cancelOrder() cancelling using id is not currently supported, please use provide the clientOrderId parameter.r  r  r;   r  r  rl  r  r   r  )r  r  r  r  r  r  r  z3 invalid orderFlags, allowed values are(0, 64, 32).zU goodTillBlockTimeInSeconds is required in params for long term or conditional order.z> goodTillBlock should be 0 for long term or conditional order.r  r  r  r  r  )r+  r  r  z!/dydxprotocol.clob.MsgCancelOrderr  r   r   r  r   r  )r  r  r   r%   r  rx  r  r  findr   rs  r  r   r  r  r  r  r  r   r  r  r  r  )rk  r%   r  rt  	isTriggerrx  r  idStringr  r  r  defaultOrderFlagsr  r  r  r  r  cancelPayloadr  r   r  r  ru  r  s                           rm  cancel_orderdydx.cancel_order  s   " $$VYF	6Iv#67fn#DGG.Y$YZZV,**6?JPRS #DGG  /S  %S  T  Tr7>hmmC025tww  *Z   Z  [  [))&/B%,"-1-J-J6S`b~  A[  .\*" #,B2&&v|=NO
#<<V]Tbdpq6  $c  d?zR/J"4Dtww)^^__>)1'  3J  )J  K  K(]Q->"477-m#mnn $1K K$$($B$B$D! 1B 6//1))+ "446*! *($Vn\: * 1
 ;"
 LL-	$$[%>PRT]_fhlm(
 11': (3F 
  	ro  idsc                    U R                  5         U R                  U5      nU R                  US5      nU(       d  [        U R                  S-   5      eSnU R                  USSU5      u  pcU R                  US5      nUc  U R                  5       nUS-   nU R                  U/ S	Q5      nU R                  5       n	U R                  5       n
UUS
   S   S.nU R                  5       US.U/US.nSUS.nU R                  S   nU R                  U	S   USXS5      nSU0nU R                  U5      nU R                  US5      nU R!                  S
U05      /$ )a  
cancel multiple orders
:param str[] ids: order ids
:param str [symbol]: unified market symbol
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str[] [params.clientOrderIds]: max length 10 e.g. ["my_id_1","my_id_2"], encode the double quotes. No space after comma
:param int [params.subAccountId]: sub account id, default is 0
:returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
clientOrderIdsz* cancelOrders only support clientOrderIds.r   r<   r  r  Nr  )r  r  r  r  r  )	clientIdsr  r  )r  shortTermCancelsr  z!/dydxprotocol.clob.MsgBatchCancelr  r   r   r  r   r  )r  rx  r  r   r%   r  rs  r  r  r  r  r  r   r  r  r  r  )rk  r  r  rt  rx  r  r  r  r  r  r  r<   r  r  r   r  r  ru  r  s                      rm  cancel_ordersdydx.cancel_orders  s    	V,0@Atww)UUVV#<<V^Uceqr))&/B  $ > > @-2M6#VW//1))+' .6
 002& ".)
 ;"
 LL-	$$[%>PRT]hlm(
 11': (3F!
   	ro  c           	          U R                  5         U R                  U5      nSUS   0nU R                  U R                  XS5      5      nU R	                  XdS   SSSSS5      $ )	a  
fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

https://docs.dydx.xyz/indexer-client/http#get-perpetual-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
rx  r%   r  Nbidsasksr  r  )r  rx  )indexerGetOrderbooksPerpetualMarketMarketr  parse_order_book)rk  r  r   rt  rx  r  ru  s          rm  fetch_order_bookdydx.fetch_order_bookL  sm     	V$fTl
 AA$++gB^_" $$Xh/?vvW^`fggro  itemcurrencyc                    U R                  US5      nU R                  X25      nU R                  X25      nU R                  US5      nS nUb  US:X  d  US:X  a  SnOUS:X  d  US:X  a  SnU R                  US	5      nU R	                  U R                  US
5      5      nU R                  US5      n	U R                  US5      n
U R                  UU R                  US5      UU R                  U	S5      U R                  U
S5      U R                  US5      U R                  U5      UU R                  U5      UU R                  U5      S S S S S.U5      $ )Nr  r  TRANSFER_INDEPOSITinTRANSFER_OUT
WITHDRAWALoutr  r  sender	recipientr%   r  transactionHash)r  r%   	directionr  referenceAccountreferenceIdr  r   r  r  r  beforeafterr  r  )
r  r  safe_currencyr  r  r  safe_ledger_entryparse_ledger_entry_typerj  r  )rk  r  r   
currencyIdcoder  r+  r  r  r(  r)  s              rm  parse_ledger_entrydydx.parse_ledger_entryo  sf   ( %%dH5
&&z<%%j;%%dF3	}$	(9 	'4<+?!	!!$/NN4#3#3D+#FG	h/NN45	%%""4."''	: $ 0 0I F++D2CD006''/"Y/'
  ! 	ro  c                 4    SSSSS.nU R                  X!U5      $ )Nr   deposit
withdrawal)r"  r%  r#  r&  r  )rk  r  
ledgerTypes      rm  r2  dydx.parse_ledger_entry_type  s*    %& &	

 
$77ro  r4  c           
          U R                  5         SnUb  U R                  U5      nU R                  XX0R                  USS05      5      nU R	                  XeX#5      $ )a  
fetch the history of changes, actions done by the user or operations that altered balance of the user

https://docs.dydx.xyz/indexer-client/http#get-transfers

:param str [code]: unified currency code, default is None
:param int [since]: timestamp in ms of the earliest ledger entry, default is None
:param int [limit]: max number of ledger entries to return, default is None
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.address]: wallet address that made trades
:param str [params.subAccountNumber]: sub account number
:returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger>`
Nr  rg   )r  r   fetch_transactions_helperr  parse_ledger)rk  r4  r  r   rt  r   ru  s          rm  fetch_ledgerdydx.fetch_ledger  sa     	}}T*H11$ukkRX[givZwFxy  UBBro  c           
         U R                  XUS   US   5      nSU0nU R                  U5      nU R                  US5      nUc  [        U R                  S-   5      eU R                  US5      nUc  [        U R                  S-   5      eU R                  U R                  S5      n	U R                  U R                  S5      n
U R                  U R                  S	5      nS nS nU	S
:X  a  US   nUS   nO
US   nUS   n[        [        R                  " U R                  [        R                  " X5      5      5      5      n[        R                  " U R                  U5      U5      nUR                  S5      S:  a=  U R                  [        [        R                  " U R                  U5      5      5      5      nUUS.nU/US.$ )Nsequencer  txBytesgas_infoz  failed to simulate transaction.gas_usedr   r   r   r   r   r   r   r   .r   )r  denom)r  gasLimit)encode_dydx_tx_for_simulation#nodeRestPostCosmosTxV1beta1Simulater  r   r%   r  r   intmathceilparse_to_numericr   rQ  r  r
  )rk  rd  r  r  rC  r  ru  gasInfogasUsedr   r   r   gasPricerG  rH  	feeAmountfeeObjs                    rm  estimate_tx_feedydx.estimate_tx_fee  s   44WGJDWY`ajYklw
 ;;GD ..:6?*L LMM""7J7?*L LMM**4<<9JK#//>TU>>$,,
;g% 01H\*E 67H/0Etyy!6!6w7I7I'7h!ijk&&t'<'<X'FQ	>>#!#--c$))D<Q<QR[<\2].^_I

 h 
 	
ro  fromAccount	toAccountc           	         US:w  a  [        U R                  S-   5      eU R                  5         U R                  US5      nU R                  US5      nUS:w  a9  Uc  [        U R                  S-   5      eUb  Uc  [	        U R                  S-   5      eU R                  USS/5      nU R                  5       nU R                  5       n	U R                  [        R                  " U R                  U5      S	5      5      n
SnSnUS:X  aG  Uc  [	        U R                  S
-   5      eU R                  5       U R                  5       US.SU
S.nSUS.nOSUUS.UUS.SU
S.0nSUS.nU R                  USU	5      nU R                  S   nU R                  US   USXSU5      nSU0nU R!                  U5      nU R#                  U5      $ )a  
transfer currency internally between wallets on the same account
:param str code: unified currency code
:param float amount: amount to transfer
:param str fromAccount: account to transfer from *main, subaccount*
:param str toAccount: account to transfer to *subaccount, address*
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.vaultAddress]: the vault address for order
:returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
rz  z transfer() only support USDCfromSubaccountIdtoSubaccountIdmainNzF transfer only support main > subaccount and subaccount <> subaccount.z7 transfer requires fromSubaccountId and toSubaccountId.1000000z$ transfer() requeire toSubaccoutnId.r  r   r(  r)  assetIdr  z,/dydxprotocol.sending.MsgDepositToSubaccountr  r   )r(  r)  r^  r  z'/dydxprotocol.sending.MsgCreateTransferr  r   r   r   )r   r%   r  rs  r   r  r  r  r  r   rQ  r  r  rT  r   r  r  parse_transfer)rk  r4  r  rV  rW  rt  rY  rZ  r  r  usdpayloadr  txFeer   r  r  ru  s                     rm  r   dydx.transfer  s    6>tww)HHII,,V5GH**63CD& ""477-u#uvv'>+A'2k(kll6$68H#IJ//1))+ 2 243H3H3PR[ \]& %'2X(XYY113!446, G J N !,"2
 "+"0"  !!G E N $$^RALL-	$$[%>PRT]hlnst(
 11': ""8,,ro  r   c           
         U R                  US5      nU R                  US5      nU R                  XB5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      n	U R                  US5      n
U R	                  U R                  US5      5      nUUUU R                  U5      UUU	U
S S.	$ )	Nr%   r  r  r(  r)  r  r  )	r  r%   r  r  r   r  rV  rW  r  )r  r  r  r  r  r  )rk  r   r   r%   r3  r4  r  r(  r)  rV  rW  r  s               rm  r_  dydx.parse_transferD  s    ( h-%%h9
&&z<!!(F3(3NN8[9	&&vy9$$Y	:	NN4#3#3Hk#JK	"Y/&"

 
	
ro  c           
      (   U R                  5         SnUb  U R                  U5      nU R                  XX0R                  USS05      5      nU R	                  USS5      nU R	                  USS5      nU R                  Xx5      n	U R                  XX#5      $ )aj  
fetch a history of internal transfers made on an account

https://docs.dydx.xyz/indexer-client/http#get-transfers

:param str code: unified currency code of the currency transferred
:param int [since]: the earliest time in ms to fetch transfers for
:param int [limit]: the maximum number of transfers structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.address]: wallet address that made trades
:param str [params.subAccountNumber]: sub account number
:returns dict[]: a list of `transfer structures <https://docs.ccxt.com/#/?id=transfer-structure>`
Nr  r   r  r"  r%  )r  r   r=  r  	filter_byarray_concatparse_transfers)
rk  r4  r  r   rt  r   ru  
transferIntransferOutr  s
             rm  fetch_transfersdydx.fetch_transfersm  s     	}}T*H11$ukkRX[giyZzF{|^^HfmD
nnXv~F  9##DEAAro  transactionc                 :   U R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      n	U R                  X5      n
U R                  U R                  US5      5      nU R	                  US5      n0 S	U_SU_S
U_SU_SU R                  U5      _SS _SU_SU_SU_SS _SS _SS _SU R                  US5      _SU_SU
_SS _SS _S S S S.E$ )Nr%   r(  r)  r  r*  r  r  r  r  txidr  r  network	addressToaddressFromtagtagTotagFromr  r  r   r  updated)internalcommentr  )r  r  r  r  r  r  r  )rk  rn  r   r%   r(  r)  rr  rs  rp  r3  r4  r  r  s                rm  parse_transactiondydx.parse_transaction  s   ( k40X6NN;<	$$Y	:	&&vy9->?%%k8<
&&z<NN4#3#3K#MN	!!+v6
K
"
 D
 	

 Y/
 t
 y
 
 ;
 4
 T
 t
 D**;?
 f
 
  d!
" t#
$ )
 	
ro  rt  c           	         US:w  a  [        U R                  S-   5      eU R                  5         U R                  U5        U R	                  US5      nUc  [        U R                  S-   5      eU R                  US/5      nU R                  U5      nU R                  5       nU R                  5       n	U R                  [        R                  " U R                  U5      S5      5      n
U R                  5       US.USU
S	.nS
US.nU R                  XU	5      nU R                   S   nU R#                  US   XXSU5      nSU0nU R%                  U5      nU R'                  US0 5      nU R)                  UU5      $ )aO  
make a withdrawal
: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>`
rz  z withdraw() only support USDCr  Nz  withdraw requires subaccountId.r\  r  r   r]  z//dydxprotocol.sending.MsgWithdrawFromSubaccountr  r   r   r   r  )r   r%   r  check_addressrs  r   r  r   r  r  r  r   rQ  r  r  rT  r   r  r  r  rz  )rk  r4  r  r  rt  rt  r  r   r  r  r`  ra  r  rb  r   r  r  ru  r  s                      rm  r   dydx.withdraw  s    6>tww)HHII7#((@#DGG.P$PQQ6N#34==&//1))+ 2 243H3H3PR[ \] 002& !
 I
 $$^'BLL-	$$[%>U^imotu(
 11': ~~h"5%%dH55ro  c           
          U R                  5         SnUb  U R                  U5      nU R                  XX0R                  USS05      5      nU R	                  USS5      nU R                  XuX#5      $ )aJ  
fetch all withdrawals made from an account

https://docs.dydx.xyz/indexer-client/http#get-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 str [params.address]: wallet address that made trades
:param str [params.subAccountNumber]: sub account number
:returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
Nr  r   r  r&  r  r   r=  r  rg  parse_transactionsrk  r4  r  r   rt  r   ru  r  s           rm  fetch_withdrawalsdydx.fetch_withdrawals  ss     	}}T*H11$ukkRX[gi{Z|F}~~~h=&&tuDDro  c           
          U R                  5         SnUb  U R                  U5      nU R                  XX0R                  USS05      5      nU R	                  USS5      nU R                  XuX#5      $ )a?  
fetch all deposits made to an account

https://docs.dydx.xyz/indexer-client/http#get-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 str [params.address]: wallet address that made trades
:param str [params.subAccountNumber]: sub account number
:returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
Nr  r^   r  r#  r  r  s           rm  fetch_depositsdydx.fetch_deposits  ss     	}}T*H11$ukkRX[gixZyFz{~~h	:&&tuDDro  c           
      (   U R                  5         SnUb  U R                  U5      nU R                  XX0R                  USS05      5      nU R	                  USS5      nU R	                  USS5      nU R                  Xx5      n	U R                  XX#5      $ )a  
fetch history of deposits and withdrawals

https://docs.dydx.xyz/indexer-client/http#get-transfers

:param str [code]: unified currency code for the currency of the deposit/withdrawals, default is None
:param int [since]: timestamp in ms of the earliest deposit/withdrawal, default is None
:param int [limit]: max number of deposit/withdrawals to return, default is None
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.address]: wallet address that made trades
:param str [params.subAccountNumber]: sub account number
:returns dict: a list of `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
Nr  r_   r  r&  r#  )r  r   r=  r  rg  rh  r  )
rk  r4  r  r   rt  r   ru  withdrawalsdepositsr  s
             rm  fetch_deposits_withdrawalsdydx.fetch_deposits_withdrawals!  s     	}}T*H11$ukkRX[g  jD  [E  GF  GnnXv|D>>(FI>  7&&tuDDro  c                    U R                  US5      nU R                  US5      nS nS nU R                  XT5      u  pdU R                  XESS5      u  ptUUS.nU R	                  U R                  X5      5      n	U R                  U	S/ 5      $ )Nr  r0  r1  r2  r   )r  r  r  r  indexerGetTransfersr  r  )
rk  r4  r  r   rt  r  r6  r0  r  ru  s
             rm  r=  dydx.fetch_transactions_helper9  s    %%fl;
6<0"88L#'#@#@Ugil#m " 0
 ++DKK,HI0 ~~hR88ro  c           	      6   SnU R                  SU5      u  p!SU0nU R                  U R                  X15      5      nU R                  US/ 5      n/ n[	        S[        U5      5       H0  nXW   nU R                  US5      n	UR                  U	SSUSS.5        M2     U$ )ax  
fetch all the accounts associated with a profile

https://docs.dydx.xyz/indexer-client/http#get-subaccounts

:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.address]: wallet address that made trades
:returns dict: a dictionary of `account structures <https://docs.ccxt.com/#/?id=account-structure>` indexed by the account type
NrQ   r  subaccountsr   r3  )r%   r  r   r  r4  )r  indexerGetAddressesAddressr  r  r  r  r  r  )
rk  rt  r6  r  ru  r  r  r  r  	accountIds
             rm  fetch_accountsdydx.fetch_accounts^  s     "88&Q{
 224;;w3OPZ ~~hr:q#d)$AgG((2DEIMM   % ro  c                    U R                  5         SnU R                  SU5      u  p!SnU R                  USSS5      u  p1UUS.nU R                  U R	                  XA5      5      nU R                  US5      nU R                  U5      $ )a<  
query for balance and get the amount of funds available for trading or funds locked in orders

https://docs.dydx.xyz/indexer-client/http#get-subaccount

:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
NrQ   r3  r   r2  
subaccount)r  r  r  :indexerGetAddressesAddressSubaccountNumberSubaccountNumberr  r  parse_balance)rk  rt  r6  r3  r  ru  r  s          rm  fetch_balancedydx.fetch_balance  s     	"88&Q#'#@#@Zlno#p " 0
 RRSWS^S^_fSopz ~~h5!!$''ro  c                 x    U R                  5       nU R                  US5      US'   UUS.nU R                  U5      $ )NfreeCollateralfree)r  rz  )r  r  safe_balance)rk  ru  r  r  s       rm  r  dydx.parse_balance  sD    ,,.**85EF
   ((ro  c                 B    U R                  5       U R                  S   -
  $ )NtimeDifference)millisecondsr   )rk  s    rm  nonce
dydx.nonce	  s       "T\\2B%CCCro  c                     U R                   b  U R                   S:w  a  U R                   $ U R                  U R                  S5      nUb  U R                  US5      nUb  U$ [	        U R
                  S-   5      e)Nr  r  r  zh getWalletAddress() requires a wallet address. Set `walletAddress` or `dydxAccount` in exchange options.)r  r  r   r  r   r%   )rk  r  wallets      rm  r  dydx.get_wallet_address	  s    )d.@.@B.F%%%nnT\\=A"%%k9=F!  +U  !U  V  	Vro  publicGETc                 V   U R                  X5      nU R                  U R                  S   U   5      nU R                  X@R	                  U5      5      nU R                  U5      nUSU-   -  nUS:X  a  U(       a  USU R                  U5      -   -  nOU R                  U5      nSS0nXXeS.$ )Nr   r~  r  ?zContent-typezapplication/json)urlmethodbodyheaders)implode_paramsimplode_hostnamer   r  extract_paramskeysort	urlencodejson)	rk  pathsectionr  rt  r  r  pathWithParamsr  s	            rm  sign	dydx.sign	  s    ,,T:##DIIe$4W$=>6#6#6t#<=f%s^##U?sT^^F33399V$D 2G dOOro  httpCodereasonr  r  r  r  c
                    U(       d  g U R                  US5      n
U R                  U
S5      nU(       d  U R                  US5      nU(       a  U R                  U5      nUS:  aj  U R                  S-   U R	                  U5      -   nU R                  U R                  S   X5        U R                  U R                  S   Xm5        [        U5      eg )Nr  r4  r   r  rc  rd  )	r  r  rN  r%   r  throw_exactly_matched_exceptionre  throw_broadly_matched_exceptionr   )rk  r  r  r  r  r  r  ru  requestHeadersrequestBodyr  	errorCodeerrorCodeNumfeedbacks                 rm  handle_errorsdydx.handle_errors!	  s     (3$$VV4	((6:I00;La77S=499X+>>44T__W5Myc44T__W5Mt^#H--ro  enablec                    > [         [        U ]  U5        SU R                  S'   SU R                  S'   SU R                  S   S'   g )Nzdydx-testnet-4r   i6 r   adv4tntr   r   )rh  r!   set_sandbox_moder   )rk  r  rl  s     rm  r  dydx.set_sandbox_mode8	  sB    dD*62$4[!"*Y7@Z !34ro   )N)X__name__
__module____qualname____firstlineno__r   ri  r	   rv  dictr   r  r   r  r   r  r  r  r  r  r  r   r  r  r   r  r  r  r-  r7  r<  r?  rT  rY  r   r   rW  re  rs  rv  objectr  r  r  r  r  r   r   floatr   r  r  rK  r  r  r  r  r   r  r   r
   r5  r2  r?  rT  r   r   r_  rl  r   rz  r   r  r  r  r=  r   r  r   r  r  r  r  r  r  boolr  __static_attributes____classcell__)rl  s   @rm  r!   r!      s   u# un !# 4s 4$`4 `F `D $& -+$v, -+^   v    D 6:UW $=3 $=s $=# $=\`af\g $=L
 
4 
6 26DW[df 3H# 3Hc 3HQT 3Hkoptku 3Hj 8<$]ajl 5O 5OC 5OWZ 5On	H 	HT 	H< <v < <|: :
9S 
9 26b 'c '3 '$ *.Dt\^ 9A3 9Ac 9A 9Acghmcn 9Av /3TXac U U3 Uc Uhlmrhs U& 154VZce U# US UPS Ujnotju U&5t 5V 5n 24 0S 0 26b 03w 03T(^ 03d3
L $Qs QS Q Qc Q\_ Qqt Q  DG Q
c !FS S  os{} k>3 k>i k>y k>Z_ k>hk k>Z-# - -_d -rw -  FK -  PS - 02 <c <( gksu 93 9i 9y 9RW 9`c 9z 9v 37r \s \C \e \| ;?r ?c ?C ?B :>b !hs !h3 !hY !hF2t 2x 2; 2h8 (,$TZ\ C CC Cs Caefqar C**
s *
# *
 *
 *
X [] U-S U-% U-c U-c U-an U-n'
t '
x '
= '
R +/TPT]_ BC Bs B# Bdhivdw B03
T 3
X 3
Q\ 3
j KOWY 96S 96% 96# 96C 96^i 96v -1tRV_a Ec E EC Efjkvfw E, *.Dt\^ E3 Ec E Ecghsct E, 6:[_hj Es E# EUX Eost  pA E0 59tZ^gi #9c #9 #9TW #9J %' H4= HT $& P(( P(d) )D	V "*%DW[ P c 3 S # X\ dg .At A Aro  r!   )&ccxt.base.exchanger   ccxt.abstract.dydxr   rL  ccxt.base.typesr   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  ro  rm  <module>r     s[    ( *            * . ' . ) ) 4 %h$A8[ h$Aro  