
    eiS                        d dl mZ d dlmZ d dlZd dlmZmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZ 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%dS )    )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                       e Zd Zdef fdZi fdefdZdedefdZ	i fde
e         fdZdkdededefd	Zddi fd
ededede
e         fdZdkd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di fd
ededefdZdedefdZdkdededefdZdefdZdefdZdi f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di fd
ededede
e         fdZdddi fd
ededede
e         fdZdkd 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% Z#d& Z$d' Z%de&fd(Z'dkd)ed*ed+ed,ed-ed.edefd/Z(defd0Z)d1 Z*d2ed3efd4Z+di fd
ede,d5e-d6e.d7e/f
d8Z0d9ed:e.d;e.d<e.d=e.defd>Z1i fde2fd?Z3di fd
ede,d5e-d6e.d7e/defd@Z4di fded
edefdAZ5di fdBe
e         d
efdCZ6di fd
edede7fdDZ8dkdEedFe9de:fdGZ;dH Z<dddi fdIededede
e:         fdJZ=d*ed+ed-edefdKZ>i fdIed6e.dLedMede?f
dNZ@dkdOedFe9de?fdPZAdddi fdIededede
e?         fdQZBdkdRedFe9deCfdSZDdi fdIed6e.d9edTedeCf
dUZEdddi fdIededede
eC         fdVZFdddi fdIededede
eC         fdWZGdddi fdIededede
eC         fdXZHdddi fdIededefdYZIi fde
eJ         fdZZKi fdeLfd[ZMdeLfd\ZNd] ZOd^ ZPd_d`i ddfdaZQdbe2dceddedeedfedgefdhZRdieSf fdjZT xZUS )ldydxreturnc                    |                      t          t          |                                           i d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d0dd1dd2di d3dd4dd5dd6dd7dd8dd9dd:dd;dd<dd=dd>dd?dd@ddAddBddCdi dDddEddFddGddHddIddJddKddLddMddNddOddPddQddRddSddTdi dUddVddWddXddYddZdd[dd\dd]dd^dd_dd`ddaddbddcdddddeddddddddfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdudydzgd{gd|d}d~di ddddddddddddddddddddddddddddddddddi dddddddddddddddddddddddddddddddddddddddddddddddidddddddiddidddddudddd|                     d          |                     d          diddddddd ddddddddddddd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 ddddddÜdddddĜddddddŜddd dddddǜddd d dddddȜddid˜	dddidΜddid dќd d dќdҜdi i dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          i dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          i dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt          dt          dt          d t
          dt
          dt
          dt
          dt
          dt
          dt
          i dt
          dt
          d	t
          d
t
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          i dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          d t
          d!t
          d"t
          d#t
          d$t
          d%t
          d&t
          d't
          d(t
          i d)t
          d*t
          d+t
          d,t
          d-t
          d.t
          d/t
          d0t
          d1t
          d2t
          d3t
          d4t
          d5t
          d6t
          d7t
          d8t
          d9t          id:t          d;          S (<  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   rE   createOrdersrl   rq   rp   rs   rT   rm   defaultr   )extendsrE   r   forSwap)linearinverse)r   r   r4   r5   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    G/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/dydx.pyrh  zdydx.describe   s   dD 1 1 : : < < 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 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 0H 6756?@;<679:;<bcfgZ[23;<_0 0 02h %&!"./-.  I! 5667 	 {F FIt?
V !%"&!..x88!..x88	 Wt?
f "#$ $gt?
p  -$#*(-"h&-%&&-(/+-,9  qt?
R #&+(,$($(%*- -
 -2).+06:#'#'"&#'	( ( #($)$)+027/4#(1$ $4 %)&+!$$&%**/& & ',#'$)*/	# # ',!$#'$(*/( ( ',!$$(%+#'$(*/$ $ ',!$$(,0%+#'$(*/	* 	*  #IG GR  ) $$  "9  $	  ## kY 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. ,/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 i 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 i 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 i 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 i 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 iV )*;Wn n^ 'gt?
 t?
 t?
 t t t	    c                 X    |                      |          }|                     |d          S )aO  
        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)rj  paramsresponses      rl  
fetch_timezdydx.fetch_time  s/     &&v..   7333rm  marketc                 f   d}|                      |d          }|                    d          }|                      |d          }|                      |d|          }|                     |          }|                     |          }d}	|                     |	          }
|dz   |z   dz   |
z   }d}d}|                      |d	          }|                      |d
          }|                      |d          }d}|dk    r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 d d d d d d d d d d d d!d |d"          S )#NUSDCticker-r   baseId/:TstepSizetickSizestatusACTIVEFr$   symbolbasequotesettlebaseNamequoteIdsettleIdtyper4   r2   r3   r5   r6   activecontract1)amountprice)minmax)r   r  r  cost)contractSizer   r   r   r   expiryexpiryDatetimestrike
