
    ih                       d dl mZ d dlm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 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"  G d dee          Z#dS )    )Exchange)ImplicitAPI)Balances
CurrenciesIntMarginModificationMarketNumOrder	OrderBookOrderRequest	OrderSide	OrderTypeStrStringsTradeTransferEntry)List)ExchangeError)ArgumentsRequired)InvalidOrder)OrderNotFound)NotSupported)ROUND)DECIMAL_PLACES)SIGNIFICANT_DIGITS)	TICK_SIZE)Precisec                       e Zd Z fdZ fdZi fdefdZi fdee         fdZ	i fdee         fdZ
i fdee         fdZ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d
d
i fdedededee         fdZdOdedefdZd
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dPdZd ZdOdefdZ d Z!d Z"d Z#d
i fded e$d!e%d"e&d#e'f
d$Z(i fd%ee)         fd&Z*d
i fd'edefd(Z+d
i fd)ee         defd*Z,d
d
i fd'eded ed!ed"e'd#e'fd+Z-d
d
d
i fdededefd,Z.d
d
d
i fdedededee/         fd-Z0d
d
d
i fdedededee/         fd.Z1d
i fd'edefd/Z2dOdede/fd0Z3d1 Z4d2 Z5d
d
d
i fdededefd3Z6dOdede7fd4Z8i fdefd5Z9d
i fd6e:fd7Z;dOdefd8Z<d
i fd9edefd:Z=d
i fd;edefd<Z>i fdede?fd=Z@i fdede?fd>ZAi fdede?fd?ZBdOdede?fd@ZCi fdAed"e&dBedCedeDf
dDZEd
i fdAefdEZFdOdFefdGZGdHedIeHfdJZIdK ZJdLdMi d
d
fdNZK xZLS )Qhyperliquidc                    |                      t          t          |                                           i dddddg 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d/dd0di d1d2d3dd4dd5dd6dd7dd8dd9dd:dd;dd<dd=dd>dd?d d@ddAddBdi dCddDddEddFddGddHddIddJddKddLddMddNddOddPddQddRddSdi dTddUddVddWddXddYddZdd[dd\dd]dd^dd_dd`ddaddbddcddddedfdgdhdidjdkdldmdndodpdqdedrdsdtdudvdwdwdxdydydxdzd{d|d}d~ddddiidddiidxd|                     d          |                     d          d|                     d          |                     d          dddddddddi t
          t
          t
          t
          t
          t
          t
          t
          t          t
          d
ddt          di ddddddi          S )Nidr    nameHyperliquid	countriesversionv1	rateLimit2   	certifiedFproThasCORSspotmarginswapfutureoption	addMarginborrowCrossMarginborrowIsolatedMargincancelAllOrderscancelOrdercancelOrderscloseAllPositionsclosePositioncreateMarketBuyOrderWithCostcreateMarketOrderWithCostcreateMarketSellOrderWithCostcreateOrdercreateOrderscreateReduceOnlyOrder	editOrderfetchAccountsfetchBalancefetchBorrowInterestfetchBorrowRateHistoriesfetchBorrowRateHistory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fetchOpenOrders
fetchOrderfetchOrderBookfetchOrdersfetchOrderTradesfetchPositionfetchPositionModefetchPositionsfetchPositionsRiskfetchPremiumIndexOHLCVfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTransferfetchTransfersfetchWithdrawalfetchWithdrawalsreduceMarginrepayCrossMarginrepayIsolatedMarginsetLeveragesetMarginModesetPositionModetransferwithdraw
timeframes1m3m5m15m30m1h2h4h6h12h1d3d1w)r   r   r   r   r   r   r   r   r   r   r   r   r   1M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   exchanger   z0.00035z0.0001)takermaker)r0   r.   requiredCredentials)apiKeysecretwalletAddress
privateKey
exceptions)
z%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 )exactbroadprecisionModecommonCurrenciesoptionsg?*0x0000000000000000000000000000000000000000)defaultTypesandboxModedefaultSlippagezeroAddress)deep_extendsuperr    describeparse_numberr   r   r   )self	__class__s    V/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/hyperliquid.pyr   zhyperliquid.describe   s   k4 8 8 A A C C sF
-sF
MsF
 sF
 t	sF

 sF
 sF
 4sF
  UUU %U 	U
 $U %U TU $UU 'U "5U tU U $UU  U /U  ,U!U" 0#U U$ t%U& 'U( ()U* T+U,  -U. /U0 &u1U2 +E3U4 )%5U6 &u7U8 $T9U: ';U< (=U> "4?U@ &uAUB (CUD  EU U UF *:GUH +EIUJ &uKUL #EMUN *4OUP $UQUR "5SUT *5UUV +EWUX uYUZ  [U\ %e]U^ $U_U` "4aUb +EcUd eUf !%gU U Uh &uiUj  kUl dmUn $UoUp +EqUr "4sUt duUv !$wUx uyUz #E{U|  }U~ $UU@ !$AUB %eCUD )%EUF uGUH IU U UJ UKUL tMUN "5OUP #EQUR  SUT !%UUV "5WUX #EYUZ [U\ #E]U^ &u_U` taUb  cUd "5eUf DgUh DiU UsF
|  }sF
\ )]sF
^ k67 
 DD  1[V: _sF
|  "A }sF
T !..y99!..x88 
 "..y99!..x88 	 	UsF
h "!%"	$ $isF
t  >J<H;GBNGSUa,8@LLY+7  usF
T YUsF
V  !WsF
Z %$#'K	 [sF
 sF
 s s s	    c                 l    t          t          |                               |           || j        d<   d S )Nr   )r   r    set_sandbox_moder   )r   enabledr   s     r   r   zhyperliquid.set_sandbox_mode   s3    k4  11':::&-]###r   returnc                 |   ddi}|                      |                     ||                    }|                     |dg           }i }t          dt	          |                    D ]W}|                     ||i           }|}|                     |d          }	|                     |	          }
