
    ei                    `   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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 d dl1m2Z2  G d dee          Z3dS )    )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MarketInterfaceTransferEntry)List)ExchangeError)ArgumentsRequired)
BadRequest)InsufficientFunds)InvalidOrder)OrderNotFound)NotSupported)RateLimitExceeded)ROUND)DECIMAL_PLACES)SIGNIFICANT_DIGITS)	TICK_SIZE)Precisec                       e Zd Zdef fdZ fdZdedef fdZi fdZ	i 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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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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+Z0dd,Z1dde2fd-Z3d. Z4d/ Z5d0 Z6d1 Z7d2 Z8d3 Z9d4 Z:d5 Z;d6ed7efd8Z<d9 Z=d: Z>dd;i fd<ed=e)fd>Z?i fd?efd@Z@i fdAeAfdBZBi fd?efdCZCdi fdedDeDdEeEdFedeFf
dGZGi fdedEeEdFedHedeHf
dIZIi fdJeeJ         fdKZKdi fdedDeDdEeEdFede)f
dLZLi fdefdMZMdi fdNede)fdOZNdi fdPee         de)fdQZOdi fdNede)fdRZPdi fdPee         de)defdSZQi fdJeeR         fdTZSi fdUefdVZTi fdWZUddi fdNededDedEedFeFdeFfdXZVi fdJeeJ         fdYZWi fdZed[ed\eXfd]ZYdddi fde)d!edefd^ZZd_ Z[dddi fde)d!ededeeH         fd`Z\dddi fde)d!ededeeH         fdaZ]dddi fde)d!ededeeH         fdbZ^dddi fde)d!ededeeH         fdcZ_dddi fde)d!ededeeH         fddZ`di fdNede)fdeZaddfededeHfdgZbdhe)fdiZcdj Zddddi fde)d!edefdkZeddlededeffdmZgi fdefdnZhddoedefdpZidi fdedeej         fdqZkddredefdsZldi fdtede)fduZmdi fdveXde)fdwZni fdedFedeofdxZpi fdedFedeofdyZqi fdedeofdzZrdd{ededeofd|Zsi fdedFed}ed~edetf
dZuddedevdetfdZwdi fdedFed=ede)dexf
dZyddedevdexfdZzi fdede{fdZ|ddedede{fdZ}dddi fde)d!ededee~         fdZddedevde~fdZd Zdddi fde)d!edefdZdddi fde)d!ededeex         fdZdi fdefdZi fdefdZddefdZdddi fde)d!edefdZddefdZi fdeFdefdZi fdZefdZg fdZdd=e)fdZdoedefdZde)fdZdeXdeded<ededefdZddi ddfdZi fdZdi fdNe)dedDeDdEeEdFedeFfdZ xZS )hyperliquidreturnc                    |                      t          t          |                                           i dddddg dddd	d
ddddddi dd ddddddddddddddddddddddddddddddd di d!dd"dd#dd$dd%dd&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0dd1di d2dd3dd4dd5dd6dd7dd8dd9d:d;dd<dd=dd>dd?dd@ddAddBddCdi dDddEddFddGd dHddIddJddKddLddMddNddOddPddQddRddSddTdi dUddVddWddXddYddZdd[dd\d:d]dd^dd_dd`ddaddbddcdddddedddddddddddf	dgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d{d|d}d}d|d~dddddddddddddddddiidddiid|d|                     d          |                     d          d|                     d          |                     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          dt
          t          t          dddt          i ddddddgddddddddddddddg ddg 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Ĝ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֜dd؜          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$createOrderWithTakeProfitAndStopLoss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fetchStatusfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTransferfetchTransfersfetchWithdrawalfetchWithdrawals)	reduceMarginrepayCrossMarginrepayIsolatedMarginsandboxsetLeveragesetMarginModesetPositionModetransferwithdraw
timeframes1m3m5m15m30m1h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candleSnapshot)costbyTypeexchange   r   z0.00045z0.00015)takermakerz0.0007z0.0004)rA   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 transferzBTWAP order value too small. Min is $1200, which is $10 per minute.)z3TWAP was never placed, already canceled, or filled.z!Too many cumulative requests sent)exactbroadprecisionModeg?hip3TokensByNamecachedCurrenciesById*0x00000000000000000000000000000000000000002ZBONKBTCETHFARTCOINPENGUPUMPSOLSPXUSDTXAUTXPL)UDZUBONKUBTCUETHUFARTHPENGUUPUMPUSOLUUUSPXUSDT0XAUT0UXPL)r?   rA   hip3
   )limitdexes)typesr   )defaultTypesandboxMode
builderFeedefaultSlippagemarketHelperPropszeroAddressspotCurrencyMappingrw   )lastmarkindex)triggerPriceTypetriggerPricetypeprice)IOCFOKPOGTD)
marginModer   r   triggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingleveragemarketBuyByCostmarketBuyRequiresPriceselfTradePreventionicebergmax  i  )r  r   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   rQ   rR   rz   r   r   r   r`   r{   extendsdefault)r  r  r  )r  rQ   forPerps)linearinverse)r  r?   r  rA   rB   g        )commonCurrenciesoptionsfeaturesrollingWindowSize)
deep_extendsuperr/   describeparse_numberr%   r$   r&   r(   r,   )self	__class__s    N/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/hyperliquid.pyr#  zhyperliquid.describe   s
   k4 8 8 A A C C WF
-WF
MWF
 WF
 t	WF

 WF
 WF
 4WF
 4WF
  ___ %_ 	_
 $_ %_ T_ $U_ '_ "5_ '_ t_ _ )$_ $U_   !_" /#_ _$ ,U%_& 0'_( t)_* +_, 7-_. (/_0 "41_2 %d3_4 T5_6 d7_8  9_: ;_< &u=_> +E?_@ )%A_B /C_D &tE_ _ _F $TG_H 'I_J (K_L "4M_N &uO_P (Q_R  S_T *:U_V +EW_X &tY_Z #E[_\ *4]_^ $T__` "5a_b *5c_d +Ee_f tg_ _ _h  i_j %ek_l $Um_n "4o_p +Eq_r s_t !%u_v &uw_x  y_z d{_| $T}_~ +E_@ %dA_B "4C_D dE_F !$G_H tI_ _ _J #EK_L  M_N $UO_P !$Q_R %eS_T )%U_V tW_X zY_Z [_\ T]_^ t__` "4a_b #Ec_d  e_f !%g_h "5i_j #Dk_ _l !%$)',#!%#(  }_ _ _WF
R  SWF
r )sWF
t k67 
 DD  1[V: uWF
R $&*++,67/0:;2323' '! !" "A# SWF
@ !..y99!..y99 
 "..x88!..x88 	 	AWF
T "!%"	$ $UWF
` ;\:L :;L A,	
 F| TUa +L ? KM *< -l XYe +L 67H :;L  >?P!" YZf#$ LY9J'   aWF
R YSWF
T!  &$"#'&8:P%QK  #!!'%#!###!( ( 655!#!# ! !- @  $&+(-,0,1).+0 ).(-).1 1
 -1$(%)	7 	7 $(#("&#(	( ( #($)$)+027/4#(;$ $@ t% ',!%$(%)*.& & ',#($)*.	# # ',!%#($)*.( ( ',!%$(%)#($)*.$ $ ',!%$(,0%)#($)*.	* 	*  #WN N` y  ))-+/6:$ $  ": ": 	  ": ": 	 Gk kX "%m
WF
 WF
 WF
 W W W	    c                 l    t          t          |                               |           || j        d<   d S )Nr   )r"  r/   set_sandbox_moder  )r%  enabledr&  s     r'  r*  zhyperliquid.set_sandbox_modev  s3    k4  11':::&-]###r(  symbolc                    | j         t          | j        dz             ||| j         vr|                    d          }|                     |d          }|                     | j        di           }||v r]|                     ||          }|                     |d          }|                     |          dz   |z   }|| j         v r| j         |         S t          t          |           
                    |          S )Nz markets not loaded/r   r   r   )marketsr!   r2   splitsafe_string	safe_dictr  safe_currency_coder"  r/   market)	r%  r,  symbolPartsbaseNamer   unifiedBaseNamequote	newSymbolr&  s	           r'  r4  zhyperliquid.marketz  s    <*? ?@@@4<)?)? ,,s++K''Q77H"&..?TVX"Y"Y..."&"2"23F"Q"Q((a88 33ODDsJUR	,,<	22[$''..v666r(  c                     ddi}|                      |                     ||                    }|                     |d          }|dnd|                     |d          dd|dS )	a  
        the latest known information on the availability of the exchange API
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/?id=exchange-status-structure>`
        r   r   specialStatusesNokmaintenancetime)statusupdatedetaurlr   )publicPostInfoextendr1  safe_integer)r%  paramsrequestresponser?  s        r'  fetch_statuszhyperliquid.fetch_status  s     $
 &&t{{7F'C'CDD !!(,=>>%~ddM((6::
 
 	
r(  c                     ddi}|                      |                     ||                    }|                     |d          S )a  
        fetches the current integer timestamp in milliseconds from the exchange server
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        r   r   r>  )rC  rD  rE  )r%  rF  rG  rH  s       r'  
fetch_timezhyperliquid.fetch_time  sL     $
 &&t{{7F'C'CDD   6222r(  c                    |                      d          r|                                  ddi}|                     |                     ||                    }|                     |dg           }i | j        d<   i }t          dt          |                    D ]m}|                     ||i           }| 	                    |d          }| 	                    |d          }	| 
                    |	          }
|	| j        d         |<   |                     ||	|
|                     | 	                    |d	                    |d
d
d
d
d
dd
d
dd
d
ddd          ||
<   | 	                    |d          }||	|                    d          o|	                    d          }|rg|	                    d          }d}t          dt          |                    D ]}|||         z   }| 
                    |          }|| j        d         |
<   o|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
        Fr   spotMetatokensr   r   r   r3   weiDecimalsNcryptominr  )amountr   )r2   r3   code	precisionr   activedepositr   networksfeer   limitsfullNamezUnit U r   )check_required_credentialsinitialize_clientrC  rD  	safe_listr  rangelenr2  r1  r3  safe_currency_structureparse_precision
startswithr0  )r%  rF  rG  rH  rN  resultidatar2   r3   rT  r[  	isWrappedpartsnameWithoutUjbaseCodes                    r'  fetch_currencieszhyperliquid.fetch_currencies  sX    **511 	%""$$$ J
 &&t{{7F'C'CDD  (B77/1+,q#f++&& (	I (	IA>>&!R00D!!$00B##D&11D**400D7;DL/0477!11$2B2B42W2WXX     $# 
  $#! !	 	9 9  F4L0 ''j99H#(8$//88QT__S=Q=Q	 I JJsOOE#%L"1c%jj11 ? ?'3eAh'>#66|DDH@HDL!67=r(  c                 V   |                      | j        di           }|                     |d          }g }t          dt	          |                    D ]}||         }|dk    r)|                    |                     |                     9|dk    r)|                    |                     |                     h|dk    r(|                    |                     |                     |}g }t          dt	          |                    D ]}| 	                    |||                   }|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
        rw   r   r   rA   r?   r   )
r2  r  r`  ra  rb  appendfetch_swap_marketsfetch_spot_marketsfetch_hip3_marketsarray_concat)	r%  rF  r  r   rawPromisesrg  
marketTypepromisesrf  s	            r'  fetch_marketszhyperliquid.fetch_markets  s4    ..~rBBw00q#e**%% 	D 	DAqJV##""4#:#:6#B#BCCCCv%%""4#:#:6#B#BCCCCv%%""4#:#:6#B#BCCCq#h--(( 	< 	<A&&vx{;;FFr(  c           
         |                      ddi          }i }t          dt          |                    D ]3}||         }|dz
  dz  }|                     d|          }|||d         <   4g }|                     | j        di           }	|                     |	di           }
|                     |
d	g           }|                     |
d
d          }t          |          }|dk    r	|dk    r|}not          |          }t          d|          D ]O}||k    r nF|                     ||i           }|$|                     |d          }|	                    |           Pg }t          dt          |                    D ]W}d|                     ||          d}|	                    |                      | 
                    ||                               X|}i | j        d<   g }t          dt          |                    D ]}||         }||         }||         }|                     |di           }|                     |d          }|                     |dg           }|                     |dg           }g }t          dt          |                    D ]}| 
                    |                     ||i           |                     ||i                     }|                     ||          |d<   ||d<   d|d<   ||d<   |                     | j        di           }||v rm|                     |d          }|                     ||          }||d<   |                     |          }||                    dd          d| j        d         |<   |	                    |           |                     ||                     |                    }|S )a  
        retrieves data on all hip3 markets for hyperliquid

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-all-perpetual-dexs
        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   perpDexsr   '  i r3   rw   r   r   r   r   r   NmetaAndAssetCtxs)r   r<   r   collateralTokenuniversebaseIdTr<   r   collateralTokenName:-)r8  rT  )rC  ra  rb  sumr2  r  r`  rE  r1  rp  rD  r3  replacert  parse_markets) r%  rF  
