
    !:h>G                    H   d dl mZ d dlmZ d dlZd dlmZmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZ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l/m0Z0  G d dee      Z1y)    )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    J/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/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_modeM  s     k41':&-]#r   c                 r   ddi}| j                  | j                  ||            }| 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 )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metauniverser   r1   N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_currenciesQ  s     F
 &&t{{7F'CD ~~h
B7q#d)$ 	A>>$2.DB##D&1D**40D77!     $#
  $#!	9 F4L	8 r   c                     | j                  |      | j                  |      g}|}|d   }|d   }| j                  ||      S )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
        r   r   )fetch_swap_marketsfetch_spot_marketsarray_concat)r   r  rawPromisespromisesswapMarketsspotMarketss         r   fetch_marketszhyperliquid.fetch_markets  sS     ##F+##F+
 qkqk  k::r   c           	         ddi}| j                  | j                  ||            }| 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 )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   metaAndAssetCtxsr   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{{7F'CD@ ~~h2.>>$
B7NN8Q3	q#h-( 	 A;;xB/y!R0D DNMM$	  !!&))r   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-  r.  r/  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                 0   ddi}| j                  | j                  ||            }| 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 ))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   spotMetaAndAssetCtxsr   r   r  tokensindexr1   r=   r   r   /spec
szDecimalsmidPxN   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  intrD  r6  r*  safe_market_structurer   parse_precision)"r   r  r  r  firstsecondr  rG  marketsr  marketrH  	extraData
marketNamer   r   r   	tokensPosbaseTokenPosquoteTokenPosbaseTokenInfoquoteTokenInfobaseNamerR  rO  rP  rN  innerBaseTokenInfoamountPrecisionStrr.  r-  r<  pricePrecisionStrr)  s"                                     r   r   zhyperliquid.fetch_spot_markets  s    *
 &&t{{7F'CD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 r   rg  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)  rI  T:r?   r   r   rK  markPxr      
isDelistedr0   rN  rO  rP  rQ  rR  rS  r   r=   Fr>   r@   rA   r	  rU  r   r4  rV  maxLeverager  rW  rX  )r   r   r   rY  rZ  r[  r\  r]  r  r  r^  r   )r  r  r  r   r`  ra  rD  r6  	safe_boolrb  r   rc  r_  )r   rg  rR  rO  rP  r)  rS  rQ  rN  rU  r?   r   r   r   rq  r.  r-  r<  rr  rx  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                 |   d}| j                  d|      \  }}d}| j                  dd|      \  }}d}| j                  d|      \  }}|dk(  }|rdnd}||d}| j                  | j	                  ||            }| 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 )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   rt  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  r`  r_  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{{7F'CD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  ((r   NrN  r   c           	      v   | j                          | j                  |      }d|d   r|d   n|d   d}| j                  | j                  ||            }| j	                  |dg       }| j	                  |dg       | j	                  |dg       d	}| j                  |d
      }	| j                  ||d   |	dddd      S )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
        r   r?   rO  r0   r   r  levelsr   r   )bidsasksr  rN  r  r  pxsz)load_marketsrg  r  r  r  r_  parse_order_book)
r   rN  r   r  rg  r  r  r  r  r  s
             r   fetch_order_bookzhyperliquid.fetch_order_bookX  s     	V$&,VnF6N&,
 &&t{{7F'CD. ~~h"5NN4B/NN4B/
 %%h7	$$VVH-=y&RXZ^`deer   symbolsc                    | j                          | j                  |      }g }| j                  |d      }| j                  |d      }|dk(  r| j	                  |      }n(|dk(  r| j                  |      }n| j                  |      }i }t        dt        |            D ]5  }||   }|d   }| j                  ||      }	| j                  |	d      }
|	||
<   7 | j                  |d|      S )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>`
        r   r=   r?   r   r   rN  )r  market_symbolsr  omitr   r  r&  r  r  parse_tickerfilter_by_array_tickers)r   r  r  r  r   r  r  rg  r   tickerrN  s              r   fetch_tickerszhyperliquid.fetch_tickers  s     	%%g./66*6>..v6HV^..v6H))&1Hq#h-( 	$Aa[F&>D&&tV4F%%fh7F#F6N	$ ++FHgFFr   c           	         ddi}| j                  | j                  ||            }| j                  |di       }| j                  |dg       }| j                  |dg       }g }t	        dt        |            D ]G  }	| j                  | j                  ||	i       | j                  ||	i             }