||	|
d|ddddddd||
<   X|S )aO  
        fetches all available currencies on an exchange
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-exchange-metadata
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        typemetauniverser   r#   N)r"   r#   code	precisionr   activedepositr   networksfeelimits)publicPostInfoextend	safe_listrangelen	safe_dictsafe_stringsafe_currency_code)r   paramsrequestresponser   resultidatar"   r#   r   s              r   fetch_currencieszhyperliquid.fetch_currencies   s     F
 &&t{{7F'C'CDD ~~h
B77q#d))$$ 	 	A>>$2..DB##D&11D**400D!   F4LL r   c                     |                      |          |                     |          g}|}|d         }|d         }|                     ||          S )a  
        retrieves data on all markets for hyperliquid
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-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   )fetch_swap_marketsfetch_spot_marketsarray_concat)r   r   rawPromisespromisesswapMarketsspotMarketss         r   fetch_marketszhyperliquid.fetch_markets  s\     ##F++##F++
 qkqk  k:::r   c           	         ddi}|                      |                     ||                    }|                     |di           }|                     |dg           }|                     |di           }g }t	          dt          |                    D ]\}|                     |                     ||i           |                     ||i                     }||d<   |                    |           ]|                     |          S )a  
        retrieves data on all swap markets for hyperliquid
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-asset-contexts-includes-mark-price-current-funding-open-interest-etc
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        r   metaAndAssetCtxsr   r   r   baseId)r   r   r   r   r   r   appendparse_markets)	r   r   r   r   r   	assetCtxsr   r   r   s	            r   r   zhyperliquid.fetch_swap_markets  s    &
 &&t{{7F'C'CDD> ~~h2..~~dJ33NN8Q33	q#d))$$ 	  	 A;;tQ++y!R00 D DNMM$!!&)))r   c                    ddi}|                      |                     ||                    }|                     |di           }|                     |dg           }|                     |dg           }g }t	          dt          |                    D ]D}|                     ||i           }	|                     |	d          }
|
                    d          }|                     |d          }|                     |d          }|                     |          }|                     |          }|dz   |z   }|                     | j	        d	i           }| 
                    |d
          }| 
                    |d          }|                     |	dg           }|                     |d          }|                     |d          }|                     ||i           }|                     ||i           }|                     |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#                     F|S )$a  
        retrieves data on all spot markets for hyperliquid
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-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   spotMetaAndAssetCtxsr   r   tokensr#   /r   r.   r   r   
szDecimalsi'  r"   symbolbasequotesettleNr   quoteIdsettleIdTr/   r0   Fr1   r2   r   contractlinearamountpriceminmaxleverager   r   costinverser   r   contractSizeexpiryexpiryDatetimestrike
optionTyper   r   createdr   )r   r   r   r   r   r   r   splitr   r   safe_numbersafe_integernumber_to_stringr   safe_market_structurer   parse_precision)r   r   r   r   firstr   r   marketsr   market
marketNamemarketPartsbaseNamer   r   r   r   r   r   r   	tokensPosbaseTokenPosquoteTokenPosbaseTokenInfoquoteTokenInfobaseDecimalsquoteDecimalsr   s                               r   r   zhyperliquid.fetch_spot_marketsH  s    *
 &&t{{7F'C'CDDH xB//~~eZ44x44q#d))$$ F	 F	A^^D!R00F))&&99J$**3//K''Q77H&&{A66G**844D++G44ECZ%'F>>$)VR88D$$T733E$$T733Evx<<I,,Y::L --i;;M NN6<DDM!^^FM2FFN++M<HHL --nlKKM**1u955FNN455 27f27&27 27 	27
 $27 &27 727 D27 27 27 $27 27 %27 %27 $27  E!27" $#27$ ! $"&""//0D0D\0R0RSS*   $#! !
  $# 
  $# 
  $#  $  c27 27 27 2 2 2 2 2 2f r   c                    d}|                      |d          }|                     |          }|                      |d          }d}|                     |          }|dz   |z   }d}	d}
|	r
|
r|dz   |z   }|                     | j        di           }|                     |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dd |d S )!NUSDCr#   r   r   T:r0   r   r   r"   r   r   r   r   r   r   r   r.   Fr/   r1   r2   r   r   r   1r      r   r   r   r   )r   r   r   r   r  r   r
  )r   r  r   r   r   r   r   r   r   r   r0   r   r   r   s                 r   parse_marketzhyperliquid.parse_market  sw   * //''00!!&(33((22e# 	/ /#.~~di44  w//  w//2
&2
f2
 D2
 U	2

 f2
 f2
 w2
 2
 F2
 E2
 d2
 D2
 e2
 e2
 d2
  !2
" d#2
$  --c22"++D,@,@AQAQRXZfAgAg,h,hii    
   
   
    $ c2
 2
 2
 2	