optionType	precisionlimitscreatedinfo)safe_stringsplitsafe_currency_codesafe_market_structureri  )rj  ru  r  marketIdpartsr  rz  r  r  r  r  r  r  r4   amountPrecisionStrpricePrecisionStrr  r  s                     rl  parse_marketzdydx.parse_market  s   6 ##FH55s####E1--!!&(H==&&v..''00((22e#c)F2!--fjAA ,,VZ@@!!&(33XF)) 3+
$""684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+
$ !--c22"++,>??**+<==    
   
   
    $ e3+
 3+
 3+
 3 3 3	rm  c                     i }|                      |                     ||                    }|                     |di           }t          |                                          }|                     |          S )a$  
        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)rj  rr  requestrs  datar  s         rl  fetch_marketszdydx.fetch_marketsB  sl    
 224;;w3O3OPP> ~~h	266t{{}}%%!!'***rm  Ntradec                    |                      |                     |d                    }|d         }|                     |d          }|                     |d          }|                     |d          }|                     |d          }|                     |||                     |          ||||d d d d d |d|          S )N	createdAtr  r  sizesider$   )r$   	timestampdatetimer  r  r  r  r  ordertakerOrMakerr  feer  )	parse8601r  safe_string_lower
safe_tradeiso8601)	rj  r  ru  r  r  r  r  r  r$   s	            rl  parse_tradezdydx.parse_tradeq  s     NN4#3#3E;#G#GHH	!  00!!%00%%eV44eT**"Y//  
  
   	rm  r  sincer   c                 &   |                                   |                     |          }d|d         i}|||d<   |                     |                     ||                    }|                     |dg           }|                     ||||          S )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>`
        ru  r$   Nr   trades)load_marketsru  %indexerGetTradesPerpetualMarketMarketr  	safe_listparse_trades)	rj  r  r  r   rr  ru  r  rs  rowss	            rl  fetch_tradeszdydx.fetch_trades  s     	V$$fTl
 $GG==dkk'SY>Z>Z[[  ~~h"55  vue<<<rm  c           	      (   |                      |                     |d                    |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS )N	startedAtopenhighlowclosebaseTokenVolume)r  r  safe_number)rj  ohlcvru  s      rl  parse_ohlcvzdydx.parse_ohlcv  s    & NN4++E;??@@UF++UF++UE**UG,,U$566
 	
rm  r   c                 :   |                                   |                     |          }|d         |                     | j        ||          d}|t	          |d          |d<   ||                     |          |d<   |                     |d          }|                     |d          }||                     |          |d<   |                     | 	                    ||                    }	| 
                    |	d	g           }
|                     |
||||          S )
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$   )ru  
resolutionNr   r   fromIsountiltoIsocandles)r  ru  r  r   r  r  rq  omit'indexerGetCandlesPerpetualMarketsMarketr  r  parse_ohlcvs)rj  r  	timeframer  r   rr  ru  r  r  rs  r  s              rl  fetch_ohlcvzdydx.fetch_ohlcv  s"    	V$$Tl**4?IyQQ
 
 "5$//GG!%e!4!4GI!!&'2267++#||E22GG??GU[@\@\]], ~~h	266  vy%GGGrm  c           
      b   |t          | j        dz             |                                  |                     |          }d|d         i}|||d<   |                     |d          }||                     |          |d<   |                     |                     ||                    }g }	|                     |dg           }
t          d	t          |
                    D ]}|
|         }|                     |                     |d
                    }|                     |d          }|	                    ||                     ||          |                     |d          ||                     |          d           |                     |	d          }|                     ||||          S )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>`
        Nz5 fetchFundingRateHistory() requires a symbol argumentru  r$   r   r  effectiveBeforeOrAthistoricalFundingr   effectiveAtrx  rate)r  r  fundingRater  r  r  )r   r$   r  ru  rq  r  !indexerGetHistoricalFundingMarketr  r  rangelenr  r  appendsafe_symbolr  sort_byfilter_by_symbol_since_limit)rj  r  r  r   rr  ru  r  r  rs  ratesr  ientryr  r  sorteds                   rl  fetch_funding_rate_historyzdydx.fetch_funding_rate_history	  s    >#DG.e$efffV$$fTl
 $GG!!&'22-1\\%-@-@G)*99$++gv:V:VWW ~~h(;R@@q#d))$$ 
	 
	AGEt'7'7}'M'MNNI''x88HLL**8V<<#//v>>& LL33      e[1100NNNrm  
methodNamerr  c                     d }|                      ||d          \  }}|}|                      ||d|          \  }}|
|dk    r||gS | j        | j        dk    r	| j        |gS t          | j        dz   |z   dz             )Nuseraddress  zE() requires a user parameter inside 'params' or the walletAddress set)handle_option_and_paramswalletAddressr   r$   )rj  r  rr  userAuxr  s        rl  handle_public_addresszdydx.handle_public_address@  s    77
FSS44VZT[\\f42::&>!*1Cr1I1I&//#
 :  >G  !G  H  H  	Hrm  r  c           
         |                      |                     |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|          S )Nr  rx  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)rj  r  ru  r  r  r  r  r  r  r  r  r  r   s                rl  parse_orderzdydx.parse_orderK  sQ   4 (()?)?x)P)PQQ##E844!!(F33!!%77NN4#3#3E;#G#GHH	  00!!%00$$T%;%;E6%J%JKK%%eV44,,UMBB  
E 
$""5$// 
 T--eZ@@ 
 	 

 Y// 
 !$ 
 "9 
 f 
 D 
 ; 
 uj99 
 $..== 
 D 
 U 
 D 
  f! 
