
    !:hHJ                    P   d dl mZ d dlmZ d dlZd dlZd dlmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z  d dl!m"Z" d dl#m$Z$ d dl#m%Z% d dl#m&Z& d d	l#m'Z' d d
l#m(Z( d dl#m)Z) d dl#m*Z* d dl+m,Z, d dl+m-Z- d dl+m.Z. d dl+m/Z/ d dl0m1Z1  G d dee      Z2y)    )Exchange)ImplicitAPIN)AnyBalances
CurrenciesCurrencyIntLedgerEntryMarginModificationMarketNumOrder	OrderBookOrderRequestCancellationRequest	OrderSide	OrderTypePositionStrStringsTickerTickersFundingRateFundingRatesTradeTradingFeeInterfaceTransactionTransferEntry)List)ExchangeError)ArgumentsRequired)
BadRequest)InsufficientFunds)InvalidOrder)OrderNotFound)NotSupported)ROUND)DECIMAL_PLACES)SIGNIFICANT_DIGITS)	TICK_SIZE)Precisec                        e Zd Zdef fdZ fdZi fdefdZi fdee	   fdZ
i fdee	   fdZdeded	efd
Zi fdee	   fdZdede	fdZi fdefdZdi fdededefdZdi fdedefdZdi fdedefdZdde	defdZddede	defdZdddi fdedededee    fdZ!dde	de fdZ"ddi fde#dedefdZ$d Z%dedefdZ&d  Z'd! Z(d" Z)dd#Z*d$ Z+dde,fd%Z-d& Z.d' Z/d( Z0d) Z1di fded*e2d+e3d,ede4f
d-Z5i fd.ee6   fd/Z7i fdefd0Z8di fd1ede#fd2Z9di fd3ee   de#fd4Z:i fd.ee;   fd5Z<i fd6efd7Z=i fd8Z>ddi fd1eded*ed+ed,e4de4fd9Z?i fd.ee6   fd:Z@i fd;ed<ed=eAfd>ZBdddi fde#dedefd?ZCdddi fde#dededeeD   fd@ZEdddi fde#dededeeD   fdAZFdddi fde#dededeeD   fdBZGdddi fde#dededeeD   fdCZHdddi fde#dededeeD   fdDZIdi fd1ede#fdEZJddFede	deDfdGZKdHe#fdIZLdJ ZMdddi fde#dedefdKZNddLede	deOfdMZPi fdefdNZQdi fdedeeR   fdOZSddPede	fdQZTdi fdRede#fdSZUdi fdTede#fdUZVi fded,edeWfdVZXi fded,edeWfdWZYi fdedeWfdXZZddYede	deWfdZZ[i fd[ed,ed\ed]ede\f
d^Z]dd_ed`e^de\fdaZ_di fd[ed,edbede`fdcZaddded`e^de`fdeZbi fdedecfdfZdddgede	decfdhZedddi fd[e#dededeef   fdiZgddjed`e^deffdkZhdl Zidddi fd[e#dedefdmZjdddi fd[e#dededee`   fdnZkdi fdefdoZli fdefdpZmdde	fdqZndddi fde#dedefdrZodde	fdsZpg fdtZqddbe#fduZrdvedwefdxZsdye#fdzZtd[eAd{ed|ed}ed~edefdZuddi ddfdZvi fdZwdi fd1e#ded*e2d+e3d,ede4fdZx xZyS )hyperliquidreturnc                    | j                  t        t        |          i dddddg dddd	d
ddddddi dd ddddddddddddddddddddddddddddddd di d!dd"dd#dd$dd%dd&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0dd1di d2dd3dd4dd5dd6dd7dd8d9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dZd9d[dd\dd]dd^dd_dd`ddaddbddcdddddedddddddddfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d{d|d}d}d|d~ddddddddddddddddiidddiid|d| j	                  d      | j	                  d      d| j	                  d      | j	                  d      dddddddddi i dt
        dt
        dt        dt
        dt
        dt
        dt
        dt
        dt        dt
        dt
        dt
        dt
        dt        dt        dt        ddt        i ddddddddd dddd dddddddddddddddiddd d dddddddddddddddd d ddddddd d d ddddddid	ddidddd ddddiddidddiddiddd      S )Nidr-   nameHyperliquid	countriesversionv1	rateLimit2   	certifiedTprodexhasCORSspotmarginFswapfutureoption	addMarginborrowCrossMarginborrowIsolatedMargincancelAllOrderscancelAllOrdersAftercancelOrdercancelOrderscancelOrdersForSymbolscloseAllPositionsclosePositioncreateMarketBuyOrderWithCostcreateMarketOrderWithCostcreateMarketSellOrderWithCostcreateOrdercreateOrderscreateReduceOnlyOrdercreateStopOrdercreateTriggerOrder	editOrder
editOrdersfetchAccountsfetchBalancefetchBorrowInterestfetchBorrowRateHistoriesfetchBorrowRateHistoryfetchCanceledAndClosedOrdersfetchCanceledOrdersfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositAddressesfetchDepositsfetchDepositWithdrawFeeemulatedfetchDepositWithdrawFeesfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchLedgerfetchLeveragefetchLeverageTiersfetchLiquidationsfetchMarginModefetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMyLiquidationsfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenInterestHistoryfetchOpenInterestsfetchOpenOrders
fetchOrderfetchOrderBookfetchOrdersfetchOrderTradesfetchPositionfetchPositionModefetchPositionsfetchPositionsRiskfetchPremiumIndexOHLCVfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTransferfetchTransfersfetchWithdrawalfetchWithdrawalsreduceMarginrepayCrossMargin)repayIsolatedMarginsandboxsetLeveragesetMarginModesetPositionModetransferwithdraw
timeframes1m3m5m15m30m1h2h4h8h12h1d3d1w1M)r   r   r   r   r   r   r   r   r   r   r   r   r   r   hostnamezhyperliquid.xyzurlszQhttps://github.com/ccxt/ccxt/assets/43336371/b371bc6c-4a8c-489f-87f4-20a913dd8d4bzhttps://api.{hostname})publicprivatez#https://api.hyperliquid-testnet.xyzzhttps://hyperliquid.xyzzBhttps://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/apiz<https://hyperliquid.gitbook.io/hyperliquid-docs/trading/feeszhttps://app.hyperliquid.xyz/)logoapitestwwwdocfeesreferralr   postinfo      )l2BookallMidsclearinghouseStateorderStatusspotClearinghouseStateexchangeStatus)costbyTypeexchange   r   z0.00045z0.00015)takermakerz0.0007z0.0004)r?   r=   requiredCredentials)apiKeysecretwalletAddress
privateKey
exceptionsz%Price must be divisible by tick size.z$Order must have minimum value of $10z#Insufficient margin to place order.z*Reduce only order would increase position.z/Post only order would have immediately matched,z=Order could not immediately match against any resting orders.zInvalid TP/SL price.z(No liquidity available for market order.z4Order was never placed, already canceled, or filled.zUser or API Wallet zOrder has invalid sizezAOrder price cannot be more than 80% away from the reference pricezOrder has zero size.zInsufficient spot balance assetz#Insufficient balance for withdrawalz'Insufficient balance for token transfer)exactbroadprecisionModeg?*0x0000000000000000000000000000000000000000)defaultTypesandboxModedefaultSlippagezeroAddress)IOCFOKPOGTD)
marginModetriggerPricetriggerPriceTypetriggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingleveragemarketBuyByCostmarketBuyRequiresPriceselfTradePreventionicebergmax  i  )r   limitdaysBack	untilDayssymbolRequired)r   triggerr   r   )r   r   r   r   r   )r   r   r   r   r   r   r   )r   r   r   daysBackCanceledr   r   r   r   r   i  )	r   rO   rP   rw   r}   r|   r   r]   rx   extendsdefault)r   r   r   )r   rO   forPerps)linearinverse)r   r=   r   r?   r@   )commonCurrenciesoptionsfeatures)	deep_extendsuperr-   describeparse_numberr$   r#   r%   r*   )self	__class__s    X/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/async_support/hyperliquid.pyr   zhyperliquid.describe   s3	   k4 A C oF
-oF
MoF
 oF
 t	oF

 oF
 oF
 4oF
 4oF
  ]]] %] 	]
 $] %] T] $U] '] "5] '] t] ] )$] $U]   !]" /#]$ ,U%]& 0']( t)]* +], (-]. "4/]0 %d1]2 T3]4 d5]6  7]8 9]: &u;]< +E=]> )%?]@ /A]B &tC]D $TE]F 'G]H (I]J "4K]L &uM]N (O]P  Q]R *:S]T +EU]V &tW]X #EY]Z *4[]\ $T]]^ "5_]` *5a]b +Ec]d te]f  g]h %ei]j $Uk]l "4m]n +Eo]p q]r !%s]t &uu]v  w]x dy]z $T{]| +E}]~ %d]@ "4A]B dC]D !$E]F tG]H #EI]J  K]L $UM]N !$O]P %eQ]R )%S]T zU]V W]X UY]Z t[]\ "4]]^ #E_]`  a]b !%c]d "5e]f #Dg]h i]j #Ek]l (-#!%#(  y]oF
N OoF
n )ooF
p k67
 DD 1[V:qoF
N $&*++,67/0:;23'
!  "A!OoF
z !..y9!..y9
 "..x8!..x8	{oF
N "!%"	$OoF
Z ;\:L :;L A,	
 F| TUa +L ? KM *< -l XYe +L 67H :;L  >?P![oF
F YGoF
H!  &$#'K	  $&+(-,0,1).+06:#'#("&#(	( #($)$)+027/4#()$. t% ',!%$(%)*.& ',#($)*.	# ',!%#($)*.( ',!%$(%)#($)*.$ ',!%$(,0%)#($)*.	*  #EEN y  ))-+/6:$ ": ": 	 ": ": 	ubYoF
 o o	    c                 J    t         t        |   |       || j                  d<   y )Nr   )r   r-   set_sandbox_moder   )r   enabledr   s     r   r   zhyperliquid.set_sandbox_modeN  s     k41':&-]#r   c                   K   ddi}| j                  | j                  ||             d{   }| j                  |dg       }i }t        dt	        |            D ]d  }| j                  ||i       }|}| j                  |d      }	| j                  |	      }
| j                  ||	|
d|ddddddddddddd	d
      ||
