
    i`                         d dl Zd dlmZmZ d dlZd dl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  G d	 d
ej        j                  ZdS )    N)
ArrayCacheArrayCacheBySymbolById)IntOrder	OrderBookStrTickerTrade)Client)List)ExchangeError)AuthenticationError)Precisec            
       \    e Zd Z fdZi fdZddi fdedededee         fdZ	i fdede
fd	Zd
efdZddef fdZd
efdZdi fdededefdZd
efdZd
efdZd
efdZd
efdZi fdZd
efdZdi fdefdZdddi fdedededee         fdZd
efdZd Zd
efdZd
efdZ xZ S )bitfinexc                     |                      t          t          |                                           dddddddddddddiid	d
dddd          S )NTF)wswatchTickerwatchTickerswatchOrderBookwatchTradeswatchBalance
watchOHLCVapir   zwss://api-pub.bitfinex.com/ws/1zwss://api.bitfinex.com/ws/1)publicprivateP0F0)precfreq  )r   ordersLimit)hasurlsoptions)deep_extendsuperr   describe)self	__class__s    W/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/pro/bitfinex.pyr(   zbitfinex.describe   s    h 5 5 > > @ @# %"&# %#  "C#@  ! # #  $ %C
 C
   	    c                 (  K   |                                   d {V  |                     |          }|d         }| j        d         d         d         }|dz   |z   }d|||d}|                     |||                     ||          |           d {V S )Nidr   r   r   :	subscribe)eventchannelsymbolmessageHash)load_marketsmarketr$   watchr&   )	r)   r2   r3   paramsr6   marketIdurlr4   requests	            r+   r0   zbitfinex.subscribe/   s      !!!!!!!!!V$$$<it$X.mh. !&	
 
 ZZ[$2B2B7F2S2SU`aaaaaaaaar,   Nr3   sincelimitreturnc                 
  K   |                                   d{V  |                     |          }|                     d||           d{V }| j        r|                    ||          }|                     |||dd          S )a  
        get the list of most recent trades for a particular symbol
        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        Ntrades	timestampT)r5   r3   r0   
newUpdatesgetLimitfilter_by_since_limit)r)   r3   r<   r=   r8   r@   s         r+   watch_tradeszbitfinex.watch_trades>   s       !!!!!!!!!V$$~~h????????? 	3OOFE22E))&%TRRRr,   c                 @   K   |                      d||           d{V S )a  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        tickerN)r0   )r)   r3   r8   s      r+   watch_tickerzbitfinex.watch_tickerN   s0       ^^Hff=========r,   clientc                    |                      |d          }|                     |d          }|dz   |z   }|                     | j        dd          }|                     |          }|d         }	|                      |d          }
|                      | j        |	          }|t          |          }|| j        |	<   t          |
t                    rR| 	                    |
|          }t          dt          |                    D ]}|                    ||                    nI|                     |d          }|d	k    rd S |                     ||          }|                    |           |                    ||           d S )
Nr2   pairr/   tradesLimitr!   r3      r   tu)
safe_valuesafe_stringsafe_integerr%   safe_marketr@   r   
isinstancelistparse_tradesrangelenappendparse_traderesolve)r)   rI   messagesubscriptionr2   r9   r4   rL   r6   r3   datastoredr@   isecondtrades                   r+   handle_tradeszbitfinex.handle_tradesW   s   . //,	::##L&99mh.''mTJJ!!(++!w**f55>,,F"(DKdD!! 		!&&tV44F1c&kk** ) )fQi(((() %%gq11F~~$$Wf55EMM%   v{+++++r,   c                 V   t          |t                    s)t          t          |                               ||          S t          |          }|                     |d          }d }|dk    r|                     ||dz
            }|                     ||dz
            }|                     ||dz
            }|                     ||dz
            }d }	|-t          j	        |d          rdnd}	t          j
        |          }|                     |d          }
|
                    d	          }|                     |d          }||                    d
