o
    ¢ØÆhk  ã                   @   s\   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 d dlmZ G dd„ deƒZdS )é    )ÚAPI)
ÚAnyÚCallableÚCloidÚListÚMetaÚOptionalÚSpotMetaÚSpotMetaAndAssetCtxsÚSubscriptionÚcast)ÚWebsocketManagerc                       s¸  e Zd Z						drdee dee dee dee deee  dee	 f‡ fd	d
„Z
dededefdd„Zdd„ Zdsdededefdd„Zdedefdd„Zdsdededefdd„Zdsdededefdd„Zdsdedefdd„Zdedefdd„Z	dtded ed!ee d"ee def
d#d$„Zdsdedefd%d&„Zdefd'd(„Zdefd)d*„Zdefd+d,„Zdefd-d.„Zdud/ed0ed1ee defd2d3„Zdud4ed0ed1ee defd5d6„Zd/edefd7d8„Zd/ed9ed0ed1edef
d:d;„Zdedefd<d=„Z dedefd>d?„Z!dedefd@dA„Z"dedefdBdC„Z#d4edefdDdE„Z$d4edFedefdGdH„Z%d4edIe&defdJdK„Z'd4edefdLdM„Z(d4edefdNdO„Z)dPedefdQdR„Z*defdSdT„Z+d4edefdUdV„Z,dud4ed0ed1ee defdWdX„Z-d4edefdYdZ„Z.d4edefd[d\„Z/d4edefd]d^„Z0d4edefd_d`„Z1d4edefdadb„Z2d4edefdcdd„Z3d4edefdedf„Z4dge5ddfdhdi„Z6dge5dje7egdf defdkdl„Z8dge5dmedefdndo„Z9d/edefdpdq„Z:‡  Z;S )vÚInfoNFÚbase_urlÚskip_wsÚmetaÚ	spot_metaÚ	perp_dexsÚtimeoutc                    s€  t ƒ  ||¡ d | _|st| jƒ| _| j ¡  |d u r|  ¡ }i | _i | _i | _	|d D ]H}|d d }|| j|d < |d | j|d < |d \}	}
|d |	 }|d |
 }|d | j	|< |d › d|d › �}|| jvrt|d | j|< q,dd	i}|d u r�dg}nt
|  ¡ d
d … ƒD ]\}}d|d  ||d < q‹|D ]!}|| }|dkr±|d ur±|  |d	¡ qœ| j|d�}|  ||¡ qœd S )NÚuniverseÚindexi'  ÚnameÚtokensÚ
szDecimalsú/Ú r   é   i°­ )Údex)ÚsuperÚ__init__Ú
ws_managerr   r   Ústartr   Úcoin_to_assetÚname_to_coinÚasset_to_sz_decimalsÚ	enumerater   Úset_perp_metar   )Úselfr   r   r   r   r   r   Ú	spot_infoÚassetÚbaseÚquoteÚ	base_infoÚ
quote_infor   Úperp_dex_to_offsetÚiÚperp_dexÚoffsetÚ
fresh_meta©Ú	__class__© ú]/var/www/html/HyperOracle/crypto_trader/venv/lib/python3.10/site-packages/hyperliquid/info.pyr      sD   

€úzInfo.__init__r1   Úreturnc                 C   sP   t |d ƒD ]\}}||7 }|| j|d < |d | j|d < |d | j|< qd S )Nr   r   r   )r%   r"   r#   r$   )r'   r   r1   r)   Ú
asset_infor5   r5   r6   r&   G   s   üzInfo.set_perp_metac                 C   s    | j d u r	tdƒ‚| j  ¡  d S )Nz7Cannot call disconnect_websocket since skip_ws was used)r    ÚRuntimeErrorÚstop©r'   r5   r5   r6   Údisconnect_websocketN   s   
zInfo.disconnect_websocketr   Úaddressr   c                 C   ó   |   dd||dœ¡S )a  Retrieve trading details about a user.

        POST /info

        Args:
            address (str): Onchain address in 42-character hexadecimal format;
                            e.g. 0x0000000000000000000000000000000000000000.
        Returns:
            {
                assetPositions: [
                    {
                        position: {
                            coin: str,
                            entryPx: Optional[float string]
                            leverage: {
                                type: "cross" | "isolated",
                                value: int,
                                rawUsd: float string  # only if type is "isolated"
                            },
                            liquidationPx: Optional[float string]
                            marginUsed: float string,
                            positionValue: float string,
                            returnOnEquity: float string,
                            szi: float string,
                            unrealizedPnl: float string
                        },
                        type: "oneWay"
                    }
                ],
                crossMarginSummary: MarginSummary,
                marginSummary: MarginSummary,
                withdrawable: float string,
            }

            where MarginSummary is {
                    accountValue: float string,
                    totalMarginUsed: float string,
                    totalNtlPos: float string,
                    totalRawUsd: float string,
                }
        ú/infoÚclearinghouseState©ÚtypeÚuserr   ©Úpost©r'   r=   r   r5   r5   r6   Ú