r   c                    d}|                      d|          \  }}d}|                     dd|          \  }}|dk    }|rdnd}||d}|                     |                     ||                    }|                     |d          }|d|i}	t          d	t          |                    D ]}
||
         }|                     |                     |d
                    }| 	                                }|                     |d          }|                     |d          }||d<   ||d<   ||	|<   | 
                    |	          S |                     |di           }||                     |d          |                     |d          dd}|                     |d          }||d<   |                     |          |d<   | 
                    |          S )aL  
        query for balance and get the amount of funds available for trading or funds locked in orders
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-state
        :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
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        NrC   r.   spotClearinghouseStateclearinghouseStater   userbalancesr   r   cointotalholdfreemarginSummaryaccountValuetotalMarginUsed)r%  used)r   r  time	timestampdatetime)handle_public_addresshandle_market_type_and_paramsr   r   r   r   r   r   r   accountsafe_balancer   
safe_floatr  iso8601)r   r   userAddressr   isSpotreqTyper   r   r#  spotBalancesr   balancer   r1  r%  r'  r   r   r-  s                      r   fetch_balancezhyperliquid.fetch_balance  s    "88PPV99.$PVWWf&./5P**<P
 
 &&t{{7F'C'CDDH >>(J77"H-L1c(mm,, - -"1+..t/?/?/P/PQQ,,..(('::''88#( "&%,T""$$\222~~h<<~>>.?@@ 
 
 %%h77	'{!\\)44z  (((r   Nr   limitc           	         |                                   |                     |          }d|d         d}|                     |                     ||                    }|                     |dg           }|                     |dg           |                     |dg           d}|                     |d          }	|                     ||d	         |	d
ddd          S )aW  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#info
        :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
        l2Bookr   r   r$  levelsr   r   )bidsasksr,  r   r@  rA  pxsz)load_marketsr  r   r   r   r  parse_order_book)
r   r   r;  r   r  r   r   r   r   r-  s
             r   fetch_order_bookzhyperliquid.fetch_order_bookl  s     	V$$6N
 
 &&t{{7F'C'CDD. ~~h"55NN4B//NN4B//
 
 %%h77	$$VVH-=y&RXZ^`deeer   r   sincec                    |                                   |                     |          }|                     |d|                                           }|d}|d}|                     |dg          }d|d         |||dd}|                     |                     ||                    }	|                     |	||||          S )	a)  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#info-1
        :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   i  candleSnapshotr   )r$  interval	startTimeendTime)r   req)rD  r  r  millisecondsomitr   r   parse_ohlcvs)
r   r   	timeframerG  r;  r   r  rI  r   r   s
             r   fetch_ohlcvzhyperliquid.fetch_ohlcv  s     	V$$!!&'43D3D3F3FGG=E=E6G9--$v%" 	 
 
 &&t{{7F'C'CDD"   69eUKKKr   r  c           	         |                      |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS )Ntohlcv)r  r  )r   ohlcvr  s      r   parse_ohlcvzhyperliquid.parse_ohlcv  s      eS))UC((UC((UC((UC((UC((
 	
r   c                    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
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills-by-time
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest trade
        :param str [params.address]: wallet address that made trades
        :param str [params.user]: wallet address that made trades
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Nrs   r"  userFillsByTimer   rL  	userFillsrI  rM  r/  rD  safe_marketr  rP  r   r   parse_trades
r   r   rG  r;  r   r5  r  r   rI  r   s
             r   fetch_tradeszhyperliquid.fetch_trades  s     "88OOV!!&))K
 /GFO#(GK  )GFO!!&'2267++!&GI&&t{{7F'C'CDD*   65%@@@r   c                 t    |                      |t          | j        |         d         d         | j                  S )Nr   r   )decimal_to_precisionr   r  r   )r   r   r   s      r   amount_to_precisionzhyperliquid.amount_to_precision  s2    ((V8L[8YZb8ceiewxxxr   c                     |                      |          }|                     |t          |d         d         t          | j                  }|                     |t          dt
          | j                  }|S )Nr   r      )r  rf  r   r   paddingModer   )r   r   r   r  r   decimalParsedResults         r   price_to_precisionzhyperliquid.price_to_precision  sc    V$$**5%9LW9UWikok{||"77q.Z^Zjkk""r   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	secp256k1rn  rs   rZ  )rw  rx  rZ  )ecdsasum)r   rq  r   	signatures       r   	sign_hashzhyperliquid.sign_hash#  sf    JJtCDDz:cdd+;[$OO		#&	#&"in--
 
 	
r   c                 d    |                      |                     |          |dd                    S )Nru  )r}  rs  )r   rr  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   rq  	isTestnetr  s       r   construct_phantom_agentz#hyperliquid.construct_phantom_agent.  s%    ", 
 
 	
r   c                    |                      |          }|                     |          }|}|d|                     |          z   z  }||dz  }n
|dz  }||z  }|                     |                     |          dd          S )N000000001ro  binary)packbbinary_to_base16int_to_base16rq  base16_to_binary)r   actionvaultAddressnonce
dataBinarydataHexr   s          r   action_hashzhyperliquid.action_hash5  s    ZZ''
''
33$,,U3333DLDDDLDL 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  chainIdr#   verifyingContractr&   Agentr  stringr#   r   r  bytes32)r  	safe_boolr   r  r   eth_encode_structured_datar  r   )r   r  r  vaultAdressrq  r  phantomAgentr   r  domainmessageTypesmsgr|  s                r   sign_l1_actionzhyperliquid.sign_l1_actionA  s    U;;NN4<FF	33D)DD. &&t|]CC!,	
 
 !844';;
 --flLQQ%%c4?;;	r   c                     |                      | j        d          }|d|dd}|                     |||          }|                     || j                  }|S )Nr   r   r  r  )r   r   r  r  r   )r   r  r  rr  r   r  r  r|  s           r   	build_sigzhyperliquid.build_sigm  sg    &&t|]CC!,	
 
 --flGLL%%c4?;;	r   c                     |                      | j        d          }|rdnd}dddddddd	d
dgi}|                     |||          S )Nr   n 鱤  UsdTransferSignPayloaddestinationr  r  r   r,  uint64r  r   r  r   rr  isSandboxModer  r  s        r   build_transfer_sigzhyperliquid.build_transfer_sigy  sm    t|]CC*6&&$&99!84422'
 ~~g|W===r   c                     |                      | j        d          }|rdnd}dddddddd	d
dgi}|                     |||          S )Nr   r  r  WithdrawFromBridge2SignPayloadr  r  r  usdr,  r  r  r  s        r   build_withdraw_sigzhyperliquid.build_withdraw_sig  sm    t|]CC*6&&,&991122/
 ~~g|W===r   r   sider   r   c                 >   |                                   |                     |          }|                     |d          }|                     |d          }|d         }||||||d}	i }
|||
d<   |                     |	g|
          }|                     |d          }|S )a%  
        create a trade order
        :see: 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 fullfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.timeInForce]: 'Gtc', 'Ioc', 'Alo'
        :param bool [params.postOnly]: True or False whether the order is post-only
        :param bool [params.reduceOnly]: True or False whether the order is reduce-only
        :param float [params.triggerPrice]: The price at which a trigger order is triggered at
        :param str [params.clientOrderId]: client order id,(optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
        :param str [params.slippage]: the slippage for market order
        :param str [params.vaultAddress]: the vault address for order
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  r   )r   r   r  r   r   r   Nr   )rD  r  r   rP  create_ordersr   )r   r   r   r  r   r   r   r  r  orderglobalParamsr   r  s                r   create_orderzhyperliquid.create_order  s    & 	V$$''??6>22!
 
 #+7L(%%ug|<<x++r   ordersc                 
   |                                   |                                  |                     | 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 }
t	          dt          |                    D ]}||         }|                     |d          }|                     |          }|d         }|                     |d          }|dk    }|                     |d          }|dk    }|                     |d          }|                     |d          }|                     |di           }|                     |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(<   |
                    |                     |!|                     |                     |                     |d)                    }"d*|
d+d,}#|"d-|#d.<   |                     |#|	|"          }$|#|	|$d/}%|"| 
                    |d)          }|"|%d)<   |                     |                     |%|                    }&|                     |&d0i           }'|                     |'d1i           }(|                     |(d2g           })|                     |)d          S )3a  
        create a list of trade orders
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order
        :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r   slippageFr   r   clientOrderId	client_idNTzV createOrders() all orders must have clientOrderId if at least one has a clientOrderId)	r  r  r  r  triggerPrice	stopPricestopLossPricetakeProfitPricetimeInForcer   r   MARKETr  BUYr   r   iocgtcpostOnlyalor  r  r  r  r  zy  market orders require price to calculate the max slippage price. Default slippage can be set in options(default is 5%).r  
reduceOnlytpslisMarket	triggerPxtpsltriggertifr;  )
r  r  r  r  r  r  r  r  r  r  r   r  r  prx  rw  rU  rY  r  r  na)r   r  groupingr   
brokerCoder  r  r|  r   r   statuses)check_required_credentialsrD  r   r   r   r   r   safe_string_2r   r"   rP  rO  r  safe_string_upperr  safe_string_lower
capitalizer   
string_mul
string_add
string_subrl  rg  parse_to_intr   r   format_vault_addressr  privatePostExchanger   parse_orders)*r   r  r   r   hasClientOrderIdr   rawOrderorderParamsr  r  orderReqmarketIdr  r   r   r  r  isBuyr   r   r  defaultTimeInForcer  r  r  r  r  	isTriggerrB  rC  r  	orderTypeisTporderObjr  orderActionr|  r   r   responseObjr   r  s*                                             r   r  zhyperliquid.create_orders  sW    	'')))**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++&& ?	@ ?	@AayH''(;;H[[**FH%F))(F;;D(H))(F;;DU]E%%h99F$$Xw77E..8R@@K ..{O[YYM''ZQQH+3!?%~~k:uEEH +%*"00mM_``K//+66K--k>;WWL ,,[/<XXM"..{<MNNO&9/IB <=+DG  7r  -r  s  s  sV[  _W'w/A#x/P/PQQQbibtuz  }D  }O  PS  U]  }^  }^  c_  c_,,VR88,,VU;;))&&99B\5IIJI ".#'#:#:6?#S#SLDD#'#:#:6=#Q#QL (!-%)4DD( (	)$$ ;&	'" ))K  2F  2F  2F  G  GK&&vh'788 H ( -OODKK+>>????001A1A&.1Y1YZZ
 
 ()K%''ULII	!"
 
 #YYv~66F&2GN#++DKK,H,HII$ nnXz2>>~~k6266>>$
B77  4000r   r"   c                 2    |                      |g||          S )a  
        cancels an open order
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s-by-cloid
        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.clientOrderId]: client order id,(optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
        :param str [params.vaultAddress]: the vault address for order
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        )cancel_orders)r   r"   r   r   s       r   cancel_orderzhyperliquid.cancel_order>  s     !!2$777r   idsc                    |                                   |t          | j        dz             |                                  |                     |          }|                     |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<   |                     |                     ||                    }|S )a  
        cancel multiple orders
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s-by-cloid
        :param str[] ids: order ids
        :param str [symbol]: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param string|str[] [params.clientOrderId]: client order ids,(optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
        :param str [params.vaultAddress]: the vault address
        :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nz* cancelOrders() requires a symbol argumentr  r  r   )r   cancelsr   cancelByCloidr   r   )assetcloidcancel)r  rV  r  r  r  r|  )r  r   r"   rD  r  safe_value_2rP  rO  parse_to_numeric
isinstancelistr   r   r   r  r   r  r  r   )r   r  r   r   r  r  r  r   	cancelReqcancelActionr   r   r  r|  r   s                  r   r  zhyperliquid.cancel_ordersL  sc    	'')))>#DG.Z$Z[[[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001A1A&.1Y1YZZ''e\JJ	((#YYv~66F&2GN#++DKK,H,HII r   c                    |                                   |t          | j        dz             |                                  |                     |          }|                                }|dk    }	|                                }|dk    }
|                     | j        d          }|                     |d|          }|	rdnd}|                     |d	d
          }|rd}| 	                    |d|          }| 
                    |          }|                     |dd          }|                     |dd          }|                     |d|          }|                     |d          }|p|}|                     |g d          }t          |          }|	rm|
r5t          t          j        |          t          j        d|                    n4t          t          j        |          t          j        d|                    }n#|                     |t          |                    }|                     ||          }|                     |dd
          }i }|rAd
}||                     ||          }d}n|                     ||          }|	||rdndd|d<   nd|i|d<   |d}|                                 }|                     |d                   |
||||d}|||d <   |                     |          |d!}d"|gd#}|                     |                     |d$                    }|                     |||          }|||d%} ||                     |d$          }|| d$<   |                     |                     | |                    }!|                     |!d&i           }"|                     |"d'i           }#|                     |#d(g           }$|                     |$d)i           }%|                     |%|          S )*a  
        edit a trade order
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#modify-an-order
        :see: 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 fullfilled, in units of the base currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.timeInForce]: 'Gtc', 'Ioc', 'Alo'
        :param bool [params.postOnly]: True or False whether the order is post-only
        :param bool [params.reduceOnly]: True or False whether the order is reduce-only
        :param float [params.triggerPrice]: The price at which a trigger order is triggered at
        :param str [params.clientOrderId]: client order id,(optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
        :param str [params.vaultAddress]: the vault address for order
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nz$ editOrder() requires an id argumentr  r  r   r  r  r  r  Fr  r  r  r  r  r  r  r  )r  r  r  r  r  r  r  r  r  Tr  r  r  r  r  r;  0r   r  rY  )oidr  batchModify)r   modifiesr  r  r   r   r  r   )r  r   r"   rD  r  upperr   r   r  r  r  r  rP  strr   r  r  r  rl  rg  rO  r  r  r  r  r   r   r   parse_order)&r   r"   r   r   r  r   r   r   r  r  r  r   r  r  r  r  r  r  r  r  r  rB  rC  r  r  r  r  r  	modifyReqmodifyActionr  r|  r   r   responseObject
dataObjectr  r  s&                                         r   
edit_orderzhyperliquid.edit_order  s   ( 	''))):#DG.T$TUUUV$$zz||H$zz||**4<9JKK##FJHH'/;UUe>>&*e<< 	'!&,,V]DVWWook22**6?KPP))&.+NN((,OO**63DEE"5o	6  $Q  $Q  $Q  R  RZZ 	=W\  eW'..0B30Q0QRRRcfgngyz  hA  hA  CJ  CU  VY  [c  Cd  Cd  de  deBB((U<<B%%ff55^^FL%@@
	 	D*#66vOO#66v}MM$)!%0D$ $Ii   {"Ig L!!##""6(#344
 
 $)HSM$$R((
 
	
 ""
 
 001A1A&.1Y1YZZ''e\JJ	""
 
 #YYv~66F&2GN#++DKK,H,HIIH *bAA^^NFB??
>>*j"==xB//v...r   c           
         |                                   |                     |          }d|d         d}|||d<   n|                                 dz
  |d<   |                     |d          }|                     |d          }|||d<   |                     |                     ||                    }g }	t          d	t          |                    D ]v}
||
         }|                     |d
          }|		                    || 
                    d|          |                     |d          ||                     |          d           w|                     |	d          }|                     ||||          S )a  
        fetches historical funding rate prices
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#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>`
        fundingHistoryr   r>  NrL  i *urI  rM  r   r,  fundingRate)r   r   r  r-  r.  r-  )rD  r  rO  r  rP  r   r   r   r   r   safe_symbolr  r4  sort_byfilter_by_symbol_since_limit)r   r   rG  r;  r   r  r   rI  r   r   r   entryr-  sorteds                 r   fetch_funding_rate_historyz&hyperliquid.fetch_funding_rate_history   s    	V$$$6N
 
 #(GK  #'#4#4#6#69M#MGK !!&'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|d}|                     |                     ||                    }|                     ||||          S )a  
        fetch all unfilled currently open orders
        :see: 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
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nrf   
openOrdersr!  r/  rD  ra  r   r   r  	r   r   rG  r;  r   r5  r  r   r   s	            r   fetch_open_orderszhyperliquid.fetch_open_ordersR  s     "889JFSSV!!&)) 
 
 &&t{{7F'C'CDD   65%@@@r   c                    d}|                      d|          \  }}|                                  |                     |          }d|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>`
        NrH   historicalOrdersr!  r  r   s	            r   fetch_closed_orderszhyperliquid.fetch_closed_ordersu  s     "889LfUUV!!&))&
 
 &&t{{7F'C'CDD   65%@@@r   c                 f   d}|                      d|          \  }}|                                  |                     |          }d|                     |          |d}|                     |                     ||                    }|                     |d          }|                     ||          S )a$  
        fetches information on an order made by the user
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#query-order-status-by-oid-or-cloid
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.user]: user address, will default to self.walletAddress if not provided
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nrg   orderStatus)r   r	  r"  r  )r/  rD  ra  r  r   r   r   r  )	r   r"   r   r   r5  r  r   r   r   s	            r   fetch_orderzhyperliquid.fetch_order  s     "88vNNV!!&))!((,,
 

 &&t{{7F'C'CDD8 ~~h00f---r   c           
      n   |                      |g d          }||}|                     |d          }d }|!|                    d          dk    r|}n|dz   }|                     |d          |                     |d           }n|                     ||          }|d         }|                     |dd	          }|                     |d
          }|                     |d          }	|	
|	dk    rdn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          r| 
                    |d           nd d!|                     |d"d#          d$d | 
                    |d%          d d |                     |          d d d&|          S )'N)r  restingfilledr$  r   
/USDC:USDCr"   r   r-  statusTimestampstatusr  Asellbuyr   r	  r  r  r.  lastTradeTimestamplastUpdateTimestampr   r  r  r  r  r  r   limitPxr  r  r  r   rC  totalSzr   avgPx)averager*  	remainingr.  r   trades)safe_dict_nr   findra  safe_integer_2
safe_orderr4  r  r  r  r  safe_number_2parse_order_status)
r   r  r  r  r$  r  r   r-  r.  r  s
             r   r  zhyperliquid.parse_order  s   R   (F(F(FGG=Ev..yy~~"",.E4((0%%h55FF%%h77F!''{<MNN	!!%22v.."ckk66D  
E 
$""5%00 
 T--eW== 
 	 

 Y// 
 !$ 
 "4 
 f 
 D**5+>> 
 411%?? 
  
 $..== 
 D 
 T%%eY77 
 DNNSXZeDfDfpD,,UK@@@lp 
  d((i@@! 
" D# 
$ ''w77--f55/ 
  
  
0 1  	r   c                 :    ddd}|                      |||          S )Nopenclosed)	triggeredr*  r   r   r.  r  s      r   r?  zhyperliquid.parse_order_status?  s.    
 
 &&999r   c                 :    ddd}|                      |||          S )Nr;  r  )z
stop limitzstop marketrD  rE  s      r   parse_order_typezhyperliquid.parse_order_typeF  s.    !#
 
 &&999r   c                    d}|                      d|          \  }}|                                  |                     |          }d|i}|d|d<   ||d<   nd|d<   |                     |d          }|                     |d          }|||d	<   |                     |                     ||                    }	|                     |	|||          S )
a  
        fetch all trades made by the user
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills-by-time
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest trade
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Nrb   r"  r^  r   rL  r_  rI  rM  r`  rc  s
             r   fetch_my_tradeszhyperliquid.fetch_my_tradesM  s     "88&QQV!!&))K
 /GFO#(GK  )GFO!!&'2267++!&GI&&t{{7F'C'CDD*   65%@@@r   c                 0   |                      |d          }|                     |d          }|                     |d          }|                     |d          }|dz   }|                     |d           }|d         }|                     |d          }	|                     |d          }