|j                  |
       I | j                  ||      S )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(  r   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{{7F'CD@ ~~h2.>>$
B7NN8Q3	q#h-( 	 A;;xB/y!R0D MM$	  ''88r   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   fundingrv  oraclePx<   r   r   r   rN  	markPrice
indexPriceinterestRateestimatedSettlePricer  r  fundingRatefundingTimestampfundingDatetimenextFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeintervalr   )	r  coin_to_market_idsafe_symbolr`  ra  mathfloormillisecondsr  )
r   r   rg  rO  marketIdrN  r  rv  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	impactPxsrN  	prevDayPxrL  r   r   	dayNtlVlm)	rN  r  r  previousCloseclosebidaskquoteVolumer   )r  safe_tickerr`  )r   r  rg  bidAsks       r   r  zhyperliquid.parse_ticker  s      4X&!--fkB%%fg6##FA.##FA.++FK@
!
 
 
	r   r   sincec                    | j                          | 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                  ||            }| j                  ||||	||      S )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
        untilNr   Fr   candleSnapshotr?   rO  r0   )r  r  	startTimeendTime)r   req)r  rg  r_  r  parse_timeframesumr  r  r   r  r  parse_ohlcvs)r   rN  	timeframer  r   r  rg  r  useTailoriginalSincetimeframeInMillisecondsr  r  s                r   fetch_ohlcvzhyperliquid.fetch_ohlcv1  s    	V$!!&'43D3D3FG4-= *.*>*>y*ID*P'(?%(G"(LM6G9-$*0.vfTl ,,T__iS" 	
 &&t{{7F'CD"   69mUT[\\r   c           	          | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS )Ntohlcv)r_  r`  )r   ohlcvrg  s      r   parse_ohlcvzhyperliquid.parse_ohlcvi  sn      eS)UC(UC(UC(UC(UC(
 	
r   c                 ^   d}| j                  d|      \  }}| j                          | j                  |      }d|i}|d|d<   ||d<   nd|d<   | j                  |d      }| j	                  |d      }|||d	<   | j                  | j                  ||            }	| j                  |	|||      S )
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_marketr_  r  r  r  parse_trades
r   rN  r  r   r  r  rg  r  r  r  s
             r   fetch_tradeszhyperliquid.fetch_trades  s      "88OV!!&)K
 /GFO#(GK )GFO!!&'267+!&GI&&t{{7F'CD*   65%@@r   c                     | j                  |      }| j                  |t        |d   d   | j                  | j                        S )Nr  r  )rg  decimal_to_precisionr'   r   paddingMode)r   rN  r  rg  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 )	Nr1  r   r3  r=   rM  rw  r  r  )rg  r6  r7  r   r  r  r'   r)   r  precision_from_stringr  r(   )
r   rN  r-  rg  r=  rC  r?  r  r/  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   r4  chainIdr1   verifyingContractr4   Agentr  stringr1   r   r  bytes32)r$  rz  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 HyperliquidSignTransactionr4  r&  )r  r   r-  r  r   )r   r1  r  r   r'  r0  r2  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r6  r   r  r1  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:UsdClassTransferr8  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:Withdrawr8  r*  r+  r9  r  r  r:  r;  r<  s      r   build_withdraw_sigzhyperliquid.build_withdraw_sig6  sF    -+X>&9!842	0
 ++L'BBr   r   sider  c           	          | j                          | j                  d||||||      \  }}| j                  |g|      }	|	d   S )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   rN  r   rD  r  r-  r  orderglobalParamsorderss
             r   create_orderzhyperliquid.create_orderA  sS    * 	"??fdTXZ`bgiop|##UG\:ayr   rJ  c                     | j                          | j                  ||      }| j                  |      }| j                  |di       }| j                  |di       }| j	                  |dg       }| j                  |d      S )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>`
        r  r  statusesN)r  create_orders_requestprivatePostExchanger  r  parse_orders)r   rJ  r  r  r  responseObjr  rM  s           r   rG  zhyperliquid.create_orders[  s}     	,,VV<++G4$ nnXz2>~~k626>>$