user_stateT   s   *zInfo.user_statec                 C   ó   |   dd|dœ¡S )Nr?   ÚspotClearinghouseState©rB   rC   rD   ©r'   r=   r5   r5   r6   Úspot_user_state€   ó   zInfo.spot_user_statec                 C   r>   )aÝ  Retrieve a user's open orders.

        POST /info

        Args:
            address (str): Onchain address in 42-character hexadecimal format;
                            e.g. 0x0000000000000000000000000000000000000000.
        Returns: [
            {
                coin: str,
                limitPx: float string,
                oid: int,
                side: "A" | "B",
                sz: float string,
                timestamp: int
            }
        ]
        r?   Ú
openOrdersrA   rD   rF   r5   r5   r6   Úopen_ordersƒ   s   zInfo.open_ordersc                 C   r>   )a‡  Retrieve a user's open orders with additional frontend info.

        POST /info

        Args:
            address (str): Onchain address in 42-character hexadecimal format;
                            e.g. 0x0000000000000000000000000000000000000000.
        Returns: [
            {
                children:
                    [
                        dict of frontend orders
                    ]
                coin: str,
                isPositionTpsl: bool,
                isTrigger: bool,
                limitPx: float string,
                oid: int,
                orderType: str,
                origSz: float string,
                reduceOnly: bool,
                side: "A" | "B",
                sz: float string,
                tif: str,
                timestamp: int,
                triggerCondition: str,
                triggerPx: float str
            }
        ]
        r?   ÚfrontendOpenOrdersrA   rD   rF   r5   r5   r6   Úfrontend_open_orders˜   s   zInfo.frontend_open_ordersc                 C   rH   )züRetrieve all mids for all actively traded coins.

        POST /info

        Returns:
            {
              ATOM: float string,
              BTC: float string,
              any other coins which are trading: float string
            }
        r?   ÚallMids©rB   r   rD   ©r'   r   r5   r5   r6   Úall_mids¹   ó   zInfo.all_midsc                 C   rH   )aŸ  Retrieve a given user's fills.

        POST /info

        Args:
            address (str): Onchain address in 42-character hexadecimal format;
                            e.g. 0x0000000000000000000000000000000000000000.

        Returns:
            [
              {
                closedPnl: float string,
                coin: str,
                crossed: bool,
                dir: str,
                hash: str,
                oid: int,
                px: float string,
                side: str,
                startPosition: float string,
                sz: float string,
                time: int
              },
              ...
            ]
        r?   Ú	userFillsrJ   rD   rK   r5   r5   r6   Ú