|

|
d	k    rd
nd}
|                     |d          }|                     |||                     |          ||	|                     |d          d |
d ||d |ddd|          S )Nr,  rB  rC  r$  r,  r   tidr  r/  r0  r1  r   r	  r  )r   currency)r   r-  r.  r   r"   r  r   r  takerOrMakerr   r   r   r   )r  r   ra  
safe_trader4  )r   trader  r-  r   r   r$  r  r   r"   r  r   s               r   parse_tradezhyperliquid.parse_trade  sG   & %%eV44	  --!!%..v..,&!!(D11!eU++v.."ckk66Due,,"Y//%%eU33 V44 
  
   	r   c                 ^    |                      |g|          }|                     |di           S )a  
        fetch data on an open position
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-state
        :param str symbol: unified market symbol of the market the position is held in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.user]: user address, will default to self.walletAddress if not provided
        :returns dict: a `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        r   )fetch_positionsr   )r   r   r   	positionss       r   fetch_positionzhyperliquid.fetch_position  s1     ((&6::	~~iB///r   symbolsc                    |                                   d}|                     d|          \  }}|                     |          }d|d}|                     |                     ||                    }|                     |dg           }g }t          dt          |                    D ]1}|                    | 	                    ||         d                     2| 
                    |d|d          S )	a   
        fetch all open positions
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-state
        :param str[] [symbols]: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.user]: user address, will default to self.walletAddress if not provided
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        Nrm   r   r!  assetPositionsr   r   F)rD  r/  market_symbolsr   r   r   r   r   r   parse_positionfilter_by_array_positions)	r   rU  r   r5  r   r   r   r   r   s	            r   rR  zhyperliquid.fetch_positions  s     	"889I6RRV%%g..(
 
 &&t{{7F'C'CDD\ ~~h(8"==q#d))$$ 	> 	>AMM$--d1gt<<====--fhOOOr   c           
         |                      |di           }|                     |d          }|dz   }|                     |d           }|d         }|                      |di           }|                     |d          dk    }|                     |d          }	d }
|	
|	d	k    rd
nd}
|                     |d          }|                     |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 d d ||                     |d!          d |d"          S )#Npositionr$  r,  r   r   r   isolatedrawUsdr   shortlongunrealizedPnl
marginUsedd   r   r"   r-  r.  hedgedr  	contractsszir   
entryPriceentryPx	markPricenotionalpositionValuevalue
collateralinitialMarginmaintenanceMarginliquidationPx)initialMarginPercentagemaintenanceMarginPercentagera  liquidationPrice
marginMode
percentage)r   r   ra  r  safe_position)r   r\  r  r  r$  r  r   r   
isIsolatedquantityr  ra  rn  ru  s                 r   rY  zhyperliquid.parse_position   sH   6 xR88v..,&!!(D11!>>%R88&&x88JF
##Hh77'!||77&D((@@((=="]2S8
!! #
H#
$#
 f#
 	#

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

                    d
d          }
|                     |	|          }|                     |||
          }|||d}|
|
|d	<   |                     |          }|S )a  
        set margin mode(symbol)
        :param str marginMode: margin mode must be either [isolated, cross]
        :param str symbol: unified market symbol of the market the position is held in, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.leverage]: the rate of leverage, is required if setting trade mode(symbol)
        :returns dict: response from the exchange
        Nz+ setMarginMode() requires a symbol argumentr   z. setMarginMode() requires a leverage parameterr   crossupdateLeverager   r  isCrossr   r  rn  r  r  )r   r"   rD  r  r  r  rO  rP  r   
startswithreplacer   r  r  )r   rt  r   r   r  r   r  r}  r  updateActionr  extendedActionr|  r   r   s                  r   set_margin_modezhyperliquid.set_margin_modeC  s    >#DG.[$[\\\V$$$$VZ88#DG.^$^___!!&"233(!!##6J<00$ 	
 
 ''??#YYv~66F&&t,, >+33D"==\6::''|LL	$"
 
 #&2GN#++G44 r   r   c                 t   |t          | j        dz             |                                  |                     |          }|                     |dd          }|dk    }|                     |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 argumentrt  rz  r   r{  r|  r  r  )r   r"   rD  r  r   r  rO  rP  r  r  r  r   )r   r   r   r   r  rt  r}  r  r  r  r  r|  r   r   s                 r   set_leveragezhyperliquid.set_leveragew  sU    >#DG.Y$YZZZV$$%%flGDD
(!!&"233!!##6<00$ 	
 
 001A1A&.1Y1YZZ''e\JJ	""
 
 #YYv~66F&2GN#++DKK,H,HII r   c                 2    |                      ||d|          S )a  
        add margin
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#update-isolated-margin
        :param str symbol: unified market symbol
        :param float amount: amount of margin to add
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=add-margin-structure>`
        addmodify_margin_helperr   r   r   r   s       r   