B7  400r   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	rS  rT  rU  rS  r   	stopPricer   r   r   rN  r   MARKETrD  BUYr  r-  iocgtcpostOnlyalor   r   rW  r   r   zy  market orders require price to calculate the max slippage price. Default slippage can be set in options(default is 5%).r4  
reduceOnlytpslisMarket	triggerPxtpslr   tifr   )
rT  rS  r   rW  r   r   r   rU  r^  r\  r)  r  r  pr  r  r  r  r   rH  na)r   rJ  groupingr   
brokerCoder  r!  r
  )check_required_credentialsr  r   r  r  r  safe_string_2r!   r0   r  r  rg  safe_string_upperrz  safe_string_lower
capitalizer+   
string_mul
string_add
string_subr  r  r;  r*  format_vault_addressr3  )&r   rJ  r  r   hasClientOrderIdr  rawOrderorderParamsrT  r!  orderReqr  rg  rN  r   rb  rD  isBuyr  r-  rS  defaultTimeInForcer\  r   r   r   r   	isTriggerr  r  r^  	orderTypeisTporderObjr   orderActionr
  r  s&                                         r   rN  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                 N    | j                  |g||      }| j                  |d      S )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>`
        r   )cancel_ordersr  )r   r0   rN  r  rJ  s        r   cancel_orderzhyperliquid.cancel_order  s+     ##RD&&9~~fa((r   idsc                 8   | j                          |t        | j                  dz         | j                          | 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#                  |      }| j%                  |d      }| j%                  |d      }| j'                  |d      }g }t        d
t        |            D ]*  }||   }|j                  | j)                  ||d             , |S )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>`
        z* cancelOrders() requires a symbol argumentrT  rU  r!  r5  r   cancelsr)  cancelByCloidr   r   )assetcloidcancel)r  r  r  r   r  r
  r  r  rM  r   status)rl  r!   r0   r  rg  safe_value_2r  r  parse_to_numeric
isinstancelistr  r  r*  rt  r  r3  rO  r  r  
safe_order)r   r  rN  r  rg  rT  r!  r  	cancelReqcancelActionr)  r  r   r
  r  innerResponser  rM  rJ  r  s                       r   r  zhyperliquid.cancel_orders  s^    	'')>#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#++G4 x<~~mV4>>$
3q#h-( 	Aa[FMM$// +  	 r   c                 H   | j                          | j                          | 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                  |      }|S )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>`
        r!  r5  r  Fr   rT  Tr0   rN  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
  )rl  r  r  r  r  r  r!   r0   r"   rg  r  r*  rt  r3  r  rO  )r   rJ  r  r!  r  r  r  r  r  rH  rT  r0   rN  assetKeyidKeyrg  	cancelObjr   r
  r  s                       r   cancel_orders_for_symbolsz%hyperliquid.cancel_orders_for_symbolsQ  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#++G4 r   timeoutc                 v   | j                          | j                          | j                  |ddg      }| j                         }d|i}d||z   d}| j	                  | j                  |d            }| j                  |||      }||d<   ||d<   || j                  |d      }||d<   | j                  |      }|S )	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
        rT  rU  r!  scheduleCancel)r   r  r   r  r
  )rl  r  r  r  rt  r  r3  rO  )	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#++G4 r   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  rT  rU  TzT editOrders() all orders must have clientOrderId if at least one has a clientOrderIdrV  r0   rN  r   rX  rD  rY  r  r-  r   rS  rZ  r[  r\  r]  r   r   rW  r   r   r^  )	rS  r   r   r   r   rT  rU  r\  r^  r4  r_  r`  ra  r   re  r   r2  r)  rf  r  )oidrH  batchModify)r   modifiesr   rk  )rl  r  r  r  rm  r!   r0   r  r  rg  rn  r   rz  ro  rp  r6  r+   rq  rr  rs  r  r  r;  r*  r  rt  r3  )(r   rJ  r  ru  r  rv  rw  rT  r  r0   r  rg  rN  r   rb  rD  ry  r  r-  r   rS  rz  r\  r   r   r   r   r{  r^  r  r  r|  r}  rx  	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           	          | j                          |t        | j                  dz         | j                  |||||||      \  }}	| j	                  |g|	      }