<   f |S 7 w)aX  
        fetches all available currencies on an exchange

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-metadata

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        typemetaNuniverser   r1   cryptominr   )amountr   )r0   r1   code	precisionr   activedepositr   networksfeer   limits)	publicPostInfoextend	safe_listrangelen	safe_dictsafe_stringsafe_currency_codesafe_currency_structure)r   paramsrequestresponser  resultidatar0   r1   r  s              r   fetch_currencieszhyperliquid.fetch_currenciesR  s     F
 ,,T[[&-IJJ ~~h
B7q#d)$ 	A>>$2.DB##D&1D**40D77!     $#
  $#!	9 F4L	8 [ Ks   )CCBCc                    K   | j                  |      | j                  |      g}t        j                  |  d{   }|d   }|d   }| j	                  ||      S 7  w)a  
        retrieves data on all markets for hyperliquid

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-asset-contexts-includes-mark-price-current-funding-open-interest-etc
        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-spot-asset-contexts

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        Nr   r   )fetch_swap_marketsfetch_spot_marketsasynciogatherarray_concat)r   r  rawPromisespromisesswapMarketsspotMarketss         r   fetch_marketszhyperliquid.fetch_markets  sh      ##F+##F+
 !55qkqk  k:: 6s   8AA!Ac           	        K   ddi}| j                  | j                  ||             d{   }| j                  |di       }| j                  |dg       }| j                  |dg       }g }t	        dt        |            D ]L  }| j                  | j                  ||i       | j                  ||i             }	||	d<   |j                  |	       N | j                  |      S 7 w)a  
        retrieves data on all swap markets for hyperliquid

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-asset-contexts-includes-mark-price-current-funding-open-interest-etc

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        r   metaAndAssetCtxsNr   r  r   baseId)r  r  r  r  r  r  appendparse_markets)
r   r  r  r  r  r  	assetCtxsr  r  r  s
             r   r  zhyperliquid.fetch_swap_markets  s      &
 ,,T[[&-IJJ@ ~~h2.>>$
B7NN8Q3	q#h-( 	 A;;xB/y!R0D DNMM$	  !!&))W Ks   )C"C B5C"priceamountPrecisionmaxDecimalsc                 f   d}| j                  |      }|y|j                  d      }t        j                  |d      rd}d}t	        ||z
  ||z
        }nt        j
                  |d      rtt        j                  |d      r^d}| j                  |dd      }	d}
|
t        |	      k  r$|	|
   dk(  r|
dz   }
|
t        |	      k  r	|	|
   dk(  r|
|z   }t	        ||z
  |      }nC| j                  |dd      }t        dt        |            }t	        ||z
  |t        |      z
        }| j                  |      S )an  
        Helper function to calculate the Hyperliquid DECIMAL_PLACES price precision
        :param float price: the price to use in the calculation
        :param int amountPrecision: the amountPrecision to use in the calculation
        :param int maxDecimals: the maxDecimals to use in the calculation
        :returns int: The calculated price precision
        r   .0   1r    )number_to_stringsplitr+   	string_eqr  	string_gt	string_ltr  r  r   parse_to_int)r   r/  r0  r1  pricePrecisionpriceStrpriceSplittedsignificantDigitsintegerDigitsdecimalPartleadingZerosintegerParts               r   calculate_price_precisionz%hyperliquid.calculate_price_precision  sV    ((/ s+Xs+ !M !>@QTa@abNx-'2C2CHc2R !**=!R@KL3{#33+l:SWZ:Z+a/  3{#33+l:SWZ:Z *,==N !>ON **=!R@K #As;'7 8 !>@QTWXcTd@deN  00r   c                 N  K   ddi}| j                  | j                  ||             d{   }| j                  |di       }| j                  |dg       }| j                  |dg       }| j                  |dg       }g }t	        dt        |            D ]  }	| j                  ||	i       }
| j                  |
d      }| j                  ||i       }| j                  |
d	      }| j                  | j                  d
i       }| j                  |d      }| j                  |d      }| j                  |
dg       }| j                  |d      }| j                  |d      }| j                  ||i       }| j                  ||i       }| j                  |d	      }| j                  |d	      }| j                  |      }| j                  |      }|dz   |z   }| j                  |d|      }| j                  |d      }t        |      }| j                  |d      }d}|| j                  ||d      }| j                  |      } | j                  |dz         }!|j                  | j                  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| j!                  | j#                  |            | j!                  | j#                  |             d$ddd%ddd%ddd%| j!                  d&      dd%d'd| j                  ||
      d(              |S 7 w))a\  
        retrieves data on all spot markets for hyperliquid

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-spot-asset-contexts

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        r   spotMetaAndAssetCtxsNr   r   r  tokensindexr1   r=   r   r   /spec
szDecimalsmidPx   i'  r0   symbolbasequotesettler+  quoteIdsettleIdTsubTyper>   r?   Fr@   rA   r	  contractr  r/  r  10r   r  r/  r   )r   r   r   r   contractSizeexpiryexpiryDatetimestrike
optionTyper  r  createdr   )r  r  r  r  r  r  safe_integerr  r   safe_numberr  intrF  r8  r,  safe_market_structurer   parse_precision)"r   r  r  r  firstsecondr  rI  marketsr  marketrJ  	extraData
marketNamer   r   r   	tokensPosbaseTokenPosquoteTokenPosbaseTokenInfoquoteTokenInfobaseNamerT  rQ  rR  rP  innerBaseTokenInfoamountPrecisionStrr0  r/  r>  pricePrecisionStrr+  s"                                     r   r   zhyperliquid.fetch_spot_markets  s     *
 ,,T[[&-IJJZ xB/!R0~~eZ4x4q#d)$ W	A^^D!R0F%%fg6Evub9I))&&9J >>$))VR8D$$T73E$$T73Evx<I,,Y:L --i;M NN6<DM!^^FM2FN''v>H&&~v>G**84D++G4ECZ%'F!%v}!U!%!1!12Dl!S!"45O$$Y8EN !%!?!?XY!Z $ 5 5n E**55=9FNN455 37j37&37 37 	37
 $37 &37 737 D37 37 37 437 $37 37 %37 %37  $!37" E#37$  $"&""//0D0DEW0XY!..t/C/CDU/VW  $#!
  $#
  $#
  $006#$  Iv6e37 3 3IW	p U Ks   )L%L"K7L%ri  c                    d}| j                  |d      }| j                  |      }| j                  |d      }d}| j                  |      }|dz   |z   }d}	d}
|	r
|
r|dz   |z   }| j                  | j                  di       }| j	                  |d      }| j	                  |d	      }| j                  |d
      }t        |      }| j	                  |dd      }d}|| j                  ||d      }| j                  |      }| j                  |d      }d}|| }| j                  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||| j                  d      d d d d | j                  | j                  |            | j                  | j                  |            d d | j                  |d!      d"d d d"d d d"| j                  d#      d d"d$d |d%      S )&NUSDCr1   r+  rK  T:r?   r   r   rM  markPxr      
isDelistedr0   rP  rQ  rR  rS  rT  rU  r   r=   Fr>   r@   rA   r	  rW  r   r6  rX  maxLeverager  rY  rZ  )r   r   r   r[  r\  r]  r^  r_  r  r  r`  r   )r  r  r  r   rb  rc  rF  r8  	safe_boolrd  r   re  ra  )r   ri  rT  rQ  rR  r+  rU  rS  rP  rW  r?   r   r   r   rs  r0  r/  r>  rt  rz  r	  s                        r   parse_marketzhyperliquid.parse_market  s   * /''0!!&(3((2e##.~~dii4  w/  w/!--flC01  15!;;E?TUVN 11.A^^FL9
!#^F)) 2+
&2+
f2+
 D2+
 U	2+

 f2+
 f2+
 w2+
 2+
 F2+
 E2+
 d2+
 D2+
 e2+
 e2+
 f2+
  !2+
" d#2+
$  --c2"++D,@,@AS,TU**4+?+?@Q+RS  ,,V]C
  
  
  ,,T2$ c2+
 2 2	r   c                   K   d}| j                  d|      \  }}d}| j                  dd|      \  }}d}| j                  d|      \  }}|dk(  }|rdnd}||d}| j                  | j	                  ||             d{   }| j                  |d      }	|	d|i}
t        d	t        |	            D ]k  }|	|   }| j                  | j                  |d
            }| j                         }| j                  |d      }| j                  |d      }||d<   ||d<   ||
|<   m | j                  |
      S | j                  |di       }d| j                  |d      i}||dk(  r| j                  |d      |d<   n| j                  |d      |d<   ||d}| j                  |d      }||d<   | j                  |      |d<   | j                  |      S 7 Kw)a  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-a-users-token-balances
        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-users-perpetuals-account-summary

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.user]: user address, will default to self.walletAddress if not provided
        :param str [params.type]: wallet type, ['spot', 'swap'], defaults to swap
        :param str [params.marginMode]: 'cross' or 'isolated', for margin trading, uses self.options.defaultMarginMode if not passed, defaults to None/None/None
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        NrW   r=   r   r   r   userbalancesr   r   cointotalholdusedmarginSummaryaccountValueisolatedwithdrawablefreetotalMarginUsed)r   rv  time	timestampdatetime)handle_public_addresshandle_market_type_and_paramshandle_margin_mode_and_paramsr  r  r  r  r  r  r  accountsafe_balancer  rb  ra  iso8601)r   r  userAddressr   r   isSpotreqTyper  r  r  spotBalancesr  balancer  r  r  r  r  usdcBalancer  r  s                        r   fetch_balancezhyperliquid.fetch_balance  s!     "88PV99.$PVWf
!??PVW
F&./5*<P
 ,,T[[&-IJJH >>(J7"((!3L1c(m, -"1+..t/?/?/PQ,,.((':''8#( "&%,T"- $$\22~~h<T%%dN;
 "z)A"&"2"28^"LK"&"2"249J"KK
 %%h7	'{!\\)4z  ((A Ks   A;G=G>EGNrP  r   c           	        K   | j                          d{    | j                  |      }d|d   r|d   n|d   d}| j                  | j                  ||             d{   }| j	                  |dg       }| j	                  |dg       | j	                  |d	g       d
}| j                  |d      }	| j                  ||d   |	dddd      S 7 7 lw)a_  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#l2-book-snapshot

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        Nr   r?   rQ  r0   r   r  levelsr   r   )bidsasksr  rP  r  r  pxsz)load_marketsri  r  r  r  ra  parse_order_book)
r   rP  r   r  ri  r  r  r  r  r  s
             r   fetch_order_bookzhyperliquid.fetch_order_bookY  s      !!!V$&,VnF6N&,
 ,,T[[&-IJJ. ~~h"5NN4B/NN4B/
 %%h7	$$VVH-=y&RXZ^`deeG 	" Ks#   CCAC"C#A+CCsymbolsc                 *  K   | j                          d{    | j                  |      }g }| j                  |d      }| j                  |d      }|dk(  r| j	                  |       d{   }n8|dk(  r| j                  |       d{   }n| j                  |       d{   }i }t        dt        |            D ]5  }||   }|d   }| j                  ||      }	| j                  |	d      }