" D# 
$ / 
  
  
0 1  	rm  r  c                 @    dddddd}|                      |||          S )Nr  closedcanceled	canceling)UNTRIGGEREDOPENFILLEDCANCELEDBEST_EFFORT_CANCELEDr  )rj  r  statusess      rl  r  zdydx.parse_order_status  s7    !"$/
 
 &&999rm  r  c                 D    dddddddd}|                      |||          S )NLIMITMARKET)r  
STOP_LIMITTAKE_PROFIT_LIMITr  STOP_MARKETTAKE_PROFIT_MARKETTRAILING_STOP)r  )rj  r  typess      rl  r  zdydx.parse_order_type  s=    !!(#"*%
 
 %%eT4888rm  r$   c                     |                                   d|i}|                     |                     ||                    }|                     |          S )a  
        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  )rj  r$   r  rr  r  r  s         rl  fetch_orderzdydx.fetch_order  sY     	r
 ,,T[[&-I-IJJ&&&rm  c                 |   d}d}|                      d|          \  }}|                     |ddd          \  }}|                                  ||d}d}| |                     |          }|d         |d<   |||d<   |                     |                     ||                    }	|                     |	|||          S )	a  
        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>`
        Nrs   subAccountNumber0r  subaccountNumberr$   rx  r   )r  r  r  ru  indexerGetOrdersr  parse_orders)
rj  r  r  r   rr  userAddressr"  r  ru  rs  s
             rl  fetch_orderszdydx.fetch_orders  s     "88OOV#'#@#@Xjlo#p#p &" 0
 
 [[((F &tGH$GG((Wf)E)EFF8   65%@@@rm  c           	      b    ddi}|                      ||||                     ||                    S )a  
        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  r)  r  rj  r  r  r   rr  r  s         rl  fetch_open_orderszdydx.fetch_open_orders  s:     f
   t{{7F7S7STTTrm  c           	      b    ddi}|                      ||||                     ||                    S )a  
        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         rl  fetch_closed_orderszdydx.fetch_closed_orders  s:     h
   t{{7F7S7STTTrm  positionc           
         |                      |d          }|                     ||          }|d         }|                     |d          }|                      |d          }|dk    rt          j        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 d          S )Nru  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  ri  r  )rj  r0  ru  r  r  r  quantityr  s           rl  parse_positionzdydx.parse_position  s   * ##Hh77!!(F33!%%h77##Hf556>>)$99HNN4#3#3Hk#J#JKK	!! #
H#
$#
 f#
 $**8\BB	#

 #
 #
 $#
 T--hHH#
 D#
 **844#
 D#
 #
 Y//#
 d#
  #
  *4!#
" T##
$ (, $/#
 #
 #
   	rm  c                 ^    |                      |g|          }|                     |di           S )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  )rj  r  rr  	positionss       rl  fetch_positionzdydx.fetch_positionI  s1     ((&6::	~~iB///rm  symbolsc                 R   d}d}|                      d|          \  }}|                     |ddd          \  }}|                                  ||dd}|                     |                     ||                    }|                     |dg           }|                     ||          S )	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>`
        Nrx   rs   r"  r#  r  )r  r%  r  rF  )r  r  r  indexerGetPerpetualPositionsr  r  parse_positions)rj  rH  rr  r(  r"  r  rs  r  s           rl  rE  zdydx.fetch_positionsX  s     "889I6RRV#'#@#@Xjlo#p#p &" 0
 

 44T[[&5Q5QRR2 ~~hR88##D'222rm  c                 0    |                      |dd          S )Nkeccakhex)hash)rj  messages     rl  hash_messagezdydx.hash_message  s    yy(E222rm  c                    |                      |dd          |dd          dd           }|d         }|d         }|                    dd          |                    dd          |                     d|d                   d	S )
N	secp256k1rs@   r#     v)rU  rV  rY  )ecdsarjustsum)rj  rO  r   	signaturerU  rV  s         rl  	sign_hashzdydx.sign_hash  s    JJtCDDz:cdd+;[$OO	cNcNS!!S!!"in--
 
 	
rm  c                 d    |                      |                     |          |dd                    S )NrS  )r^  rQ  )rj  rP  r   s      rl  sign_messagezdydx.sign_message  s-    ~~d//88*STT:JKKKrm  c                     ddi}| j         d         }|dd}ddddgi}|                     |||          }| j        | j        d	k    rt          | j        d
z             |                     || j                  }|S )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$   r`  )rj  rP  r   domainmessageTypesmsgr]  s          rl  sign_onboarding_actionzdydx.sign_onboarding_action  s    45,y) 
 

 !844

 --flGLL?"do&;&;#DG.h$hiii%%c4?;;	rm  r   rP  memor   accountauthenticatorsc                     |                      ||||||          \  }}	|                     ||          }
|                     |	|
d         |
d         z             S )NrU  rV  )encode_dydx_tx_for_signingr^  encode_dydx_tx_raw)rj  r   rP  ri  r   rj  rk  r  	encodedTxsignDocr]  s              rl  sign_dydx_txzdydx.sign_dydx_tx  s]    !<<WdGU\^lnqrr	7NN9j99	&&w	#30OPPPrm  c                    |                      | j        d          }||S |                     | j        d          }|K|                                 }|                     |                     |d         |d         z                       }|                     |          }|                     |d                   |d<   |                     |d                   |d<   || j        d<   |S )NdydxCredentialsr   rU  rV  r   	publicKey)r  r   r  rh  rQ  base16_to_binaryretrieve_dydx_credentialsbinary_to_base16)rj  credentialsentropyr]  s       rl  retrieve_credentialszdydx.retrieve_credentials  s    nnT\3DEE"""4<<<?3355I''(=(=inyY\~>](^(^__G44W==$($9$9+l:S$T$TL!#'#8#8[9Q#R#RK *5&'rm  c                    |                                   |                     | j        d          }||S | j        t	          | j        dz             | j                            d          st	          | j        dz             d| j        i}|                     |          }|                     |d          }d|d         d         i|d<   || j        d<   |S )	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)rj  r|  r  rs  rj  s        rl  fetch_dydx_accountzdydx.fetch_dydx_account  s	   nnT\=AA"%#DG  /v  %v  w  w  w!,,V44 	R#DG  /Q  %Q  R  R  R4-
  JJ7SS..622 79%e,
	 '.]#rm  nmc                     t          j        |d          }|                     |          }t          d|          D ]}t          j        ||          }|S )Nr  r   )r   r@  parse_to_intr  )rj  r  r  rU  cr  s         rl  powzdydx.pow  sW    q#&&a  q! 	) 	)A"1a((AArm  r  r  r  c                 X   |                      |ddd          }|                                }|                     |          }	|                                }
d}|                     |dd|          \  }}|                     |dd          }|                     |d	|          }|                     |d
          }|d up|d up|d u}|dk    }|                     |dd          }|                     |d |          }|                     ||          }| 	                    ||          }| 
                    |	d          }|d         }|                     dt          j        |                    }t          j        ||          }|d         }|                     dt          j        t          j        ||          d                    }t          j        ||          }d}d}d}d }d } |dk    rt!          | j        dz             |dk    r	d}d}|d} n0|dk    r*|dk    r
d}|rd} nd} nd}|dk    rd} nt!          d          |rLd}|d}| 	                    ||          }n|d}| 	                    ||          }t          j        ||          }|                     |d          }!|                     |d          }"d }#d}$|                     |dd |$          \  }$}|dk    r|"|!d!z   }"n(|$t'          d"          |                                 |$z   }#|
d#k    rdnd}%|                     d$          }&|                     |d%|&          }'d&|                                 |d'|'||d(         d)|%|                     |          |                     |          |"|#| ||||                     |          |                     | j        d*d+          d,i}(d-|(d.})|                     |g d/          }|                     |                                 ||'||d(                   }*|*|                     |)|          gS )0Nr  reduce_onlyFr   rE   subAccountIdr   	stopPricer   r   r  r   GTTr  atomicResolutionr   quantumConversionExponentz-6r#  r   z$ timeInForce fok has been deprecatedr   r  rW     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upperru  r  safe_string_2
safe_valuer  is_post_onlyamount_to_precisionprice_to_precisionr  r  r   
string_negr@  
string_subr   r$   rq  r   secondsrand_numberget_wallet_addressto_dydx_longr  r   r  create_order_id_from_partsr  )+rj  r  r  r  r  r  rr  r  	orderTyperu  	orderSider  r   r   r   isConditionalisMarketr   r  	amountStrpriceStr
marketInfor  quantumScaler  r  
priceScaler  r  conditionalTyper  	orderFlagtimeInForceNumberr  r  goodTillBlockTimer  
sideNumberdefaultClientOrderIdr  orderPayloadsigningPayloadr  s+                                              rl  create_order_requestzdydx.create_order_request  s%   %%flM5QQ
JJLL	V$$JJLL	#<<V]Tbdpqqf))&.+NNNN//&2CDD$D0lM4MlQ`hlQl(,,V]EJJ$$XtV<<,,VV<<	**6599^^FF33
%&89xxg&89I&J&JKK%i>>$./J$K!XXdG$6w7IJZ\u7v7vx|$}$}~~
%h
;;*-'	 %tw)OOPPP  IN&$%!'!!e##	 *()%%()%%	%''()%%&'JKKK 		nI("#262I2I&R_2`2`// ,"#262I2I&Ra2b2b/.5.@A`bl.m.m+ --f6IJJ))&/BB %,"-1-J-J6S`b~  A[  .\  .\*"F>>$ 1B 6)1'(QRRR $1K K$--QQA
#//22))&/CWXX "&!8!8!:!:".% % !."+",\":  # --h77 --h77 -$50("0!0373D3DEd3e3e&*&6&6t|_  WD  'E  'E) 
2 :!
 
 6  $x  $x  $x  y  y11$2I2I2K2K\[hjsu  AM  vN  O  O^V<<==rm  r  r"  r  r  r  c                 V   |                      | j        dd          }|dz   t          |          z   }|                     ||          }|dz   |                     |          z   dz   |                     |          z   dz   |                     |          z   }	|                     ||	          S )N	namespacez$0f9da948-a6fb-4c45-9edc-4685c3f3317dry  )r  r   struuid5number_to_string)
rj  r  r"  r  r  r  nameSpprefixAddressprefix	orderInfos
             rl  r  zdydx.create_order_id_from_partsW  s    !!$,=cdd#,<(=(==FM22SL4#8#8#G#GG#MPTPePefpPqPqqtwwz~  {P  {P  Q[  {\  {\  \	zz&),,,rm  c                     |                      |          }|                     |d          }|                     |d          }|                     |d          S )Nresultrs  last_block_height)nodeRpcGetAbciInfor  rq  )rj  rr  rs  r  r  s        rl  fetch_latest_block_heightzdydx.fetch_latest_block_height^  sT    **622 (33~~fj11  ':;;;rm  c                 @   |                                   |                                 }|                                 }|                                 }	|                     |d|	i          }
|                     ||||||
          }|d         }|d         }| j        d         }|                     |d         |d||d          }d|i}|                     |          }| 	                    |d	          }| 
                    |||d
         d         d         d         d          S )a  

        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  rz  r  r  r  r  r   rq  nodeRpcGetBroadcastTxSyncr  r  )rj  r  r  r  r  r  rr  rx  rj  lastBlockHeight	newParamsorderRequestResr  orderRequestr   signedTxr  rs  r  s                      rl  create_orderzdydx.create_orderr  s9   . 	//11))++88::KK)<o(NOO	33FD$PUW`aa!!$&q)L-	$$[%>bR[]dfjkk(
 11':: (33)'27;IFzR 
  
   	rm  c                    |                      |ddd          }|                     |ddg          }|s|t          | j        dz             |                                  |                     |          }|                     |dd|          }|t          | j        dz             t          |          }|0|                    d	          d