|
d   S )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>`
        z$ editOrder() requires an id argumentr   )r  r!   r0   rF  edit_orders)r   r0   rN  r   rD  r  r-  r  rH  rI  rJ  s              r   
edit_orderzhyperliquid.edit_order#  sm    * 	:#DGG.T$TUU"??FDRVX^`egmn|!!5'<8ayr   c                     | j                          | j                  ||      }| j                  |      }| j                  |di       }| j                  |di       }| j	                  |dg       }| j                  |      S )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>`
        r  r  rM  )r  r  rO  r  r  rP  )r   rJ  r  r  r  responseObject
dataObjectrM  s           r   r  zhyperliquid.edit_orders?  s|     	**66:++G4H *bA^^NFB?
>>*j"=  **r   r1   description
initialUsdc                 `   | j                          | j                          | j                         }d|i}| j                  t	        j
                  | j                  |      d            }d||||d}| j                  ||      }	||d<   |	|d<   | j                  | j                  ||            }
|
S )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
        r!  1000000createVault)r   r1   r  r  r!  r  r
  )
rl  r  r  r;  r+   rq  r6  r3  rO  r  )r   r1   r  r  r  r!  r  usdr  r
  r  s              r   create_vaultzhyperliquid.create_vaultt  s     	'')!!#U
  2 243H3H3TV_ `a!&
 ''6	"(++DKK,HI r   c           
         | j                          |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                  ||            }	g }