|	||
<   7 | j                  |d|      S 7 7 7 7 lw)aT  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-asset-contexts-includes-mark-price-current-funding-open-interest-etc
        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-spot-asset-contexts

        :param str[] [symbols]: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.type]: 'spot' or 'swap', by default fetches both
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        Nr   r=   r?   r   r   rP  )r  market_symbolsr  omitr   r  r(  r  r  parse_tickerfilter_by_array_tickers)r   r  r  r  r   r  r  ri  r   tickerrP  s              r   fetch_tickerszhyperliquid.fetch_tickers  s      !!!%%g./66*6>!44V<<HV^!44V<<H!//77Hq#h-( 	$Aa[F&>D&&tV4F%%fh7F#F6N	$ ++FHgFF) 	" =<7sG   DDAD+D,D
DD$D%A'DDDDc           	        K   ddi}| j                  | j                  ||             d{   }| j                  |di       }| j                  |dg       }| j                  |dg       }g }t	        dt        |            D ]G  }	| j                  | j                  ||	i       | j                  ||	i             }
|j                  |
       I | j                  ||      S 7 w)a  
        retrieves data on all swap markets for hyperliquid

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-asset-contexts-includes-mark-price-current-funding-open-interest-etc

        :param str[] [symbols]: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        r   r*  Nr   r  r   )r  r  r  r  r  r  r,  parse_funding_rates)r   r  r  r  r  r  r  r.  r  r  r  s              r   fetch_funding_rateszhyperliquid.fetch_funding_rates  s      &
 ,,T[[&-IJJ@ ~~h2.>>$
B7NN8Q3	q#h-( 	 A;;xB/y!R0D MM$	  ''88U Ks   )CCB1Cc                    | j                  |d      }| j                  |      }| j                  ||      }| j                  |d      }| j                  |d      }| j                  |d      }t	        t        j                  | j                               dz  dz  dz        dz   dz  dz  dz  }	i d|d	|d
|d|dd dd dd dd d|d|	d| j                  |	      dd dd dd dd dd dd ddiS )Nr1   fundingrx  oraclePx<   r   r   r   rP  	markPrice
indexPriceinterestRateestimatedSettlePricer  r  fundingRatefundingTimestampfundingDatetimenextFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeintervalr   )	r  coin_to_market_idsafe_symbolrb  rc  mathfloormillisecondsr  )
r   r   ri  rQ  marketIdrP  r  rx  r  r  s
             r   parse_funding_ratezhyperliquid.parse_funding_rate  s   * f-))$/!!(F3""43!!$1##D*5

4+<+<+> ?" Dr ID PQTUUY[[^``cgg
D
f
 
 (	

 D
 #D
 
 
 7
  0
 t||,<=
 t
 #D
 "4
 "4
  '!
" &t#
$ %
 	
r   r  c                    | j                  |d      }| j                  |d   d d | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      |d	|      S )	N	impactPxsrP  	prevDayPxrN  r   r   	dayNtlVlm)	rP  r  r  previousCloseclosebidaskquoteVolumer   )r  safe_tickerrb  )r   r  ri  bidAsks       r   r  zhyperliquid.parse_ticker  s      4X&!--fkB%%fg6##FA.##FA.++FK@
!
 
 
	r   r   sincec                 $  K   | j                          d{    | j                  |      }| j                  |d| j                               }|du }|}	|3|/| j	                  |      dz  }
| j                  ||
|z  dz        }d}nd}| j                  |dg      }d|d   r|d	   n|d
   | j                  | j                  ||      ||dd}| j                  | j                  ||             d{   }| j                  ||||	||      S 7 7 w)a.  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#candle-snapshot

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents, support '1m', '15m', '1h', '1d'
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest candle to fetch
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Nuntilr   Fr   candleSnapshotr?   rQ  r0   )r  r  	startTimeendTime)r   req)r  ri  ra  r  parse_timeframesumr  r  r   r  r  parse_ohlcvs)r   rP  	timeframer  r   r  ri  r  useTailoriginalSincetimeframeInMillisecondsr  r  s                r   fetch_ohlcvzhyperliquid.fetch_ohlcv2  s4     !!!V$!!&'43D3D3FG4-= *.*>*>y*ID*P'(?%(G"(LM6G9-$*0.vfTl ,,T__iS" 	
 ,,T[[&-IJJ"   69mUT[\\Q 	". Ks"   DDCD1D2DDc           	          | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS )Ntohlcv)ra  rb  )r   ohlcvri  s      r   parse_ohlcvzhyperliquid.parse_ohlcvj  sn      eS)UC(UC(UC(UC(UC(
 	
r   c                   K   d}| j                  d|      \  }}| j                          d{    | j                  |      }d|i}|d|d<   ||d<   nd|d<   | j                  |d      }| j	                  |d      }|||d	<   | j                  | j                  ||             d{   }	| j                  |	|||      S 7 7 w)
a  
        get the list of most recent trades for a particular symbol

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills
        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills-by-time

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest trade
        :param str [params.address]: wallet address that made trades
        :param str [params.user]: wallet address that made trades
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Nr   r  userFillsByTimer   r  	userFillsr  r  r  r  safe_marketra  r  r  r  parse_trades
r   rP  r  r   r  r  ri  r  r  r  s
             r   fetch_tradeszhyperliquid.fetch_trades  s       "88OV!!!!!&)K
 /GFO#(GK )GFO!!&'267+!&GI,,T[[&-IJJ*   65%@@G 	" K"   +CCA:C(C)CCc                     | j                  |      }| j                  |t        |d   d   | j                  | j                        S )Nr  r  )ri  decimal_to_precisionr'   r   paddingMode)r   rP  r  ri  s       r   amount_to_precisionzhyperliquid.amount_to_precision  sA    V$(({8KH8UW[WiWikok{k{||r   c                    | j                  |      }| j                  |      }|j                  d      d   }t        dt	        |            }| j                  |t        |t        | j                        }|d   rdnd}|| j                  | j                  |d   d            z
  }	| j                  |t        |	t        | j                        S )	Nr3  r   r5  r=   rO  ry  r  r  )ri  r8  r9  r   r  r  r'   r)   r  precision_from_stringr  r(   )
r   rP  r/  ri  r?  rE  rA  r  r1  subtractedValues
             r   price_to_precisionzhyperliquid.price_to_precision  s    V$((/nnS)!,3{#34**5%9JL^`d`p`pq!&>aq%(B(B4CSCSTZ[fTgiqCr(ss((Y]YiYijjr   c                 .    d| j                  |dd      z   S )N0xkeccakhex)hash)r   messages     r   hash_messagezhyperliquid.hash_message  s    dii5999r   c                     | j                  |dd  |dd  dd       }d|d   z   d|d   z   | j                  d|d         dS )	N	secp256k1r   rs   r  )r	  r
  r  )ecdsar  )r   r  r   	signatures       r   	sign_hashzhyperliquid.sign_hash  sW    JJtCDz:cd+;[$O		#&	#&"in-
 	
r   c                 J    | j                  | j                  |      |dd        S )Nr  )r  r  )r   r  r   s      r   sign_messagezhyperliquid.sign_message  s%    ~~d//8*ST:JKKr   c                     |rdnd}||dS )Nba)sourceconnectionId )r   r  	isTestnetr  s       r   construct_phantom_agentz#hyperliquid.construct_phantom_agent  s    " 
 	
r   c                     | j                  |      }| j                  |      }|}|d| j                  |      z   z  }||dz  }n
|dz  }||z  }| j                  | j	                  |      dd      S )N000000001r  binary)packbbinary_to_base16int_to_base16r  base16_to_binary)r   actionvaultAddressnonce
dataBinarydataHexr  s          r   action_hashzhyperliquid.action_hash  s    ZZ'
''
3$,,U333DLDDLDL Dyy..t4hIIr   c                 J   | j                  |||      }| j                  | j                  dd      }| j                  ||      }| j	                  | j                  d      }d}|d|dd}	dd	d
ddddgi}
| j                  |	|
|      }| j                  || j                        }|S )Nr   Fr   i9  r   r6  chainIdr1   verifyingContractr4   Agentr  stringr1   r   r  bytes32)r'  r|  r   r  r  eth_encode_structured_datar  r   )r   r"  r$  vaultAdressr  r  phantomAgentr   r*  domainmessageTypesmsgr  s                r   sign_l1_actionzhyperliquid.sign_l1_action  s    U;NN4<<F	33D)D. &&t||]C!,	
 !84';
 --flLQ%%c4??;	r   c                     | j                  | j                  d      }d}|d|dd}| j                  |||      }| j                  || j                        }|S )Nr   in HyperliquidSignTransactionr6  r)  )r  r   r0  r  r   )r   r4  r  r   r*  r3  r5  r  s           r   sign_user_signed_actionz#hyperliquid.sign_user_signed_action  sb    &&t||]C0!,	
 --flGL%%c4??;	r   c                 N    dddddddddddddgi}| j                  ||      S )	NzHyperliquidTransaction:UsdSendhyperliquidChainr-  r.  destinationr  r  uint64r9  r   r  r4  s      r   build_usd_send_sigzhyperliquid.build_usd_send_sig!  sF    ,+X>&9!842	/
 ++L'BBr   c                 N    dddddddddddd	dgi}| j                  ||      S )