fetchDexesperpDexesOffsetrg  r<   
secondPartoffsetfetchDexesListr  r   dexesProvidedmaxLimituserProvidedDexesLengthfetchDexesLengthdexNameru  rG  rw  r/  rH  metar}  r~  	assetCtxsrf  rl  rh  cachedCurrenciesr3   collateralTokenCodesafeCodes                                    r'  rs  zhyperliquid.fetch_hip3_markets  s*    ((J*
  
* !#q#j//** 	2 	2AQ-Ca%5JXXfj11F+1OCK((..~rBB~~gvr22tWb99$$T7B77"%m"4"4"Q&&&**!.":1h'' / /(((EnnZB77;**377%%g....q#n--.. 	R 	RA*'':: G t224;;w3O3OPPQQQQ+-'(q#h--(( !	M !	MA$Q'G$W-F{H>>(Ar22D"..t5FGGO~~dJ;;HxB77IF 1c(mm,, $ ${{NN8Q33NN9a44  "&!V!4!4X*9&'#V%U#'>>$,@VXZ#[#[ "&666++D&99D*.*:*:;K_*]*]'2ED./#66t<<H!4 ( 0 0c : :> >DL!34T: d####''1C1CF1K1KLLGG@ r(  c           	         ddi}|                      |                     ||                    }|                     |di           }|                     |dg           }|                     |dg           }g }t	          dt          |                    D ]\}|                     |                     ||i           |                     ||i                     }	||	d<   |                    |	           ]|                     |          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   r|  r   r~  r   r  )rC  rD  r2  r`  ra  rb  rp  r  )
r%  rF  rG  rH  r  r~  r  rf  rg  rh  s
             r'  rq  zhyperliquid.fetch_swap_markets  s    &
 &&t{{7F'C'CDD@ ~~h2..>>$
B77NN8Q33	q#h--(( 	  	 A;;xB//y!R00 D DNMM$!!&)))r(  r   amountPrecisionmaxDecimalsc                    d}|                      |          }|dS |                    d          }t          j        |d          rd}d}t	          ||z
  ||z
            }nt          j        |d          rt          j        |d          rwd}|                     |dd          }	d}
|
t          |	          k    r0|	|
         dk    r$|
dz   }
|
t          |	          k    r|	|
         dk    $|
|z   }t	          ||z
  |          }nW|                     |dd          }t          dt          |                    }t	          ||z
  |t          |          z
            }| 
                    |          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   N.0   1r   r]  )number_to_stringr0  r-   	string_eqrR  	string_gt	string_ltr1  rb  r  parse_to_int)r%  r   r  r  pricePrecisionpriceStrpriceSplittedsignificantDigitsintegerDigitsdecimalPartleadingZerosintegerParts               r'  calculate_price_precisionz%hyperliquid.calculate_price_precision  s    ((//1 s++Xs++ 	f !M !>@QTa@abbNNx-- 	f'2CHc2R2R 	f !**=!R@@KL3{#3#333+l:SWZ:Z:Z+a/  3{#3#333+l:SWZ:Z:Z *,==N !>OONN **=!R@@K #As;'7'7 8 8 !>@QTWXcTdTd@deeN  000r(  c                     ddi}|                      |                     ||                    }|                     |di           }|                     |dg           }|                     |dg           }|                     |dg           }g }t	          dt          |                    D ]S}	|                     ||	i           }
|                     |
d          }|                     ||i           }|                     |
d          }|                     | j        d	i           }| 	                    |d
          }| 	                    |d          }|                     |
dg           }|                     |d          }|                     |d          }|                     ||i           }|                     ||i           }|                     |d          }|                     |d          }||H|                     | j
        di           }|                     |||          }|                     |||          }|                     |          }|                     |          }|dz   |z   }|                     |d|          }|                     |d          }t          |          } | 	                    |d          }!d}"|!|                     |!| d          }"|                     |"          }#|                     |dz             }$i d|d|d|d|ddd|$d|d|dddd	d	dddddd d!d"d!d#d!d$dd!dd||ddddd|                     |                     |                    |                     |                     |#                    d%ddd&ddd&ddd&|                     d'          dd&d(d|                     ||
          d)}%|                    |                     |%                     U|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~  rN  r   r3   r?   r   r   Nr   r.  spec
szDecimalsmidPx   r{  r2   r,  baser8  settler  r6  quoteIdsettleIdTsubTyper@   rA   FrB   rC   rV  rS  r   rQ  10r  rS  r   r   )contractr  r  r   r   contractSizeexpiryexpiryDatetimestrike
optionTyperU  rZ  createdr   )rC  rD  r2  r`  ra  rb  rE  r1  r   safe_numberr  r3  intr  r  r$  rd  rp  safe_market_structure)&r%  rF  rG  rH  firstsecondr  rN  r/  rg  r4  r   	extraData
marketNamer   r   r   	tokensPosbaseTokenPosquoteTokenPosbaseTokenInfoquoteTokenInfor6  r  r   mappedBaseNamemappedQuoteId
mappedBasemappedQuotemappedSymbolinnerBaseTokenInfoamountPrecisionStrr  r   r  pricePrecisionStrr  entrys&                                         r'  rr  zhyperliquid.fetch_spot_markets  s    *
 &&t{{7F'C'CDDZ xB//!R00~~eZ44x44q#d))$$ `	> `	>A^^D!R00F%%fg66Evub99I))&&99J >>$)VR88D$$T733E$$T733Evx<<I,,Y::L --i;;M NN6<DDM!^^FM2FFN''v>>H&&~v>>G7? #'..?TVX"Y"Y!--.A8XVVN ,,-@'7SSM00@@J11-@@K%+k9L!%v}!U!U!%!1!12Dl!S!S!"455O$$Y88EN !%!?!?XY!Z!Z $ 5 5n E E**55=99F4j4,4 
4 	4
 $4 &4 H4 74 D4 4 4 44 $4 4 %4  %!4" $#4$ " $"&""//0D0DEW0X0XYY!..t/C/CDU/V/VWW   $#! !
  $# 
  $# 
  $0066#  $  Iv66g4 4 4Ej NN455e<<==== r(  r4  c                    |                      |d          }|dn|}|dn|}|                      |d          }|                     |          }|                    dd          }|                     |          }|                      |d          }|                     |          }	|dz   |z   }
d}d}|r
|r|
dz   |	z   }
|                     | j        d	i           }|                     |d
          }|                     |d          }|                      |d          }t          |          }|                     |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 d d$d d d$|                     d%          d d$d&d |d'          S )(Nr  USDCr3   r  r  r  r.  TrA   r   r   r  markPxr      
isDelistedr2   r,  r  r8  r  r6  r  r  r   r?   Fr@   rB   rC   rV  r  r  r  maxLeveragerQ  r  r  )r  r  r   r   r  r  r  r  r  rU  rZ  r  r   )r1  r3  r  r2  r   r  r  r  r  	safe_boolr  r$  rd  rE  )r%  r4  r  r  r  r6  r  r8  r  r  r,  r  rA   r   r   r   r  r  r   r  r  r  rV  s                          r'  parse_marketzhyperliquid.parse_market  s   , #..v7LMM08&&?R1966@S##FF33&&x00||C%%''00!!&(33((22e# 	/ /#.~~di44  w//  w//!--flCC011  155!;;E?TUVVN 11.AA^^FL99
!#^F)) 3+
&3+
f3+
 D3+
 U	3+

 f3+
 f3+
 3+
 w3+
 3+
 F3+
 E3+
 d3+
 D3+
 e3+
 e3+
  f!3+
" #3+
$  --c22"++D,@,@AS,T,TUU**4+?+?@Q+R+RSS   ,,V]CC 
   
   
  ,,T22  $ e3+
 3+
 3+
 3 3 3	r(  rT  c                 p    ||S |                      | j        di           }|                     |||          S )Nr   )r2  r  r1  )r%  rT  r   s      r'  update_spot_currency_codez%hyperliquid.update_spot_currency_code  s?    <K"nnT\;PRTUU 3T4@@@r(  c                 ,   |                      |dd          duo|                     |d          du }d}|                     d|          \  }}d}|                     dd|          \  }}d}|                     d|          \  }}d}|                     d|||          \  }}|                     |d          }|dk    s|o|du }|rdnd	|d
}	|                     |                     |	|                    }
| 	                    |
d          }|d|
i}t          dt          |                    D ]}||         }|                     |                     |d                    }|r|                     |          n|}|                                 }|                     |d          }|                     |d          }||d<   ||d<   |||<   |                     |          S |                     |
di           }d|                     |d          i}| |dk    r|                     |
d          |d<   n|                     |d          |d<   |
|d}|                     |
d          }||d<   |                     |          |d<   |                     |          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
        :param str [params.dex]: for hip3 markets, the dex name, eg: 'xyz'
        :param str [params.subAccountAddress]: sub account user address
        :param boolean [params.enableUnifiedMargin]: enable unified margin, CCXT tries to auto-detects self value but you can override it
        :returns dict: a `balance structure <https://docs.ccxt.com/?id=balance-structure>`
        useraddressNenableUnifiedMarginrZ   r<   r?   r   r   r   r  balancesr   r   cointotalholdusedmarginSummaryaccountValueisolatedwithdrawablefreetotalMarginUsed)r   r  r>  	timestampdatetime)safe_string_2r  handle_public_addresshandle_market_type_and_paramshandle_margin_mode_and_paramsis_unified_enabledr1  rC  rD  r`  ra  rb  r3  r  accountsafe_balancer2  r  rE  iso8601)r%  rF  shouldRefreshuserAddressr   r  isUnifiedEnabledr<   isSpotrG  rH  r  spotBalancesrg  balanceunifiedCoderT  r  r  r  rh  usdcBalancerf  r  s                           r'  fetch_balancezhyperliquid.fetch_balance  s   " ++FFIFFdR  NX\XfXfgm  pE  YF  YF  JN  YN"88PPV99.$PVWWf
!??PVWW
F#'#:#:>;Xegm#n#n &vu--6>6&6ISD[17R,,>R
 
 &&t{{7F'C'CDDH >>(J77"((!3L1c(mm,, 	- 	-"1+"55d6F6FwPV6W6WXXFL]t55kBBBR],,..(('::''88#( "&%,T""$$\222~~h<<T%%dN;;
 "z)A)A"&"2"28^"L"LK"&"2"249J"K"KK
 
 %%h77	'{!\\)44z  (((r(  Nr   c           	         |                                   |                     |          }d|d         r|d         n|d         d}|                     |                     ||                    }|                     |dg           }|                     |dg           |                     |dg           d	}|                     |d
          }	|                     ||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   rA   r6  r2   r   r  levelsr   r   )bidsasksr>  r,  r  r  pxsz)load_marketsr4  rC  rD  r`  rE  parse_order_book)
r%  r,  r   rF  r4  rG  rH  rh  rf  r  s
             r'  fetch_order_bookzhyperliquid.fetch_order_book  s     	V$$*0.JF:&&fTl
 
 &&t{{7F'C'CDD. ~~h"55NN4B//NN4B//
 
 %%h77	$$VVH-=y&RXZ^`deeer(  symbolsc                    |                                   |                     |          }g }|                     |d          }|                     |d          }d}|                     |ddd          \  }}|Y|                     |d          }|A|                     |          }|                     |                     |d          d          rd}|r,|                     |d          }|                     |          }nM|d	k    r| 	                    |          }n1|d
k    r| 
                    |          }n|                     |          }i }t          dt          |                    D ]C}	||	         }|d         }
|                     |
|          }|                     |d          }|||<   D|                     |d|          S )a  
        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
        :param boolean [params.hip3]: set to True to fetch hip3 markets only
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/?id=ticker-structure>`
        r   Fr   r   Nr   r   Tr?   rA   r,  )r	  market_symbolsr1  omithandle_option_and_paramsr4  r  r2  rs  rr  rq  rx  ra  rb  parse_tickerfilter_by_array_tickers)r%  r  rF  rH  r   r   firstSymbolr4  rf  rg  r   tickerr,  s                r'  fetch_tickerszhyperliquid.fetch_tickers  s    	%%g..//66**44V^VUZ[[f**7A66K&[11>>$.."@"@&II  D 	2YYvv..F..v66HHV^^..v66HHV^^..v66HH))&11Hq#h--(( 	$ 	$Aa[F&>D&&tV44F%%fh77F#F6NN++FHgFFFr(  c           	          ddi}|                      |                     ||                    }|                     |di           }|                     |dg           }|                     |dg           }g }t	          dt          |                    D ]W}	|                     |                     ||	i           |                     ||	i                     }