t        dt        |	            D ]_  }|	|   }| j                  |d      }|
j                  || j                  d|      | j                  |d      || j                  |      d       a | j                  |
d      }| j!                  ||||      S )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fundingHistoryrO  r  r  i  r  r   r  r  r   r  r  )r   rN  r  r  r  r  )r  r!   r0   rg  r  r_  r  r  r  r  r  r*  r  r`  r  sort_byfilter_by_symbol_since_limit)r   rN  r  r   r  rg  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{{7F'CD q#h-( 		AQKE))%8IMM**48#//}E& LL3 		 fk200NNr   c                    d}| j                  d|      \  }}d}| j                  |ddd      \  }}| j                          | j                  |      }||d}| j	                  | j                  ||            }	g }
t        dt        |	            D ]A  }|	|   }i }| j                  |d      d|d	<   |
j                  | j                  ||             C | j                  |
|||      S )
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*  rP  )r   rN  r  r   r  r  r  rg  r  r  orderWithStatusr  rH  extendOrders                 r   fetch_open_orderszhyperliquid.fetch_open_orders  s	    "889JFSV66v?PRZ\pq!!&)
 &&t{{7F'CD q#h-( 	DAQKEKx08,2L)""4;;uk#BC	D   &%GGr   c                     | j                          | j                  |dd|      }| j                  |ddgd      }| j                  ||||      S )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   rN  r  r   r  rJ  closedOrderss          r   fetch_closed_orderszhyperliquid.fetch_closed_orders   sU     	""64v>++FHxj%P00vueTTr   c                     | j                          | j                  |dd|      }| j                  |ddgd      }| j                  ||||      S )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  sU     	""64v>++FHzlER00vueTTr   c                     | j                          | j                  |dd|      }| j                  |dg dd      }| j                  ||||      S )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  sU     	""64v>++FH>`bgh00vueTTr   c                     d}| j                  d|      \  }}| j                          | j                  |      }d|d}| j                  | j	                  ||            }| j                  ||||      S )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  rP  )	r   rN  r  r   r  r  rg  r  r  s	            r   r  zhyperliquid.fetch_orders-  s     "88OV!!&)&
 &&t{{7F'CD   65%@@r   c                 J   d}| j                  d|      \  }}| j                          | j                  |      }t        |      dk\  }d|r|n| j	                  |      |d}| j                  | j                  ||            }| j                  |d      }	| j                  |	|      S )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~  rH  )	r  r  r  r  r  r  r  r  parse_order)
r   r0   rN  r  r  rg  isClientOrderIdr  r  r  s
             r   fetch_orderzhyperliquid.fetch_orderO  s     "88vNV!!&)b'R-!(2d.C.CB.G

 &&t{{7F'CD8 ~~h0f--r   rH  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  )rH  restingfilledr  r0   rN  r  r  r  rD  AsellbuyorigSztotalSzr  re  ALOr   r  rT  r  r  lastTradeTimestamplastUpdateTimestampstatusTimestampr   r|  r   r\  r^  r-  limitPxr   r{  rc  r  r   avgPx)averager  	remainingr  r  trades)r  r  safe_dict_nr  r  r_  rm  r  rn  r  parse_order_typero  rz  r`  r+   rs  parse_order_status)r   rH  rg  r  r  r  r  rN  r  r  rD  totalAmountr  re  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  rM  s      r   r  zhyperliquid.parse_order_status	  s2    ""(
 &&99r   c                 2    ddd}| j                  |||      S )Nr   rg  )z
stop limitzstop marketr  r  s      r   r  zhyperliquid.parse_order_type'	  s&    !#
 &&99r   c                 ^   d}| j                  d|      \  }}| j                          | j                  |      }d|i}|d|d<   ||d<   nd|d<   | j                  |d      }| j	                  |d      }|||d	<   | j                  | j                  ||            }	| j                  |	|||      S )
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{{7F'CD,   65%@@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  rN  tidrD  r  r  r  r  crossedr   r   r  feeToken)r   currencyrate)r   r  r  rN  r0   rH  r   rD  takerOrMakerr-  r  r   r  )r_  r  r  r  rz  
safe_trader  )r   r  rg  r  r-  r  r  r  rN  r0   rD  r  r  r  s                 r   parse_tradezhyperliquid.parse_traded	  sU   & %%eV4	  -!!%.v.))$/!!(D1!eU+v."ck6Due,..	2&-77L"Y/%%eU3( ,,UJ? 
$ % 	r   c                 N    | j                  |g|      }| j                  |di       S )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>`
        r   )fetch_positionsr  )r   rN  r  	positionss       r   fetch_positionzhyperliquid.fetch_position	  s+     ((&6:	~~iB//r   c                    | j                          d}| j                  d|      \  }}| j                  |      }d|d}| j                  | j	                  ||            }| j                  |dg       }g }t        dt        |            D ]&  }|j                  | j                  ||   d             ( | j                  |d|d      S )	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   rN  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{{7F'CD\ ~~h(8"=q#d)$ 	>AMM$--d1gt<=	>--fhOOr   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  rN  r   r   r  szir2  longshortunrealizedPnl
marginUsed100r   r0   r  r  r   rD  	contractsrY  
entryPriceentryPxr  notionalpositionValuevalue
collateralinitialMarginmaintenanceMarginliquidationPx)initialMarginPercentagemaintenanceMarginPercentager  liquidationPricer   
percentage)r  r  r  r  r+   r9  
string_absrq  
string_divsafe_positionr   r`  )r   r  rg  r  r  r  rN  r   r   
isIsolatedrawSizesizerD  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                 N   |t        | j                  dz         | j                          | 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                  |      }|S )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
        z+ setMarginMode() requires a symbol argumentr   z. setMarginMode() requires a leverage parameterr)  crossupdateLeverager   r  isCrossr   r   r  r5  rk  )r!   r0   r  rg  r_  r;  r  r  r  
startswithreplacer3  rO  )r   r   rN  r  rg  r   r  r*  r!  updateActionr   r
  r  r  s                 r   set_margin_modezhyperliquid.set_margin_mode7
  sN    >#DGG.[$[\\V$$$VZ8#DGG.^$^__!!&"23(!!#6J<0$ 	
 ''?#YYv~6F&&t,+33D"=''e\J	""
 #&2GN#++G4 r   r   c                    |t        | j                  dz         | j                          | j                  |      }| j	                  |dd      }|dk(  }| j                  |d         }| j                         }| j                  |d      }d|||d}	| j                  | j	                  |d            }
| j                  |	||
      }|	||d}|