user_fillsÇ   s   zInfo.user_fillsÚ
start_timeÚend_timeÚaggregate_by_timec              	   C   s   |   dd||||dœ¡S )a  Retrieve a given user's fills by time.

        POST /info

        Args:
            address (str): Onchain address in 42-character hexadecimal format;
                            e.g. 0x0000000000000000000000000000000000000000.
            start_time (int): Unix timestamp in milliseconds
            end_time (Optional[int]): Unix timestamp in milliseconds
            aggregate_by_time (Optional[bool]): When true, partial fills are combined when a crossing order gets filled by multiple different resting orders. Resting orders filled by multiple crossing orders will not be aggregated.

        Returns:
            [
              {
                closedPnl: float string,
                coin: str,
                crossed: bool,
                dir: str,
                hash: str,
                oid: int,
                px: float string,
                side: str,
                startPosition: float string,
                sz: float string,
                time: int
              },
              ...
            ]
        r?   ÚuserFillsByTime)rB   rC   Ú	startTimeÚendTimeÚaggregateByTimerD   )r'   r=   rY   rZ   r[   r5   r5   r6   Úuser_fills_by_timeä   s    ûþzInfo.user_fills_by_timec                 C   s   t t|  dd|dœ¡ƒS )a(  Retrieve exchange perp metadata

        POST /info

        Returns:
            {
                universe: [
                    {
                        name: str,
                        szDecimals: int
                    },
                    ...
                ]
            }
        r?   r   rS   )r   r   rE   rT   r5   r5   r6   r     s   z	Info.metac                 C   ó   |   dddi¡S )aî  Retrieve exchange MetaAndAssetCtxs

        POST /info

        Returns:
            [
                {
                    universe: [
                        {
                            'name': str,
                            'szDecimals': int
                            'maxLeverage': int,
                            'onlyIsolated': bool,
                        },
                        ...
                    ]
                },
            [
                {
                    "dayNtlVlm": float string,
                    "funding": float string,
                    "impactPxs": Optional([float string, float string]),
                    "markPx": Optional(float string),
                    "midPx": Optional(float string),
                    "openInterest": float string,
                    "oraclePx": float string,
                    "premium": Optional(float string),
                    "prevDayPx": float string
                },
                ...
            ]
        r?   rB   ÚmetaAndAssetCtxsrD   r;   r5   r5   r6   Úmeta_and_asset_ctxs!  s   !zInfo.meta_and_asset_ctxsc                 C   ra   )Nr?   rB   ÚperpDexsrD   r;   r5   r5   r6   r   D  ó   zInfo.perp_dexsc                 C   ó   t t|  dddi¡ƒS )aÖ  Retrieve exchange spot metadata

        POST /info

        Returns:
            {
                universe: [
                    {
                        tokens: [int, int],
                        name: str,
                        index: int,
                        isCanonical: bool
                    },
                    ...
                ],
                tokens: [
                    {
                        name: str,
                        szDecimals: int,
                        weiDecimals: int,
                        index: int,
                        tokenId: str,
                        isCanonical: bool
                    },
                    ...
                ]
            }
        r?   rB   ÚspotMeta)r   r	   rE   r;   r5   r5   r6   r   G  s   zInfo.spot_metac                 C   rf   )aÙ  Retrieve exchange spot asset contexts
        POST /info
        Returns:
            [
                {
                    universe: [
                        {
                            tokens: [int, int],
                            name: str,
                            index: int,
                            isCanonical: bool
                        },
                        ...
                    ],
                    tokens: [
                        {
                            name: str,
                            szDecimals: int,
                            weiDecimals: int,
                            index: int,
                            tokenId: str,
                            isCanonical: bool
                        },
                        ...
                    ]
                },
                [
                    {
                        dayNtlVlm: float string,
                        markPx: float string,
                        midPx: Optional(float string),
                        prevDayPx: float string,
                        circulatingSupply: float string,
                        coin: str
                    }
                    ...
                ]
            ]
        r?   rB   ÚspotMetaAndAssetCtxs)r   r
   rE   r;   r5   r5   r6   Úspot_meta_and_asset_ctxsf  s   (zInfo.spot_meta_and_asset_ctxsr   r]   r^   c                 C   s<   | j | }|dur|  dd|||dœ¡S |  dd||dœ¡S )a	  Retrieve funding history for a given coin

        POST /info

        Args:
            name (str): Coin to retrieve funding history for.
            startTime (int): Unix timestamp in milliseconds.
            endTime (int): Unix timestamp in milliseconds.

        Returns:
            [
                {
                    coin: str,
                    fundingRate: float string,
                    premium: float string,
                    time: int
                },
                ...
            ]
        Nr?   ÚfundingHistory)rB   Úcoinr]   r^   )rB   rk   r]   ©r#   rE   )r'   r   r]   r^   rk   r5   r5   r6   Úfunding_history�  s   