d          }|                     ||          }d }d }|                     |||                     |          |||d ||	||d d d          S )NrM   rN            0buysell-t )inforA   datetimer3   r.   ordertypetakerOrMakersidepriceamountcostfee)rS   rT   r'   r   rY   rW   rP   safe_timestampr   	string_gt
string_abssplitreplacesafe_symbol
safe_tradeiso8601)r)   ra   r6   tradeLengthr1   r.   rA   rs   rt   rr   seqpartsr9   r3   rq   orderIdr*   s                   r+   rY   zbitfinex.parse_trade   s   " %&& 	D4((44UFCCC%jj  **D==!!%q99B''{Q??	  a88!!%q99#-fc::F55D'//Fua((		###E1--''R00H!!(F33"Y//( 
  
   	r,   c                 <   |                      |d          }|                     |          }d}|dz   |z   }|                      |d          }|                      |d          }	d }
||	t          j        ||	          }
i d|dd dd d	|                     |d
          d|                     |d          d|                     |d          dd d|                     |d          dd dd d|                     |
          d|                     |          d|                     |          dd d|                     |	          d|                     |d          dd |                     |d          d |d}|| j        |<   |                    ||           d S )NrK   rG   r/         r3   rA   rn   high	   low
   bidrM   	bidVolumeaskre   	askVolumevwapopencloselastpreviousClosechange
percentage   average   )
baseVolumequoteVolumerm   )rP   r|   r   
string_sub
safe_floatparse_numbertickersrZ   )r)   rI   r[   r\   r9   r3   r2   r4   r   r   r   results               r+   handle_tickerzbitfinex.handle_ticker   s(     ##L&99!!(++mh.++!!'1--6#5%dF33D
f

 
 DOOGQ//	

 4??7B//
 4??7A..
 
 4??7A..
 
 D
 D%%d++
 T&&t,,
 D%%d++
 T
 d''//
  $//'155!
" t#
$ //'155)
 
 
,  &Vv{+++++r,   c                 z  K   |#|dk    r|dk    rt          | j        dz             |                     | j        di           }|                     |dd          }|                     |dd	          }|||d
}|                     d||                     ||                     d{V }|                                S )a  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :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
        N   d   z6 watchOrderBook limit argument must be None, 25 or 100r   r   r   r    r   )r   r    rW   book)r   r.   rO   r%   rP   r0   r&   r=   )	r)   r3   r=   r8   r%   r   r    r;   	orderbooks	            r+   watch_order_bookzbitfinex.watch_order_book   s       %3,,#DG.f$fggg//$,0@"EE6666
 
 
 ..9I9I'SY9Z9Z[[[[[[[[	   r,   c                 &   |                      |d          }|                     |          }d}|dz   |z   }|                      |dd          }|dk    }	t          |d         t                    r|                     |d          }
|	r|                     i |
          | j        |<   n|                     i |
          | j        |<   | j        |         }|	r|d         }t          d	t          |                    D ]r}||         }|                      |d	          }| 
                    |d          }|d
         }|d	k     r| n|}|d	k     rdnd}||         }|                    |||           snx|d         }t          d	t          |                    D ]R}||         }|d
         }|d	k     r| n|}|d	k     rdnd}||         }|                    |d	         ||d                    S|                    ||           d S | j        |         }|	r|                      |d          }|                      |d
          }|d         }|d	k     r| n|}|d	k     rdnd}||         }t          j        |d          r|nd}|                    |                     |          |                     |          |           nH|d         }|d	k     r| n|}|d	k     rdnd}||         }|                    |d         ||d
                    |                    ||           d S )NrK   r   r/   r   r   R0rM   rW   r   rf   asksbidsre   rg   )rP   r|   rS   rT   rQ   indexed_order_book
