o
    ”±ii4  ã                	   @   sÔ  d Z ddlZddlZddlZddlmZ ddlmZmZmZ ddl	m
Z
 ddlmZ ddlZe
ƒ  e e¡Ze dd¡ ¡ Ze d	¡Zd
ZdZdZdZee e¡ƒZG dd„ dƒZedkrèejejdd� eƒ Zedƒ edƒ edƒ eƒ  edƒ edƒ e  ¡ Z!e!rÛe! "¡ D ]P\Z#Z$e$d r“dndZ%ede$d › de%› de$d › d�ƒ ede#dd … › d!�ƒ ed"e$d# d$›�ƒ ed%e$d& d'›�ƒ ed(e$d) › �ƒ ed*e$d+ › �ƒ q‰ned,ƒ eƒ  edƒ dS dS )-u±   
Position Monitor - Sources de donnÃ©es fiables
VÃ©rifie l'Ã©tat rÃ©el des positions via 2 sources:
1. The Graph (Arbitrum) - Source principale
2. Etherscan V2 (BSC) - Fallback
é    N)Údatetime)ÚDictÚListÚOptional)Úload_dotenv)ÚWeb3ÚWALLET_ADDRESSÚ*0x7476737C49d55bea691e54c2c96fD39a6bAf3049ÚBSCSCAN_API_KEYzŒhttps://gateway-arbitrum.network.thegraph.com/api/6edc89d15e0bffdb56057765735dfdc8/subgraphs/id/HxvztN7GmfYYDPb89K4FFYKFkRvBtscxYQqvX79D4XSQzhttps://api.etherscan.io/v2/apiÚ*0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0z!https://bsc-dataseed.binance.org/c                   @   sÈ   e Zd ZdZdd„ Zddedee fdd„Zd	ee dee	ef fd
d„Z
ddededee fdd„Zde	dee	 fdd„Zdee	ef fdd„Zddedee	ef fdd„Zde	dee	 fdd„ZdS )ÚPositionMonitoru6   
    Monitor l'Ã©tat rÃ©el des positions on-chain
    c                 C   s
   t | _d S )N)r   Úwallet)Úself© r   úL/var/www/html/HyperOracle/crypto_trader/apollo_degen_bot/position_monitor.pyÚ__init__+   s   
zPositionMonitor.__init__éd   ÚlimitÚreturnc              
   C   sÚ   d}| j d|dœ}zGt d¡ tjt||dœdddd	d