ÿzInfo.funding_historyrC   c                 C   s2   |dur|   dd|||dœ¡S |   dd||dœ¡S )aÄ  Retrieve a user's funding history
        POST /info
        Args:
            user (str): Address of the user in 42-character hexadecimal format.
            startTime (int): Start time in milliseconds, inclusive.
            endTime (int, optional): End time in milliseconds, inclusive. Defaults to current time.
        Returns:
            List[Dict]: A list of funding history records, where each record contains:
                - user (str): User address.
                - type (str): Type of the record, e.g., "userFunding".
                - startTime (int): Unix timestamp of the start time in milliseconds.
                - endTime (int): Unix timestamp of the end time in milliseconds.
        Nr?   ÚuserFunding©rB   rC   r]   r^   )rB   rC   r]   rD   ©r'   rC   r]   r^   r5   r5   r6   Úuser_funding_history¬  s   zInfo.user_funding_historyc                 C   s   |   dd| j| dœ¡S )a0  Retrieve L2 snapshot for a given coin

        POST /info

        Args:
            name (str): Coin to retrieve L2 snapshot for.

        Returns:
            {
                coin: str,
                levels: [
                    [
                        {
                            n: int,
                            px: float string,
                            sz: float string
                        },
                        ...
                    ],
                    ...
                ],
                time: int
            }
        r?   Úl2Book)rB   rk   )rE   r#   ©r'   r   r5   r5   r6   Úl2_snapshot¾  s   zInfo.l2_snapshotÚintervalc                 C   s&   | j | |||dœ}|  dd|dœ¡S )aí  Retrieve candles snapshot for a given coin

        POST /info

        Args:
            name (str): Coin to retrieve candles snapshot for.
            interval (str): Candlestick interval.
            startTime (int): Unix timestamp in milliseconds.
            endTime (int): Unix timestamp in milliseconds.

        Returns:
            [
                {
                    T: int,
                    c: float string,
                    h: float string,
                    i: str,
                    l: float string,
                    n: int,
                    o: float string,
                    s: string,
                    t: int,
                    v: float string
                },
                ...
            ]
        )rk   ru   r]   r^   r?   ÚcandleSnapshot)rB   Úreqrl   )r'   r   ru   r]   r^   rw   r5   r5   r6   Úcandles_snapshotÙ  s   zInfo.candles_snapshotc                 C   rH   )a²  Retrieve the volume of trading activity associated with a user.
        POST /info
        Args:
            address (str): Onchain address in 42-character hexadecimal format;
                            e.g. 0x0000000000000000000000000000000000000000.
        Returns:
            {
                activeReferralDiscount: float string,
                dailyUserVlm: [
                    {
                        date: str,
                        exchange: str,
                        userAdd: float string,
                        userCross: float string
                    },
                ],
                feeSchedule: {
                    add: float string,
                    cross: float string,
                    referralDiscount: float string,
                    tiers: {
                        mm: [
                            {
                                add: float string,
                                makerFractionCutoff: float string
                            },
                        ],
                        vip: [
                            {
                                add: float string,
                                cross: float string,
                                ntlCutoff: float string
                            },
                        ]
                    }
                },
                userAddRate: float string,
                userCrossRate: float string
            }
        r?   ÚuserFeesrJ   rD   rK   r5   r5   r6   Ú	user_feesø  s   )zInfo.user_feesc                 C   rH   )aÚ  Retrieve the staking summary associated with a user.
        POST /info
        Args:
            address (str): Onchain address in 42-character hexadecimal format;
                            e.g. 0x0000000000000000000000000000000000000000.
        Returns:
            {
                delegated: float string,
                undelegated: float string,
                totalPendingWithdrawal: float string,
                nPendingWithdrawals: int
            }
        r?   ÚdelegatorSummaryrJ   rD   rK   r5   r5   r6   Úuser_staking_summary#  s   zInfo.user_staking_summaryc                 C   rH   )a¿  Retrieve the user's staking delegations.
        POST /info
        Args:
            address (str): Onchain address in 42-character hexadecimal format;
                            e.g. 0x0000000000000000000000000000000000000000.
        Returns:
            [
                {
                    validator: string,
                    amount: float string,
                    lockedUntilTimestamp: int
                },
            ]
        r?   ÚdelegationsrJ   rD   rK   r5   r5   r6   Úuser_staking_delegations3  ó   zInfo.user_staking_delegationsc                 C   rH   )aÆ  Retrieve the historic staking rewards associated with a user.
        POST /info
        Args:
            address (str): Onchain address in 42-character hexadecimal format;
                            e.g. 0x0000000000000000000000000000000000000000.
        Returns:
            [
                {
                    time: int,
                    source: string,
                    totalAmount: float string
                },
            ]
        r?   ÚdelegatorRewardsrJ   rD   rK   r5   r5   r6   Úuser_staking_rewardsD  r   zInfo.user_staking_rewardsc                 C   rH   )ad  Retrieve comprehensive staking history for a user.

        POST /info

        Args:
            user (str): Onchain address in 42-character hexadecimal format.

        Returns:
            Comprehensive staking history including delegation and undelegation
            events with timestamps, transaction hashes, and detailed delta information.
        r?   ÚdelegatorHistoryrJ   rD   ©r'   rC   r5   r5   r6   Údelegator_historyU  rV   zInfo.delegator_historyÚoidc                 C   r>   ©Nr?   ÚorderStatus)rB   rC   r…   rD   )r'   rC   r…   r5   r5   r6   Úquery_order_by_oidc  s   zInfo.query_order_by_oidÚcloidc                 C   s   |   dd|| ¡ dœ¡S r†   )rE   Úto_raw)r'   rC   r‰   r5   r5   r6   Úquery_order_by_cloidf  s   zInfo.query_order_by_cloidc                 C   rH   )Nr?   ÚreferralrJ   rD   rƒ   r5   r5   r6   Úquery_referral_statei  rM   zInfo.query_referral_statec                 C   rH   )Nr?   ÚsubAccountsrJ   rD   rƒ   r5   r5   r6   Úquery_sub_accountsl  rM   zInfo.query_sub_accountsÚmulti_sig_userc                 C   rH   )Nr?   ÚuserToMultiSigSignersrJ   rD   )r'   r�   r5   r5   r6   Úquery_user_to_multi_sig_signerso  rM   z$Info.query_user_to_multi_sig_signersc                 C   ra   )Nr?   rB   ÚperpDeployAuctionStatusrD   r;   r5   r5   r6   Ú query_perp_deploy_auction_statusr  re   z%Info.query_perp_deploy_auction_statusc                 C   rH   )a|  Retrieve a user's historical orders.

        POST /info

        Args:
            user (str): Onchain address in 42-character hexadecimal format;
                        e.g. 0x0000000000000000000000000000000000000000.

        Returns:
            Returns at most 2000 most recent historical orders with their current
            status and detailed order information.
        r?   ÚhistoricalOrdersrJ   rD   rƒ   r5   r5   r6   Úhistorical_ordersu  s   zInfo.historical_ordersc                 C   s   |   dd|||dœ¡S )aý  Retrieve non-funding ledger updates for a user.

        POST /info

        Args:
            user (str): Onchain address in 42-character hexadecimal format.
            startTime (int): Start time in milliseconds (epoch timestamp).
            endTime (Optional[int]): End time in milliseconds (epoch timestamp).

        Returns:
            Comprehensive ledger updates including deposits, withdrawals, transfers,
            liquidations, and other account activities excluding funding payments.
        r?   ÚuserNonFundingLedgerUpdatesro   rD   rp   r5   r5   r6   Úuser_non_funding_ledger_updates„  s   þz$Info.user_non_funding_ledger_updatesc                 C   rH   )a^  Retrieve comprehensive portfolio performance data.

        POST /info

        Args:
            user (str): Onchain address in 42-character hexadecimal format.

        Returns:
            Comprehensive portfolio performance data across different time periods,
            including account value history, PnL history, and volume metrics.
        r?   Ú	portfoliorJ   rD   rƒ   r5   r5   r6   r™   —  rV   zInfo.portfolioc                 C   rH   )a  Retrieve a user's TWAP slice fills.

        POST /info

        Args:
            user (str): Onchain address in 42-character hexadecimal format.

        Returns:
            Returns at most 2000 most recent TWAP slice fills with detailed
            execution information.
        r?   ÚuserTwapSliceFillsrJ   rD   rƒ   r5   r5   r6   Úuser_twap_slice_fills¥  rV   zInfo.user_twap_slice_fillsc                 C   rH   )aa  Retrieve user's equity positions across all vaults.

        POST /info

        Args:
            user (str): Onchain address in 42-character hexadecimal format.

        Returns:
            Detailed information about user's equity positions across all vaults
            including current values, profit/loss metrics, and withdrawal details.
        r?   ÚuserVaultEquitiesrJ   rD   rƒ   r5   r5   r6   Úuser_vault_equities³  rV   zInfo.user_vault_equitiesc                 C   rH   )a\  Retrieve the role and account type information for a user.

        POST /info

        Args:
            user (str): Onchain address in 42-character hexadecimal format.

        Returns:
            Role and account type information including account structure,
            permissions, and relationships within the Hyperliquid ecosystem.
        r?   ÚuserRolerJ   rD   rƒ   r5   r5   r6   Ú	user_roleÁ  rV   zInfo.user_rolec                 C   rH   )a]  Retrieve user's API rate limit configuration and usage.

        POST /info

        Args:
            user (str): Onchain address in 42-character hexadecimal format.

        Returns:
            Detailed information about user's API rate limit configuration
            and current usage for managing API usage and avoiding rate limiting.
        r?   ÚuserRateLimitrJ   rD   rƒ   r5   r5   r6   Úuser_rate_limitÏ  rV   zInfo.user_rate_limitc                 C   rH   )Nr?   ÚspotDeployStaterJ   rD   rƒ   r5   r5   r6   Ú query_spot_deploy_auction_statusÝ  rM   z%Info.query_spot_deploy_auction_statusc                 C   rH   )aÀ  Retrieve extra agents associated with a user.

        POST /info

        Args:
            user (str): Onchain address in 42-character hexadecimal format;
                        e.g. 0x0000000000000000000000000000000000000000.

        Returns:
            [
                {
                    "name": str,
                    "address": str,
                    "validUntil": int
                },
                ...
            ]
        r?   ÚextraAgentsrJ   rD   rƒ   r5   r5   r6   Úextra_agentsà  s   zInfo.extra_agentsÚsubscriptionc                 C   sV   |d dks|d dks|d dks|d dks|d dkr)| j |d  |d< d S d S )NrB   rr   ÚtradesÚcandleÚbboÚactiveAssetCtxrk   )r#   )r'   r¦   r5   r5   r6   Ú_remap_coin_subscriptionõ  s   þzInfo._remap_coin_subscriptionÚcallbackc                 C   ó*   |   |¡ | jd u rtdƒ‚| j ||¡S )Nz,Cannot call subscribe since skip_ws was used)r«   r    r9   Ú	subscribe)r'   r¦   r¬   r5   r5   r6   r®   ÿ  ó   

zInfo.subscribeÚsubscription_idc                 C   r­   )Nz.Cannot call unsubscribe since skip_ws was used)r«   r    r9   Úunsubscribe)r'   r¦   r°   r5   r5   r6   r±     r¯   zInfo.unsubscribec                 C   s   | j | j|  S ©N)r"   r#   rs   r5   r5   r6   Úname_to_asset  re   zInfo.name_to_asset)NFNNNN)r   )NFr²   )<Ú__name__Ú
__module__Ú__qualname__r   ÚstrÚboolr   r	   r   Úfloatr   Úintr   r&   r<   rG   rL   rO   rQ   rU   rX   r`   r   rc   r   r   r
   ri   rm   rq   rt   rx   rz   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³   Ú__classcell__r5   r5   r3   r6   r      s’    ÷þýüû
ø	÷5,!ÿÿÿÿÿ
þ+# * +  
r   N)Úhyperliquid.apir   Úhyperliquid.utils.typesr   r   r   r   r   r   r	   r
   r   r   Úhyperliquid.websocket_managerr   r   r5   r5   r5   r6   Ú<module>   s    0