Nz'HyperliquidTransaction:UsdClassTransferr;  r-  r.  r  toPerpboolr$  r=  r>  r?  s      r   build_usd_class_send_sigz$hyperliquid.build_usd_class_send_sig,  sF    5+X>!84!62 (3	8
 ++L'BBr   c                 N    dddddddddddddgi}| j                  ||      S )	NzHyperliquidTransaction:Withdrawr;  r-  r.  r<  r  r  r=  r>  r?  s      r   build_withdraw_sigzhyperliquid.build_withdraw_sig7  sF    -+X>&9!842	0
 ++L'BBr   r   sider  c           	         K   | j                          d{    | j                  d||||||      \  }}| j                  |g|       d{   }	|	d   S 7 >7 w)a   
        create a trade order

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-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]: 'Gtc', 'Ioc', 'Alo'
        :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.triggerPrice]: The price at which a trigger order is triggered at
        :param str [params.clientOrderId]: client order id,(optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
        :param str [params.slippage]: the slippage for market order
        :param str [params.vaultAddress]: the vault address for order
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   )r  parse_create_edit_order_argscreate_orders)
r   rP  r   rG  r  r/  r  orderglobalParamsorderss
             r   create_orderzhyperliquid.create_orderB  si     * !!!"??fdTXZ`bgiop|))5'<@@ay 	"@s!   AA4AA
AArM  c                 .  K   | j                          d{    | j                  ||      }| j                  |       d{   }| j                  |di       }| j                  |di       }| j	                  |dg       }| j                  |d      S 7 z7 Qw)a  
        create a list of trade orders

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order

        :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r  statuses)r  create_orders_requestprivatePostExchanger  r  parse_orders)r   rM  r  r  r  responseObjr  rP  s           r   rJ  zhyperliquid.create_orders\  s      !!!,,VV<11'::$ nnXz2>~~k626>>$
B7  400/ 	":s"   BB*BBABBc                 "   | j                          | j                  | j                  d      }| j                  |d|      }d}t        dt	        |            D ]2  }||   }| j                  |di       }| j                  |dd      }|1d	}4 |r_t        dt	        |            D ]G  }||   }| j                  |di       }| j                  |dd      }|1t        | j                  d
z          | j                  |g d      }| j                         }	g }
t        dt	        |            D ]  }||   }| j                  |d      }| j                  |      }|d   }| j                  |d      }|dk(  }| j                  |d      }|dk(  }| j                  |d      }| j                  |d      }| j                  |di       }| j                  |dd      }| j                  |d|      }|rdnd}| j                  |dd      }|rd}| j                  |d|      }| j                  |      }| j                  |dd      }| j                  |d|      }| j                  |d      }|xs |}d}|r|t        | j                  dz         |r*t!        j"                  |t!        j$                  d|            n)t!        j"                  |t!        j&                  d|            }| j)                  ||      }n| j)                  ||      }| j+                  ||      }| j                  |dd      }i }|r9d} || j)                  ||      }d	} n| j)                  ||      }||| rdnd d!|d"<   nd#|i|d$<   | j                  |g d%      }| j-                  |d&         |||||d'}!|||!d(<   |
j/                  |!        | j1                  | j                  |d)            }"d*|
d+d,}#|"d-|#d.<   | j3                  |#|	|"      }$|#|	|$d/}%|"| j                  |d)      }|"|%d)<   |%S )0a  
        create a list of trade orders
        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order
        :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r   slippageFr   r  clientOrderId	client_idNTzV createOrders() all orders must have clientOrderId if at least one has a clientOrderId	rV  rW  rX  rV  r   	stopPricer   r   r   rP  r   MARKETrG  BUYr  r/  iocgtcpostOnlyalor   r   rZ  r   r   zy  market orders require price to calculate the max slippage price. Default slippage can be set in options(default is 5%).r6  
reduceOnlytpslisMarket	triggerPxtpslr   tifr   )
rW  rV  r   rZ  r   r   r   rX  ra  r_  r+  r  r  pr
  r	  r  r  r#  rK  na)r   rM  groupingr   
brokerCoder"  r$  r  )check_required_credentialsr  r   r  r  r  safe_string_2r!   r0   r  r  ri  safe_string_upperr|  safe_string_lower
capitalizer+   
string_mul
string_add
string_subr  r  r=  r,  format_vault_addressr6  )&r   rM  r  r   hasClientOrderIdr  rawOrderorderParamsrW  r$  orderReqr  ri  rP  r   re  rG  isBuyr  r/  rV  defaultTimeInForcer_  r   r   r   r   	isTriggerr  r  ra  	orderTypeisTporderObjr#  orderActionr  r  s&                                         r   rQ  z!hyperliquid.create_orders_request  s    	'')**4<<9JK**6:O q#f+& 	(AayH..8R@K ..{O[YM(#' 	( 1c&k* P!!9"nnXxD $ 2 2;Q\ ] (+DGG  7O  -O  P  PP 6  $j  k!!#q#f+& ?	&AayH''(;H[[*FH%F))(F;D(H))(F;DU]E%%h9F$$Xw7E..8R@K ..{O[YM''ZQH+3%~~k:uEH%*"00mM_`K//+6K--k>;WL ,,[/<XM"..{<MNO&9/IB=+DGG  7r  -r  s  sV[W''w/A/A#x/PQbibtbtuz  }D  }O  }O  PS  U]  }^  c_,,VR8,,VU;))&&9B\5IJ I".#'#:#:6?#SLD#'#:#:6=#QL (!-%)D(	)$ ;&	'" ))K  2F  GK&&vh'78H ( -OOH%?	&@ 001A1A&.1YZ
 ()K%''ULI	!"
 #YYv~6F&2GN#r   r0   c                 j   K   | j                  |g||       d{   }| j                  |d      S 7 w)a  
        cancels an open order

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s
        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s-by-cloid

        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.clientOrderId]: client order id,(optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
        :param str [params.vaultAddress]: the vault address for order
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   )cancel_ordersr  )r   r0   rP  r  rM  s        r   cancel_orderzhyperliquid.cancel_order  s8      ))2$??~~fa(( @s   313idsc                 j  K   | j                          |t        | j                  dz         | j                          d{    | j	                  |      }| j                  |dd      }| j                  |ddg      }| j                         }d|i}g }dg d}	| j                  |d         }
|Jt        |t              s|g}d	|	d
<   t        dt        |            D ]  }|j                  |
||   d        nEd|	d
<   t        dt        |            D ](  }|j                  |
| j                  ||         d       * ||	d<   | j                  | j                  |d            }| j!                  |	||      }|	|d<   ||d<   || j                  |d      }||d<   | j#                  |       d{   }| j%                  |d      }| j%                  |d      }| j'                  |d      }g }t        dt        |            D ]*  }||   }|j                  | j)                  ||d             , |S 7 7 w)a  
        cancel multiple orders

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s
        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s-by-cloid

        :param str[] ids: order ids
        :param str [symbol]: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param string|str[] [params.clientOrderId]: client order ids,(optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
        :param str [params.vaultAddress]: the vault address
        :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nz* cancelOrders() requires a symbol argumentrW  rX  r$  r7  r   cancelsr+  cancelByCloidr   r   )assetcloidcancel)r  r  r  r#  r"  r  r  r  rP  r   status)ro  r!   r0   r  ri  safe_value_2r  r  parse_to_numeric
isinstancelistr  r  r,  rw  r  r6  rR  r  r  
safe_order)r   r  rP  r  ri  rW  r$  r  	cancelReqcancelActionr+  r  r#  r  r  innerResponser  rP  rM  r  s                       r   r  zhyperliquid.cancel_orders   sx     	'')>#DGG.Z$Z[[!!!V$))&/;O6O[#AB!!#U
 	
 &&vh'78$mT2!.#2L 1c-01   #*1-"  $,L 1c#h'   ..s1v6" 
 #,Y001A1A&.1YZ''e\J	((#YYv~6F&2GN#11':: x<~~mV4>>$
3q#h-( 	Aa[FMM$// +  	  	"N ;s%   >H3 H.E,H3-H1.BH31H3c                 z  K   | j                          | j                          d{    | j                         }d|i}g }dg d}d}t        dt	        |            D ]  }||   }	| j                  |	d      }
|
d}| j                  |	d	      }| j                  |	d
      }|t        | j                  dz         ||rt        | j                  dz         |rdnd}|rdnd}| j                  |      }i }| j                  |d         ||<   |r|
n| j                  |      ||<   |j                  |        |rdnd|d<   ||d<   | j                  | j                  |d            }| j                  |||      }||d<   ||d<   || j                  |d      }||d<   | j                  |       d{   }|S 7 7 	w)a  
        cancel multiple orders for multiple symbols

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s
        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s-by-cloid

        :param CancellationRequest[] orders: each order should contain the parameters required by cancelOrder namely id and symbol, example [{"id": "a", "symbol": "BTC/USDT"}, {"id": "b", "symbol": "ETH/USDT"}]
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.vaultAddress]: the vault address
        :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr$  r7  r  Fr   rW  Tr0   rP  zB cancelOrdersForSymbols() requires a symbol argument in each orderzI cancelOrdersForSymbols() all orders must have either id or clientOrderIdr  r  r  r  r+  r  r  r   r  r#  r"  r  )ro  r  r  r  r  r  r!   r0   r"   ri  r  r,  rw  r6  r  rR  )r   rM  r  r$  r  r  r  r  r  rK  rW  r0   rP  assetKeyidKeyri  	cancelObjr#  r  r  s                       r   cancel_orders_for_symbolsz%hyperliquid.cancel_orders_for_symbolsR  s     	'')!!!!!#U
 	
 q#f+& 	(A1IE ,,UODM( $!!%.B%%eX6F~'2v(vww~- +v!vww"/wSH,G#E[[(F I"&"7"7x8H"IIh0=}4CXCXY[C\IeY'#	($ 3@XV"+Y001A1A&.1YZ''e\J	((#YYv~6F&2GN#11':: k 	"N ;s"   $F;F6FF;/F90F;9F;timeoutc                   K   | j                          | j                          d{    | j                  |ddg      }| j                         }d|i}d||z   d}| j	                  | j                  |d            }| j                  |||      }||d<   ||d	<   || j                  |d      }||d<   | j                  |       d{   }|S 7 7 w)