| j                  |d      }|
|d<   | j                  |      }|S )	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
        z) setLeverage() requires a symbol argumentr   r'  r)  r(  r)  r   rk  )r!   r0   r  rg  r  r;  r  r  rt  r3  rO  )r   r   rN  r  rg  r   r*  r  r!  r-  r   r
  r  r  s                 r   set_leveragezhyperliquid.set_leveragej
  s    >#DGG.Y$YZZV$%%flGD
(!!&"23!!#6<0$ 	
 001A1A&.1YZ''e\J	""
 #YYv~6F&2GN#++G4 r   c                 *    | j                  ||d|      S )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>`
        addmodify_margin_helperr   rN  r  r  s       r   
add_marginzhyperliquid.add_margin
  s     ((GGr   c                 *    | j                  ||d|      S )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>`
        reducer3  r5  s       r   reduce_marginzhyperliquid.reduce_margin
  s     ((6JJr   c                 D   | j                          | j                  |      }| j                  |d         }| j                  t        j                  | j                  ||      d            }|dk(  r| }| j                         }d|d|d}	| j                  | j                  |d            }
| j                  |	||
      }|	||d}|
| j                  |d      }|
|d<   | j                  |      }| j                  | j                  ||      d	| j                  |d
      i      S )Nr)  r  r8  updateIsolatedMarginT)r   r  ry  ntlir   rk  r  r  )r  rg  r;  r+   rq  r  r  rt  r  r3  r  rO  r  parse_margin_modification)r   rN  r  r   r  rg  r  r  r!  r-  r   r
  r  r  s                 r   r4  z hyperliquid.modify_margin_helper
  s<   V$!!&"23w11$2J2J6SY2Z\efg8B!!#*	
 001A1A&.1YZ''e\J	""
 #YYv~6F&2GN#++G4 {{499(FKD$$Xx8N
  	r   r  c                 \    || j                  d |      d dd d | j                  |d      d d d d
S )Nr  rQ  )
r   rN  r   r   r  r  r  r  r  r  )r  r  )r   r  rg  s      r   r=  z%hyperliquid.parse_margin_modification
  sF     &&tV4$$$VX6
 	
r   r  fromAccount	toAccountc                    | j                          | j                          | 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                  |      }|S | j                  |       |-|j                         }|dk7  rt        | j                  dz         |rdnd	|| j                  |      |d}| j!                  |      }|d   d|t#        |      |dd||d}| j                  |      }| j%                  |      S )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>`
        r   )r=   r?   perpz. transfer() only support spot <> swap transferr   z subaccount:rB  r?   TestnetMainnet)r8  r  r?  r!  r8  0x66eeeusdClassTransfer)r8  signatureChainIdr   r  r?  r!  rk  rt  z transfer() only support USDCr8  r9  r  r  usdSendr8  rG  r9  r  r  r   )rl  r  rz  r   r  in_arrayr&   r0   r6  rt  r  r  rA  rO  check_addressupperr=  strparse_transfer)r   r  r  r?  r@  r  isSandboxModer!  	strAmountr   r?  transferPayloadtransferSigtransferRequesttransferResponsepayloadsigr  r  s                      r   r   zhyperliquid.transfer
  s    	'')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>/#77H##9%::<Dv~"477-L#LMM-:		$++F3	
 %%g. %,,>$?$-(f+! 
 ++G4 ""8,,r   r   r  c           
          |d d d d d d d dd	S )Nok)	r   r0   r  r  r  r  r?  r@  r  r  )r   r   r  s      r   rO  zhyperliquid.parse_transfer=  s)    
 

 
	