k    rt          | j        dz             | 
                    |d          }d}	|                     |dd|	          \  }	}d}
|rdnd}| 
                    |d|          }d}|                     |dd|          \  }}|                     |g d          }|dk    r#|dk    r|dk    rt          | j        dz             |dk    rP|	t          | j        dz             ||dk    rt          | j        dz             |                                 |	z   }
n||                                 }|dz   }|                                 }|                                 }|                                 |d|||d         d         d||
d}d|d }| j        d!         }|                     |d"         |d#||d          }d$|i}|                     |          }|                     |d%          }|                     d|i          S )&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.ry  zn cancelOrder() cancelling using id is not currently supported, please use provide the clientOrderId parameter.r  r  r:   r  r  rW  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  ru  r  r  findr   rq  r  r   r  r  rz  r  r  r   rq  r  r  r  )rj  r$   r  rr  	isTriggerru  r  idStringr  r  r  defaultOrderFlagsr  r  r  rx  rj  cancelPayloadr  r   r  r  rs  r  s                           rl  cancel_orderzdydx.cancel_order  s   " $$VYFF	6Iv#677 	[fn#DG.Y$YZZZV,,**6?JPRSS #DG  /S  %S  T  T  Tr77>hmmC00255tw  *Z   Z  [  [  [))&/BB%,"-1-J-J6S`b~  A[  .\  .\*"F #,5BB2&&v|=NOO
#<<V]Tbdpqqf6  $c  $c  $c  d  d??zR//J"4D4Dtw)^^___>>)1'  3J  )J  K  K  K(]Q->->"47-m#mnnn $1K K$$($B$B$D$D! 1B 6//11))++ "4466*! ! *($Vn\:  * 1
 
 ;"
 
 L-	$$[%>PRT]_fhlmm(
 11':: (33F 
   	rm  idsc                    |                                   |                     |          }|                     |d          }|st          | j        dz             d}|                     |dd|          \  }}|                     |d          }||                                 }|dz   }|                     |g d	          }| 	                                }	| 
                                }