aX  
        dead man's switch, cancel all orders after the given timeout
        :param number timeout: time in milliseconds, 0 represents cancel the timer
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.vaultAddress]: the vault address
        :returns dict: the api result
        NrW  rX  r$  scheduleCancel)r   r  r#  r"  r  )ro  r  r  r  rw  r  r6  rR  )	r   r  r  r$  r  r  r#  r  r  s	            r   cancel_all_orders_afterz#hyperliquid.cancel_all_orders_after  s      	'')!!!6O[#AB!!#U

 %GO
 001A1A&.1YZ''e\J	((#YYv~6F&2GN#11':: 3 	"$ ;s"   $CCBCCCCc                 *   | j                          d}t        dt        |            D ]2  }||   }| j                  |di       }| j	                  |dd      }|1d}4 |r_t        dt        |            D ]G  }||   }| j                  |di       }| j	                  |dd      }|1t        | j                  dz          | j                  |g d      }g }t        dt        |            D ]  }||   }| j                  |d	      }	| j                  |d
      }
| j                  |
      }|d
   }| j                  |d      }|dk(  }| j                  |d      }|dk(  }| j                  |d      }| j                  |d      }| j                  |di       }| j                  | j                  d      }| j                  |d|      }|rdnd}| j                  |dd      }|rd}| j                  |d|      }| j                  |      }| j	                  |dd      }| j	                  |dd      }| j                  |d|      }| j                  |d      }|xs |}| j                  |dd      }| j                  |g d      }| j                  |      }|ri|r*t!        j"                  |t!        j$                  d|            n)t!        j"                  |t!        j&                  d|            }| j)                  ||      }n| j)                  ||      }| j+                  ||      }i }|r9d} || j)                  ||      }d} n| j)                  ||      }||| rdnd d!|d"<   nd#|i|d$<   |d%}| j-                  |d&         |||||d'}!|||!d(<   | j-                  |	      |!d)}"|j/                  |"        | j1                         }#d*|d+}$| j3                  | j                  |d,            }%| j5                  |$|#|%      }&|$|#|&d-}'|%| j                  |d,      }|%|'d,<   |'S ).NFr   r  rW  rX  TzT editOrders() all orders must have clientOrderId if at least one has a clientOrderIdrY  r0   rP  r   r[  rG  r\  r  r/  r   rV  r]  r^  r_  r`  r   r   rZ  r   r   ra  )	rV  r   r   r   r   rW  rX  r_  ra  r6  rb  rc  rd  r   rh  r   r4  r+  ri  r  )oidrK  batchModify)r   modifiesr#  rn  )ro  r  r  r  rp  r!   r0   r  r  ri  rq  r   r|  rr  rs  r8  r+   rt  ru  rv  r  r  r=  r,  r  rw  r6  )(r   rM  r  rx  r  ry  rz  rW  r  r0   r  ri  rP  r   re  rG  r|  r  r/  r   rV  r}  r_  r   r   r   r   r~  ra  r  r  r  r  r{  	modifyReqr$  modifyActionr#  r  r  s(                                           r   edit_orders_requestzhyperliquid.edit_orders_request  s   '') q#f+& 	(AayH..8R@K ..{O[YM(#' 	( 1c&k* N!!9"nnXxD $ 2 2;Q\ ] (+DGG  7M  -M  N  NN 6  $j  kq#f+& E	'AayH!!(D1B''(;H[[*FH%F))(F;D(H))(F;DU]E%%h9F$$Xw7E..8R@K"..t||=NOO''ZQH+3%~~k:uEH%*"00mM_`K//+6K ..{O[YM--k>;WL ,,[/<XM"..{<MNO&9/I\5IJ))K  2y  zK&&u-BSXW''G,>,>sH,MN_f_q_qrtv}  wI  wI  JM  OW  wX  `Y,,VR8,,VR8))&&9B I".#'#:#:6?#SLD#'#:#:6=#QL (!-%)D(	)$ ;&	'" #"&&vh'78H ( -((,!I OOI&KE	'L !!#! 
 001A1A&.1YZ''e\J	""
 #YYv~6F&2GN#r   c           	         K   | j                          d{    |t        | j                  dz         | j                  |||||||      \  }}	| j	                  |g|	       d{   }
|
d   S 7 X7 w)a	  
        edit a trade order

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#modify-multiple-orders

        :param str id: cancel order id
        :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]: 'Gtc', 'Ioc', 'Alo'
        :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.triggerPrice]: The price at which a trigger order is triggered at
        :param str [params.clientOrderId]: client order id,(optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
        :param str [params.vaultAddress]: the vault address for order
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nz$ editOrder() requires an id argumentr   )r  r!   r0   rI  edit_orders)r   r0   rP  r   rG  r  r/  r  rK  rL  rM  s              r   
edit_orderzhyperliquid.edit_order$  s     * !!!:#DGG.T$TUU"??FDRVX^`egmn|''>>ay 	" ?s"   A3A/AA3%A1&
A31A3c                 ,  K   | j                          d{    | j                  ||      }| j                  |       d{   }| j                  |di       }| j                  |di       }| j	                  |dg       }| j                  |      S 7 y7 Pw)a   
        edit a list of trade orders

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#modify-multiple-orders

        :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r  rP  )r  r  rR  r  r  rS  )r   rM  r  r  r  responseObject
dataObjectrP  s           r   r  zhyperliquid.edit_orders@  s      !!!**66:11'::H *bA^^NFB?
>>*j"=  **S 	":s"   BB*BBABBr1   description
initialUsdc                   K   | j                          | j                          d{    | j                         }d|i}| j                  t	        j
                  | j                  |      d            }d||||d}| j                  ||      }	||d<   |	|d<   | j                  | j                  ||             d{   }
|
S 7 7 w)aF  
        creates a value
        :param str name: The name of the vault
        :param str description: The description of the vault
        :param number initialUsd: The initialUsd of the vault
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: the api result
        Nr$  1000000createVault)r   r1   r  r  r$  r"  r  )
ro  r  r  r=  r+   rt  r8  r6  rR  r  )r   r1   r  r  r  r$  r  usdr"  r  r  s              r   create_vaultzhyperliquid.create_vaultu  s      	'')!!!!!#U
  2 243H3H3TV_ `a!&
 ''6	"(11$++gv2NOO 5 	"  Ps"   $CCBC;C<CCc           
        K   | j                          d{    |t        | j                  dz         | j                  |      }d|d   d}|||d<   n%|dn|}| j	                         |dz  dz  d	z  z
  |d<   | j                  |d
      }| j                  |d
      }|||d<   | j                  | j                  ||             d{   }	g }
t        dt        |	            D ]_  }|	|   }| j                  |d      }|
j                  || j                  d|      | j                  |d      || j                  |      d       a | j                  |
d      }| j!                  ||||      S 7 X7 w)a  
        fetches historical funding rate prices

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-historical-funding-rates

        :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 argumentfundingHistoryrQ  r  r  i  r  r   r  r  r   r  r  )r   rP  r  r  r  r  )r  r!   r0   ri  r  ra  r  r  r  r  r  r,  r  rb  r  sort_byfilter_by_symbol_since_limit)r   rP  r  r   r  ri  r  maxLimitr  r  r  r  entryr  sorteds                  r   fetch_funding_rate_historyz&hyperliquid.fetch_funding_rate_history  s     !!!>#DGG.e$effV$$6N
 #(GK $}s5H#'#4#4#6B9Kd9R#RGK !!&'267+!&GI,,T[[&-IJJ q#h-( 		AQKE))%8IMM**48#//}E& LL3 		 fk200NNQ 	"" Ks#   E3E.B3E3
E1B$E31E3c                   K   d}| j                  d|      \  }}d}| j                  |ddd      \  }}| j                          d{    | j                  |      }||d}| j	                  | j                  ||             d{   }	g }
t        dt        |	            D ]A  }|	|   }i }| j                  |d      d|d	<   |
j                  | j                  ||             C | j                  |
|||      S 7 7 uw)
a  
        fetch all unfilled currently open orders

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-open-orders

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.user]: user address, will default to self.walletAddress if not provided
        :param str [params.method]: 'openOrders' or 'frontendOpenOrders' default is 'frontendOpenOrders'
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr|   methodfrontendOpenOrdersr  r   r  open
ccxtStatus)r  handle_option_and_paramsr  r  r  r  r  r  r  r,  rS  )r   rP  r  r   r  r  r  ri  r  r  orderWithStatusr  rK  extendOrders                 r   fetch_open_orderszhyperliquid.fetch_open_orders  s"     "889JFSV66v?PRZ\pq!!!!!&)
 ,,T[[&-IJJ q#h-( 	DAQKEKx08,2L)""4;;uk#BC	D   &%GG7 	" Ks%   AC=C9>C=C;A4C=;C=c                    K   | j                          d{    | j                  |dd|       d{   }| j                  |ddgd      }| j                  ||||      S 7 I7 /w)a,  
        fetch all unfilled currently closed orders
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.user]: user address, will default to self.walletAddress if not provided
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  closedFr  fetch_ordersfilter_by_arrayr  r   rP  r  r   r  rM  closedOrderss          r   fetch_closed_orderszhyperliquid.fetch_closed_orders  sk      !!!((tVDD++FHxj%P00vueTT 	"D   A$A A$A".A$"A$c                    K   | j                          d{    | j                  |dd|       d{   }| j                  |ddgd      }| j                  ||||      S 7 I7 /w)a  
        fetch all canceled orders
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.user]: user address, will default to self.walletAddress if not provided
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  canceledFr  r  s          r   fetch_canceled_ordersz!hyperliquid.fetch_canceled_orders  sk      !!!((tVDD++FHzlER00vueTT 	"Dr  c                    K   | j                          d{    | j                  |dd|       d{   }| j                  |dg dd      }| j                  ||||      S 7 J7 0w)a&  
        fetch all closed and canceled orders
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.user]: user address, will default to self.walletAddress if not provided
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  )r  r  rejectedFr  r  s          r    fetch_canceled_and_closed_ordersz,hyperliquid.fetch_canceled_and_closed_orders  sk      !!!((tVDD++FH>`bgh00vueTT 	"Ds   A%A!A%A#/A%#A%c                   K   d}| j                  d|      \  }}| j                          d{    | j                  |      }d|d}| j                  | j	                  ||             d{   }| j                  ||||      S 7 W7 w)a  
        fetch all orders
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.user]: user address, will default to self.walletAddress if not provided
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   historicalOrdersr  )r  r  r  r  r  rS  )	r   rP  r  r   r  r  ri  r  r  s	            r   r  zhyperliquid.fetch_orders.  s      "88OV!!!!!&)&
 ,,T[[&-IJJ   65%@@) 	" Ks!   +B	B>B	,B-B	B	c                 z  K   d}| j                  d|      \  }}| j                          d{    | j                  |      }t        |      dk\  }d|r|n| j	                  |      |d}| j                  | j                  ||             d{   }| j                  |d      }	| j                  |	|      S 7 7 *w)a@  
        fetches information on an order made by the user

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#query-order-status-by-oid-or-cloid

        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.user]: user address, will default to self.walletAddress if not provided
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr}   "   r   )r   r  r  rK  )	r  r  r  r  r  r  r  r  parse_order)
r   r0   rP  r  r  ri  isClientOrderIdr  r  r  s
             r   fetch_orderzhyperliquid.fetch_orderP  s      "88vNV!!!!!&)b'R-!(2d.C.CB.G

 ,,T[[&-IJJ8 ~~h0f--K 	" Ks"   +B;B7A B;B9)B;9B;rK  c           
         | j                  |d      }|| j                  |dd      S | j                  |g d      }||}| j                  |d      }d }|| j                  |      }| j                  |d      | j	                  |d       }n| j	                  ||      }|d   }| j                  |d      }| j                  |d	d
      }	| j                  |d