|                    |
           X|                     ||          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   )rC  rD  r2  r`  ra  rb  rp  parse_funding_rates)r%  r  rF  rG  rH  r  r~  r  rf  rg  rh  s              r'  fetch_funding_rateszhyperliquid.fetch_funding_rates  s     &
 &&t{{7F'C'CDD@ ~~h2..>>$
B77NN8Q33	q#h--(( 	  	 A;;xB//y!R00 D MM$''888r(  c                 0   |                      |d          }|                     |          }|                     ||          }|                     |d          }|                     |d          }|                     |d          }t	          t          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|                     |	          dd dd dd dd dd dd ddiS )Nr3   fundingr  oraclePx<   r  r   r   r,  	markPrice
indexPriceinterestRateestimatedSettlePricer  r  fundingRatefundingTimestampfundingDatetimenextFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeintervalr   )	r1  coin_to_market_idsafe_symbolr  r  mathfloormillisecondsr  )
r%  r   r4  r  marketIdr,  r  r  r  r"  s
             r'  parse_funding_ratezhyperliquid.parse_funding_rate  s   * f--))$//!!(F33""433!!$11##D*55
4+<+<+>+> ? ?" Dr ID PQQTUUY[[^``cgg
D
f
 
 (	

 D
 #D
 
 
 7
  0
 t||,<==
 t
 #D
 "4
 "4
  '!
" &t#
$ %
 
 	
r(  r  c                    |                      |d          }|                     |          }|                     ||          }|                     |d          }|                     |d         d d |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d	          |d

|          S )Nr3   	impactPxsr,  	prevDayPxr  r   r   r   	dayNtlVlm)
r,  r  r  previousClosecloser   bidaskquoteVolumer   )r1  r+  safe_marketr`  safe_tickerr  )r%  r  r4  r3   r0  bidAsks         r'  r  zhyperliquid.parse_tickerI  s      //))$//!!(F3344X&!--fkBB%%fg66$$VW55##FA..##FA..++FK@@!
 !
   	r(  r   	timeframesincec                 d   |                                   |                     |          }|                     |d|                                           }|du }|}	|C|?|                     |          dz  }
|                     ||
|z  dz            }|dk     rd}d}nd}|                     |dg          }d|d         r|d	         n|d
         |                     | j        ||          ||dd}| 	                    | 
                    ||                    }|                     ||||	||          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  r   Fr   rA   r6  r2   )r  r*  	startTimeendTime)r   req)r	  r4  rE  r/  parse_timeframer  r  r1  r   rC  rD  parse_ohlcvs)r%  r,  r>  r?  r   rF  r4  rA  useTailoriginalSincetimeframeInMillisecondsrG  rH  s                r'  fetch_ohlcvzhyperliquid.fetch_ohlcvj  s]    	V$$!!&'43D3D3F3FGG4-= *.*>*>y*I*ID*P'(?%(G"(LMM199E6G9--$.4VnNz**&, ,,T_iSS" 	 
 
 &&t{{7F'C'CDD"   69mUT[\\\r(  c           	         |                      |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS )Ntohlcv)rE  r  )r%  ohlcvr4  s      r'  parse_ohlcvzhyperliquid.parse_ohlcv  s      eS))UC((UC((UC((UC((UC((
 	
r(  c                    d}|                      d|          \  }}|                                  d}||                     |          }d|i}|d|d<   ||d<   nd|d<   |                     |d          }|                     |d          }|||d	<   |                     |                     ||                    }	|                     |	|||          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
        :param str [params.subAccountAddress]: sub account user address
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        Nr   r  userFillsByTimer   rC  	userFillsrA  rD  r  r	  r4  rE  r  rC  rD  parse_trades
r%  r,  r?  r   rF  r  r4  rG  rA  rH  s
             r'  fetch_tradeszhyperliquid.fetch_trades  s    " "88OOV[[((FK
 /GFO#(GK  )GFO!!&'2267++!&GI&&t{{7F'C'CDD*   65%@@@r(  c                     |                      |          }|                     |t          |d         d         | j        | j                  S )NrU  rS  )r4  decimal_to_precisionr)   r   paddingMode)r%  r,  rS  r4  s       r'  amount_to_precisionzhyperliquid.amount_to_precision  sA    V$$(({8KH8UW[Wikok{|||r(  c                    |                      |          }|                     |          }|                    d          d         }t          dt	          |                    }|                     |t          |t          | j                  }|d         rdnd}|| 	                    | 
                    |d         d                    z
  }	|                     |t          |	t          | j                  S )	Nr  r   r  r?   r  r  rU  rS  )r4  r  r0  r  rb  r]  r)   r+   r^  precision_from_stringr1  r*   )
r%  r,  r   r4  r  r  r  rf  r  subtractedValues
             r'  price_to_precisionzhyperliquid.price_to_precision  s    V$$((//nnS))!,3{#3#344**5%9JL^`d`pqq!&>0aaq%(B(B4CSCSTZ[fTgiqCrCr(s(ss((Y]Yijjjr(  c                 6    d|                      |dd          z   S )N0xkeccakhex)hash)r%  messages     r'  hash_messagezhyperliquid.hash_message  s    dii59999r(  c                     |                      |dd          |dd          dd           }d|d         z   d|d         z   |                     d|d                   dS )	N	secp256k1re  rs   rR  )rn  ro  rR  )ecdsar  )r%  rh  r   	signatures       r'  	sign_hashzhyperliquid.sign_hash  sf    JJtCDDz:cdd+;[$OO		#&	#&"in--
 
 	
r(  c                 d    |                      |                     |          |dd                    S )Nrl  )rs  rj  )r%  ri  r   s      r'  sign_messagezhyperliquid.sign_message  s-    ~~d//88*STT:JKKKr(  Tc                     |rdnd}||dS )Nba)sourceconnectionId )r%  rh  	isTestnetry  s       r'  construct_phantom_agentz#hyperliquid.construct_phantom_agent  s%    ", 
 
 	
r(  c                 L   |                      |          }|                     |          }|}|d|                     |          z   z  }||dz  }n
|dz  }||z  }| |dz  }|d|                     |          z   z  }|                     |                     |          dd          S )N000000001rf  binary)packbbinary_to_base16int_to_base16rh  base16_to_binary)r%  actionvaultAddressnonceexpiresAfter
dataBinarydataHexrh  s           r'  action_hashzhyperliquid.action_hash  s    ZZ''
''
33$,,U3333DLDDDLDL D#DLDGd00>>>>Dyy..t44hIIIr(  c                 ^   |                      ||||          }|                     | j        dd          }|                     ||          }|                     | j        d          }d}	|	d|dd}
dd	d
ddddgi}|                     |
||          }|                     || j                  }|S )Nr   Fr   i9  r   r  chainIdr3   verifyingContractr6   Agentry  stringr3   r   rz  bytes32)r  r  r  r}  r1  eth_encode_structured_dataru  r   )r%  r  r  vaultAdressr  rh  r|  phantomAgentr   r  domainmessageTypesmsgrr  s                 r'  sign_l1_actionzhyperliquid.sign_l1_action(  s    ULIINN4<FF	33D)DD. &&t|]CC!,	
 
 !844';;
 --flLQQ%%c4?;;	r(  c                     |                      | j        d          }d}|d|dd}|                     |||          }|                     || j                  }|S )Nr   in HyperliquidSignTransactionr  r  )r1  r  r  ru  r   )r%  r  ri  r   r  r  r  rr  s           r'  sign_user_signed_actionz#hyperliquid.sign_user_signed_actionT  sl    &&t|]CC0!,	
 
 --flGLL%%c4?;;	r(  c                 V    dddddddddddddgi}|                      ||          S )	NzHyperliquidTransaction:UsdSendhyperliquidChainr  r  destinationrS  r>  uint64r  r%  ri  r  s      r'  build_usd_send_sigzhyperliquid.build_usd_send_siga  sU    ,+X>>&99!84422	/
 ++L'BBBr(  c                 V    dddddddddddd	dgi}|                      ||          S )
Nz'HyperliquidTransaction:UsdClassTransferr  r  r  rS  toPerpboolr  r  r  r  s      r'  build_usd_class_send_sigz$hyperliquid.build_usd_class_send_sigl  sU    5+X>>!844!622 (33	8
 ++L'BBBr(  c                 V    dddddddddddddgi}|                      ||          S )	NzHyperliquidTransaction:Withdrawr  r  r  r  rS  r>  r  r  r  s      r'  build_withdraw_sigzhyperliquid.build_withdraw_sigw  sU    -+X>>&99!84422	0
 ++L'BBBr(  c                 V    ddddddddddd	d
dgi}|                      ||          S )Nz)HyperliquidTransaction:UserDexAbstractionr  r  r  r  r  r+  r  r  r  r  r  s      r'  build_user_dex_abstraction_sigz*hyperliquid.build_user_dex_abstraction_sig  sU    7+X>>33"F33 (33	:
 ++L'BBBr(  c                 V    dddddddddddd	dgi}|                      ||          S )
Nz)HyperliquidTransaction:UserSetAbstractionr  r  r  r  r  abstractionr  r  r  r  s      r'  build_user_abstraction_sigz&hyperliquid.build_user_abstraction_sig  sU    7+X>>33&99 (33	:
 ++L'BBBr(  c                 V    dddddddddddd	dgi}|                      ||          S )
Nz(HyperliquidTransaction:ApproveBuilderFeer  r  r  
maxFeeRatebuilderr  r  r  r  r  s      r'  build_approve_builder_fee_sigz)hyperliquid.build_approve_builder_fee_sig  sU    6+X>>%x88"I66 (33	9
 ++L'BBBr(  c                 Z   |                      | j        dd          rdS d| j        d<   d|                     | j        dd          d}|                                 }|                     ||          }|||d}d }	 |                     |          }|S # t          $ r}d }Y d }~nd }~ww xY w|S )	NrefSetFTsetReferrerrefCCXT1)r   rT  r  r  rr  )r  r  r1  r/  r  privatePostExchange	Exception)r%  r  r  rr  rG  rH  es          r'  set_refzhyperliquid.set_ref  s    >>$,%88 	4!%X!$$T\5'BB
 
 !!##''66	"
 

 	//88HO 	 	 	HHHHHH	s   ;B 
B(B##B(r  r  c                    |                                  }|                     | j        dd          }|rdnd|||d}|                     |          }|d         d|d         |d	         |d
d}|||d d}|                     |          S )Nr   FTestnetMainnet)r  r  r  r  r  0x66eeer  r  approveBuilderFee)r  signatureChainIdr  r  r  r   r  r  rr  r  )r/  r  r  r  r  )	r%  r  r  r  isSandboxModepayloadsigr  rG  s	            r'  approve_builder_feezhyperliquid.approve_builder_fee  s    !!##t|]EJJ-: I			$	
 
 0099 '(: ; )!,/y)'
 
  	
 
 ''000r(  c                     	 |                                  |                                 |                     dd di           g n# t          $ r}Y d }~dS d }~ww xY wdS )NrZ   FT)handle_builder_fee_approvalr  r  r  )r%  r  s     r'  r_  zhyperliquid.initialize_client  st    	--//AXAXYgimotvxAyAyzzz 	 	 	55555	ts   ?A 
AAc                 |   |                      | j        dd          }|sdS |                      | j        dd          }|rdS 	 |                     | j        dd          }|                     | j        dd          }|                     ||           d| j        d<   n!# t          $ r}d| j        d<   Y d }~nd }~ww xY wdS )	Nr   TFapprovedBuilderFeer  *0x6530512A6c89C7cfCEbC3BA7fcD9aDa5f30827a6feeRatez0.01%)r  r  r1  r  r  )r%  buildFeer  r  r  r  s         r'  r  z'hyperliquid.handle_builder_fee_approval  s    >>$,dCC 	5!^^DL:NPUVV 	4	/&&t|Y@lmmG))$,	7KKJ$$Wj99915DL-.. 	/ 	/ 	/).DL&&&&&&	/ts   AB 
B9%
B44B9Fmethodr  c                 @   d}||}n|                      d|          \  }}d}|                     ||d          \  }}||r[d|d}d}	 |                     |                     ||                    }n# t          $ r}	d}Y d}	~	nd}	~	ww xY w|dk    }|| j        d<   ||gS )a[  

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#query-a-users-abstraction-state

        returns enableUnifiedMargin so the user can check if unified account is enabled
        :param str method: the method for which we want to check if unified margin is enabled, self is used to check options for specific methods(e.g. fetchBalance can have a specific option to enable unified margin)
 @param address
 @param shouldRefresh
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns bool: enableUnifiedMargin
        Nr  r  userAbstractionr  z"unifiedAccount")r  r  rC  rD  r  r  )
r%  r  r  r  rF  r  r  rG  rH  r  s
             r'  r  zhyperliquid.is_unified_enabled  s     !KK"&"<"<=OQW"X"XK"&*&C&CFFTi&j&j#V&-&)# G H ..t{{7F/K/KLL       
 #+.@"@2EDL./#V,,s   	)A3 3