||d
         d         d}|                                 |d|g|d}d|d}| j        d         }|                     |	d         |d||
d          }d|i}|                     |          }|                     |d          }|                     d
|i          gS )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  ru  r  r   r$   r  rq  r  r  rz  r  r  r   rq  r  r  r  )rj  r  r  rr  ru  r  r  r  r  rx  rj  r;   r  r  r   r  r  rs  r  s                      rl  cancel_orderszdydx.cancel_orders  s    	V,,0@AA 	Wtw)UUVVV#<<V^Uceqrrf))&/BB  $ > > @ @-2M6#V#V#VWW//11))++' .6
 
 0022&  ".)
 
 ;"
 
 L-	$$[%>PRT]_fhlmm(
 11':: (33F!
    	rm  c           	          |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     ||d         ddddd          S )	aD  
        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
        ru  r$   r  Nbidsasksr  r  )r  ru  )indexerGetOrderbooksPerpetualMarketMarketr  parse_order_book)rj  r  r   rr  ru  r  rs  s          rl  fetch_order_bookzdydx.fetch_order_bookL  s     	V$$fTl
 AA$++gW]B^B^__" $$Xvh/?vvW^`fgggrm  itemcurrencyc                 (   |                      |d          }|                     ||          }|                     ||          }|                     |d          }d }||dk    s|dk    rd}n|dk    s|dk    rd}|                      |d	          }|                     |                      |d
                    }|                     |d          }	|                     |d          }