add_marginzhyperliquid.add_margin  s     ((GGGr   c                 2    |                      ||d|          S )a  
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#update-isolated-margin
        remove margin from a position
        :param str symbol: unified market symbol
        :param float amount: the amount of margin to remove
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=reduce-margin-structure>`
        reducer  r  s       r   reduce_marginzhyperliquid.reduce_margin  s     ((6JJJr   c                    |                                   |                     |          }|                     |d                   }|                     t          j        |                     ||          d                    }|dk    r| }|                                 }d|d|d}	|                     |                     |d                    }
| 	                    |	||
          }|	||d}|
| 
                    |d          }|
|d<   |                     |                     ||                    }|                     |                     ||          d	|                     |d
          i          S )Nr   1000000r  updateIsolatedMarginT)r   r  r  ntlir  r  r   r.  )rD  r  r  r   r  rg  rO  r  r   r  rP  r  r   parse_margin_modification)r   r   r   r   r   r  r  rC  r  r  r  r|  r   r   s                 r   r  z hyperliquid.modify_margin_helper  s   V$$!!&"233w1$2J2J6SY2Z2Z\effgg8B!!##*	
 
 001A1A&.1Y1YZZ''e\JJ	""
 
 #YYv~66F&2GN#++DKK,H,HII {{499(FKKD$$Xx88N
   	r   c                 l    ||                      d |          d dd d |                     |d          d d d d
S )Nr]  r   )
r   r   r   rt  r   r%  r   r.  r-  r.  )r  r   )r   r   r  s      r   r  z%hyperliquid.parse_margin_modification  sQ     &&tV44$$$VX66
 
 	
r   r   fromAccount	toAccountc                    |                                   |                                  |                     | j        d          }|                                 }|                     |g d          r|                     |g d          st          | j        dz             |                     | 	                    |d                    }| 
                    |d          }|dk    p|dk    }	d||	dd	}
|                     |
||          }|                     |
|          ||d
}|||d<   |                     |          }|S |                     |           |1|                                }|dk    rt          | j        dz             ||                     |          |d}|                     |          }|rdnd|dd||d
}|                     |                     ||                    }|S )a  
        transfer currency internally between wallets on the same account
        :see: 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.   r0   perpz-transfer() only support spot <> swap transferr  r  r0   spotUser)usdctoPerp)r   classTransferr  Nr  withdraw() only support USDC)r  r   r,  ArbitrumTestnetArbitrumusdTransferchainpayloadr   )r  rD  r  r   rO  in_arrayr   r"   r  r   rP  r  r   r  check_addressr  r  r  )r   r   r   r  r  r   r  r  r  r  r  r|  innerRequesttransferResponser  sigr   r   s                     r   r   zhyperliquid.transfer  sJ    	'')))t|]CC!!##==&>&>&>?? 	$==,D,D,DEE ^"47-\#\]]]44T5E5Efn5]5]^^LYYv~66F6)CyF/BF""$" " F ++FE<HHI++ff55& L
 '/;^,#77EE##9%%%::<<Dv~~"47-K#KLLL$++F33
 

 %%g.. 0=M**:"% 
 
 
 ++DKK,H,HIIr   c                    |                                   |                                  |                     |           |1|                                }|dk    rt	          | j        dz             |                     | j        d          }|                                 }|t          |          |d}| 
                    |          }	|rdnd|dd	||	d
}
|                     |                     |
|                    }|S )a#  
        make a withdrawal(only support USDC)
        :see: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#initiate-a-withdrawal-request
        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr  r  r   )r  r  r,  r  r  	withdraw2r  r  )r  rD  r  r  r   r"   r  r   rO  r  r  r  r   )r   r   r   addresstagr   r  r  r  r  r   r   s               r   r   zhyperliquid.withdraw4  s     	'')))7###::<<Dv~~"47-K#KLLLt|]CC!!##"v;;
 

 %%g.. 0=M**:"# 
 
 
 ++DKK,H,HIIr   r  c                 d    |d S |                     d          r|                    dd          S |S )Nrn  r  )r~  r  )r   r  s     r   r  z hyperliquid.format_vault_addressZ  s;    ?4d## 	-??4,,,r   
methodNamer   c                     d }|                      ||d          \  }}|}|                      ||d|          \  }}|
|dk    r||gS | j        | j        dk    r	| j        |gS t          | j        dz   |z   dz             )Nr"  r  r   zF() requires a user parameter inside 'params' or the wallet address set)handle_option_and_paramsr   r   r"   )r   r  r   userAuxr"  s        r   r/  z!hyperliquid.handle_public_addressa  s    77
FSS44VZT[\\f42::&>!*1Cr1I1I&//#
 :  >H  !H  I  I  	Ir   c
                 8   |sd S |                      |dd          }
d }|
dk    r|                      |d          }nq|                     |di           }|                     |di           }|                     |dg           }|                     |d          }|                      |d          }| j        d	z   |z   }|d uo|dk    }|rD|                     | j        d
         ||           |                     | j        d         ||           |rt          |          d S )Nr.  r  errr   r   r  r   errorr  r   r   )r   r   r   r"   throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr   )r   r   reasonurlmethodheadersbodyr   requestHeadersrequestBodyr.  rr  responsePayloadr   r  firstStatusfeedbacknonEmptyMessages                     r   handle_errorszhyperliquid.handle_errorsl  s;    	4 !!(Hb99U??&&x<<GG"nnXz2FFO>>/62>>D~~dJ;;H..155K&&{G<<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)r  r  r  r  )implode_hostnamer   json)r   pathr   r  r   r  r  r  s           r   signzhyperliquid.sign  sh    ##DIe$4S$9::S@4GV 2G 99V$$DfdwOOOr   )N)T)M__name__
__module____qualname__r   r   r   r   r   r	   r   r   r   r  r   r:  r  r   r   rF  r  rS  r\  r   rd  rg  rl  rs  r}  r  r  r  objectr  r  r  r  r   r   floatr
   r  r   r  r  r  r  r  r   r!  r$  r'  r  r?  rG  rI  r   rP  rT  r   rR  rY  r  r  r   r  r  r  r  r   r   r   r  dictr/  r  r  __classcell__)r   s   @r   r    r       s       t t t t tl. . . . . ') . .Z . . . .` $& ; ;$v, ; ; ; ;  )+ 4* 4*tF| 4* 4* 4* 4*l )+ y ytF| y y y yvV