B	=BB	r  c                    d}|                      d|          \  }}|                                 }|                     | j        dd          }|                     |dd          }|                     |d          }|rdnd|||d	}|                     |          }|d
         d|d         |d         ||d}	|	||dd}
|                     |
          S )a  
        set user abstraction mode

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#set-user-abstraction

        :param str abstraction: one of the strings ["disabled", "unifiedAccount", "portfolioMargin"],
        :param dict [params]:
        :param str [params.type]: 'userSetAbstraction' or 'agentSetAbstraction' default is 'userSetAbstraction'
        :returns: dictionary response from the exchange
        NsetUserAbstractionr   Fr   userSetAbstractionr  r  )r  r  r  r  r  r  r  r  )r  r  r  r  r  r   r  )r  r/  r  r  r1  r  r  r  )r%  r  rF  r  r  r  r   r  r  r  rG  s              r'  set_user_abstractionz hyperliquid.set_user_abstraction  s
    "889MvVVV!!##t|]EJJ0DEE66**-: I			&	
 
 --g66 '(: ; )"=1FO
 
  	
 
 ''000r(  r+  c                    d}|                      d|          \  }}|                                 }|                     | j        dd          }|                     |dd          }|                     |d          }|rdnd|||d	}|                     |          }|d
         d|d         |d         ||d}	|	||dd}
|                     |
          S )a  
        If set, actions on HIP-3 perps will automatically transfer collateral from validator-operated USDC perps balance for HIP-3 DEXs where USDC is the collateral token, and spot otherwise
 @param enabled
 @param params
        :param str [params.type]: 'userDexAbstraction' or 'agentEnableDexAbstraction' default is 'userDexAbstraction'
        :returns: dictionary response from the exchange
        NenableUserDexAbstractionr   Fr   userDexAbstractionr  r  )r  r  r+  r  r  r  r+  r  )r  r  r+  r  r  r   r  )r  r/  r  r  r1  r  r  r  )r%  r+  rF  r  r  r  r   r  r  r  rG  s              r'  enable_user_dex_abstractionz'hyperliquid.enable_user_dex_abstractionH  s    "889SU[\\V!!##t|]EJJ0DEE66**-: I				
 
 11':: '(: ; )y)FO
 
  	
 
 ''000r(  c                     |                                  }d|i}d|d}|                     ||          }||d<   ||d<   |                     |                     ||                    }|S )a  
        set agent abstraction mode
        :param str abstraction: one of the strings ["i", "u", "p"] where "i" is "disabled", "u" is "unifiedAccount", and "p" is "portfolioMargin"
        :param dict [params]:
        :returns: dictionary response from the exchange
        r  agentSetAbstraction)r   r  r  rr  r/  r  r  rD  )r%  r  rF  r  rG  r  rr  rH  s           r'  set_agent_abstractionz!hyperliquid.set_agent_abstractionu  s     !!##U
 *&
 
 ''66	"(++DKK,H,HIIr(  r   siderS  c           	          |                                   |                     d||||||          \  }}|                     |g|          }	|	d         S )af  
        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
        :param str [params.subAccountAddress]: sub account user address
        :returns dict: an `order structure <https://docs.ccxt.com/?id=order-structure>`
        Nr   )r	  parse_create_edit_order_argscreate_orders)
r%  r,  r   r  rS  r   rF  orderglobalParamsorderss
             r'  create_orderzhyperliquid.create_order  s_    , 	"??fdTXZ`bgiopp|##UG\::ayr(  durationc                 t   |                                   |                                  |                     |          }|                                 }|dk    }d}	|                     |dd          }
|                     |d          }|                     |dd          \  }	}|                     |	          }	t          t          j
        |dz  dz                      }|                     |d	                   ||                     ||          |                     |d
d          ||
d}d|d}|                     |||	          }|||d}|	|                     |d          }|	|d<   |                     |d          }|||d<   |                     |d          }|                     |          }|                     |di           }|                     |di           }|                     |di           }|                     |di           }|                     |d          }|                     d|d|          S )a  
        create a trade order that is executed TWAP order over a specified duration.
        :param str symbol: unified symbol of the market to create an order in
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param int duration: the duration of the TWAP order in milliseconds
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param bool [params.randomize]: whether to randomize the time intervals of the TWAP order slices(default is False, meaning equal intervals)
        :param bool [params.reduceOnly]: True or False whether the order is reduce-only
        :param int [params.expiresAfter]: time in ms after which the twap order expires
        :param str [params.vaultAddress]: the vault address for order
        :returns dict: an `order structure <https://docs.ccxt.com/?id=order-structure>`
        BUYN	randomizeFrQ   r  r  r  r  
reduceOnly)rx  rw  ro  rn  mrM  	twapOrder)r   twapr  r  rH  rh  r?  runningtwapIdr?  oid)r	  r_  r4  r/  r  r  r  format_vault_addressr  r-  r.  r  r_  r  rE  r  r2  r1  parse_order)r%  r,  r  rS  r  rF  r4  r  isBuyr  r  durationMinsorderObjorderActionrr  rG  r  rH  responseObjrh  r?  r  orderIds                          r'  create_twap_orderzhyperliquid.create_twap_order  s\    	   V$$!!##NN6;>>	6;//#<<V]Tbccf00>>4:ho&:;;<<""6(#344))&&99e<<
 
  
 
 ''ULII	!"
 
 #YYv~66F&2GN#((@@#&2GN#YYv~66F++G44 nnXz2>>~~k6266h33..B77""7H559W E EvNNNr(  r  c                    |                                   |                                  |                     ||          }|                     |          }|                     |di           }|                     |di           }|                     |dg           }g }t          dt          |                    D ]=}	||	         }
|
dk    r|                    d|
i           (|                    |
           >| 	                    |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>`
        rH  rh  statusesr   waitingForTriggerr?  N)
r	  r_  create_orders_requestr  r2  r`  ra  rb  rp  parse_orders)r%  r  rF  rG  rH  r  rh  r  ordersToBeParsedrg  r  s              r'  r  zhyperliquid.create_orders  s    	   ,,VV<<++G44$ nnXz2>>~~k6266>>$
B77q#h--(( 	/ 	/AQKE+++ ''5(9:::: ''....  !14888r(  c                    |                      |          }|                                }|                                }|dk    }|dk    }	|                     |dd          }
|                     |d          }|rdnd}|                     |dd	          }|rd
}|                     |d|          }|                     |          }|                     |dd          }|                     |d|          }|                     |d          }|p|}d }|r|t          | j        dz             |	r(t          j
        |t          j        d|                    n't          j
        |t          j        d|                    }|                     ||          }n|                     ||          }|                     ||          }|                     |dd	          }i }|rAd	}||                     ||          }d}n|                     ||          }|||rdndd|d<   nd|i|d<   |                     |g d          }|                     |d                   |	||||d}|
|
|d<   |S )NMARKETr  clientOrderId	client_idslippageiocgtcpostOnlyFalor	  r   	stopPricer  r  zy  market orders require price to calculate the max slippage price. Default slippage can be set in options(default is 5%).r  r  TtpslisMarket	triggerPxtpslr  tifr   )
r  r  r   r  r  r  r	  r  r  r  r  rx  rw  pro  rn  rM  rQ  )r4  upperr  r1  r  safe_string_lower
capitalizer"   r2   r-   
string_mul
string_add
string_subrc  r_  r  r  )r%  r,  r   r  rS  r   rF  r4  r  r  r  r  defaultTimeInForcer  r	  r   r  r  	isTriggerr  r  r  	orderTypeisTpr  s                            r'  create_order_requestz hyperliquid.create_order_request  s   V$$zz||zz||H$**6?KPP##FJ77'/;UUe>>&*e<< 	'!&,,V]DVWWook22))&.+NN((,OO**63DEE"5o	 	8}'  3n  )n  o  o  oRW  [#E7+=c8+L+LMMM^e^pqvx  yK  LO  QY  yZ  yZ  _[  _[B((44BB((77B%%ff55^^FL%@@
	 	D*#66vOO#66v}MM$)!%0D$ $Ii   {"Ig 6  $x  $x  $x  y  y""6(#344
 
 $)HSMr(  c                 .
   |                                   |                     | j        d          }|                     |d|          }d}t          dt	          |                    D ]<}||         }|                     |di           }|                     |dd          }|d	}=|rot          dt	          |                    D ]Q}||         }|                     |di           }|                     |dd          }|t          | j        d
z             R| 	                    |g d          }| 
                                }	g }
d}t          dt	          |                    D ]}||         }|                     |d          }|                     |          }|d         }|                     |d          }|                     |d          }|                     |d          }|                     |d          }|                     |di           }|                     |d|          }||d<   |                     |d          }|                     |d          }|du}|du}| 	                    |ddg          }|                     ||||||          }|s|r|                     |ddg          }|                     |dd          }|                     |ddg|          }|                     |ddg          }|                     |dd          }|                     |ddg|          }|                     |dd          }|dk    rd}d}d}n3|dk    r|
                    |           nt#          | j        dz             | 	                    |g d          }d }|d!k    rd"}nd#}|rF|                     ||||||                     ||d	d$                    } |
                    |            |rF|                     ||||||                     ||d	d%                    } |
                    |            |
                    |           d}!|                     |d&d'          \  }!}|                     |!          }!d(|
|d)}"|                     | j        d*d          r>|                     | j        d+d,          }#|#|                     | j        d-d.          d/|"d+<   |                     |"|	|!          }$|"|	|$d0}%|!| 	                    |d'          }|!|%d'<   |%S )1a  
        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   r  Fr   rF  r  r  NTzV createOrders() all orders must have clientOrderId if at least one has a clientOrderId	r  r  r  r  r   r  r  r  r	  nar,  r   r  rS  r   stopLoss
takeProfitr   r  r   r  r  grouping
normalTpslpositionTpslr  r4  z3 only support grouping normalTpsl and positionTpsl.)r%  r&  r'  r]  r  sellbuy)r  r  )r  r  rQ   r  r  )r   r  r'  r  r  r  feeIntr   )rw  fr  )r^  r1  r  ra  rb  r2  r  r"   r2   r  r/  r4  safe_string_upper
safe_valuer!  safe_string_nrp  r'   rD  r  r  r  r  rE  r  )&r%  r  rF  r   hasClientOrderIdrg  rawOrderorderParamsr  r  orderReqr'  r0  r4  r,  r   r  rS  r   r  r%  r&  hasStopLosshasTakeProfitmainOrderObjstopLossOrderTriggerPricestopLossOrderTypestopLossOrderLimitPricetakeProfitOrderTriggerPricetakeProfitOrderTypetakeProfitOrderLimitPricetriggerOrderSider  r  r  walletrr  rG  s&                                         r'  r  z!hyperliquid.create_orders_requestS  sF    	'')))**4<9JKK**6:OO q#f++&& 	( 	(AayH..8R@@K ..{O[YYM(#'  	P1c&kk** P P!!9"nnXxDD $ 2 2;Q\ ] ] (+DG  7O  -O  P  P  P )6  $j  $j  $j  k  k!!##q#f++&& 6	. 6	.AayH''(;;H[[**FH%F))(F;;D))(F;;D%%h99F$$Xw77E..8R@@K''ZQQH&.K
#{J??HlCCJ#4/K't3M))K*l1KLLK!%!:!:64vW\^i!j!jL $.m $.,0,>,>x.ZeIf,g,g)$($4$4Xvw$O$O!*.*<*<XQ`Gac|*}*}'.2.@.@n^iMj.k.k+&*&6&6z67&S&S#,0,>,>zGUfKg  jE  -F  -F)++K\RR~-- F(0%*2''--OOL1111&tw1f'fggg"ii5[5[5[\\#% 5=='-$$',$  .%)%>%>vGZ\lnt  wP  RV  R]  R]  ^i+F&*k k R R & &H OOH--- .%)%>%>vGXZjlr  uL  NR  NY  NY  Ze)B&*g g N N & &H OOH-------#<<V]Tbccf00>> 
 

 >>$,(<eDD 	g++DL)EqrrF+18I8I$,X`bd8e8e%f%fK	"''ULII	!"
 
 #YYv~66F&2GN#r(  r2   c                     |                      |dd          r-|                     |d          }|                     |||          S |                     |g||          }|                     |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
        :param str [params.subAccountAddress]: sub account user address
        :param boolean [params.twap]: whether the order to cancel is a twap order,(default is False)
        :returns dict: An `order structure <https://docs.ccxt.com/?id=order-structure>`
        r  Fr   )r  r  cancel_twap_ordercancel_ordersr2  )r%  r2   r,  rF  r  s        r'  cancel_orderzhyperliquid.cancel_order  st      >>&&%00 	>YYvv..F))"ff===##RD&&99~~fa(((r(  idsc                 6   |                                   |t          | j        dz             |                                  |                                  |                     |||          }|                     |          }|                     |d          }|                     |d          }|                     |d          }g }	t          dt          |                    D ]5}