|                     ||                      |d          ||                      |	d          |                      |
d          |                      |d          |                     |          ||                     |          || 	                    |          d d d d d|          S )Nr  r  TRANSFER_INDEPOSITinTRANSFER_OUT
WITHDRAWALoutr  r  sender	recipientr$   r  transactionHash)r  r$   	directionrj  referenceAccountreferenceIdr  r  r  r  r  beforeafterr  r  )
r  r  safe_currencyr  r  r  safe_ledger_entryparse_ledger_entry_typeri  r  )rj  r  r  
currencyIdcoder  r  r  r  r  r  s              rl  parse_ledger_entryzdydx.parse_ledger_entryo  s   ( %%dH55
&&z8<<%%j(;;%%dF33	}$$	(9(9 		''4<+?+?!	!!$//NN4#3#3D+#F#FGG	h//NN455	%%""4.."''	:: $ 0 0I F F++D2CDD0066''//"Y//'
 '
  !  	rm  c                 >    ddddd}|                      |||          S )Nr   deposit
withdrawal)r  r  r  r  r  )rj  r  
ledgerTypes      rl  r  zdydx.parse_ledger_entry_type  s4    %& &	
 

 
D$777rm  r  c           
          |                                   d}||                     |          }|                     ||||                     |ddi                    }|                     ||||          S )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-entry-structure>`
        Nr  rf   )r  r  fetch_transactions_helperr  parse_ledger)rj  r  r  r   rr  r  rs  s          rl  fetch_ledgerzdydx.fetch_ledger  s{     	}}T**H11$udkkRX[givZwFxFxyy  8UEBBBrm  c           
         |                      |||d         |d                   }d|i}|                     |          }|                     |d          }|t          | j        dz             |                     |d          }|t          | j        dz             |                     | j        d          }	|                     | j        d          }
|                     | j        d	          }d }d }|	d
k    r|d         }|d         }n|d         }|d         }t          t          j	        | 
                    t          j        ||
                                        }t          j        |                     |          |          }|                    d          dk    rG|                     t          t          j	        | 
                    |                                        }||d}|g|d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   r@  r  r  )rj  rP  ri  rj  r  r  rs  gasInfogasUsedr   r   r   gasPricer   r!  	feeAmountfeeObjs                    rl  estimate_tx_feezdydx.estimate_tx_fee  s   44WdGJDWY`ajYkllw
 ;;GDD ..:66?*L LMMM""7J77?*L LMMM**4<9JKK#//>TUU>>$,
;;g%% 01H\*EE 67H/0Ety!6!6w7I'Sg7h7h!i!ijjkk&t'<'<X'F'FQQ	>>#!##--c$)D<Q<QR[<\<\2]2].^.^__I
 

 h 
 
 	
rm  fromAccount	toAccountc           	         |dk    rt          | j        dz             |                                  |                     |d          }|                     |d          }|dk    r4|t          | j        dz             ||t	          | j        dz             |                     |ddg          }|                                 }|                                 }	|                     t          j
        |                     |          d	                    }
d}d}|dk    rM|t	          | j        d
z             |                                 |                                 |dd|
d}d|d}nd||d||dd|
di}d|d}|                     |d|	          }| j        d         }|                     |d         |d||	d|          }d|i}|                     |          }|                     |          S )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>`
        rw  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  r6  r  z'/dydxprotocol.sending.MsgCreateTransferr  r   r   r   )r   r$   r  rq  r   r  rz  r  r  r   r@  r  r  r-  r   rq  r  parse_transfer)rj  r  r  r.  r/  rr  r1  r2  rx  rj  usdpayloadr  txFeer   r  r  rs  s                     rl  r   zdydx.transfer  sv    6>>tw)HHIII,,V5GHH**63CDD&  ""47-u#uvvv'>+A'2k(klll6$68H#IJJ//11))++ 243H3H3P3PR[ \ \]]&  %'2X(XYYY1133!4466,   G J  NN !,"2 
 "+"0" "  !! G E  N $$^RAAL-	$$[%>PRT]_fhlnstt(
 11':: ""8,,,rm  r   c           
         |                      |d          }|                      |d          }|                     ||          }|                     |d          }|                     |d          }|                     |d          }|                      |d          }	|                      |d          }
|                     |                      |d                    }||||                     |          |||	|
d d	S )	Nr$   r  r  r  r  r  r  )	r  r$   r  r  r  r  r.  r/  r  )r  r  r  r  r  r  )rj  r   r  r$   r  r  r  r  r  r.  r/  r  s               rl  r7  zdydx.parse_transferD  s    ( h--%%h99
&&z8<<!!(F33(33NN8[99	&&vy99$$Y	::	NN4#3#3Hk#J#JKK	"Y//&"

 

 
	
rm  c           
      p   |                                   d}||                     |          }|                     ||||                     |ddi                    }|                     |dd          }|                     |dd          }|                     ||          }	|                     |	|||          S )a  
        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)
rj  r  r  r   rr  r  rs  
transferIntransferOutr  s
             rl  fetch_transferszdydx.fetch_transfersm  s     	}}T**H11$udkkRX[giyZzF{F{||^^HfmDD
nnXv~FF  [99##D(E5AAArm  transactionc                    |                      |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S )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  )rj  rC  r  r$   r  r  rG  rH  rE  r  r  r  r  s                rl  parse_transactionzdydx.parse_transaction  s   ( k400X66NN;<<	$$Y	::	&&vy99->??%%k8<<
&&z8<<NN4#3#3K#M#MNN	!!+v66
K
"
 D
 	

 Y//
 t
 y
 
 ;
 4
 T
 t
 D**;??
 f
 
  d!
" t#
$ )
 
 
 	
rm  rI  c           	      b   |dk    rt          | j        dz             |                                  |                     |           |                     |d          }|t          | j        dz             |                     |dg          }|                     |          }|                                 }| 	                                }	| 
                    t          j        |                     |          d                    }
|                                 |d|d|
d	}d
|d}|                     |||	          }| j        d         }|                     |d         ||||	d|          }d|i}|                     |          }|                     |di           }|                     ||          S )a  
        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>`
        rw  z withdraw() only support USDCr  Nz  withdraw requires subaccountId.r4  r  r   r5  z//dydxprotocol.sending.MsgWithdrawFromSubaccountr  r   r   r   r  )r   r$   r  check_addressrq  r   r  r  rz  r  r  r   r@  r  r  r-  r   rq  r  r  rO  )rj  r  r  r  rI  rr  r  r  rx  rj  r8  r9  r  r:  r   r  r  rs  r  s                      rl  r   zdydx.withdraw  s    6>>tw)HHIII7###((@@#DG.P$PQQQ6N#344==&&//11))++ 243H3H3P3PR[ \ \]] 0022&  !
 
 I
 
 $$^S'BBL-	$$[%>PSU^`gimotuu(
 11':: ~~h"55%%dH555rm  c           
         |                                   d}||                     |          }|                     ||||                     |ddi                    }|                     |dd          }|                     ||||          S )a  
        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  r=  parse_transactionsrj  r  r  r   rr  r  rs  r  s           rl  fetch_withdrawalszdydx.fetch_withdrawals  s     	}}T**H11$udkkRX[gi{Z|F}F}~~~~h==&&tXueDDDrm  c           
         |                                   d}||                     |          }|                     ||||                     |ddi                    }|                     |dd          }|                     ||||          S )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  rS  rU  s           rl  fetch_depositszdydx.fetch_deposits  s     	}}T**H11$udkkRX[gixZyFzFz{{~~h	::&&tXueDDDrm  c           
      p   |                                   d}||                     |          }|                     ||||                     |ddi                    }|                     |dd          }|                     |dd          }|                     ||          }	|                     |	|||          S )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  r=  r>  rT  )