r   addressc                    | j                          | j                          | 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                  |      }| j!                  |      S )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>`
        Nrt  z withdraw() only support USDCr   vaultTransferr  F)r   r   	isDepositr  r   rC  rD  rH  r8  rE  	withdraw3rJ  rk  )rl  r  rL  rM  r&   r0   rt  r  r  r  r3  rz  r   rN  rC  rO  parse_transaction)r   r  r  rZ  tagr  r   r!  r  rW  rP  rV  r  r  s                 r   r   zhyperliquid.withdrawM  si    	'')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 

 ++G4%%h//r   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  rt  r  r   r   internalTransferr   r0   txidr   r  r  networkrZ  	addressTor9  addressFromr~  r`  tagTotagFromr  usdcr  r  updated)commentinternalr  )r_  r  r  r  r`  )	r   ra  r  r  rc  r  feeCostro  r   s	            r   r_  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                 ,   | j                          d}| j                  d|      \  }}| j                  |      }d|d}| j                  | j	                  ||            }| j                  |d      | j                  |d      d}| j                  ||      S )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)rs  rt  )r  r  rg  r  r  r  parse_trading_fee)r   rN  r  r  rg  r  r  r  s           r   fetch_trading_feezhyperliquid.fetch_trading_fee  s     	"889JFSVV$
 &&t{{7F'CDJ "--hH++HmD
 %%dF33r   r  c                 x    | j                  d |      }||| j                  |d      | j                  |d      d d dS )Nrt  rs  )r   rN  r   r   r  	tierBased)r  r`  )r   r  rg  rN  s       r   ru  zhyperliquid.parse_trading_fee  sM    H !!$/%%c=9%%c?;
 	
r   c                 *   | j                          d}| j                  d|      \  }}d|d}|||d<   | j                  |d      }|||d<   | j                  |dg      }| j	                  | j                  ||            }| j                  |d||      S )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  r_  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{{7F'CD   4>>r   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  rc  r  rt  rd  r   rl  r   r~  )r   r0   	directionr  referenceAccountreferenceIdr   r  r  r  r  beforeafterr  r  )r_  r  r  safe_ledger_entryparse_ledger_entry_typer   r  )	r   r}  r  r  rc  r  rp  r   r  s	            r   parse_ledger_entryzhyperliquid.parse_ledger_entryK  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   )re  accountClassTransferr  )r   r   
ledgerTypes      r   r  z#hyperliquid.parse_ledger_entry_typet  s&     *$.

 
D$77r   c                 v   | j                          d}| j                  d|      \  }}d|d}|||d<   | j                  |d      }|||d<   | j                  |dg      }| j	                  | j                  ||            }| j                  |      }	| j                  |	dd	gd
      }
| j                  |
d||      S )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fetchDepositsWithdrawalsrz  r}  r  r  r  r   r
  F	r  r  r_  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{{7F'CD ..x8'')eL&&xueDDr   c                 v   | j                          d}| j                  d|      \  }}d|d}|||d<   | j                  |d      }|||d<   | j                  |dg      }| j	                  | j                  ||            }| j                  |      }	| j                  |	dd	gd
      }
| j                  |
d||      S )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  rz  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{{7F'CD ..x8**7FZL%P&&{D%GGr   c                     | j                          | j                  |      }| j                         }| j                  ||      S )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:
        )r  r  r  parse_open_interests)r   r  r  r$  s       r   fetch_open_interestsz hyperliquid.fetch_open_interests  sA     	%%g.--/((g>>r   c                 t    | j                  |      }| j                          | j                  |g|      }||   S )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>`
        )rN  r  r  )r   rN  r  oiss       r   fetch_open_interestzhyperliquid.fetch_open_interest  s<     V$''&96{r   c           	          | j                  |di       }| j                  |d      }d }|| j                  |      }| j                  | j	                  |      | j                  |d      d d d |d|      S )Nr   r1   openInterest)rN  openInterestAmountopenInterestValuer  r  r   )r  r  r  safe_open_interestr  r`  )r   interestrg  r  r  s        r   parse_open_interestzhyperliquid.parse_open_interest  s    & >>(FB7&1--d3H&&&&x0"&"2"28^"L!%(
  	r   c                 R   | j                          d}|| j                  |      }d}| j                  d|      \  }}|dd}|||d<   | j                  |d      }| j	                  |d      }|||d<   | j                  | j                  ||            }	| j                  |	|||      S )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  rg  r  r_  r  r  r  parse_incomes)