||
         }|	                    |                     ||d                     6|	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
        :param str [params.subAccountAddress]: sub account user address
        :returns dict: an list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nz* cancelOrders() requires a symbol argumentrH  rh  r  r   r   r?  )r^  r"   r2   r	  r_  cancel_orders_requestr  r2  r`  ra  rb  rp  
safe_order)r%  rD  r,  rF  rG  rH  innerResponserh  r  r  rg  r?  s               r'  rB  zhyperliquid.cancel_orders  s)    	'')))>#DG.Z$Z[[[   ,,S&&AA++G44 x<<~~mV44>>$
33q#h--(( 	 	Aa[FMM$// + +       r(  c                 2   |                                   |t          | j        dz             |                     |          }d}|                     |dd          \  }}|                     |          }d|                     |d                   |                     |          d}|                                 }| 	                    |||          }|||d}	|| 
                    |d          }||	d<   |                     |d	          }
|
|
|	d	<   | 
                    |d	          }|                     |	          }|                     |d
i           }|                     |di           }|                     |d          }|                     ||d|          S )aZ  
        cancels a running twap order

        https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-a-twap-order

        :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 int [params.expiresAfter]: time in ms after which the twap order expires
        :param str [params.vaultAddress]: the vault address for order
        :returns dict: An `order structure <https://docs.ccxt.com/?id=order-structure>`
        Nz- cancelTwapOrder() requires a symbol argumentcancelTwapOrderr  
twapCancelr  )r   rx  rM  r  r  rH  rh  r?  r  )r	  r"   r2   r4  r  r  r  parse_to_numericr/  r  r  rE  r  r2  r1  r  )r%  r2   r,  rF  r4  r  r  r  rr  rG  r  rH  r  rh  r?  s                  r'  rA  zhyperliquid.cancel_twap_order	  s    	>#DG.]$]^^^V$$#<<VEVXfggf00>> ""6(#344&&r**
 

 !!##''|DD	"
 
 #YYv~66F&2GN#((@@#&2GN#YYv~66F++G44 nnXz2>>~~k6266!!$116" = =vFFFr(  c                 T   |                      |          }|                     |dd          }|                     |ddg          }|                                 }d|i}g }dg d}	|                     |d                   }
|\t          |t                    s|g}d|	d	<   t          d
t          |                    D ] }|	                    |
||         d           !nVd|	d	<   t          d
t          |                    D ]3}|	                    |
|                     ||                   d           4||	d<   d}| 
                    |ddd          \  }}|                     |          }|                     |	||          }|	|d<   ||d<   ||                     |d          }||d<   |S )a  
        build the request payload for cancelling 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]:
        :returns dict: the raw request object to be sent to the exchange
        r  r  r  r]  r   cancelsr  NcancelByCloidr   r   )assetcloidcancel)rx  rN  rP  rJ   r  subAccountAddressr  rr  )r4  safe_value_2r  r/  rM  
isinstancelistra  rb  rp  handle_option_and_params_2r  r  )r%  rD  r,  rF  r4  r  r  rG  	cancelReqcancelActionr  rg  r  rr  s                 r'  rG  z!hyperliquid.cancel_orders_request;	  s    V$$))&/;OO6O[#ABB!!##U
 	
 
 &&vh'788$mT22 0!.#2L 1c-0011    #*1-" "     $,L 1c#hh''    ..s1v66" "     #,Y#>>v~Wegz{{f00>>''e\JJ	((#YYv~66F&2GN#r(  c                 :   |                                   |                                  |                                  |                                 }d|i}g }dg d}d}t	          dt          |                    D ]}||         }	|                     |	d          }
|
d}|                     |	d	          }|                     |	d
          }|t          | j        dz             ||rt          | j        dz             |rdnd}|rdnd}| 
                    |          }i }|                     |d                   ||<   |r|
n|                     |          ||<   |                    |           |rdnd|d<   ||d<   d}|                     |ddd          \  }}|                     |          }|                     |||          }||d<   ||d<   ||                     |d          }||d<   |                     |          }|                     d|i          g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
        :param str [params.subAccountAddress]: sub account user address
        :returns dict: an list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        r  r]  rO  Fr   r  NTr2   r,  zB cancelOrdersForSymbols() requires a symbol argument in each orderzI cancelOrdersForSymbols() all orders must have either id or clientOrderIdrR  rx  rS  rN  r  rQ  rT  r   rP  rK   r  rU  r  rr  r   )r^  r	  r_  r/  ra  rb  r1  r"   r2   r#   r4  rM  rp  rY  r  r  r  r  rH  )r%  r  rF  r  rG  rZ  r[  rQ  rg  r  r  r2   r,  assetKeyidKeyr4  	cancelObjr  rr  rH  s                       r'  cancel_orders_for_symbolsz%hyperliquid.cancel_orders_for_symbolso	  s    	'')))   !!##U
 	
 
 q#f++&& 	( 	(A1IE ,,UODDM( $!!%..B%%eX66F~'2v(vwww~-~ +v!vwww"/8wwSH,5GG#E[[((F I"&"7"7x8H"I"IIh0=\}}4CXCXY[C\C\IeY''''2?MXV"+Y#>>vG_ao  rE   F   Ff00>>''e\JJ	((#YYv~66F&2GN#++G44  23344r(  timeoutc                    |                                   |                                  |                                  |                     |ddg          }|                                 }d|i}d||z   d}d}|                     |ddd	          \  }}|                     |          }|                     |||          }||d
<   ||d<   ||                     |d          }||d<   |                     |          }|S )a  
        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
        :param str [params.subAccountAddress]: sub account user address
        :returns dict: the api result
        r  r  r  scheduleCancel)r   r>  NrH   r  rU  r  rr  )	r^  r	  r_  r  r/  rY  r  r  r  )	r%  ra  rF  r  rG  r[  r  rr  rH  s	            r'  cancel_all_orders_afterz#hyperliquid.cancel_all_orders_after	  s4    	'')))   6O[#ABB!!##U

 %GO
 
 #>>vG]_m  pC   D   Df00>>''e\JJ	((#YYv~66F&2GN#++G44 r(  c                 r	   |                                   d}t          dt          |                    D ]<}||         }|                     |di           }|                     |dd          }|d}=|rot          dt          |                    D ]Q}||         }|                     |di           }|                     |dd          }|t          | j        dz             R|                     |g d          }g }t          dt          |                    D ].}||         }|                     |d	          }	|                     |d
          }
| 	                    |
          }|d
         }| 
                    |d          }|dk    }| 
                    |d          }|dk    }|                     |d          }|                     |d          }|                     |di           }|                     | j        d          }|                     |d|          }|rdnd}|                     |dd          }|rd}|                     |d|          }|                     |          }|                     |dd          }|                     |dd          }|                     |d|          }|                     |d          }|p|}|                     |dd          }|                     |g d          }|                     |          }|ri|r(t!          j        |t!          j        d|                    n't!          j        |t!          j        d|                    }|                     ||          }n|                     ||          }|                     ||          }i }|rAd} ||                     ||          }d} n|                     ||          }||| rdnd d!|d"<   nd#|i|d$<   |d%}|                     |d&                   |||||d'}!|||!d(<   |                     |	          |!d)}"|                    |"           0|                                 }#d*|d+}$d }%|                     |d,d-          \  }%}|                     |%          }%|                     |$|#|%          }&|$|#|&d.}'|%|%|'d-<   |'S )/NFr   rF  r  r  TzT editOrders() all orders must have clientOrderId if at least one has a clientOrderIdr#  r2   r,  r   r  r  r  rS  r   r   r  r	  r
  r  r  r	  r   r  r  r  r  )	r  r	  r   r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  rQ  )r  r  batchModify)r   modifiesrW   r  r  )r^  ra  rb  r2  r  r"   r2   r  r1  r4  r.  r  r  r  r  r  r-   r  r  r  rc  r_  r  rp  r/  r  r  r  )(r%  r  rF  r1  rg  r2  r3  r  rg  r2   r0  r4  r,  r   r  r  r  rS  r   r   r  r  r  r	  r   r  r  r  r  r  r  r  r   r4  	modifyReqr  modifyActionr  rr  rG  s(                                           r'  edit_orders_requestzhyperliquid.edit_orders_request	  s   ''))) q#f++&& 	( 	(AayH..8R@@K ..{O[YYM(#'  	N1c&kk** N N!!9"nnXxDD $ 2 2;Q\ ] ] (+DG  7M  -M  N  N  N )6  $j  $j  $j  k  kq#f++&& E	' E	'AayH!!(D11B''(;;H[[**FH%F))(F;;D(H))(F;;DU]E%%h99F$$Xw77E..8R@@K"..t|=NOOO''ZQQH+3!?%~~k:uEEH +%*"00mM_``K//+66K ..{O[YYM--k>;WWL ,,[/<XXM"..{<MNNO&9/I\5IIJ))K  2y  2y  2y  z  zK&&u--B 9SX  YW'G,>sH,M,MNNN_f_qrtv}  wI  JM  OW  wX  wX  `Y  `Y,,VR88,,VR88))&&99B I ".#'#:#:6?#S#SLDD#'#:#:6=#Q#QL (!-%)4DD( (	)$$ ;&	'" #"&&vh'788 H ( -((,,! I OOI&&&&!!##! 
 
 #<<V[R`aaf00>>''e\JJ	""
 
 #&2GN#r(  c           	          |                                   |t          | j        dz             |                     |||||||          \  }}	|                     |g|	          }
|
d         S )aO  
        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
        :param str [params.subAccountAddress]: sub account user address
        :returns dict: an `order structure <https://docs.ccxt.com/?id=order-structure>`
        Nz$ editOrder() requires an id argumentr   )r	  r"   r2   r  edit_orders)r%  r2   r,  r   r  rS  r   rF  r  r  r  s              r'  
edit_orderzhyperliquid.edit_orderJ
  sz    , 	:#DG.T$TUUU"??FDRVX^`egmnn|!!5'<88ayr(  c                 \   |                                   |                                  |                     ||          }|                     |          }|                     |di           }|                     |di           }|                     |dg           }|                     |          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>`
        rH  rh  r  )r	  r_  rj  r  r2  r`  r  )r%  r  rF  rG  rH  responseObject
dataObjectr  s           r'  rl  zhyperliquid.edit_ordersg
  s     	   **66::++G44H *bAA^^NFB??
>>*j"==  ***r(  r3   description
initialUsdc                    |                                   |                                  |                                 }d|i}|                     t	          j        |                     |          d                    }d||||d}|                     ||          }	||d<   |	|d<   |                     | 	                    ||                    }
|
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   r3   rq  rr  r  r  rr  )
r^  r	  r/  r  r-   r  r  r  r  rD  )r%  r3   rq  rr  rF  r  rG  usdr  rr  rH  s              r'  create_vaultzhyperliquid.create_vault
  s     	'')))!!##U
  243H3H3T3TV_ ` `aa!&
 
 ''66	"(++DKK,H,HII r(  c           
      >   |                                   |t          | j        dz             |                     |          }d|d         d}|||d<   n)|dn|}|                                 |dz  dz  d	z  z
  |d<   |                     |d
          }|                     |d
          }|||d<   |                     |                     ||                    }	g }
t          dt          |	                    D ]v}|	|         }|                     |d          }|
                    ||                     d|          |                     |d          ||                     |          d           w|                     |
d          }|                     ||||          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fundingHistoryr6  r  rC  i  r  r  rA  rD  r   r>  r!  )r   r,  r!  r  r  r  )r	  r"   r2   r4  r/  rE  r  rC  rD  ra  rb  rp  r,  r  r  sort_byfilter_by_symbol_since_limit)r%  r,  r?  r   rF  r4  rG  r  rA  rH  rf  rg  r  r  sorteds                  r'  fetch_funding_rate_historyz&hyperliquid.fetch_funding_rate_history
  s    	>#DG.e$efffV$$$:&
 
 #(GK  $}ss5H#'#4#4#6#6B9Kd9R#RGK !!&'2267++!&GI&&t{{7F'C'CDD q#h--(( 		 		AQKE))%88IMM**488#//}EE& LL33      fk2200NNNr(  c                     |                      |dd          }|                    d          }t          |          }|dk    r|                      |d          S d S )Nr6  r]  r  r   r   )r1  r0  rb  )r%  r4  r6  partpartsLengths        r'  get_dex_from_hip3_symbolz$hyperliquid.get_dex_from_hip3_symbol
  sY    ##FJ;;~~c""$ii??##D!,,,tr(  c                 p   d}|                      d|          \  }}d}|                     |ddd          \  }}|                                  ||d}d}|1|                     |          }|                     |          }	|	|	|d<   |                     |                     ||                    }
g }t          dt          |
                    D ]P}|
|         }i }| 	                    |d          d	|d
<   |
                    |                     ||                     Q|                     ||||          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'
        :param str [params.subAccountAddress]: sub account user address
        :param str [params.dex]: perp dex name. default is None
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nr   r  frontendOpenOrdersr  r<   r   r?  open
ccxtStatus)r  r  r	  r4  r  rC  rD  ra  rb  r1  rp  r  )r%  r,  r?  r   rF  r  r  rG  r4  r  rH  orderWithStatusrg  r  extendOrders                  r'  fetch_open_orderszhyperliquid.fetch_open_orders  sc     "889JFSSV66v?PRZ\pqq
 
 [[((F33F;;G"!(&&t{{7F'C'CDD q#h--(( 	D 	DAQKEKx008,2L)""4;;uk#B#BCCCC  &%GGGr(  c                     |                                   |                     |dd|          }|                     |ddgd          }|                     ||||          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%  r,  r?  r   rF  r  closedOrderss          r'  fetch_closed_orderszhyperliquid.fetch_closed_orders9  sd     	""64v>>++FHxj%PP00vueTTTr(  c                     |                                   |                     |dd|          }|                     |ddgd          }|                     ||||          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_ordersH  sd     	""64v>>++FHzlERR00vueTTTr(  c                     |                                   |                     |dd|          }|                     |dg dd          }|                     ||||          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_ordersW  sj     	""64v>>++FH>`>`>`bghh00vueTTTr(  c                    d}|                      d|          \  }}|                                  d}d|d}|1|                     |          }|                     |          }|||d<   |                     |                     ||                    }	i }