orderbookscounted_order_bookrV   rW   r   storerZ   r   rx   r   )r)   rI   r[   r\   r9   r3   r2   r4   r   isRawr=   r   deltasr_   deltar.   rs   delta2Valuesizerr   booksidedelta2countedBookSidemessage3rt   message3Values                             r+   handle_order_bookzbitfinex.handle_order_book  st   2 ##L&99!!(++mh.fd;;gaj$'' 0	3%%lE::E M*.*A*A"e*L*L'' +/*A*A"e*L*L'/I D q#f++.. 4 4A"1IE))%33B OOE155E"'(K,7!OOK<<+D&1Aoo66FD(HNN5$33334 !q#f++.. D DA"1IE"1XF'-zzF77D&,qjj66vD&/oO#))%(D%(CCCCNN9k22222/I D%%gq11((!44"1:%-\\yy"*Q,,vvV$T?!(!25#!>!>GCt00779J9J69R9RTVWWWW '
*7!*;*;~~-"/!"3"3vv&"+D/%%gaj$
CCCNN9k22222r,   c                 ^    |                      |d          }|                    ||           d S )Nr1   )rP   rZ   )r)   rI   r[   r1   s       r+   handle_heartbeatzbitfinex.handle_heartbeatY  s3       '22w&&&&&r,   c                     |S N )r)   rI   r[   s      r+   handle_system_statuszbitfinex.handle_system_statusb  s	     r,   c                 F    |                      |d          }||j        |<   |S )NchanId)rP   subscriptions)r)   rI   r[   	channelIds       r+   handle_subscription_statusz#bitfinex.handle_subscription_statusq  s+     $$Wh77	*1Y'r,   c                   K   | j         d         d         d         }|                     |          }|                    d          }d}|                     |j        |          }||                                 }dt          |          z   }|                     |                     |          |                     | j	                  t          j        d          }	| j        |	|||dd	gd
}
|                     | j        |||
d           | d {V S )Nr   r   r   authenticatedauthAUTHhextradingwallet)apiKeyauthSig	authNonceauthPayloadr1   filterrM   )r$   rI   futurerO   r   millisecondsstrhmacencodesecrethashlibsha384r   spawnr7   )r)   r8   r:   rI   r   methodr   noncepayload	signaturer;   s              r+   authenticatezbitfinex.authenticate  s     it$Y/S!!//(<fEE %%''Es5zz)G		$++g"6"6DK8P8PRYR`bghhI+$"&
 
G JJtz3;;;||||||r,   c                 d   |                      |d          }|dk    r2|                     |j        d          }|                    d           d S t	          |                     |                    }|                    |d           |                      |d          }||j        v r
|j        |= d S d S )NstatusOKr   Tr1   )rP   rO   futuresrZ   r   jsonrejectr   )r)   rI   r[   r   r   errorr   s          r+   handle_authentication_messagez&bitfinex.handle_authentication_message  s    !!'844T>>__V^_EEFNN4     '		'(:(:;;EMM%111%%gw77F---(000 .-r,   c                    K   |                                   d {V  | j        d         d         d         }|                                  d {V  |                     ||d d           d {V S )Nr   r   r   rM   )r5   r$   r   r7   )r)   r.   r3   r8   r:   s        r+   watch_orderzbitfinex.watch_order  s      !!!!!!!!!it$Y/!!!!!!!!!ZZRq111111111r,   c                 v  K   |                                   d{V  |                                  d{V  ||                     |          }| j        d         d         d         }|                     |ddd           d{V }| j        r|                    ||          }|                     ||||d          S )a  
        watches information on multiple orders made by the user
        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   r   r   osrM   T)r5   r   r3   r$   r7   rB   rC   filter_by_symbol_since_limit)r)   r3   r<   r=   r8   r:   orderss          r+   watch_orderszbitfinex.watch_orders  s       !!!!!!!!!!!!!!!!!![[((Fit$Y/zz#tT155555555? 	3OOFE22E00tTTTr,   c                 ^   |                      |dg           }|                     |d          }|dk    r?t          dt          |                    D ] }||         }|                     ||           !n|                     ||           | j        |                    | j        d           d S d S )Nrf   rM   r   r   )rO   rP   rV   rW   handle_orderr   rZ   )r)   rI   r[   r\   r]   messageTyper_   values           r+   handle_orderszbitfinex.handle_orders  s    \ w2..&&w22$1c$ii(( 1 1Q!!&%00001 fd+++;"NN4;----- #"r,   c                 :    ddd}|                      |||          S )Nr   canceled)ACTIVECANCELED)rP   )r)   r   statusess      r+   parse_ws_order_statuszbitfinex.parse_ws_order_status  s.    "
 
 &&999r,   c                 d   |                      |d          }|                      |d          }|                     |          }|                      |d          }|                      |d          }d}t          j        |d          r*t          j        |          }t          j        |          }d}|                      |d          }	|	                    d	          d