g      }| j                  |d      }
|
	|
dk(  rdnd}
| j                  |dd      }| j                  |d      }| j                  |d      }d }||dk(  }| j                  i d|d| j                  |d      d| j                  |d      d|d| j                  |      dd d| j                  |d      d|d| j                  | j                  |d            d|d|d | j                  |d       d|
d!| j                  |d"      d#| j                  |d$      r| j                  |d%      nd d&|d'd | j                  |d(      t        j                  ||      || j!                  |	      d d d)|      S )*Nerrorr  r  )rK  restingfilledr  r0   rP  r  r  r  rG  AsellbuyorigSztotalSzr  rh  ALOr   r  rW  r  r  lastTradeTimestamplastUpdateTimestampstatusTimestampr   r  r   r_  ra  r/  limitPxr   r~  rf  r  r   avgPx)averager  	remainingr  r  trades)r  r  safe_dict_nr  r  ra  rp  r  rq  r  parse_order_typerr  r|  rb  r+   rv  parse_order_status)r   rK  ri  r  r  r  r  rP  r  r  rG  totalAmountr  rh  r_  s                  r   r  zhyperliquid.parse_order  s   @   0??$$     (FG=Ev.--d3HE4(0%%h5F%%h7F!%%e[9	##E8\B		%,0v."ck6D(()D$$UD1	$$UE2?uH  
E 
$""5%0 
 T--eW= 
 	 

 Y/ 
 !$ 
 "4#4#4U<M#N 
 f 
 D))$*@*@*TU 
 3 
  
 $..= 
 D 
 T%%eY7 
 DNNSXZeDfD,,UK@lp 
  k! 
" D# 
$ ''w7((i@"--f5/ 
0 1 	r   r  c                 :    ddddddd}| j                  |||      S )Nr  r  r  r  )	triggeredr  r  r  r  marginCanceledr  r   r  rP  s      r   r  zhyperliquid.parse_order_status	  s2    ""(
 &&99r   c                 2    ddd}| j                  |||      S )Nr   ri  )z
stop limitzstop marketr  r  s      r   r  zhyperliquid.parse_order_type(	  s&    !#
 &&99r   c                   K   d}| j                  d|      \  }}| j                          d{    | j                  |      }d|i}|d|d<   ||d<   nd|d<   | j                  |d      }| j	                  |d      }|||d	<   | j                  | j                  ||             d{   }	| j                  |	|||      S 7 7 w)
a  
        fetch all trades made by the user

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills
        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills-by-time

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest trade
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Nrw   r  r  r   r  r  r  r  r  r  s
             r   fetch_my_tradeszhyperliquid.fetch_my_trades/	  s      "88&QV!!!!!&)K
 /GFO#(GK )GFO!!&'267+!&GI,,T[[&-IJJ,   65%@@I 	" Kr  tradec                 B   | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |d       }|d   }| j                  |d      }	| j                  |d      }
|
	|
dk(  rd	nd
}
| j                  |d      }d }| j	                  |d      }||rdnd}| j                  ||| j                  |      ||	| j                  |d      d |
|||d || j                  |d      d dd|      S )Nr  r  r  r  rP  tidrG  r  r  r  r  crossedr   r   r  feeToken)r   currencyrate)r   r  r  rP  r0   rK  r   rG  takerOrMakerr/  r  r   r  )ra  r  r  r  r|  
safe_trader  )r   r  ri  r  r/  r  r  r  rP  r0   rG  r  r  r  s                 r   parse_tradezhyperliquid.parse_tradee	  sU   & %%eV4	  -!!%.v.))$/!!(D1!eU+v."ck6Due,..	2&-77L"Y/%%eU3( ,,UJ? 
$ % 	r   c                 j   K   | j                  |g|       d{   }| j                  |di       S 7 w)a.  
        fetch data on an open position

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-users-perpetuals-account-summary

        :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.user]: user address, will default to self.walletAddress if not provided
        :returns dict: a `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        Nr   )fetch_positionsr  )r   rP  r  	positionss       r   fetch_positionzhyperliquid.fetch_position	  s8      ..x@@	~~iB// As   313c                   K   | j                          d{    d}| j                  d|      \  }}| j                  |      }d|d}| j                  | j	                  ||             d{   }| j                  |dg       }g }t        dt        |            D ]&  }|j                  | j                  ||   d             ( | j                  |d|d      S 7 7 mw)	a  
        fetch all open positions

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-users-perpetuals-account-summary

        :param str[] [symbols]: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.user]: user address, will default to self.walletAddress if not provided
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        Nr   r   r  assetPositionsr   rP  F)r  r  r  r  r  r  r  r  r,  parse_positionfilter_by_array_positions)	r   r  r  r  r  r  r  r  r  s	            r   r  zhyperliquid.fetch_positions	  s      !!!"889I6RV%%g.(
 ,,T[[&-IJJ\ ~~h(8"=q#d)$ 	>AMM$--d1gt<=	>--fhOOu 	" Ks#   CCAC,C-A,CCpositionc                    | j                  |di       }| j                  |d      }| j                  |      }| j                  |d       }|d   }| j                  |di       }| j                  |d      }|dk(  }	| j                  |d      }
|
}d }|/t	        j
                  |
d      rd	nd
}t	        j                  |      }| j                  |d      }t	        j                  |      }| j                  |d      }t	        j                  t	        j                  ||      d      }| j                  i d|dd d|dd dd d|	dd d|d| j                  |      dd d| j                  |d      dd d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |      dd d d | j                  |      | j                  |d      || j                  |      d       S )!Nr  r  rP  r   r   r  szir4  longshortunrealizedPnl
marginUsed100r   r0   r  r  r   rG  	contractsr[  
entryPriceentryPxr  notionalpositionValuevalue
collateralinitialMarginmaintenanceMarginliquidationPx)initialMarginPercentagemaintenanceMarginPercentager  liquidationPricer   
percentage)r  r  r  r  r+   r;  
string_absrt  
string_divsafe_positionr   rb  )r   r  ri  r  r  r  rP  r   r   
isIsolatedrawSizesizerG  rawUnrealizedPnlabsRawUnrealizedPnlr  r!  s                    r   r
  zhyperliquid.parse_position	  s   6 xR8v.))$/!!(D1!>>%R8%%h7
 J.
""5%0$..w<6'D%%d+D++E?C%001AB((=''(:(:;NP](^`ef
!! #
H#
$#
 f#
 	#

 #
 
#
 d#
 D#
 **40#
 D#
 $**5)<#
 #
 ((@#
 ((7;#
 $**5,?#
  T..}=!#
"  ##
$ (,+/!../?@ $ 0 0 H$++J7/#
  	r   r   c                   K   |t        | j                  dz         | j                          d{    | j                  |      }| j	                  |d      }|t        | j                  dz         | j                  |d         }|dk(  }| j                         }| j                  |dg      }d|||d}	| j                  |d	      }
|
5| j                  |d	      }|
j                  d
      r|
j                  d
d      }
| j                  |	||
      }|	||d}|
|
|d	<   | j                  |       d{   }|S 7 	7 	w)a  
        set margin mode(symbol)
        :param str marginMode: margin mode must be either [isolated, cross]
        :param str symbol: unified market symbol of the market the position is held in, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.leverage]: the rate of leverage, is required if setting trade mode(symbol)
        :returns dict: response from the exchange
        Nz+ setMarginMode() requires a symbol argumentr   z. setMarginMode() requires a leverage parameterr+  crossupdateLeverager   r  isCrossr   r#  r   r7  rn  )r!   r0   r  ri  ra  r=  r  r  r  
startswithreplacer6  rR  )r   r   rP  r  ri  r   r  r.  r$  updateActionr#  r  r  r  s                 r   set_margin_modezhyperliquid.set_margin_mode8
  sg     >#DGG.[$[\\!!!V$$$VZ8#DGG.^$^__!!&"23(!!#6J<0$ 	
 ''?#YYv~6F&&t,+33D"=''e\J	""
 #&2GN#11':: M 	": ;s"   .D>D9DD>2D<3D><D>r   c                   K   |t        | j                  dz         | j                          d{    | j                  |      }| j	                  |dd      }|dk(  }| j                  |d         }| j                         }| j                  |d      }d|||d}	| j                  | j	                  |d            }
| j                  |	||
      }|	||d	}|
| j                  |d      }|
|d<   | j                  |       d{   }|S 7 7 w)
a  
        set the level of leverage for a market
        :param float leverage: the rate of leverage
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: margin mode must be either [isolated, cross], default is cross
        :returns dict: response from the exchange
        Nz) setLeverage() requires a symbol argumentr   r+  r+  r,  r-  r#  rn  )r!   r0   r  ri  r  r=  r  r  rw  r6  rR  )r   r   rP  r  ri  r   r.  r  r$  r1  r#  r  r  r  s                 r   set_leveragezhyperliquid.set_leveragek
  s1     >#DGG.Y$YZZ!!!V$%%flGD
(!!&"23!!#6<0$ 	
 001A1A&.1YZ''e\J	""
 #YYv~6F&2GN#11':: C 	"0 ;s"   .DD	CDDDDc                 F   K   | j                  ||d|       d{   S 7 w)a  
        add margin

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#update-isolated-margin

        :param str symbol: unified market symbol
        :param float amount: amount of margin to add
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=add-margin-structure>`
        addNmodify_margin_helperr   rP  r  r  s       r   
add_marginzhyperliquid.add_margin
  s%      ..vvufMMMM   !!c                 F   K   | j                  ||d|       d{   S 7 w)a  

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#update-isolated-margin

        remove margin from a position
        :param str symbol: unified market symbol
        :param float amount: the amount of margin to remove
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=reduce-margin-structure>`
        reduceNr7  r9  s       r   reduce_marginzhyperliquid.reduce_margin
  s%      ..vvxPPPPr;  c                 v  K   | j                          d {    | j                  |      }| j                  |d         }| j                  t        j                  | j                  ||      d            }|dk(  r| }| j                         }d|d|d}	| j                  | j                  |d            }