t          dt          |	                    D ]}|	|         }|                     |d          }||}| 	                    |d          }|K||
vr||
|<   F| 
                    |
|         d	          }| 
                    |d	          }||||k    r||
|<   t          |
                                          }|                     ||||          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
        :param str [params.subAccountAddress]: sub account user address
        :param str [params.dex]: perp dex name. default is None
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nr   historicalOrdersr  r<   r   r  r  statusTimestamp)r  r	  r4  r  rC  rD  ra  rb  r2  r1  rE  rX  valuesr  )r%  r,  r?  r   rF  r  r4  rG  r  rH  deduplicatedByOidrg  r2  r  r  existingTimestampcurrentTimestampdeduplicateds                     r'  r  zhyperliquid.fetch_ordersf  s    "88OOV&
 
 [[((F33F;;G"!(&&t{{7F'C'CDD* #%q#h--(( 	: 	:A{HNN8W55E} ""5%00C000-5%c**(,(9(9:KC:PRc(d(d%'+'8'8CT'U'U$'39J9RVfizVzVz19)#.-446677  vueDDDr(  c                    d}|                      d|          \  }}|                                  d}||                     |          }|                     |d          }d|d}||                     |d          }||d<   n/t          |          dk    }|r|n|                     |          |d<   |                     |                     ||                    }	| 	                    |	d          }
| 
                    |
|          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.clientOrderId]: client order id,(optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
        :param str [params.user]: user address, will default to self.walletAddress if not provided
        :param str [params.subAccountAddress]: sub account user address
        :returns dict: An `order structure <https://docs.ccxt.com/?id=order-structure>`
        Nr   r  r   r  r  "   r  )r  r	  r4  r1  r  rb  rM  rC  rD  r2  r  )r%  r2   r,  rF  r  r4  r  rG  isClientOrderIdrH  rh  s              r'  fetch_orderzhyperliquid.fetch_order  s    "88vNNV[[((F((AA!
 

 $YYv77F*GENN!"ggmO#2QRR8M8Mb8Q8QGEN&&t{{7F'C'CDD8 ~~h00f---r(  r  c                    |                      |d          }||                     |dd          S |                     |g d          }||}|                     |di           }|                      |d          }d }||                     |          }|                      |d          |                     |d           }n|                     ||          }|d         }|                     |d	          }	|                     |d
d          }
|                     |dg          }|                      |d          }|
|dk    rdnd}|                     |dd          }|                      |d          }| 	                    |d          }d }||dk    }|                     i d|d|                      |d          d|                      |d          d	|	d| 
                    |	          dd d|                     |d          d|d|                     |                     |d                    d|d |d!|                     |d!          d|d"|                      |d#          d$|                     |d%          r|                     |d&          nd d'|d(d |                      |d)          |                      |dt          j        ||                    ||                     |
          d d d*|          S )+Nerrorr  rF  )r  restingfilledr  r  r2   r,  r  r?  r  r  Ar*  r+  origSztotalSzr  r  ALOr   r  r  rS  r  lastTradeTimestamplastUpdateTimestampr  r   r  r	  r  r  r   limitPxr   r  r  rS  r   avgPx)averager  	remainingr?  rY  trades)r1  rH  safe_dict_nr2  r+  r;  rE  r  r  r.  r  parse_order_typer  r  r  r-   r  parse_order_status)r%  r  r4  r  r  r  r  r0  r,  r  r?  r  totalAmountr  r  r  s                   r'  r  zhyperliquid.parse_order  s   @   00??$$ $      (F(F(FGG=Ex44v..--d33HE4((0%%h55FF%%h77F!%%e[99	##E8\BB		%,00v.."ckk66D(()DD$$UD11	$$UE22?uH  
E 
$""5%00 
 T--eW== 
 	 

 Y// 
 !$ 
 "4#4#4U<M#N#N 
 f 
 D))$*@*@*T*TUU 
 3 
  
 $..== 
 D 
 T%%eY77 
 DNNSXZeDfDfpD,,UK@@@lp 
  k! 
" D# 
$ ''w77&&vy':L[Zc:d:dee"--f55/ 
  
  
0 1  	r(  r?  c                     |d S ddddddd}|                     d          rdS |                     d          rdS |                     |||          S )Nr  r  r  r  )	triggeredr  r  r  r  marginCanceledRejectedCanceled)endswithr1  r%  r?  r  s      r'  r  zhyperliquid.parse_order_status  sv    >4""(
 
 ??:&& 	:??:&& 	:&&999r(  c                 :    ddd}|                      |||          S )Nr   r4  )z
stop limitzstop marketr1  r  s      r'  r  zhyperliquid.parse_order_type  s.    !#
 
 &&999r(  c                    d}|                      d|          \  }}|                                  d}||                     |          }d|i}|d|d<   ||d<   nd|d<   |                     |d          }|                     |d          }|||d	<   |                     |                     ||                    }	|                     |	|||          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
        :param str [params.subAccountAddress]: sub account user address
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        Nrz   r  rV  r   rC  rW  rA  rD  rX  rZ  s
             r'  fetch_my_tradeszhyperliquid.fetch_my_trades  s     "88&QQV[[((FK
 /GFO#(GK  )GFO!!&'2267++!&GI&&t{{7F'C'CDD,   65%@@@r(  tradec                    |                      |d          }|                     |d          }|                     |d          }|                     |d          }|                     |          }|                     |d           }|d         }|                     |d          }	|                     |d          }
|

|
dk    rd	nd
}
|                     |d          }d }|                     |d          }||rdnd}|                     |d          }|t          j        ||          }|                     |||                     |          ||	|                     |d          d |
|||d ||                     |d          d dd|          S )Nr>  r  r  r  r,  tidr  r  r*  r+  rY  crossedr   r   r   r  feeToken)r   currencyrate)r   r  r  r,  r2   r  r   r  takerOrMakerr   rS  r   rY  )	rE  r1  r+  r;  r  r-   r  
safe_trader  )r%  r  r4  r  r   rS  r  r0  r,  r2   r  rY  r  r  r   s                  r'  parse_tradezhyperliquid.parse_trade  s   & %%eV44	  --!!%..v..))$//!!(D11!eU++v.."ckk66Due,,..	22&-:777L%%e\::
!$S*55C"Y//%%eU33( ,,UJ??  
  
$ %  	r(  c                 ^    |                      |g|          }|                     |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_positionsr2  )r%  r,  rF  	positionss       r'  fetch_positionzhyperliquid.fetch_position
  s1     ((&6::	~~iB///r(  
methodNamec                 r   |d S t          |          }|dk    rd S d }t          d|          D ]}|1|                     ||                   }|                     |          }5|                     ||                   }|                     |          }||k    rt	          | j        dz   |z   dz             |S )Nr    zH only supports fetching positions for one DEX at a time for HIP3 markets)rb  ra  r4  r  r'   r2   )r%  r  r  symbolsLengthr  rg  r4  currentDexNames           r'  get_dex_from_symbolsz hyperliquid.get_dex_from_symbols  s    ?4GA4q-(( 	P 	PAWQZ0077??WQZ00!%!>!>v!F!F!W,,&tw}z'A  EO  (O  P  P  P -r(  c                     |                                   d}|                     d|          \  }}|                     |          }d|d}|                     d|          }|||d<   |                     |                     ||                    }|                     |dg           }g }t          dt          |                    D ]1}	|	                    | 
                    ||	         d                     2|                     |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
        :param str [params.subAccountAddress]: sub account user address
        :param str [params.dex]: perp dex name, eg: XYZ
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/?id=position-structure>`
        Nr   r   r  r<   assetPositionsr   r,  F)r	  r  r  r  rC  rD  r`  ra  rb  rp  parse_positionfilter_by_array_positions)
r%  r  rF  r  rG  r  rH  rh  rf  rg  s
             r'  r  zhyperliquid.fetch_positions*  s#    	"889I6RRV%%g..(
 
 ++,<gFF$GEN&&t{{7F'C'CDD\ ~~h(8"==q#d))$$ 	> 	>AMM$--d1gt<<====--fhOOOr(  positionc                    |                      |di           }|                     |d          }|                     |          }|                     |d           }|d         }|                      |di           }|                     |d          }|dk    }	|                     |d          }
|
}d }|-t	          j        |
d          rd	nd
}t	          j        |          }|                     |d          }t	          j        |          }|                     |d          }d }|	rt	          j        ||          }n|}t	          j        t	          j	        ||          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           S )!Nr  r  r,  r  r   r  szir  longshortunrealizedPnl
marginUsed100r   r2   r  r  r
  r  	contractsr  
entryPriceentryPxr  notionalpositionValuevalue
collateralinitialMarginmaintenanceMarginliquidationPx)initialMarginPercentagemaintenanceMarginPercentager  liquidationPricer  
percentage)r2  r1  r+  r;  r-   r  
string_absr  r  
string_divsafe_positionr$  r  )r%  r  r4  r  r  r0  r,  r  r  
isIsolatedrawSizesizer  rawUnrealizedPnlabsRawUnrealizedPnlr  r  r  s                     r'  r  zhyperliquid.parse_positionv  s   6 xR88v..))$//!!(D11!>>%R88%%h77
 J.
""5%00$.w<<I66'D%d++D++E?CC%01ABB%%e\::
 	'#.z;KLLMM&M'(:;NPZ([([]bcc
!! #
H#
$#
 f#
 	#

 #
 
#
 d#
 D#
 **400#
 D#
 $**5)<<#
 #
 ((@@#
 ((7;;#
 $++J77#
  T..}==!#
"  ##
$ (,+/!../?@@ $ 0 0 H H$++J77/#
 #
 #
   	r(  r  c                    |t          | j        dz             |                                  |                     |          }|                     |d          }|t          | j        dz             |                     |d                   }|dk    }|                                 }|                     |dg          }d|||d}	d}
|                     |d	d
d          \  }
}|
+|
	                    d          r|

                    dd          }
|                     |	||
          }|	||d}|
|
|d
<   |                     |          }|S )aN  
        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)
        :param str [params.vaultAddress]: the vault address
        :param str [params.subAccountAddress]: sub account user address
        :returns dict: response from the exchange
        Nz+ setMarginMode() requires a symbol argumentr  z. setMarginMode() requires a leverage parameterr  crossupdateLeverager   rR  isCrossr  r   r  rU  re  r]  r  )r"   r2   r	  r4  rE  r  r/  r  rY  re  r  r  r  )r%  r  r,  rF  r4  r  rR  r  r  updateActionr  rr  rG  rH  s                 r'  set_margin_modezhyperliquid.set_margin_mode  s    >#DG.[$[\\\V$$$$VZ88#DG.^$^___!!&"233(!!##6J<00$ 	
 
 #>>vXfh{||f#&&t,, >+33D"==''e\JJ	""
 
 #&2GN#++G44 r(  r  c                 ^   |t          | j        dz             |                                  |                     |          }|                     |dd          }|dk    }|                     |d                   }|                                 }|                     |d          }d|||d}	d}
|                     |dd	d
          \  }
}| 	                    |
          }
| 
                    |	||
          }|	||d}|
|                     |d	          }|
|d	<   |                     |          }|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
        Nz) setLeverage() requires a symbol argumentr  r  r  r  r  r   r  rU  r  )r"   r2   r	  r4  r1  r  r/  r  rY  r  r  r  )r%  r  r,  rF  r4  r  r  rR  r  r  r  rr  rG  rH  s                 r'  set_leveragezhyperliquid.set_leverage  s\    >#DG.Y$YZZZV$$%%flGDD