rj  r  r  r   rr  r  rs  withdrawalsdepositsr  s
             rl  fetch_deposits_withdrawalszdydx.fetch_deposits_withdrawals!  s     	}}T**H11$udkkRX[g  jD  [E  GF  GF  G  GnnXv|DD>>(FI>>  h77&&tXueDDDrm  c                 T   |                      |d          }|                     |d          }d }d }|                     ||          \  }}|                     ||dd          \  }}||d}|                     |                     ||                    }	|                     |	dg           S )Nr  r"  r#  r$  r   )r  r  r  r  indexerGetTransfersr  r  )
rj  r  r  r   rr  r  r(  r"  r  rs  s
             rl  r  zdydx.fetch_transactions_helper9  s    %%fl;;
6<00"88VLLV#'#@#@Ugil#m#m &" 0
 
 ++DKK,H,HII0 ~~hR888rm  c           	      z   d}|                      d|          \  }}d|i}|                     |                     ||                    }|                     |dg           }g }t	          dt          |                    D ];}||         }|                     |d          }	|                    |	dd|dd           <|S )a  
        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
        NrP   r  subaccountsr   r%  )r$   r  r  r  r  )r  indexerGetAddressesAddressr  r  r  r  r  r  )
rj  rr  r(  r  rs  r  r  r  rj  	accountIds
             rl  fetch_accountszdydx.fetch_accounts^  s     "88&QQV{
 224;;w3O3OPPZ ~~hr::q#d))$$ 		 		A1gG((2DEEIMM       rm  c                 L   |                                   d}|                     d|          \  }}d}|                     |ddd          \  }}||d}|                     |                     ||                    }|                     |d          }|                     |          S )ab  
        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>`
        NrP   r%  r   r$  
subaccount)r  r  r  :indexerGetAddressesAddressSubaccountNumberSubaccountNumberr  r  parse_balance)rj  rr  r(  r%  r  rs  r  s          rl  fetch_balancezdydx.fetch_balance  s     	"88&QQV#'#@#@Zlno#p#p &" 0
 
 RRSWS^S^_fhnSoSoppz ~~h55!!$'''rm  c                     |                                  }|                     |d          |d<   ||d}|                     |          S )NfreeCollateralfree)r  rw  )rj  r  safe_balance)rj  rs  rj  r  s       rl  rg  zdydx.parse_balance  sQ    ,,..**85EFF
 
   (((rm  c                 F    |                                  | j        d         z
  S )NtimeDifference)millisecondsr   )rj  s    rl  noncez
dydx.nonce	  s!      ""T\2B%CCCrm  c                     | j         | j         dk    r| j         S |                     | j        d          }||                     |d          }||S t	          | j        dz             )Nr  r|  r  zh getWalletAddress() requires a wallet address. Set `walletAddress` or `dydxAccount` in exchange options.)r  r  r   r  r   r$   )rj  r|  wallets      rl  r  zdydx.get_wallet_address	  s    )d.@B.F.F%%nnT\=AA"%%k9==F!  +U  !U  V  V  	Vrm  publicGETc                    |                      ||          }|                     | j        d         |                   }|                     ||                     |                    }|                     |          }|d|z   z  }|dk    r|r|d|                     |          z   z  }n|                     |          }ddi}||||dS )Nr   r{  rt  ?zContent-typezapplication/json)urlmethodbodyheaders)implode_paramsimplode_hostnamer   r  extract_paramskeysort	urlencodejson)	rj  pathsectionrx  rr  rz  ry  pathWithParamsrw  s	            rl  signz	dydx.sign	  s    ,,T6::##DIe$4W$=>>64#6#6t#<#<==f%%s^##U?? 4sT^^F333399V$$D 2G fdwOOOrm  httpCodereasonrw  rx  rz  ry  c
                    |sd S |                      |d          }
|                     |
d          }|s|                     |d          }|r|                     |          }|dk    rs| j        dz   |                     |          z   }|                     | j        d         ||           |                     | j        d         ||           t          |          d S )Nr  r  r   r  rb  rc  )	r  r  r'  r$   r  throw_exactly_matched_exceptionrd  throw_broadly_matched_exceptionr   )rj  r  r  rw  rx  rz  ry  rs  requestHeadersrequestBodyr  	errorCodeerrorCodeNumfeedbacks                 rl  handle_errorszdydx.handle_errors!	  s     	4 (33$$VV44	 	;((6::I 	.00;;La7S=499X+>+>>44T_W5MyZbccc44T_W5MtU]^^^#H---trm  enablec                     t          t          |                               |           d| j        d<   d| j        d<   d| j        d         d<   d S )Nzdydx-testnet-4r   i6 r   adv4tntr   r   )rg  r!   set_sandbox_moder   )rj  r  rk  s     rl  r  zdydx.set_sandbox_mode8	  sQ    dD**6222$4[!"*Y7@Z !3444rm  )N)V__name__
__module____qualname__r   rh  r	   rt  dictr   r  r   r  r   r  r  r  r  r  r  r   r  r  r   r  r  r  r   r)  r-  r/  rC  rG  r   r   rE  rQ  r^  r`  objectrh  rq  rz  r  r  r   r   floatr   r  r  r$  r  r  r  r  r   r  r   r
   r  r  r  r-  r   r   r7  rB  r   rO  r   rV  rX  r\  r  r   rc  r   rh  rg  rp  r  r  r  boolr  __classcell__)rk  s   @rl  r!   r!      sS       u# u u u u u un !# 4 4s 4 4 4 4$`4 `F ` ` ` `D $& -+ -+$v, -+ -+ -+ -+^     v          D 6:UW $= $=3 $=s $=# $=\`af\g $= $= $= $=L
 
 