| j                  |	||
      }|	||d}|
| j                  |d      }|
|d<   | j                  |       d {   }| j                  | j                  ||      d	| j                  |d
      i      S 7 7 ;w)Nr+  r  r=  updateIsolatedMarginT)r   r  r|  ntlir#  rn  r  r  )r  ri  r=  r+   rt  r  r  rw  r  r6  r  rR  r  parse_margin_modification)r   rP  r  r   r  ri  r  r  r$  r1  r#  r  r  r  s                 r   r8  z hyperliquid.modify_margin_helper
  sU    !!!V$!!&"23w11$2J2J6SY2Z\efg8B!!#*	
 001A1A&.1YZ''e\J	""
 #YYv~6F&2GN#11':: {{499(FKD$$Xx8N
  	C 	"0 ;s"   D9D4C$D9;D7<9D97D9r  c                 \    || j                  d |      d dd d | j                  |d      d d d d
S )Nr  rS  )
r   rP  r   r   r  r  r  r  r  r  )r  r  )r   r  ri  s      r   rB  z%hyperliquid.parse_margin_modification
  sF     &&tV4$$$VX6
 	
r   r  fromAccount	toAccountc                   K   | j                          | j                          d{    | j                  | j                  d      }| j	                         }| j                  |g d      r| j                  |g d      st        | j                  dz         | j                  |      }| j                  | j                  |d            }	| j                  |d      }|	|dz   |	z   }|dk(  xs |dk(  }
|rd	nd
||
|d}| j                  |      }|d   dd||
|d||d}|	|	|d<   | j                  |       d{   }|S | j                  |       |-|j                         }|dk7  rt        | j                  dz         |rd	nd
|| j                  |      |d}| j!                  |      }|d   d|t#        |      |dd||d}| j                  |       d{   }| j%                  |      S 7 7 7 w)a  
        transfer currency internally between wallets on the same account

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#l1-usdc-transfer

        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: account to transfer from *spot, swap*
        :param str toAccount: account to transfer to *swap, spot or 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>`
        Nr   )r=   r?   perpz. transfer() only support spot <> swap transferr#  z subaccount:rG  r?   TestnetMainnet)r;  r  rB  r$  r;  0x66eeeusdClassTransfer)r;  signatureChainIdr   r  rB  r$  rn  rv  z transfer() only support USDCr;  r<  r  r  usdSendr;  rL  r<  r  r  r   )ro  r  r|  r   r  in_arrayr&   r0   r8  rw  r  r  rD  rR  check_addressupperr@  strparse_transfer)r   r  r  rD  rE  r  isSandboxModer$  	strAmountr#  rB  transferPayloadtransferSigtransferRequesttransferResponsepayloadsigr  r  s                      r   r   zhyperliquid.transfer
  sA     	'')!!!t||]C!!#==&>?==,DE"477-]#]^^--f5I44T5E5Efn5]^LYYv~6F'%6E	6)CyF/BF1>II# 	%O 77HK )88J(K(1.'$" (%O '2>/%)%=%=o%NN##9%::<Dv~"477-L#LMM-:		$++F3	
 %%g. %,,>$?$-(f+! 
 11':: ""8,,C 	"D  O6 ;s5   $G4G-DG48G09BG4G2G40G42G4r   r  c           
          |d d d d d d d dd	S )Nok)	r   r0   r  r  r  r  rD  rE  r  r  )r   r   r  s      r   rT  zhyperliquid.parse_transfer>  s)    
 

 
	
r   addressc                   K   | j                          | j                          d{    | j                  |       |-|j                         }|dk7  rt	        | j
                  dz         | j                  | j                  |d            }| j                  |d      }| j                         }i }d}	|dd|z   d|d}| j                  ||      }	nW| j                  | j                  d	d      }
|
rd
nd|t        |      |d}| j                  |      }	|d   d|t        |      |dd}|||	d}| j                  |       d{   }| j!                  |      S 7 27 w)a  
        make a withdrawal(only support USDC)

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#initiate-a-withdrawal-request
        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#deposit-or-withdraw-from-a-vault

        :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
        :param str [params.vaultAddress]: vault address withdraw from
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nrv  z withdraw() only support USDCr#  vaultTransferr   F)r   r#  	isDepositr  r   rH  rI  rM  r;  rJ  	withdraw3rO  rn  )ro  r  rQ  rR  r&   r0   rw  r  r  r  r6  r|  r   rS  rF  rR  parse_transaction)r   r  r  r_  tagr  r#  r$  r"  r\  rU  r[  r  r  s                 r   r   zhyperliquid.withdrawN  s     	'')!!!7#::<Dv~"477-L#LMM001A1A&.1YZ6>2!!##' $| 3"	F %%fe4C NN4<<NM1>II&f+	G ))'2C$+,>$?$-&f+#F 

 11'::%%h//U 	"R ;s"   $EEDEEEEtransactionc                    | j                  |d      }| j                  |di       }d }| j                  |d      }|d|d}d }| j                  |d      }||dk(  }i d|d	d d
| j                  |d      d|d| j                  |      dd dd d| j                  |d      d| j                  |d      dd dd dd dd d| j	                  |d      dd d| j                  |d      dd d ||dS )Nr  deltar  rv  r  r   r   internalTransferr   r0   txidr  r  r  networkr_  	addressTor<  addressFromr  re  tagTotagFromr  usdcr  r  updated)commentinternalr  )ra  r  r  r  rb  )	r   rf  r  r  rh  r  feeCostrt  r   s	            r   rd  zhyperliquid.parse_transaction  s    %%k6:	{GR8##E51"C v. 22H
K
$
 D$$[&9
 	

 Y/
 t
 t
 ))%?
 4++E6:
 4
 T
 t
 D
 d&&uf5
 
  d&&{H=!
" t#
$  )
 	
r   c                 \  K   | j                          d{    d}| j                  d|      \  }}| j                  |      }d|d}| j                  | j	                  ||             d{   }| j                  |d      | j                  |d      d}| j                  ||      S 7 7 =w)as  
        fetch the trading fees for a market
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.user]: user address, will default to self.walletAddress if not provided
        :returns dict: a `fee structure <https://docs.ccxt.com/#/?id=fee-structure>`
        Nr   userFeesr  userCrossRateuserAddRate)rx  ry  )r  r  ri  r  r  r  parse_trading_fee)r   rP  r  r  ri  r  r  r  s           r   fetch_trading_feezhyperliquid.fetch_trading_fee  s      !!!"889JFSVV$
 ,,T[[&-IJJJ "--hH++HmD
 %%dF33a 	" Ks"   B,B(AB,,B*-<B,*B,r  c                 x    | j                  d |      }||| j                  |d      | j                  |d      d d dS )Nry  rx  )r   rP  r   r   r!  	tierBased)r  rb  )r   r  ri  rP  s       r   rz  zhyperliquid.parse_trading_fee  sM    H !!$/%%c=9%%c?;
 	
r   c                 Z  K   | j                          d{    d}| j                  d|      \  }}d|d}|||d<   | j                  |d      }|||d<   | j                  |dg      }| j	                  | j                  ||             d{   }| j                  |d||      S 7 7 w)a,  
        fetch the history of changes, actions done by the user or operations that altered the balance of the user
        :param str [code]: unified currency code
        :param int [since]: timestamp in ms of the earliest ledger entry
        :param int [limit]: max number of ledger entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest ledger entry
        :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger>`
        Nrn   userNonFundingLedgerUpdatesr  r  r  r  )r  r  ra  r  r  r  parse_ledger)	r   r  r  r   r  r  r  r  r  s	            r   fetch_ledgerzhyperliquid.fetch_ledger%  s      !!!"88OV1
 #(GK !!&'2!&GIYYvy1F,,T[[&-IJJ   4>>7 	" Ks"   B+B'A7B+B)B+)B+itemc                    | j                  |d      }| j                  |di       }d }| j                  |d      }|d|d}| j                  |d      }| j                  |d      }| j                  || j                  |d      d d | j                  |d	      | j                  |d      | j	                  |      d | j                  |      || j                  |      d d d |d
|      S )Nr  rh  r  rv  ri  r   rq  r  r  )r   r0   	directionr  referenceAccountreferenceIdr   r  r  r  r  beforeafterr  r  )ra  r  r  safe_ledger_entryparse_ledger_entry_typer   r  )	r   r  r  r  rh  r  ru  r   r  s	            r   parse_ledger_entryzhyperliquid.parse_ledger_entryL  s    %%dF3	tWb1##E51"C v.!!%0%%""40 $ 0 0 ?++D&9006''/"Y/'
  ! 	r   c                 2    ddd}| j                  |||      S )Nr   )rj  accountClassTransferr  )r   r   
ledgerTypes      r   r  z#hyperliquid.parse_ledger_entry_typeu  s&     *$.

 
D$77r   c                   K   | j                          d{    d}| j                  d|      \  }}d|d}|||d<   | j                  |d      }|||d<   | j                  |dg      }| j	                  | j                  ||             d{   }| j                  |      }	| j                  |	dd	gd
      }
| j                  |
d||      S 7 7 @w)a  
        fetch all deposits made to an account
        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch withdrawals for
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        NfetchDepositsWithdrawalsr  r  r  r  r  r   r
  F	r  r  ra  r  r  r  extract_type_from_deltar  parse_transactions)r   r  r  r   r  r  r  r  r  recordsdepositss              r   fetch_depositszhyperliquid.fetch_deposits|  s      !!!"889SU[\V1
 #(GK !!&'2!&GIYYvy1F,,T[[&-IJJ ..x8'')eL&&xueDD; 	" K"   CCA7CC?CCc                   K   | j                          d{    d}| j                  d|      \  }}d|d}|||d<   | j                  |d      }|||d<   | j                  |dg      }| j	                  | j                  ||             d{   }| j                  |      }	| j                  |	dd	gd
      }
| j                  |
d||      S 7 7 @w)a$  
        fetch all withdrawals made from an account
        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of withdrawals structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch withdrawals for
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr  r  r  r  r  r  r   r   Fr  )r   r  r  r   r  r  r  r  r  r  withdrawalss              r   fetch_withdrawalszhyperliquid.fetch_withdrawals  s      !!!"889SU[\V1
 #(GK !!&'2!&GIYYvy1F,,T[[&-IJJ ..x8**7FZL%P&&{D%GG; 	" Kr  c                    K   | j                          d{    | j                  |      }| j                          d{   }| j                  ||      S 7 ?7 w)a&  
        Retrieves the open interest for a list of symbols
        :param str[] [symbols]: Unified CCXT market symbol
        :param dict [params]: exchange specific parameters
        :returns dict} an open interest structure{@link https://docs.ccxt.com/#/?id=open-interest-structure:
        N)r  r  r  parse_open_interests)r   r  r  r&  s       r   fetch_open_interestsz hyperliquid.fetch_open_interests  sW      !!!%%g. 3355((g>> 	"5s    AA(AA AAc                    K   | j                  |      }| j                          d{    | j                  |g|       d{   }||   S 7 $7 w)a#  
        retrieves the open interest of a contract trading pair
        :param str symbol: unified CCXT market symbol
        :param dict [params]: exchange specific parameters
        :returns dict: an `open interest structure <https://docs.ccxt.com/#/?id=open-interest-structure>`
        N)rP  r  r  )r   rP  r  oiss       r   fetch_open_interestzhyperliquid.fetch_open_interest  sR      V$!!!--vh??6{ 	"?s!   %AAAA
AAc           	          | j                  |di       }| j                  |d      }d }|| j                  |      }| j                  | j	                  |      | j                  |d      d d d |d|      S )Nr   r1   openInterest)rP  openInterestAmountopenInterestValuer  r  r   )r  r  r  safe_open_interestr  rb  )r   interestri  r  r  s        r   parse_open_interestzhyperliquid.parse_open_interest  s    & >>(FB7&1--d3H&&&&x0"&"2"28^"L!%(
  	r   c                   K   | j                          d{    d}|| j                  |      }d}| j                  d|      \  }}|dd}|||d<   | j                  |d      }| j	                  |d      }|||d<   | j                  | j                  ||             d{   }	| j                  |	|||      S 7 7 w)a  
        fetch the history of funding payments paid and received on self account
        :param str [symbol]: unified market symbol
        :param int [since]: the earliest time in ms to fetch funding history for
        :param int [limit]: the maximum number of funding history structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding history structure <https://docs.ccxt.com/#/?id=funding-history-structure>`
        Nrg   userFunding)r  r   r  r  r  )r  ri  r  ra  r  r  r  parse_incomes)