(!!&"233!!##6<00$ 	
 
 #>>v}Vdfyzzf00>>''e\JJ	""
 
 #YYv~66F&2GN#++G44 r(  c                 2    |                      ||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
        :param str [params.vaultAddress]: the vault address
        :param str [params.subAccountAddress]: sub account user address
        :returns dict: a `margin structure <https://docs.ccxt.com/?id=margin-structure>`
        addmodify_margin_helperr%  r,  rS  rF  s       r'  
add_marginzhyperliquid.add_margin'  s     ((GGGr(  c                 2    |                      ||d|          S )aD  

        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
        :param str [params.vaultAddress]: the vault address
        :param str [params.subAccountAddress]: sub account user address
        :returns dict: a `margin structure <https://docs.ccxt.com/?id=margin-structure>`
        reducer  r  s       r'  reduce_marginzhyperliquid.reduce_margin6  s     ((6JJJr(  c                    |                                   |                     |          }|                     |d                   }|                     t          j        |                     ||          d                    }|dk    r| }|                                 }d|d|d}	d }
|                     |ddd	          \  }
}|                     |
          }
| 	                    |	||
          }|	||d
}|
|
|d<   | 
                    |          }|                     |                     ||          d|                     |d          i          S )Nr  rt  r  updateIsolatedMarginT)r   rR  r  ntlimodifyMarginr  rU  r  rT  r?  )r	  r4  r  r-   r  r_  r/  rY  r  r  r  rD  parse_margin_modificationr1  )r%  r,  rS  r   rF  r4  rR  r  r  r  r  rr  rG  rH  s                 r'  r  z hyperliquid.modify_margin_helperE  sz   V$$!!&"233w1$2J2J6SY2Z2Z\effgg8B!!##*	
 
 #>>v~Wegz{{f00>>''e\JJ	""
 
 #&2GN#++G44 {{499(FKKD$$Xx88N
   	r(  rh  c                 l    ||                      d |          d dd d |                     |d          d d d d
S )Nr  r  )
r   r,  r   r  rS  r  rT  r?  r  r  )r,  r1  )r%  rh  r4  s      r'  r  z%hyperliquid.parse_margin_modificationl  sQ     &&tV44$$$VX66
 
 	
r(  fromAccount	toAccountc                 8   |                                   |                                  |                     | j        d          }|                                 }|                     |g d          r|                     |g d          st          | j        dz             |                     |          }| 	                    |dd          }	|	| 
                    |	          }	|dz   |	z   }|dk    p|d	k    }
|rd
nd||
|d}|                     |          }|d         dd||
|d||d}|                     |          }|S d}d}|dk    r|}d}n |dk    r|}nt          | j        dz             |                     |           ||                                dk    r|                     t!          j        |                     |          d                    }d|||d}|                     ||          }|||d}|                     |          }|                     |          S |                     |          }d||||                     |          d}|                     ||          }|||d}|                     |          }|                     |          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?   rA   perpz. transfer() only support spot <> swap transferr  rU  Nz subaccount:r  rA   r  r  )r  rS  r  r  r  r  usdClassTransfer)r  r  r   rS  r  r  r  FmainTz4 transfer() only support main <> subaccount transferr  rt  subAccountTransfer)r   subAccountUser	isDepositrv  subAccountSpotTransfer)r   r  r  tokenrS  )r^  r	  r  r  r/  in_arrayr'   r2   r  r  r  r  r  check_addressr  r  r-   r  r  parse_transferr,  )r%  rT  rS  r  r  rF  r  r  	strAmountr  r  transferPayloadtransferSigtransferRequesttransferResponser  rU  rv  r  r  rG  rH  r,  s                          r'  r   zhyperliquid.transfer  s8    	'')))t|]CC!!##==&>&>&>?? 	$==,D,D,DEE _"47-]#]^^^--f55I--fnFYZZL'#88FF%6E	6)CyF/BF1>$MIII# 	% %O 77HHK )88J(K(1.'$"  (% %O  $77HH##	 &   )II&   +tw)__```,---<4::<<611##G$6t7L7LV7T7TV_$`$`aaC,"3&	 F %%fe44C   G
 //88H &&x000 [[&&F0"3&//77 F %%fe44C   G
 //88H&&x000r(  r   r  c           
          |d d d d d d d dd	S )Nr<  )	r   r2   r  r  r  rS  r  r  r?  r{  )r%  r   r  s      r'  r  zhyperliquid.parse_transfer  s.    
 

 

 
	
r(  tagc                    |                                   |                                  |                     |           |1|                                }|dk    rt	          | j        dz             d}|                     |dd          \  }}|                     |          }|                     |d          }| 	                                }i }d}	|!dd|z   d|d	}| 
                    ||          }	ne|                     | j        d
d          }
|
rdnd|t          |          |d}|                     |          }	|d         d|t          |          |dd}|||	d}|                     |          }|                     |          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>`
        Nr  z withdraw() only support USDCr   r  vaultTransferre  F)r   r  r  rv  r   r  r  )r  r  rS  r>  r  r  	withdraw3)r  r  r  rS  r>  r   r  )r^  r	  r  r  r'   r2   r  r  r  r/  r  r  r  strr  r  parse_transaction)r%  rT  rS  r  r#  rF  r  r  r  r  r  r  rG  rH  s                 r'  r   zhyperliquid.withdraw  s    	'')))7###::<<Dv~~"47-L#LMMM#<<VZQ_``f00>>6>22!!###' $| 3"	 F %%fe44CC NN4<NNM1>$MIII&f++	 G ))'22C$+,>$?$-&f++# F 
 

 ++G44%%h///r(  transactionc                 >   |                      |d          }|                     |di           }d }|                      |d          }|d|d}d }|                     |d          }||dk    }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S )Nr>  deltarY  r  r  r   r   internalTransferr   r2   txidrh  r  r  networkr  	addressTor  addressFromr  r#  tagTotagFromrS  usdcr  r?  r@  )commentinternalrY  )rE  r2  r1  r  r  )	r%  r)  r  r  r+  rY  feeCostr6  r   s	            r'  r(  zhyperliquid.parse_transaction0  s    %%k6::	{GR88##E511" C v.. 22H
K
$
 D$$[&99
 	

 Y//
 t
 t
 ))%??
 4++E6::
 4
 T
 t
 D
 d&&uf55
 
  d&&{H==!
" t#
$  )
 
 
 	
r(  c                 l   |                                   d}|                     d|          \  }}|                     |          }d|d}|                     |                     ||                    }|                     |d          |                     |d          d}|                     ||          S )a  
        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
        :param str [params.subAccountAddress]: sub account user address
        :returns dict: a `fee structure <https://docs.ccxt.com/?id=fee-structure>`
        Nr   userFeesr  userCrossRateuserAddRate)r:  r;  )r	  r  r4  rC  rD  r1  parse_trading_fee)r%  r,  rF  r  r4  rG  rH  rh  s           r'  fetch_trading_feezhyperliquid.fetch_trading_feec  s     	"889JFSSVV$$
 
 &&t{{7F'C'CDDJ "--hHH++HmDD
 
 %%dF333r(  rY  c                     |                      d |          }|||                     |d          |                     |d          d d dS )Nr;  r:  )r   r,  r   r   r  	tierBased)r,  r  )r%  rY  r4  r,  s       r'  r<  zhyperliquid.parse_trading_fee  s[    H !!$//%%c=99%%c?;;
 
 	
r(  c                 b   |                                   d}|                     d|          \  }}d|d}|||d<   |                     |d          }|||d<   |                     |dg          }|                     |                     ||                    }|                     |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
        :param str [params.subAccountAddress]: sub account user address
        :returns dict: a `ledger structure <https://docs.ccxt.com/?id=ledger-entry-structure>`
        Nrq   userNonFundingLedgerUpdatesr  rC  rA  rD  )r	  r  rE  r  rC  rD  parse_ledger)	r%  rT  r?  r   rF  r  rG  rA  rH  s	            r'  fetch_ledgerzhyperliquid.fetch_ledger  s     	"88OOV1
 
 #(GK !!&'22!&GIYYvy11F&&t{{7F'C'CDD   4>>>r(  itemc                 (   |                      |d          }|                     |di           }d }|                      |d          }|d|d}|                     |d          }|                     |d          }|                     ||                     |d          d d |                     |d	          |                     |d          |                     |          d |                     |          ||                     |          d d d |d
|          S )Nr>  r+  rY  r  r,  r   r4  rh  r  )r   r2   	directionr  referenceAccountreferenceIdr   r  rS  r  r  beforeafterr?  rY  )rE  r2  r1  safe_ledger_entryparse_ledger_entry_typer$  r  )	r%  rD  r  r  r+  rY  r7  r   rS  s	            r'  parse_ledger_entryzhyperliquid.parse_ledger_entry  s8    %%dF33	tWb11##E511" C v..!!%00%%""400 $ 0 0 ? ?++D&990066''//"Y//'
 '
  !  	r(  c                 :    ddd}|                      |||          S )Nr   )r-  accountClassTransferr  )r%  r   
ledgerTypes      r'  rL  z#hyperliquid.parse_ledger_entry_type  s.     *$.
 

 
D$777r(  c                 8   |                                   d}|                     d|          \  }}d|d}|||d<   |                     |d          }|5|t          | j        dz             ||d<   |                     |dg          }|                     |                     ||                    }|                     |          }	d}
| 	                    |dd	          \  }
}| 
                    |
          }
g }|
ot          d
t          |	                    D ]P}|	|         }|d         dk    r:|                     |d          }|d         d|
z   k    r|                    |           Qn|                     |	ddgd          }|                     |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
        :param str [params.subAccountAddress]: sub account user address
        :param str [params.vaultAddress]: vault address
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/?id=transaction-structure>`
        NfetchDepositsWithdrawalsrA  r  rC  rA  z0 fetchDeposits requires since while until is setrD  r  r   r   vaultDepositr+  vaultre  rW  F)r	  r  rE  r"   r2   r  rC  rD  extract_type_from_deltar  r  ra  rb  r2  rp  r  parse_transactions)r%  rT  r?  r   rF  r  rG  rA  rH  recordsr  depositsrg  recordr+  s                  r'  fetch_depositszhyperliquid.fetch_deposits$  s    	"889SU[\\V1
 
 #(GK !!&'22}'2d(deee!&GIYYvy11F&&t{{7F'C'CDD ..x88#<<VE_aoppf00>>#1c'll++ 0 0 &>^33 NN67;;EW~)<<< ///0 ++GVi[%PPH&&xueDDDr(  c                    |                                   d}|                     d|          \  }}d|d}|||d<   |                     |d          }|||d<   |                     |dg          }|                     |                     ||                    }|                     |          }	d}
|                     |dd          \  }
}|                     |
          }
g }|
ot          d	t          |	                    D ]P}|	|         }|d
         dk    r:|                     |d          }|d         d|
z   k    r|                    |           Qn|                     |	d
dgd          }|                     |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
        :param str [params.subAccountAddress]: sub account user address
        :param str [params.vaultAddress]: vault address
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/?id=transaction-structure>`
        NrR  rA  r  rC  rA  rD  r  r   r   vaultWithdrawr+  rT  re  r   F)r	  r  rE  r  rC  rD  rU  r  r  ra  rb  r2  rp  r  rV  )r%  rT  r?  r   rF  r  rG  rA  rH  rW  r  withdrawalsrg  rY  r+  s                  r'  fetch_withdrawalszhyperliquid.fetch_withdrawals]  s    	"889SU[\\V1
 
 #(GK !!&'22!&GIYYvy11F&&t{{7F'C'CDD ..x88#<<VE_aoppf00>>#1c'll++ 3 3 &>_44 NN67;;EW~)<<<#**62223 ..weTTK&&{D%GGGr(  c                     |                                   |                     |          }|                                 }|                     ||          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  rq  parse_open_interests)r%  r  rF  swapMarketss       r'  fetch_open_interestsz hyperliquid.fetch_open_interests  sP     	%%g..--//((g>>>r(  c                     |                      |          }|                                  |                     |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>`
        )r,  r	  rb  )r%  r,  rF  oiss       r'  fetch_open_interestzhyperliquid.fetch_open_interest  sH     V$$''&996{r(  c           	         |                      |di           }|                     |d          }d }||                     |          }|                     |                     |          |                     |d          d d d |d|          S )Nr   r3   openInterest)r,  openInterestAmountopenInterestValuer  r  r   )r2  r1  r+  safe_open_interestr,  r  )r%  interestr4  r  r0  s        r'  parse_open_interestzhyperliquid.parse_open_interest  s    & >>(FB77&11--d33H&&&&x00"&"2"28^"L"L!%(
 (
   	r(  c                    |                                   d}||                     |          }d}|                     d|          \  }}|dd}|||d<   |                     |d          }|                     |d          }|||d<   |                     |                     ||                    }	|                     |	|||          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
        :param str [params.subAccountAddress]: sub account user address
        :returns dict: a `funding history structure <https://docs.ccxt.com/?id=funding-history-structure>`
        Nrj   userFunding)r  r   rC  rA  rD  )r	  r4  r  rE  r  rC  rD  parse_incomes)