4 
 
 
 
6 26DW[df 3H 3H# 3Hc 3HQT 3Hkoptku 3H 3H 3H 3Hj 8<$]ajl 5O 5O 5OC 5OWZ 5O 5O 5O 5On	H 	HT 	H 	H 	H 	H< < <v < < < < <|: : : : :
9S 
9 
9 
9 
9 26b ' 'c '3 ' ' ' '$ *.Dt\^ 9A 9A3 9Ac 9A 9Acghmcn 9A 9A 9A 9Av /3TXac U U U3 Uc Uhlmrhs U U U U& 154VZce U U# US UPS Ujnotju U U U U&5 5t 5V 5 5 5 5n 24 0 0S 0 0 0 0 26b 03 03w 03T(^ 03 03 03 03d3 3 3
 
 
L L L    $Q Qs QS Q Qc Q\_ Qqt Q  DG Q Q Q Q
c    ! ! !FS S     os{} k> k>3 k>i k>y k>Z_ k>hk k> k> k> k>Z-# - -_d -rw -  FK -  PS - - - - 02 < <c < < < <( gksu 9 93 9i 9y 9RW 9`c 9z 9 9 9 9v 37r \ \s \C \e \ \ \ \| ;?r ? ?c ?C ? ? ? ?B :>b !h !hs !h3 !hY !h !h !h !hF2 2t 2x 2; 2 2 2 2h8 8 8 (,$TZ\ C C CC Cs Caefqar C C C C**
s *
# *
 *
 *
 *
 *
 *
X [] U- U-S U-% U-c U-c U-an U- U- U- U-n'
 '
t '
x '
= '
 '
 '
 '
R +/TPT]_ B BC Bs B# Bdhivdw B B B B03
 3
T 3
X 3
Q\ 3
 3
 3
 3
j KOWY 96 96S 96% 96# 96C 96^i 96 96 96 96v -1tRV_a E Ec E EC Efjkvfw E E E E, *.Dt\^ E E3 Ec E Ecghsct E E E E, 6:[_hj E Es E# EUX Eost  pA E E E E0 59tZ^gi #9 #9c #9 #9TW #9 #9 #9 #9J %' H H4= H H H HT $& P( P(( P( P( P( P(d) ) ) ) )D D D	V 	V 	V "*%DW[ P P P P c 3 S # X\ dg    .At A A A A A A A A A Arm  r!   )&ccxt.base.exchanger   ccxt.abstract.dydxr   r%  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!    rm  rl  <module>r     s   ( ' ' ' ' ' * * * * * *                                                                                       * * * * * * . . . . . . ' ' ' ' ' ' . . . . . . ) ) ) ) ) ) ) ) ) ) ) ) 4 4 4 4 4 4 % % % % % %h$A h$A h$A h$A h$A8[ h$A h$A h$A h$A h$Arm  