r   rP  r  r   r  ri  r  r  r  r  s
             r   fetch_funding_historyz!hyperliquid.fetch_funding_history  s      !!![[(F"889NPVWV!
 #(GK !!&'267+!&GI,,T[[&-IJJ" !!(FE5AAC 	"  Ks"   B?B;BB?"B=#B?=B?c           	         | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }|dz   }| j                  |      }|d   }| j                  |d      }	| j	                  d      }
| j                  |d	      }|||
|| j                  |      || j                  |	      |d
S )Nr  r  rh  r  
/USDC:USDCrP  rq  rv  r  )r   rP  r  r  r  r0   r  r   )r  ra  r  r  r  rb  r  r   )r   incomeri  r0   r  rh  r+  marketSymbolrP  r  r  r   s               r   parse_incomezhyperliquid.parse_income3  s     ff-%%ff5	vw/!!%0,!!,/!!!%0&&v.}5"Y/''/	
 		
r   c                     g }t        dt        |            D ]#  }||   }|d   d   |d<   |j                  |       % |S )Nr   rh  r   )r  r  r,  )r   r  r  r  records        r   r  z#hyperliquid.extract_type_from_deltaW  sO    q#d)$ 	#A!WF#G_V4F6NNN6"	# r   c                 R    |y |j                  d      r|j                  dd      S |S )Nr   r7  )r/  r0  )r   r_  s     r   rw  z hyperliquid.format_vault_address_  s.    ?d#??4,,r   
methodNamer  c                    d }| j                  ||d      \  }}|}| j                  ||d|      \  }}|	|dk7  r||gS | j                  | j                  dk7  r| j                  |gS t        | j                  dz   |z   dz         )Nr  r_  r7   zF() requires a user parameter inside 'params' or the wallet address set)r  r   r!   r0   )r   r  r  userAuxr  s        r   r  z!hyperliquid.handle_public_addressf  s    77
FS44VZT[\f42:&>!*1C1Cr1I&&//#
 :  >H  !H  I  	Ir   r  c                 `    |j                  d      dkD  s|j                  d      dkD  r|S |dz   S )NrK  r  @r  )find)r   r  s     r   r  zhyperliquid.coin_to_market_idq  s1    99S>B$))C.2"5Kl""r   reasonurlr  headersbodyc
                 $   |sy | j                  |dd      }
| j                  |d      }d }|
dk(  r| j                  |d      }nb||}n]| j                  |di       }| j                  |di       }| j                  |dg       }| j                  |d      }| j                  |d      }| j                  d	z   |z   }|d uxr |dk7  }|r@| j	                  | j
                  d
   ||       | j                  | j
                  d   ||       |rt        |      y )Nr  r7  r  errr  r  rP  r   r  r   r   )r  r  r  r0   throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr    )r   r  r  r  r  r  r  r  requestHeadersrequestBodyr  r  r  responsePayloadr  rP  firstStatusfeedbacknonEmptyMessages                      r   handle_errorszhyperliquid.handle_errorsv  s"    !!(Hb9  73U?&&x<GG"nnXz2FO>>/62>D~~dJ;H..15K&&{G<G77S=4'#4/Dgm001I7T\]001I7T\]))r   r   GETc                     | j                  | j                  d   |         dz   |z   }|dk(  rddi}| j                  |      }||||dS )Nr   rK  POSTzContent-Typezapplication/json)r  r  r  r  )implode_hostnamer   json)r   pathr   r  r  r  r  r  s           r   signzhyperliquid.sign  s^    ##DIIe$4S$9:S@4GV 2G 99V$DfdwOOr   c                 ^    d|v rd|v r|d   }|d   }||v r||   S | j                  |dd      S )Nr   r   r   r   )
safe_value)r   r   r  r  r  configr   r   s           r   calculate_rate_limiter_costz'hyperliquid.calculate_rate_limiter_cost  sH    Vv%5&>DH%Fv~d|#vvq11r   c                     | j                  |      }| j                  |d      }	| j                  |d      }|d   }||||||d}
i }|	|	|d<   |||
d<   |
|gS )Nr#  rP  )rP  r   rG  r  r/  r  r0   )ri  r  r  )r   r0   rP  r   rG  r  r/  r  ri  r#  rK  rL  s               r   rI  z(hyperliquid.parse_create_edit_order_args  s    V$''?6>2!
 #+7L(>E$K|$$r   )N)T)z__name__
__module____qualname__r   r   r   r   r  r   r   r(  r  floatrF  r   dictr}  r   r  rS  r	   r   r  r   r   r  r   r  r   r  r   r  r  r  r  r   r  r  r  r  r  r  r  r'  objectr6  r9  r@  rD  rF  r   r   r   rN  r   rJ  rQ  r  r  r   r  r  r  r  r  rc  r  r  r   r  r  r  r  r  r  r  r  r  r  r   r  r  r   r  r
  r2  r4  r   r:  r>  r8  rB  r   r   r   rT  r   r   rd  r   r{  rz  r
   r  r  r  r  r  r  r  r  r  r  r  rw  r  r  r  r  r  rI  __classcell__)r   s   @r   r-   r-      s6	   p# pd	. -/ 9: 9v *, ;V ;& /1 7*T&\ 7*r(1u (1u (1[` (1T /1 VT&\ Vpa4 aF aF *, Y) Y)v @DB .fS .f .fS\ .f` 6:"  G7  G  GD <@ 79 79| 79r/
v /
 /
b4  6 : 8<$]ajl 6] 6]C 6]WZ 6]quvzq{ 6]p
 
4 
0 <@d[] 5A 5AS 5A 5An}k k k:
L

J* *X	C	C	C mqy{  I Y X] fi 4 FH !1$|*< !1F 46 n$ n` 9=R )S )# )" AER PtCy P# Pd Y[ Bd;N6O BH BD "S "H 24 hT Z^lpy{ 3  3 c SV fi 8 DF 3+\(: 3+j WY $s $ $# $L >BPTcgpr 5Os 5O# 5O]` 5On 59tZ^gi -Hc -H -HTW -Hnrsxny -H^ 7;\`ik U U3 UVY Uptuzp{ U 9=4^bkm U# US UX[ Urvw|r} U DHVZimvx US UPS Ucf U  ~B  CH  ~I U 04$UYbd  A  AC  As  Aimnsit  AD 8<B 3.C 3. 3.jV Vv V Vp	: 	:: 37TX\eg 4AC 4As 4ARU 4Al5 5v 5 5n 8: 03 0 8<B EPW EP4PX> EPNEt EV EN DHPR 1 1S 1f ?C2 ,3 , ,\ CE Ns NE NI[ N FH Q# Qu QL^ Q LN $ $Rd $L
d 
F 
N` 
& ac P-3 P- P-C P-TW P-gt P-d
t 
x 
= 
  JNVX :03 :0 :0 :0]h :0x1
T 1
X 1
Q\ 1
f ;= 84c 84AT 84t,
T ,
6 ,
EX ,
\ .2SW`b %?s %?# %?S %?gklwgx %?N't 'x '; 'R8 04$UYbd 'E 'EC 'Es 'ER 37TX\eg 'HC 'Hs 'HRU 'Hlpq|l} 'HR =A 
?' 
? =? 
 
F B 9=4^bkm *B# *BS *BX[ *BX"
6 "
H ,. C 	I 	IT 	I#c #
# s  c TX `c B &eBSW P MO 2 @D  MO %s %C %y %Xa %kp %y| %r   r-   )3 ccxt.async_support.base.exchanger   ccxt.abstract.hyperliquidr   r!  r  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr    r!   r"   r#   r$   r%   r&   ccxt.base.decimal_to_precisionr'   r(   r)   r*   ccxt.base.preciser+   r-   r  r   r   <module>r     st    6 1   z  z  z  z  z  z  z  * . ' . ) * ) 0 9 = 4 %`6%(K `6%r   