k    rd}	n|	                    d          d
k    r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"          }| j
        0|                     | j        d#d$          }t          |          | _
        | j
        }|                    |           |                    ||           |S )%Nr   rM   rf   re   rh   rg   ri   rd   LIMITr=   MARKETr6   r   r   r   rm   r.   clientOrderIdrA   rn   lastTradeTimestampr3   rp   rr   rs   	stopPricetriggerPricer   rt   	remainingfilledr   )rv   ru   r@   r"   r!   )rP   r|   r   	string_ltry   findr   	parse8601
safe_orderr~   r   rQ   r%   r   rX   rZ   )r)   rI   ro   r.   r9   r3   rt   r   rr   rp   r   rs   rawDatetimerA   parsedr=   r   s                    r+   r   zbitfinex.handle_order  s    eQ''##E1--!!(++!!%++$$UA..	VS)) 	'//F*955IDq))99W""DDYYx  2%%D++D,<,<UA,F,FGG  **&&ua00NN;//	 "
E"
""
 T"
 	"

 Y//"
 !$"
 f"
 D"
 D"
 U"
 "
 D"
 t"
 f"
 "
  d!"
" f#"
$ )"
 "
 "
  , ;%%dlM4HHE077DKfvr"""r,   c                 T   t          |t                    r|                     |d          }|d         dk    rd S |                     |j        |i           }|                     |d          }|                     |d          }| j        | j        | j        | j        | j        | j        d}| 	                    |||          }| ||||           d S d S |                     |d          }	|	;| j
        | j        | j        d}|                     ||	          }| |||           d S d S d S )Nr   rM   hbr2   )r   rG   r@   r   onocr1   )rm   
subscribedr   )rS   rT   rP   rO   r   r   r   rb   r   safe_value_2r   r   r   )
r)   rI   r[   r   r\   r2   namemethodsr   r1   s
             r+   handle_messagezbitfinex.handle_message?  sp   gt$$ -	,((!44I qzT!!??6+?BOOL&&|Y??G##GQ//D.,,((( G &&w>>F!vw55555 "! $$Wg66E  5"&"A >	  %88%F67+++++ !  &%r,   r   )!__name__
__module____qualname__r(   r0   r   r   r   r
   rE   r	   rH   r   rb   rY   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  __classcell__)r*   s   @r+   r   r      s           8 79 b b b b <@d[] S S SS S Sbfglbm S S S S  68 > > >F > > > >,,F ,, ,, ,, ,,\5 5 5 5 5 5 5 5n0,F 0, 0, 0, 0,d @DB ! !S ! !S\ ! ! ! !2P3 P3 P3 P3 P3d'v ' ' ' '6        " )+    01F 1 1 1 1 37r 2 2C 2 2 2 2 04$UYbd U U UC Us Uimnsit U U U U&7.F 7. 7. 7. 7.r: : :<6 < < < <|.,V ., ., ., ., ., ., ., .,r,   r   )ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   r   ccxt.base.typesr   r   r   r   r	   r
   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   ccxt.base.preciser   async_supportr   r   r,   r+   <module>r     s       O O O O O O O O  E E E E E E E E E E E E E E E E 4 4 4 4 4 4       * * * * * * 0 0 0 0 0 0 % % % % % %\	, \	, \	, \	, \	,t!* \	, \	, \	, \	, \	,r,   