r   rN  r  r   r  rg  r  r  r  r  s
             r   fetch_funding_historyz!hyperliquid.fetch_funding_history  s     	[[(F"889NPVWV!
 #(GK !!&'267+!&GI&&t{{7F'CD" !!(FE5AAr   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  rc  r  
/USDC:USDCrN  rl  rt  r  )r   rN  r  r  r  r0   r  r  )r  r_  r  r  r  r`  r  r   )r   incomerg  r0   r  rc  r)  marketSymbolrN  r  r  r  s               r   parse_incomezhyperliquid.parse_income2  s     ff-%%ff5	vw/!!%0,!!,/!!!%0&&v.}5"Y/''/	
 		
r   c                     g }t        dt        |            D ]#  }||   }|d   d   |d<   |j                  |       % |S )Nr   rc  r   )r  r  r*  )r   r  r  r  records        r   r  z#hyperliquid.extract_type_from_deltaV  sO    q#d)$ 	#A!WF#G_V4F6NNN6"	# r   c                 R    |y |j                  d      r|j                  dd      S |S )Nr  r5  )r+  r,  )r   rZ  s     r   rt  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~  rZ  r5   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_addresse  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 )NrI  r  @r  )find)r   r  s     r   r  zhyperliquid.coin_to_market_idp  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  r5  r  errr  r  rM  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  rM  firstStatusfeedbacknonEmptyMessages                      r   handle_errorszhyperliquid.handle_errorsu  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   rI  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   rN  )rN  r   rD  r  r-  r  r0   )rg  r  r  )r   r0   rN  r   rD  r  r-  r  rg  r   rH  rI  s               r   rF  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  floatrD  r   dictr{  r   r  rN  r	   r   r  r   r   r  r   r  r   r  r   r  r  r  r  r   r  r  r  r  r  r  r  r$  objectr3  r6  r=  rA  rC  r   r   r   rK  r   rG  rN  r  r  r   r  r  r  r  r  ra  r  r  r   r  r  r  r  r  r  r  r  r  r  r   r  r  r   r  r  r.  r0  r   r6  r9  r4  r=  r   r   r   rO  r   r   r_  r   rv  ru  r
   r|  r  r  r  r  r  r  r  r  r  r  rt  r  r  r  r  r  rF  __classcell__)r   s   @r   r-   r-      s	   p# pd	. ') 9Z 9v $& ;$v, ;& )+ 7*tF| 7*r(1u (1u (1[` (1T )+ VtF| Vpa4 aF aF $& Y)( Y)v :>b .fs .f3 .fY .f` 04B  GW  G7  GD 6:" 797 79 79r/
v /
 /
b4  6 : 26DW[df 6]# 6]c 6]QT 6]koptku 6]p
 
4 
0 6:UW 5A3 5As 5A# 5An}k k k:
L

J* *X	C	C	C gksu 3 i y RW `c 4 @B !1D$6 !1F 46 n$ n` 37r )s )C )" ;?r Pc PC Pd SU B5H0I BH <> "s "H 24 hT TXfjsu S # S  S `c 8 >@ 3+$|"4 3+j QS $ $3 $C $L 8<$]ajl 5O 5OC 5OWZ 5On /3TXac -H -H3 -Hc -Hhlmrhs -H^ 154VZce U# US UPS Ujnotju U 37TX\eg UC Us URU Ulpqvlw U >BPTcgpr Us U# U]` Uw{  }B  xC U *.Dt\^  A3  Ac  A  Acghmcn  AD 26b 3.c 3.3 3.jV Vv V Vp	: 	:: -1tRV_a 4Ac 4A 4AC 4Al5 5v 5 5n 24 0S 0 26b EPw EPT(^ EPNEt EV EN >B" 1# 1s 1f 9=R ,S ,# ,\ =? H He HCU H @B KC K KFX K FH $3 $L^ $L
d 
F 
N` 
& [] P-S P-% P-c P-c P-an P-d
t 
x 
= 
  DHPR :0S :0% :0# :0Wb :0x1
T 1
X 1
Q\ 1
f 57 84 84;N 84t,
T ,
6 ,
EX ,
\ (,$TZ\ %? %?C %?s %?aefqar %?N't 'x '; 'R8 *.Dt\^ 'E3 'Ec 'E 'ER -1tRV_a 'Hc 'H 'HC 'Hfjkvfw 'HR 7;2 
?G 
? 79 
# 
F B 37TX\eg *BC *Bs *BRU *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-   )2ccxt.base.exchanger   ccxt.abstract.hyperliquidr   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     sq    ( 1  z  z  z  z  z  z  z  * . ' . ) * ) 0 9 = 4 %`6%(K `6%r   