f V
 V
 V
 V
p $& O) O)( O) O) O) O)b :>b ,f ,fs ,f3 ,fY ,f ,f ,f ,f\ 26DW[df .L .L# .Lc .LQT .Lkoptku .L .L .L .L`
 
 
4 
 
 
 
0 *.Dt\^ 3A 3A3 3Ac 3A 3A 3A 3A 3Ajy y y# # # # # #: : :
 
 
L L L
 
 
 

J 
J 
J* * * * * *X
 
 

> 
> 
>
> 
> 
> gksu % %3 %i %y %RW %`c % % % %N @B D1 D1D$6 D1 D1 D1 D1L 37r 8 8s 8C 8 8 8 8 ;?r D Dc DC D D D DL TXfjsu L/ L/S L/# L/S L/ L/S L/`c L/ L/ L/ L/\ 8<$]ajl 0O 0O 0OC 0OWZ 0O 0O 0O 0Od /3TXac !A !A !A3 !Ac !Ahlmrhs !A !A !A !AF 154VZce  A  A#  AS  APS  Ajnotju  A  A  A  AD 26b /. /.c /.3 /. /. /. /.bu u u5 u u u un: : :: : : -1tRV_a 1A 1Ac 1A 1AC 1A 1A 1A 1Af- - -5 - - - -^ 24 
0 
0S 
0 
0 
0 
0 26b CP CPw CP CP CP CPJA Av A A A AF >B" 2 2# 2s 2 2 2 2h 9=R , ,S ,# , , , ,\ 68 	H 	H 	H<N 	H 	H 	H 	H 9; 	K 	KC 	K?Q 	K 	K 	K 	K FH $ $3 $L^ $ $ $ $L
 
f 
HZ 
 
 
 
& [] > >S >% >c >c >an > > > >@ 8<B $ $S $ $ $ $L C    	I 	IT 	I 	I 	I 	I  : &eBSW P P P P P P P Pr   r    N)$ccxt.base.exchanger   ccxt.abstract.hyperliquidr   ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   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 q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q  q       * * * * * * . . . . . . ) ) ) ) ) ) * * * * * * ) ) ) ) ) ) 0 0 0 0 0 0 9 9 9 9 9 9 = = = = = = 4 4 4 4 4 4 % % % % % %z!P z!P z!P z!P z!P(K z!P z!P z!P z!P z!Pr   