r%  r,  r?  r   rF  r4  r  rG  rA  rH  s
             r'  fetch_funding_historyz!hyperliquid.fetch_funding_history  s     	[[((F"889NPVWWV!
 
 #(GK !!&'2267++!&GI&&t{{7F'C'CDD" !!(FE5AAAr(  c           	         |                      |d          }|                     |d          }|                     |d          }|                      |d          }d }||                     |          }|                     ||          }|                      |d          }|                      |dd          }	|                     |d          }
||d	         |	||                     |          ||                     |          |
d
S )Nrh  r>  r+  r  r4  r  r  r!  r,  )r   r,  rT  r  r  r2   rS  r  )r1  rE  r2  r+  r;  r  r  r$  )r%  incomer4  r2   r  r+  r  r0  rS  rT  r  s              r'  parse_incomezhyperliquid.parse_income  s    ff--%%ff55	vw//v..--d33H!!(F33!!%00&99}55X&"Y//''//	
 	
 		
r(  weightc                     |                                  }d|i}d|d}|                     ||          }||d<   ||d<   |                     |                     ||                    }|S )a  
        Instead of trading to increase the address based rate limits, self action allows reserving additional actions for 0.0005 USDC per request. The cost is paid from the Perps balance.
        :param number weight: the weight to reserve, 1 weight = 1 action, 0.0005 USDC per action
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a response object
        r  reserveRequestWeight)r   rt  r  rr  r  )r%  rt  rF  r  rG  r  rr  rH  s           r'  reserve_request_weightz"hyperliquid.reserve_request_weight  s     !!##U
 +
 
 ''66	"(++DKK,H,HIIr(  c                 <   |                                  }d|i}d|d}|                     |d          }||                     |d          }||d<   |                     ||d|          }||d<   ||d<   |                     |                     ||                    }|S )aN  
        creates a sub-account under the main account
        :param str name: the name of the sub-account
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.expiresAfter]: time in ms after which the sub-account will expire
        :returns dict: a response object
        r  createSubAccount)r   r3   r  Nr  rr  )r/  rE  r  r  r  rD  )	r%  r3   rF  r  rG  r  r  rr  rH  s	            r'  create_sub_accountzhyperliquid.create_sub_account4  s     !!##U
 '
 
 ((@@#YYv~66F&2GN#''t\JJ	"(++DKK,H,HIIr(  c                     g }t          dt          |                    D ]0}||         }|d         d         |d<   |                    |           1|S )Nr   r+  r   )ra  rb  rp  )r%  rh  rW  rg  rY  s        r'  rU  z#hyperliquid.extract_type_from_deltaN  s[    q#d))$$ 	# 	#A!WF#G_V4F6NNN6""""r(  c                 d    |d S |                     d          r|                    dd          S |S )Nre  r]  )re  r  )r%  r  s     r'  r  z hyperliquid.format_vault_addressV  s;    ?4d## 	-??4,,,r(  rF  c                     d }|                      ||dd          \  }}|}|                     ||d|          \  }}|
|dk    r||gS | j        | j        dk    r	| j        |gS t          | j        dz   |z   dz             )Nr  rU  r  r]  r  zF() requires a user parameter inside 'params' or the wallet address set)rY  r  r   r"   r2   )r%  r  rF  userAuxr  s        r'  r  z!hyperliquid.handle_public_address]  s    99&*fVijj44VZT[\\f42::&>!*1Cr1I1I&//#
 :  >H  !H  I  I  	Ir(  r  c                    |d S |                      | j        di           }|                      ||          rR|                      ||          }|                     |dd          }|                     |d|          }|dz   |z   dz   |z   S |                    d          dk    s|                    d          dk    r|S |                    d          dk    r|                    dd	          }|                     |          d
z   S )Nr   r8  r  rT  r.  r  rB  @r  z
/USDC:USDC)r2  r  r1  findr  r3  )r%  r  hi3TokensBynamehip3Dictr8  rT  s         r'  r+  zhyperliquid.coin_to_market_idh  s   <4..7I2NN>>/400 	4~~ot<<H$$Xw??E##Hfd;;D#:%+e3399S>>B$))C..2"5"5K99S>>B<<S))D&&t,,|;;r(  reasonrB  headersbodyc
                 @   |sd S |                      |dd          }
|                      |d          }d }|
dk    r|                      |d          }n|
dk    rt          | j        dz   |z             ||}n|                     |di           }|                     |di           }|                     |d	g           }t          d
t          |                    D ]"}|                      ||         d          }| n#d|v r1|                     |di           }|                      |d          }||}| j        dz   |z   }|d uo|dk    }|rD|                     | j        d         ||           | 	                    | j        d         ||           |rt          |          d S )Nr?  r]  r  errrH  
unknownOidr  rh  r  r   r   r   )r1  r&   r2   r2  r`  ra  rb  throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr!   )r%  rT  r  rB  r  r  r  rH  requestHeadersrequestBodyr?  r  ri  responsePayloadrh  r  rg  errorStatuserrorMsgfeedbacknonEmptyMessages                        r'  handle_errorszhyperliquid.handle_errorsx  s    	4 !!(Hb99  733U??&&x<<GG|### 4555GG"nnXz2FFO>>/62>>D~~dJ;;H1c(mm,,  **8A;@@&E '4"nnT8R@@++KAA*&G7S=4'#4/Dgm 	^001I7T\]]]001I7T\]]] 	*)))tr(  r   GETc                     |                      | j        d         |                   dz   |z   }|dk    rddi}|                     |          }||||dS )Nr   r.  POSTzContent-Typezapplication/json)rB  r  r  r  )implode_hostnamer   json)r%  pathr   r  rF  r  r  rB  s           r'  signzhyperliquid.sign  sh    ##DIe$4S$9::S@4GV 2G 99V$$DfdwOOOr(  c                 x    d|v r d|v r|d         }|d         }||v r||         S |                      |dd          S )Nr   r   r   r   )r/  )r%  r   r  r  rF  configr   r   s           r'  calculate_rate_limiter_costz'hyperliquid.calculate_rate_limiter_cost  sS    Vv%5%5&>DH%Fv~~d|#vvq111r(  c                     |                      |          }d }	|                     |ddd          \  }	}|                     |	          }	|d         }||||||d}
i }|	|	|d<   |||
d<   |
|gS )NrQ   r  rU  r,  )r,  r   r  rS  r   rF  r2   )r4  rY  r  )r%  r2   r,  r   r  rS  r   rF  r4  r  r  r  s               r'  r  z(hyperliquid.parse_create_edit_order_args  s    V$$#>>v}Vdfyzzf00>>!
 
 #+7L(>E$K|$$r(  )N)T)NN)__name__
__module____qualname__r   r#  r*  r'  r   r4  rI  rK  r   rn  r    r   rx  rs  rq  floatr  rr  dictr  r  r   r  r	   r   r  r   r   r  r   r  r   r1  r   r  rX  rK  rT  r   r[  r_  rc  rj  rs  ru  r}  r  objectr  r  r  r  r  r  r  r  r  r  r_  r  r  r  r  r  r  r   r   r   r  r   r  r   r  r!  r  rC  rB  rA  rG  r   r`  rd  rj  rm  rl  r  rw  r}  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r   r  r  r  r  r   r  r  r  r  r   r   r   r  r   r   r(  r   r=  r<  r
   rC  rM  rL  rZ  r^  rb  re  rl  rp  rs  rw  rz  rU  r  r  r+  r  r  r  r  __classcell__)r&  s   @r'  r/   r/      sO       X# X X X X X Xt
. . . . .7S 7_ 7 7 7 7 7 7 #% 
 
 
 
0 !# 3 3 3 3 ') L LZ L L L L\ $&  $v,    6 )+ D DtF| D D D DL )+ 7* 7*tF| 7* 7* 7* 7*r(1u (1u (1[` (1 (1 (1 (1T )+ k ktF| k k k kZf4 fF f f f fPAc Ac A A A A $& a) a)( a) a) a) a)F :>b .f .fs .f3 .fY .f .f .f .f` 04B -G -GW -G7 -G -G -G -G^ 6:" 79 797 79 79 79 79 79r/
 /
v /
 /
 /
 /
 /
b 4  6    B 9=4^bkm 8] 8]# 8]# 8]S 8]X[ 8]rvw{r| 8] 8] 8] 8]t
 
 
4 
 
 
 
0 6:UW 8A 8A3 8As 8A# 8A 8A 8A 8At} } }k k k k k k: : :
 
 
L L L
 
 
 
J J J J* *TZ * * * *X  	C 	C 	C	C 	C 	C	C 	C 	C	C 	C 	C	C 	C 	C	C 	C 	C  . 13  1C  1  1  1  1D      >BQV_a #- #- #-s #- #- #- #-J =? .1 .1 .1 .1 .1 .1` AC +1 +14 +1 +1 +1 +1Z >@      * gksu  3 i y RW `c    6 fh FO FO FO9 FOe FOW\ FOlq FO FO FO FOP @B )9 )9D$6 )9 )9 )9 )9V mqy{ 9 93 9i 9y 9Z] 9fi 9 9 9 9v 46 h h$ h h h hT 37r ) )s )C ) ) ) ), ;?r - -c -C - - - -^ 8<B 7G 7GC 7G 7G 7G 7G 7Gr CGr 2 2c 2C 2VZ 2 2 2 2h SU F5 F55H0I F5 F5 F5 F5P <> & &s & & & &P 24 i i i iV TXfjsu  S # S  S `c    : >@ 4+ 4+$|"4 4+ 4+ 4+ 4+l QS $ $ $3 $C $ $ $ $L 8<$]ajl 5O 5O 5OC 5OWZ 5O 5O 5O 5On   /3TXac 5H 5H 5H3 5Hc 5Hhlmrhs 5H 5H 5H 5Hn 154VZce U U# US UPS Ujnotju U U U U 37TX\eg U UC Us URU Ulpqvlw U U U U >BPTcgpr U Us U# U]` Uw{  }B  xC U U U U *.Dt\^ ?E ?E3 ?Ec ?E ?Ecghmcn ?E ?E ?E ?EB 26b =. =.c =.3 =. =. =. =.~W W Wv W W W W Wr: : : : :": : : -1tRV_a 7A 7Ac 7A 7AC 7A 7A 7A 7Ar8 8 8v 8 8 8 8 8t 24 0 0S 0 0 0 0 s W    $ 26b JP JPw JPT(^ JP JP JP JPXJ Jt JV J J J JX >B" 3 3# 3s 3 3 3 3j 9=R . .S .# . . . .` =? H H He HCU H H H H @B K KC K KFX K K K K FH % %3 %L^ % % % %N
 
d 
F 
N` 
 
 
 
& [] a1 a1S a1% a1c a1c a1an a1 a1 a1 a1F
 
t 
x 
= 
 
 
 
  KOWY <0 <0S <0% <0# <0C <0^i <0 <0 <0 <0|1
 1
T 1
X 1
Q\ 1
 1
 1
 1
f 57 94 94 94;N 94 94 94 94v,
 ,
T ,
6 ,
EX ,
 ,
 ,
 ,
\ (,$TZ\ &? &? &?C &?s &?aefqar &? &? &? &?P' 't 'x '; ' ' ' 'R8 8 8 *.Dt\^ 7E 7E3 7Ec 7E 7E 7E 7E 7Er -1tRV_a 5H 5Hc 5H 5HC 5Hfjkvfw 5H 5H 5H 5Hn 7;2 
? 
?G 
? 
? 
? 
? 79 
 
# 
 
 
 
 F    B 37TX\eg +B +BC +Bs +BRU +B +B +B +BZ#
 #
6 #
 #
 #
 #
J :<  S     * 46  s    4 ,.     C    	I 	IT 	I 	I 	I 	I<c < < < < *# *s * *c *TX *`c * * * *X &eBSW P P P P MO 2 2 2 2 @D  MO % %s %C %y %Xa %kp %y| % % % % % % % %r(  r/   )4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   r   typingr    ccxt.base.errorsr!   r"   r#   r$   r%   r&   r'   r(   ccxt.base.decimal_to_precisionr)   r*   r+   r,   ccxt.base.preciser-   r/   r{  r(  r'  <module>r     s   ( ' ' ' ' ' 1 1 1 1 1 1  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K       * * * * * * . . . . . . ' ' ' ' ' ' . . . . . . ) ) ) ) ) ) * * * * * * ) ) ) ) ) ) . . . . . . 0 0 0 0 0 0 9 9 9 9 9 9 = = = = = = 4 4 4 4 4 4 % % % % % %nF% nF% nF% nF% nF%(K nF% nF% nF% nF% nF%r(  