œdd�}| ¡  | ¡ }d|v r9t d|d › �¡ g W S | 	di ¡ 	dg ¡}t dt
|ƒ› d�¡ |W S  tyl } zt d|› �¡ g W  Y d}~S d}~ww )uo   
        RÃ©cupÃ¨re les positions depuis The Graph (Arbitrum)
        Source principale la plus fiable
        a)  
        query OrderAndTradeHistorys($skip: Int, $first: Int, $user: String) {
            orderAndTradeHistories(
                skip: $skip
                first: $first
                orderBy: timestamp
                orderDirection: desc
                where: {
                    user: $user
                    actionType_not: ADD_MARGIN
                }
            ) {
                id
                orderOrTradeHash
                actionType
                timestamp
                txHash
                limitOrder {
                    pair { name }
                    isLong
                    token { symbol }
                    amountIn
                    limitPrice
                    qty
                    takeProfit
                    stopLoss
                }
                trade {
                    pair { name }
                    isLong
                    token { symbol }
                    margin
                    entryPrice
                    qty
                    openFee
                    executionFee
                    closeType
                    closePrice
                    closeFee
                    fundingFee
                    holdingFee
                    pnl
                    actualPnl
                }
            }
        }
        r   )ÚuserÚskipÚfirstu*   ðŸ“¡ Interrogation The Graph (Arbitrum)...)ÚqueryÚ	variableszapplication/jsonz*/*zhttps://www.apollox.financezMozilla/5.0)zContent-TypeÚAcceptÚOriginz
User-Agenté   )ÚjsonÚheadersÚtimeoutÚerrorszGraphQL errors: ÚdataÚorderAndTradeHistoriesõ   âœ… u(    entrÃ©es rÃ©cupÃ©rÃ©es depuis The Graphu   â�Œ Erreur The Graph: N)r   ÚloggerÚinfoÚrequestsÚpostÚTHEGRAPH_URLÚraise_for_statusr   ÚerrorÚgetÚlenÚ	Exception)r   r   Úgraphql_queryr   Úresponser!   Ú	historiesÚer   r   r   Úfetch_from_thegraph0   s<   1ý
ü÷€þz#PositionMonitor.fetch_from_thegraphr0   c                 C   s‚  i }|D �]9}|  d¡}|  d¡}|s|sq|  dd¡}t|  dd¡ƒ}|  dd¡}|  d	d¡}	|	r4|	n|}
|r:|n|}|  d
i ¡  dd¡}|  dd¡}|rÄt|  dd¡ƒ}t|  dd¡ƒ}t|  dd¡ƒ}|  d¡}|  d¡rxt|  dd¡ƒnd}|  d¡r‡t|  dd¡ƒnd}|dkr™|dkr™t|| | ƒnd}|r©d| ¡ v r¦d}nd}nd}t|  dd¡ƒ}t|  dd¡ƒ}t|  dd¡ƒ}n,t|  dd¡ƒ}t|  dd¡ƒ}t|  dd¡ƒ}d}|dkräd nd!}d}d}d}d}d}i d"|
“d#|“d$|› d%�“d&|“d|“d'|“d(|“d|“d)|“d*|�rt |¡ ¡ nd“d+|“d,|“d-|“d.|“d/|“d0|“d1d2“d3t ¡  ¡ i¥}|||
< q|S )4uJ   
        Parse les donnÃ©es The Graph en positions standardisÃ©es
        ÚtradeÚ
limitOrderÚ
actionTypeÚUNKNOWNÚ	timestampr   ÚtxHashÚ ÚorderOrTradeHashÚpairÚnameÚBTCUSDÚisLongFÚmarginÚ
entryPriceÚqtyÚ	closeTypeÚ
closePriceNÚ	actualPnlÚLIQUIDATÚ
LIQUIDATEDÚCLOSEDÚOPENÚopenFeeÚcloseFeeÚ
fundingFeeÚamountInÚ
limitPriceÚ
OPEN_LIMITÚPENDINGÚ	CANCELLEDÚ
trade_hashÚtx_hashÚsymbolÚ_DEGENÚis_longÚleverageÚentry_priceÚstatusÚ	opened_atÚclose_priceÚpnlÚopen_feeÚ	close_feeÚfunding_feeÚaction_typeÚsourceÚthegraph_arbitrumÚlast_checked)r+   ÚintÚfloatÚupperr   ÚfromtimestampÚ	isoformatÚnow)r   r0   Ú	positionsÚentryr3   Úlimit_orderr_   r7   rR   Úorder_trade_hashrQ   r!   Ú	pair_namerU   r?   rW   rA   Ú
close_typerZ   r[   rV   rX   r\   r]   r^   Úpositionr   r   r   Úparse_thegraph_positions‹   sž   



$ÿþ
ýüûúùø	÷
öõôóòñðïî
z(PositionMonitor.parse_thegraph_positionsr   Ú
startblockc           	      C   s  t s	t d¡ g S ddd| j|dd|dt dœ
}zRt d	¡ tjt|d
d�}| ¡ }| d¡dkrVt	| d¡t
ƒrV|d }dd„ |D ƒ}t dt|ƒ› dt|ƒ› d�¡ |W S t d| d¡› d| d¡› �¡ g W S  ty… } zt d|› �¡ g W  Y d}~S d}~ww )uc   
        RÃ©cupÃ¨re les TX depuis Etherscan V2 (BSC)
        Fallback si The Graph Ã©choue
        u!   âš ï¸�  BSCSCAN_API_KEY manquanteÚ56ÚaccountÚtxlistiÿàõé   Údesc)
ÚchainidÚmoduleÚactionÚaddressrq   ÚendblockÚpageÚoffsetÚsortÚapikeyu(   ðŸ“¡ Interrogation Etherscan V2 (BSC)...r   )Úparamsr   rX   Ú1Úresultc                 S   s(   g | ]}|  d d¡ ¡ t ¡ kr|‘qS )Útor9   )r+   ÚlowerÚAPOLLOX_CONTRACT_BSC©Ú.0Útxr   r   r   Ú
<listcomp>
  s
    ÿz8PositionMonitor.fetch_from_etherscan.<locals>.<listcomp>r#   u    TX ApolloX rÃ©cupÃ©rÃ©es (sur z total)u   âš ï¸�  Etherscan V2: Úmessagez - u   â�Œ Erreur Etherscan V2: N)r
   r$   Úwarningr   r%   r&   r+   ÚETHERSCAN_V2_URLr   Ú
isinstanceÚlistr,   r-   r*   )	r   rq   r   r€   r/   r!   ÚtxsÚapollox_txsr1   r   r   r   Úfetch_from_etherscané   s@   
ö
ÿ "€þz$PositionMonitor.fetch_from_etherscanrR   c              
   C   sœ   z/t j |¡}|d D ]!}|d  ¡ t ¡ kr,t|d ƒdkr,|d d  ¡ }|  W S qW dS  tyM } zt 	d|› d|› �¡ W Y d}~dS d}~ww )	z@
        Extrait le trade hash depuis les logs d'une TX
        Úlogsrz   Útopicsé   ru   Nz$Impossible d'extraire trade hash de z: )
Úw3ÚethÚget_transaction_receiptr„   r…   r,   Úhexr-   r$   Údebug)r   rR   ÚreceiptÚlogrQ   r1   r   r   r   Úextract_trade_hash_from_tx  s   
€€þz*PositionMonitor.extract_trade_hash_from_txc                 C   s    | j dd�}|r#|  |¡}dd„ | ¡ D ƒ}t dt|ƒ› d�¡ |S t d¡ | jdd�}|rIdd	„ |D ƒ}t dt|ƒ› d
�¡ t d¡ i S t d¡ i S )u9   
        RÃ©cupÃ¨re les positions ACTIVES (OPEN)
        é2   ©r   c                 S   s"   i | ]\}}|d  dkr||“qS )rX   rH   r   )r‡   ÚthÚposr   r   r   Ú
<dictcomp>;  s
    ÿz8PositionMonitor.get_active_positions.<locals>.<dictcomp>õ   ðŸ“Š u(    positions actives trouvÃ©es (The Graph)u$   âš ï¸�  Fallback sur Etherscan V2...c                 S   s$   g | ]}d |  dd¡ ¡ v r|‘qS )ÚopenMarketTradeÚfunctionNamer9   )r+   r„   r†   r   r   r   r‰   I  s
    ÿz8PositionMonitor.get_active_positions.<locals>.<listcomp>u+    ouvertures rÃ©centes trouvÃ©es (Etherscan)uD   âš ï¸�  Etherscan ne peut pas dÃ©terminer si positions sont ouvertesu   â�Œ Aucune source disponible)	r2   rp   Úitemsr$   r%   r,   r‹   r‘   r*   )r   r0   Úall_positionsÚactive_positionsr�   Úopen_txsr   r   r   Úget_active_positions1  s&   
ÿ
ÿ

z$PositionMonitor.get_active_positionsc                 C   sB   | j |d�}|r|  |¡}t dt|ƒ› d�¡ |S t d¡ i S )uF   
        RÃ©cupÃ¨re TOUTES les positions (historique complet)
        rž   r¢   u    positions totales trouvÃ©esu*   â�Œ Impossible de rÃ©cupÃ©rer l'historique)r2   rp   r$   r%   r,   r*   )r   r   r0   r¦   r   r   r   Úget_all_positionsY  s   

z!PositionMonitor.get_all_positionsrQ   c                 C   s`   | j dd�}||v r!|| d }t d|dd… › d|› �¡ |S t d|dd… › d	�¡ dS )
u    
        VÃ©rifie le statut d'une position spÃ©cifique

        Returns:
            'OPEN', 'CLOSED', 'LIQUIDATED', 'PENDING', ou None si non trouvÃ©e
        éÈ   rž   rX   z	Position Né   z... = u   âš ï¸�  Position u   ... non trouvÃ©e)rª   r$   r%   r‹   )r   rQ   r¦   rX   r   r   r   Úcheck_position_statush  s   z%PositionMonitor.check_position_statusN)r   )r   r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   rc   r   r   r2   Ústrrp   r‘   r   rœ   r©   rª   r­   r   r   r   r   r   &   s    [^0(r   Ú__main__z%(message)s)ÚlevelÚformatzP================================================================================u   ðŸ”� TEST POSITION MONITORu   1ï¸�âƒ£  POSITIONS ACTIVES:zP--------------------------------------------------------------------------------rU   ÚLONGÚSHORTu   
ðŸ“Š rS   Ú rV   Úxz   Trade Hash: é   z...z   Margin: $r?   z.2fz   Entry: $rW   z,.2fz   Status: rX   z   Opened: rY   u!      âš ï¸�  Aucune position active)&r±   r&   r   Úosr   Útypingr   r   r   Údotenvr   Úweb3r   ÚloggingÚ	getLoggerr®   r$   Úgetenvr„   r   r
   r(   rŒ   r…   ÚBSC_RPCÚHTTPProviderr•   r   ÚbasicConfigÚINFOÚmonitorÚprintr©   Úactiver¥   rQ   r    Úsider   r   r   r   Ú<module>   sZ   

  W$ù	ã